answer
stringlengths 15
1.25M
|
|---|
<?php
/* TwigBundle:Exception:exception.json.twig */
class <API key> extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 1
if (isset($context["exception"])) { $_exception_ = $context["exception"]; } else { $_exception_ = null; }
echo <API key>($this->getAttribute($_exception_, "toarray"));
echo "
";
}
public function getTemplateName()
{
return "TwigBundle:Exception:exception.json.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 47 => 8, 30 => 4, 27 => 3, 22 => 4, 117 => 22, 112 => 21, 109 => 20, 104 => 19, 96 => 18, 84 => 14, 80 => 12, 68 => 9, 44 => 7, 26 => 4, 23 => 3, 20 => 2, 17 => 1, 92 => 39, 86 => 6, 79 => 40, 57 => 22, 46 => 7, 37 => 8, 33 => 7, 29 => 6, 24 => 4, 19 => 1, 144 => 54, 138 => 50, 130 => 46, 124 => 24, 121 => 41, 115 => 40, 111 => 38, 108 => 37, 99 => 32, 94 => 29, 91 => 17, 88 => 16, 85 => 26, 77 => 39, 74 => 20, 71 => 19, 65 => 16, 62 => 15, 58 => 8, 54 => 11, 51 => 10, 42 => 9, 38 => 8, 35 => 5, 31 => 4, 28 => 3,);
}
}
|
<div id="menu-logo-wrapper" class="animated slideInDown">
<div class="main-menu">
<div class="pull-left">
<div class="<API key>">
<div class="toggle-menu">
<a href="javascript:void(0)">
<span class="nav-bar"></span>
<span class="nav-bar"></span>
<span class="nav-bar"></span>
</a>
</div>
</div>
<div class="main-nav-wrapper">
<ul class="main-nav">
<li><a href="<?php echo View::url('/'); ?>#about">About</a></li>
<li><a href="<?php echo View::url('/'); ?>#flavours">Flavours</a></li>
<li><a href="<?php echo View::url('/'); ?>#news">News</a></li>
<li><a href="<?php echo View::url('/'); ?>#locate">Locate</a></li>
<li><a href="<?php echo View::url('/'); ?>#wholesale">Wholesale</a></li>
</ul>
</div>
</div>
<a href="<?php echo View::url('/'); ?>" class="logo pull-right"><img src="<?= $view->getThemePath() ?>/images/logos/main-logo.png" alt=""></a>
</div>
</div>
|
[
* `ember test`
* `ember test --server`
## Building
* `ember build`
For more information on using ember-cli, visit [http:
|
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.vmwarecloudsimple.models;
import com.azure.resourcemanager.vmwarecloudsimple.fluent.models.<API key>;
/** An immutable client-side representation of CustomizationPolicy. */
public interface CustomizationPolicy {
/**
* Gets the id property: Customization policy azure id.
*
* @return the id value.
*/
String id();
/**
* Gets the location property: Azure region.
*
* @return the location value.
*/
String location();
/**
* Gets the name property: Customization policy name.
*
* @return the name value.
*/
String name();
/**
* Gets the type property: The type property.
*
* @return the type value.
*/
String type();
/**
* Gets the description property: Policy description.
*
* @return the description value.
*/
String description();
/**
* Gets the privateCloudId property: The Private cloud id.
*
* @return the privateCloudId value.
*/
String privateCloudId();
/**
* Gets the specification property: Detailed customization policy specification.
*
* @return the specification value.
*/
<API key> specification();
/**
* Gets the typePropertiesType property: The type of customization (Linux or Windows).
*
* @return the typePropertiesType value.
*/
<API key> typePropertiesType();
/**
* Gets the version property: Policy version.
*
* @return the version value.
*/
String version();
/**
* Gets the inner com.azure.resourcemanager.vmwarecloudsimple.fluent.models.<API key> object.
*
* @return the inner object.
*/
<API key> innerModel();
}
|
import React from 'react';
import ErrorIcon from './ErrorIcon';
export const symbols = {
'ErrorIcon -> with filled': <ErrorIcon filled={true} />,
'ErrorIcon -> without filled': <ErrorIcon filled={false} />
};
|
{% extends "base.html"%}
{% block title %}Sequence{% endblock %}
<!
{% block head %}
<link rel="stylesheet" type="text/css" href="{{ static_file('css/rhizo/app.css') }}">
<script type="text/javascript" src="/static/js/moment.min.js"></script>
<script type="text/javascript" src="/static/js/paho-mqtt.js"></script>
<script type="text/javascript" src="{{ static_file('js/rhizo/messages.js') }}"></script>
<script type="text/javascript" src="{{ static_file('js/manyplot.js') }}"></script>
<style>
div#plot {
display: none;
margin-bottom: 20px;
}
</style>
{% endblock head %}
<!
{% block script %}
<script>
var g_resource = {{ resource|safe }};
var g_resourcePath = '{{ resource_path|safe }}'; // assume includes leading slash
var <API key> = '{{ <API key>|safe }}'; // assume includes leading slash
var g_timestamps = {{ timestamps|safe }};
var g_values = {{ values|safe }};
var g_thumbnailRevs = {{ thumbnail_revs|safe }};
var g_fullImageRevs = {{ full_image_revs|safe }};
var g_plotHandler = null;
var g_xData = null;
var g_yData = null;
var g_tableData = null;
$(function() {
// add a menus
var menuData = createMenuData();
menuData.add('Download', downloadHistory);
menuData.add('Summary', dataSummary);
menuData.add('Delete Data', deleteAllData);
createDropDownMenu({id: 'dataMenu', label: 'Data', compact: true, menuData: menuData}).appendTo($('#menuArea'));
// add summary area
var dataTypeName = '';
switch (g_resource.system_attributes.data_type) {
case 1: dataTypeName = 'numeric'; break;
case 2: dataTypeName = 'text'; break;
case 3: dataTypeName = 'image'; break;
}
var nvd = createNameValueData();
nvd.add('ID', g_resource.id);
nvd.add('Name', g_resource.name);
nvd.add('Data Type', dataTypeName);
nvd.add('Decimal Places', g_resource.system_attributes.decimal_places);
nvd.add('Units', g_resource.system_attributes.units);
nvd.add('Max History', g_resource.system_attributes.max_history);
nvd.add('Min Storage Interval', g_resource.system_attributes.<API key> ? g_resource.system_attributes.<API key> + ' seconds' : '0');
createNameValueView(nvd).appendTo($('#sequenceInfo'));
var decimalPlaces = g_resource.decimal_places;
var format = '.' + decimalPlaces + 'f';
// create plot (for numeric sequences)
if (g_resource.system_attributes.data_type == 1) {
var valuesRev = g_values.slice(0).reverse(); // fix(faster): do we need to make a copy if we're reversing?
var timestampsRev = g_timestamps.slice(0).reverse();
var canvas = document.getElementById('canvas');
// make sure all values are numeric (or null)
// fix(faster): combine with reverse (or do on server)
var len = valuesRev.length;
for (var i = 0; i < len; i++) {
var val = valuesRev[i];
if (val !== null) {
valuesRev[i] = +val; // convert to number
}
}
// create plot using manyplot library
g_plotHandler = createPlotHandler(canvas);
g_xData = createDataColumn('timestamp', timestampsRev);
g_xData.type = 'timestamp';
g_yData = createDataColumn('value', valuesRev);
g_yData.name = g_resource.name;
var dataPairs = [
{
'xData': g_xData,
'yData': g_yData,
}
];
g_plotHandler.plotter.setData(dataPairs);
g_plotHandler.drawPlot(null, null);
$('#plot').show();
}
// create table of historical values
if (g_values.length) {
// prep data
var tableLength = 200;
var timestamps = g_timestamps.slice(0, tableLength);
for (var i = 0; i < timestamps.length; i++) {
timestamps[i] *= 1000; // fix(later): do this automatically in table? standardize on unix or unix * 1000?
}
var values = [];
if (g_resource.system_attributes.data_type == 3) {
values = [];
for (var i = 0; i < tableLength; i++) {
var fullImageUrl = '/api/v1/resources' + g_resourcePath + '?rev=' + g_fullImageRevs[i];
if (g_thumbnailRevs[i]) {
var thumbnailUrl = '/api/v1/resources' + <API key> + '?rev=' + g_thumbnailRevs[i];
var link = $('<a>', {href: fullImageUrl});
$('<img>', {src: thumbnailUrl}).appendTo(link);
} else {
var link = createLink({'text': 'image', 'href': fullImageUrl});
}
values.push(link);
}
} else {
values = g_values.slice(0, tableLength);
}
// create table
var div = $('#history');
$('<h2>', {html: 'Recent History'}).appendTo(div);
g_tableData = createTableData();
g_tableData.addColumn('Timestamp', timestamps);
g_tableData.addColumn('Value', values);
g_tableData.setFormat('Timestamp', 'timestamp');
createTable(g_tableData).appendTo(div);
}
// subscribe to updates
var lastSlashPos = g_resourcePath.lastIndexOf('/');
var folderName = g_resourcePath.slice(0, lastSlashPos);
subscribeToFolder(folderName);
connectWebSocket();
g_wsh.addSequenceHandler(function(path, timestamp, value) {
if (path == g_resourcePath) {
var unixTimestamp = timestamp.unix();
// update plot
if (g_resource.system_attributes.data_type == 1) {
g_xData.data.push(unixTimestamp);
g_yData.data.push(value);
g_plotHandler.plotter.autoBounds();
g_plotHandler.drawPlot(null, null);
}
// update image
// note: not every sequence update will be stored in DB, so not every image update message will include revision_ids
if (g_resource.system_attributes.data_type == 3 && params.revision_id && params.<API key>) {
var fullImageUrl = '/api/v1/resources' + g_resourcePath + '?rev=' + params.revision_id;
var thumbnailUrl = '/api/v1/resources' + <API key> + '?rev=' + params.<API key>;
var link = $('<a>', {href: fullImageUrl});
$('<img>', {src: thumbnailUrl}).appendTo(link);
value = link;
}
// update table
// fix(faster): just add row?
if (value) {
g_tableData.column('Timestamp').values.unshift(unixTimestamp * 1000);
g_tableData.column('Value').values.unshift(value);
var div = $('#history');
div.html('');
$('<h2>', {html: 'Recent History'}).appendTo(div);
createTable(g_tableData).appendTo(div);
}
}
});
});
function dataSummary() {
var handler = function(data) {
var len = data.length;
var messages = [];
var counts = [];
for (var i = 0; i < len; i++) {
var item = data[i];
messages.push(item[0]);
counts.push(item[1]);
}
var div = $('#history');
div.html(''); // clear out old html
$('<h2>', {html: 'History Summary'}).appendTo(div);
var tableData = createTableData();
tableData.addColumn('Message', messages);
tableData.addColumn('Count', counts);
createTable(tableData).appendTo(div);
}
var params = {
'summary': 1,
'prefix_length': 10,
'count': 10000,
'csrf_token': g_csrfToken,
};
$.get('/api/v1/resources' + g_resourcePath, params, handler);
}
function downloadHistory() {
// create a modal
var modalDiv = createBasicModal('downloadHistory', 'Download History');
modalDiv.appendTo($('body'));
// add date range selectors
var todayStr = moment().format('YYYY-MM-DD');
var fg = createFormGroup({id: 'startDate', label: 'Start Date'}).appendTo($('#<API key>'));
createTextInput({id: 'startDate', value: todayStr}).appendTo(fg);
var fg = createFormGroup({id: 'endDate', label: 'End Date'}).appendTo($('#<API key>'));
createTextInput({id: 'endDate', value: todayStr}).appendTo(fg);
// handle user choosing to proceed
$('#downloadHistory-ok').click(function() {
var startDate = $('#startDate').val();
var endDate = $('#endDate').val();
var startMoment = moment(startDate);
var endMoment = moment(endDate);
if (!startMoment.isValid()) {
alert('Please enter a valid start date.');
$('#startDate').focus();
} else if (!endMoment.isValid()) {
alert('Please enter a valid end date.');
$('#endDate').focus();
} else {
var startTimestamp = startMoment.startOf('day').toISOString();
var endTimestamp = endMoment.endOf('day').toISOString();
$('#downloadHistory').modal('hide');
window.location.href = '/api/v1/resources' + g_resourcePath + '?download=1&start_timestamp=' + startTimestamp + '&end_timestamp=' + endTimestamp;
}
});
// display the modal
$('#downloadHistory').modal('show');
}
function deleteAllData() {
modalConfirm({
title: 'Delete Sequence Data',
'prompt': 'Are you sure you want to <b>delete all data</b> for sequence <b>' + g_resource.name + '</b>?',
yesFunc: function() {
$.ajax({
url: '/api/v1/resources' + g_resourcePath,
data: {'csrf_token': g_csrfToken, 'data_only': 1},
type: 'DELETE',
success: function() {window.location.reload();}, // fix(later): make more graceful
});
}
});
}
</script>
{% endblock %}
<!
{% block content %}
<h2>Sequence</h2>
<div id="sequenceInfo"></div>
<div id="plot">
<canvas id="canvas" width="900" height="400"></canvas>
<br>
<button class="btn" onclick="g_plotHandler.zoomIn()">Zoom In</button>
<button class="btn" onclick="g_plotHandler.zoomOut()">Zoom Out</button>
</div>
<div id="history"></div>
{% endblock %}
|
<!DOCTYPE HTML>
<?php include '../inc/draft_config.php'; ?><!-- Use relative path to find config file -->
<html lang="">
<head>
<base href="<?php echo BASE_URL; ?>">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Project Draft — 404</title>
<meta name="robots" content="noindex, nofollow">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<?php include INC_PATH . 'pages_resources.php'; ?>
<link rel="icon" sizes="16x16" href="assets/favicon-16.png">
<link rel="icon" sizes="32x32" href="assets/favicon-32.png">
<link rel="icon" sizes="48x48" href="assets/favicon-48.png">
<link rel="icon" sizes="64x64" href="assets/favicon-64.png">
<link rel="icon" sizes="128x128" href="assets/favicon-128.png">
<link rel="icon" sizes="192x192" href="assets/favicon-192.png">
</head>
<body class="error-404">
<?php $page = 'error-404'; include INC_PATH . 'pages_overhead.php'; ?>
<!-- Example 404 content (markup based on Bootstrap 3 framework) -->
<div class="container">
<div class="row">
<div class="col-md-12">
<h1>Error 404
<br>Page not found!</h1>
<p>Oops! Seems like the page you are looking for no longer exists.
<br>You may go <a href='javascript:history.back(1)'>back</a> or <a href='<?php echo BASE_URL; ?>'>start over</a>.</p>
<hr>
<p class="small text-muted">Rename and edit <code>htaccess</code> file to activate custom error pages.</p>
</div>
</div>
</div>
<!-- END of example content -->
<?php include INC_PATH . 'pages_scripts.php'; ?>
</body>
</html>
|
#entry {
margin: 10px auto 10px auto;
font-size: 10pt;
width: 100%;
height: 70px;
display: table;
border-radius: 10px;
background-color: #301E19;
border: 10px;
text-align: center;
vertical-align: middle;
}
.coffeeType {
width: 265px;
height: 34px;
margin: 0 auto 0 auto;
border-bottom: solid;
border-width: 1px;
line-height: 30px;
display: table;
}
.coffeeTypeCell {
display: table-cell;
}
.coffeeTime {
height: 35px;
margin: 0 auto 0 auto;
line-height: 30px;
display: table;
}
.coffeeTimeCell {
display: table-cell;
width: 1000px;
}
|
package commands
import (
"compress/gzip"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
core "github.com/ipfs/go-ipfs/core"
cmdenv "github.com/ipfs/go-ipfs/core/commands/cmdenv"
e "github.com/ipfs/go-ipfs/core/commands/e"
tar "gx/ipfs/<API key>/tar-utils"
uarchive "gx/ipfs/<API key>/go-unixfs/archive"
"gx/ipfs/<API key>/go-ipfs-cmds"
path "gx/ipfs/<API key>/go-path"
"gx/ipfs/<API key>/pb"
dag "gx/ipfs/<API key>/go-merkledag"
"gx/ipfs/<API key>/go-ipfs-cmdkit"
)
var <API key> = errors.New("compression level must be between 1 and 9")
const (
outputOptionName = "output"
archiveOptionName = "archive"
compressOptionName = "compress"
<API key> = "compression-level"
)
var GetCmd = &cmds.Command{
Helptext: cmdkit.HelpText{
Tagline: "Download IPFS objects.",
ShortDescription: `
Stores to disk the data contained an IPFS or IPNS object(s) at the given path.
By default, the output will be stored at './<ipfs-path>', but an alternate
path can be specified with '--output=<path>' or '-o=<path>'.
To output a TAR archive instead of unpacked files, use '--archive' or '-a'.
To compress the output with GZIP compression, use '--compress' or '-C'. You
may also specify the level of compression by specifying '-l=<1-9>'.
`,
},
Arguments: []cmdkit.Argument{
cmdkit.StringArg("ipfs-path", true, false, "The path to the IPFS object(s) to be outputted.").EnableStdin(),
},
Options: []cmdkit.Option{
cmdkit.StringOption(outputOptionName, "o", "The path where the output should be stored."),
cmdkit.BoolOption(archiveOptionName, "a", "Output a TAR archive."),
cmdkit.BoolOption(compressOptionName, "C", "Compress the output with GZIP compression."),
cmdkit.IntOption(<API key>, "l", "The level of compression (1-9)."),
},
PreRun: func(req *cmds.Request, env cmds.Environment) error {
_, err := getCompressOptions(req)
return err
},
Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
cmplvl, err := getCompressOptions(req)
if err != nil {
return err
}
node, err := cmdenv.GetNode(env)
if err != nil {
return err
}
p := path.Path(req.Arguments[0])
ctx := req.Context
dn, err := core.Resolve(ctx, node.Namesys, node.Resolver, p)
if err != nil {
return err
}
switch dn := dn.(type) {
case *dag.ProtoNode:
size, err := dn.Size()
if err != nil {
return err
}
res.SetLength(size)
case *dag.RawNode:
res.SetLength(uint64(len(dn.RawData())))
default:
return err
}
archive, _ := req.Options[archiveOptionName].(bool)
reader, err := uarchive.DagArchive(ctx, dn, p.String(), node.DAG, archive, cmplvl)
if err != nil {
return err
}
return res.Emit(reader)
},
PostRun: cmds.PostRunMap{
cmds.CLI: func(res cmds.Response, re cmds.ResponseEmitter) error {
req := res.Request()
v, err := res.Next()
if err != nil {
return err
}
outReader, ok := v.(io.Reader)
if !ok {
return e.New(e.TypeErr(outReader, v))
}
outPath := getOutPath(req)
cmplvl, err := getCompressOptions(req)
if err != nil {
return err
}
archive, _ := req.Options[archiveOptionName].(bool)
gw := getWriter{
Out: os.Stdout,
Err: os.Stderr,
Archive: archive,
Compression: cmplvl,
Size: int64(res.Length()),
}
return gw.Write(outReader, outPath)
},
},
}
type clearlineReader struct {
io.Reader
out io.Writer
}
func (r *clearlineReader) Read(p []byte) (n int, err error) {
n, err = r.Reader.Read(p)
if err == io.EOF {
// callback
fmt.Fprintf(r.out, "\033[2K\r") // clear progress bar line on EOF
}
return
}
func <API key>(out io.Writer, r io.Reader, l int64) (*pb.ProgressBar, io.Reader) {
bar := makeProgressBar(out, l)
barR := bar.NewProxyReader(r)
return bar, &clearlineReader{barR, out}
}
func makeProgressBar(out io.Writer, l int64) *pb.ProgressBar {
// setup bar reader
// TODO: get total length of files
bar := pb.New64(l).SetUnits(pb.U_BYTES)
bar.Output = out
// the progress bar lib doesn't give us a way to get the width of the output,
// so as a hack we just use a callback to measure the output, then git rid of it
bar.Callback = func(line string) {
terminalWidth := len(line)
bar.Callback = nil
log.Infof("terminal width: %v\n", terminalWidth)
}
return bar
}
func getOutPath(req *cmds.Request) string {
outPath, _ := req.Options[outputOptionName].(string)
if outPath == "" {
trimmed := strings.TrimRight(req.Arguments[0], "/")
_, outPath = filepath.Split(trimmed)
outPath = filepath.Clean(outPath)
}
return outPath
}
type getWriter struct {
Out io.Writer // for output to user
Err io.Writer // for progress bar output
Archive bool
Compression int
Size int64
}
func (gw *getWriter) Write(r io.Reader, fpath string) error {
if gw.Archive || gw.Compression != gzip.NoCompression {
return gw.writeArchive(r, fpath)
}
return gw.writeExtracted(r, fpath)
}
func (gw *getWriter) writeArchive(r io.Reader, fpath string) error {
// adjust file name if tar
if gw.Archive {
if !strings.HasSuffix(fpath, ".tar") && !strings.HasSuffix(fpath, ".tar.gz") {
fpath += ".tar"
}
}
// adjust file name if gz
if gw.Compression != gzip.NoCompression {
if !strings.HasSuffix(fpath, ".gz") {
fpath += ".gz"
}
}
// create file
file, err := os.Create(fpath)
if err != nil {
return err
}
defer file.Close()
fmt.Fprintf(gw.Out, "Saving archive to %s\n", fpath)
bar, barR := <API key>(gw.Err, r, gw.Size)
bar.Start()
defer bar.Finish()
_, err = io.Copy(file, barR)
return err
}
func (gw *getWriter) writeExtracted(r io.Reader, fpath string) error {
fmt.Fprintf(gw.Out, "Saving file(s) to %s\n", fpath)
bar := makeProgressBar(gw.Err, gw.Size)
bar.Start()
defer bar.Finish()
defer bar.Set64(gw.Size)
extractor := &tar.Extractor{Path: fpath, Progress: bar.Add64}
return extractor.Extract(r)
}
func getCompressOptions(req *cmds.Request) (int, error) {
cmprs, _ := req.Options[compressOptionName].(bool)
cmplvl, cmplvlFound := req.Options[<API key>].(int)
switch {
case !cmprs:
return gzip.NoCompression, nil
case cmprs && !cmplvlFound:
return gzip.DefaultCompression, nil
case cmprs && (cmplvl < 1 || cmplvl > 9):
return gzip.NoCompression, <API key>
}
return cmplvl, nil
}
|
package org.reasm.m68k.assembly.internal;
import javax.annotation.Nonnull;
import javax.annotation.concurrent.Immutable;
import org.reasm.Value;
import org.reasm.<API key>;
@Immutable
class WhileDirective extends Mnemonic {
@Nonnull
static final WhileDirective WHILE = new WhileDirective();
private WhileDirective() {
}
@Override
void assemble(M68KAssemblyContext context) {
context.sizeNotAllowed();
final Object blockState = context.getParentBlock();
if (!(blockState instanceof WhileBlockState)) {
throw new AssertionError();
}
final WhileBlockState whileBlockState = (WhileBlockState) blockState;
// The WHILE directive is assembled on every iteration.
// Parse the condition operand on the first iteration only.
if (!whileBlockState.parsedCondition) {
if (context.<API key>(1)) {
whileBlockState.conditionExpression = <API key>(context, 0);
}
whileBlockState.parsedCondition = true;
}
final Value condition;
if (whileBlockState.conditionExpression != null) {
condition = whileBlockState.conditionExpression.evaluate(context.<API key>());
} else {
condition = null;
}
final Boolean result = Value.accept(condition, <API key>.INSTANCE);
if (!(result != null && result.booleanValue())) {
// Skip the block body and stop the iteration.
whileBlockState.iterator.next();
whileBlockState.hasNextIteration = false;
}
}
}
|
package com.github.games647.flexiblelogin.listener.prevent;
import com.flowpowered.math.vector.Vector3i;
import com.github.games647.flexiblelogin.FlexibleLogin;
import com.github.games647.flexiblelogin.PomData;
import com.github.games647.flexiblelogin.config.Settings;
import com.google.inject.Inject;
import java.util.List;
import java.util.Optional;
import org.spongepowered.api.command.CommandManager;
import org.spongepowered.api.command.CommandMapping;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.Order;
import org.spongepowered.api.event.block.InteractBlockEvent;
import org.spongepowered.api.event.command.SendCommandEvent;
import org.spongepowered.api.event.entity.DamageEntityEvent;
import org.spongepowered.api.event.entity.InteractEntityEvent;
import org.spongepowered.api.event.entity.MoveEntityEvent;
import org.spongepowered.api.event.filter.Getter;
import org.spongepowered.api.event.filter.cause.First;
import org.spongepowered.api.event.filter.cause.Root;
import org.spongepowered.api.event.filter.type.Exclude;
import org.spongepowered.api.event.item.inventory.<API key>;
import org.spongepowered.api.event.item.inventory.ClickInventoryEvent;
import org.spongepowered.api.event.item.inventory.ClickInventoryEvent.NumberPress;
import org.spongepowered.api.event.item.inventory.DropItemEvent;
import org.spongepowered.api.event.item.inventory.<API key>;
import org.spongepowered.api.event.item.inventory.InteractItemEvent;
import org.spongepowered.api.event.item.inventory.UseItemStackEvent;
import org.spongepowered.api.event.message.MessageChannelEvent;
public class PreventListener extends <API key> {
private final CommandManager commandManager;
@Inject PreventListener(FlexibleLogin plugin, Settings settings, CommandManager commandManager) {
super(plugin, settings);
this.commandManager = commandManager;
}
@Listener(order = Order.FIRST, beforeModifications = true)
public void onPlayerMove(MoveEntityEvent playerMoveEvent, @First Player player) {
if (playerMoveEvent instanceof MoveEntityEvent.Teleport) {
return;
}
Vector3i oldLocation = playerMoveEvent.getFromTransform().getPosition().toInt();
Vector3i newLocation = playerMoveEvent.getToTransform().getPosition().toInt();
if (oldLocation.getX() != newLocation.getX() || oldLocation.getZ() != newLocation.getZ()) {
checkLoginStatus(playerMoveEvent, player);
}
}
@Listener(order = Order.FIRST, beforeModifications = true)
public void onChat(MessageChannelEvent.Chat chatEvent, @First Player player) {
checkLoginStatus(chatEvent, player);
}
@Listener(order = Order.FIRST, beforeModifications = true)
public void onCommand(SendCommandEvent commandEvent, @First Player player) {
String command = commandEvent.getCommand();
Optional<? extends CommandMapping> commandOpt = commandManager.get(command);
if (commandOpt.isPresent()) {
CommandMapping mapping = commandOpt.get();
command = mapping.getPrimaryAlias();
//do not blacklist our own commands
if (commandManager.getOwner(mapping)
.map(pc -> pc.getId().equals(PomData.ARTIFACT_ID))
.orElse(false)) {
return;
}
}
commandEvent.setResult(CommandResult.empty());
if (settings.getGeneral().<API key>()) {
List<String> protectedCommands = settings.getGeneral().<API key>();
if (protectedCommands.contains(command) && !plugin.getDatabase().isLoggedIn(player)) {
player.sendMessage(settings.getText().getProtectedCommand());
commandEvent.setCancelled(true);
}
} else {
checkLoginStatus(commandEvent, player);
}
}
@Listener(order = Order.FIRST, beforeModifications = true)
public void onPlayerItemDrop(DropItemEvent dropItemEvent, @First Player player) {
checkLoginStatus(dropItemEvent, player);
}
@Listener(order = Order.FIRST, beforeModifications = true)
public void onPlayerItemPickup(<API key>.Pickup pickupItemEvent, @Root Player player) {
checkLoginStatus(pickupItemEvent, player);
}
@Listener(order = Order.FIRST, beforeModifications = true)
public void onItemConsume(UseItemStackEvent.Start itemConsumeEvent, @First Player player) {
checkLoginStatus(itemConsumeEvent, player);
}
@Listener(order = Order.FIRST, beforeModifications = true)
public void onItemInteract(InteractItemEvent interactItemEvent, @First Player player) {
checkLoginStatus(interactItemEvent, player);
}
// Ignore number press events, because Sponge before this commit
// has a duplicate bug. Using this exclude we can ignore it, but still cancel the movement of the item
// it appears to be fixed using SpongeForge 4005 (fixed) and 4004 with this change
@Exclude(NumberPress.class)
@Listener(order = Order.FIRST, beforeModifications = true)
public void onInventoryChange(<API key> <API key>, @First Player player) {
checkLoginStatus(<API key>, player);
}
@Exclude(NumberPress.class)
@Listener(order = Order.FIRST, beforeModifications = true)
public void onInventoryInteract(<API key> <API key>, @First Player player) {
checkLoginStatus(<API key>, player);
}
@Exclude(NumberPress.class)
@Listener(order = Order.FIRST, beforeModifications = true)
public void onInventoryClick(ClickInventoryEvent clickInventoryEvent, @First Player player) {
checkLoginStatus(clickInventoryEvent, player);
}
@Listener(order = Order.FIRST, beforeModifications = true)
public void onBlockInteract(InteractBlockEvent interactBlockEvent, @First Player player) {
checkLoginStatus(interactBlockEvent, player);
}
@Listener(order = Order.FIRST, beforeModifications = true)
public void <API key>(InteractEntityEvent interactEntityEvent, @First Player player) {
checkLoginStatus(interactEntityEvent, player);
}
@Listener(order = Order.FIRST, beforeModifications = true)
public void onPlayerDamage(DamageEntityEvent damageEntityEvent, @First Player player) {
//player is damage source
checkLoginStatus(damageEntityEvent, player);
}
@Listener(order = Order.FIRST, beforeModifications = true)
public void onDamagePlayer(DamageEntityEvent damageEntityEvent, @Getter("getTargetEntity") Player player) {
//player is damage target
checkLoginStatus(damageEntityEvent, player);
}
}
|
<div class="card">
<div class="card-header">
<span class="h3">
Chat Page!!
</span>
</div>
<div class="card-block">
<div class="panel-body">
<ngb-alert [dismissible]="false">
<strong>Warning!</strong> You need to login to see contextual data in chat!!
</ngb-alert>
<ul class="chat">
<li *ngFor="let message of messages" class="right clearfix"><span class="chat-img" [class.pull-right]="message.isSelf" >
<img src="http://placehold.it/50/FA6F57/fff&text={{message.user}}" alt="User Avatar" class="img-circle"/>
</span>
<div class="chat-body clearfix">
<div class="header">
<small class=" text-muted"><span class="glyphicon glyphicon-time"></span>{{message.timestamp}}</small>
<strong [class.pull-right]="message.isSelf" class="primary-font">{{message.user}}</strong>
</div>
<p>
{{message.content}}
<a *ngIf="message.isNavigation" [routerLink]="['/indoor-map', {fromLocationId: message.meta.fromLocationId, toLocationId: message.meta.toLocationId }]" >Here</a>
</p>
</div>
</li>
</ul>
</div>
<div class="panel-footer">
<div class="input-group">
<input [(ngModel)]="newMessage.content" id="btn-input" type="text" class="form-control input-sm" placeholder="Type your message here...">
<span class="input-group-btn">
<button class="btn btn-warning btn-sm" id="btn-chat" (click)="send(newMessage)">
Send</button>
</span>
</div>
</div>
</div>
</div>
|
# coding: utf-8
from pprint import pformat
from six import iteritems
import re
class ContributorOrcid(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, uri=None, path=None, host=None):
"""
ContributorOrcid - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition.
"""
self.swagger_types = {
'uri': 'str',
'path': 'str',
'host': 'str'
}
self.attribute_map = {
'uri': 'uri',
'path': 'path',
'host': 'host'
}
self._uri = uri
self._path = path
self._host = host
@property
def uri(self):
"""
Gets the uri of this ContributorOrcid.
:return: The uri of this ContributorOrcid.
:rtype: str
"""
return self._uri
@uri.setter
def uri(self, uri):
"""
Sets the uri of this ContributorOrcid.
:param uri: The uri of this ContributorOrcid.
:type: str
"""
self._uri = uri
@property
def path(self):
"""
Gets the path of this ContributorOrcid.
:return: The path of this ContributorOrcid.
:rtype: str
"""
return self._path
@path.setter
def path(self, path):
"""
Sets the path of this ContributorOrcid.
:param path: The path of this ContributorOrcid.
:type: str
"""
self._path = path
@property
def host(self):
"""
Gets the host of this ContributorOrcid.
:return: The host of this ContributorOrcid.
:rtype: str
"""
return self._host
@host.setter
def host(self, host):
"""
Sets the host of this ContributorOrcid.
:param host: The host of this ContributorOrcid.
:type: str
"""
self._host = host
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
if not isinstance(other, ContributorOrcid):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
|
package com.contexthub.storageapp;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuItem;
import com.chaione.contexthub.sdk.model.VaultDocument;
import com.contexthub.storageapp.fragments.AboutFragment;
import com.contexthub.storageapp.fragments.<API key>;
import com.contexthub.storageapp.fragments.<API key>;
import com.contexthub.storageapp.models.Person;
public class MainActivity extends ActionBarActivity implements <API key>.Listener, FragmentManager.<API key> {
private MenuItem menuSearch;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState == null) {
<API key>().beginTransaction()
.replace(android.R.id.content, new <API key>())
.commit();
<API key>().<API key>(this);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
setupSearchView(menu.findItem(R.id.action_search));
return true;
}
private void setupSearchView(final MenuItem menuSearch) {
this.menuSearch = menuSearch;
SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuSearch);
SearchView.SearchAutoComplete searchAutoComplete = (SearchView.SearchAutoComplete) searchView.findViewById(R.id.search_src_text);
searchAutoComplete.setHint(R.string.search_hint);
searchView.<API key>(new android.support.v7.widget.SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
menuSearch.collapseActionView();
<API key>().beginTransaction()
.addToBackStack(null)
.replace(android.R.id.content, <API key>.newInstance(query))
.commit();
return true;
}
@Override
public boolean onQueryTextChange(String query) {
return false;
}
});
}
@Override
public boolean <API key>(Menu menu) {
boolean isMainFragment = <API key>().<API key>() <= 0;
menu.findItem(R.id.action_search).setVisible(isMainFragment);
menu.findItem(R.id.action_add).setVisible(isMainFragment);
menu.findItem(R.id.action_about).setVisible(isMainFragment);
return super.<API key>(menu);
}
@Override
public boolean <API key>(MenuItem item) {
menuSearch.collapseActionView();
switch(item.getItemId()) {
case R.id.action_add:
<API key>(null);
return true;
case R.id.action_about:
<API key>().beginTransaction()
.addToBackStack(null)
.replace(android.R.id.content, new AboutFragment())
.commit();
return true;
default:
return super.<API key>(item);
}
}
private void <API key>(VaultDocument<Person> document) {
<API key> fragment = document == null ? new <API key>() :
<API key>.newInstance(document);
<API key>().beginTransaction()
.addToBackStack(null)
.replace(android.R.id.content, fragment)
.commit();
}
@Override
public void onItemClick(VaultDocument<Person> document) {
menuSearch.collapseActionView();
<API key>(document);
}
@Override
public void onBackStackChanged() {
<API key>();
}
}
|
namespace Kephas.Model.Tests
{
using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;
using Kephas.Composition.Conventions;
using Kephas.Composition.Lite;
using Kephas.Model.Elements;
using Kephas.Services;
using Kephas.Testing.Model;
using NUnit.Framework;
[TestFixture]
public class <API key> : ModelTestBase
{
public override IEnumerable<Assembly> <API key>()
{
return new List<Assembly>(base.<API key>())
{
typeof(IModelSpace).Assembly,
};
}
[Test]
public async Task <API key>()
{
var ambientServices = new AmbientServices()
.RegisterMultiple<<API key>>(b => b.WithType<<API key>>());
var container = this.CreateContainer(ambientServices);
var provider = container.GetExport<IModelSpaceProvider>();
await provider.InitializeAsync(new Context(container));
var modelSpace = container.GetExport<IModelSpace>();
Assert.IsInstanceOf<DefaultModelSpace>(modelSpace);
}
}
}
|
<?php
namespace GlenDemon\ZabbixApi\Repository;
use \GlenDemon\ZabbixApi\Entity\HostGroup;
/**
* HostGroup repository.
*/
class HostGroupRepository extends AbstractRepository
{
/**
* Finds an object by its primary key / identifier.
*
* @param mixed $id The identifier.
*
* @return HostGroup The object.
*/
public function find($id)
{
return parent::find($id);
}
/**
* Finds all objects in the repository.
*
* @return HostGroup[] The objects.
*/
public function findAll()
{
return parent::findAll();
}
/**
* @inherit
*/
protected function getRawData(array $params)
{
return $this->api->hostgroupGet($params);
}
/**
* Finds a single object by a set of criteria.
*
* @param array $criteria The criteria.
*
* @return HostGroup|null The object.
*/
public function findOneBy(array $criteria)
{
return parent::findOneBy($criteria);
}
}
|
// Preprocessed version of "lslboost/mpl/list/list10_c.hpp" header
// -- DO NOT modify by hand!
namespace lslboost { namespace mpl {
template<
typename T
, T C0
>
struct list1_c
: l_item<
long_<1>
, integral_c< T,C0 >
, l_end
>
{
typedef list1_c type;
typedef T value_type;
};
template<
typename T
, T C0, T C1
>
struct list2_c
: l_item<
long_<2>
, integral_c< T,C0 >
, list1_c< T,C1 >
>
{
typedef list2_c type;
typedef T value_type;
};
template<
typename T
, T C0, T C1, T C2
>
struct list3_c
: l_item<
long_<3>
, integral_c< T,C0 >
, list2_c< T,C1,C2 >
>
{
typedef list3_c type;
typedef T value_type;
};
template<
typename T
, T C0, T C1, T C2, T C3
>
struct list4_c
: l_item<
long_<4>
, integral_c< T,C0 >
, list3_c< T,C1,C2,C3 >
>
{
typedef list4_c type;
typedef T value_type;
};
template<
typename T
, T C0, T C1, T C2, T C3, T C4
>
struct list5_c
: l_item<
long_<5>
, integral_c< T,C0 >
, list4_c< T,C1,C2,C3,C4 >
>
{
typedef list5_c type;
typedef T value_type;
};
template<
typename T
, T C0, T C1, T C2, T C3, T C4, T C5
>
struct list6_c
: l_item<
long_<6>
, integral_c< T,C0 >
, list5_c< T,C1,C2,C3,C4,C5 >
>
{
typedef list6_c type;
typedef T value_type;
};
template<
typename T
, T C0, T C1, T C2, T C3, T C4, T C5, T C6
>
struct list7_c
: l_item<
long_<7>
, integral_c< T,C0 >
, list6_c< T,C1,C2,C3,C4,C5,C6 >
>
{
typedef list7_c type;
typedef T value_type;
};
template<
typename T
, T C0, T C1, T C2, T C3, T C4, T C5, T C6, T C7
>
struct list8_c
: l_item<
long_<8>
, integral_c< T,C0 >
, list7_c< T,C1,C2,C3,C4,C5,C6,C7 >
>
{
typedef list8_c type;
typedef T value_type;
};
template<
typename T
, T C0, T C1, T C2, T C3, T C4, T C5, T C6, T C7, T C8
>
struct list9_c
: l_item<
long_<9>
, integral_c< T,C0 >
, list8_c< T,C1,C2,C3,C4,C5,C6,C7,C8 >
>
{
typedef list9_c type;
typedef T value_type;
};
template<
typename T
, T C0, T C1, T C2, T C3, T C4, T C5, T C6, T C7, T C8, T C9
>
struct list10_c
: l_item<
long_<10>
, integral_c< T,C0 >
, list9_c< T,C1,C2,C3,C4,C5,C6,C7,C8,C9 >
>
{
typedef list10_c type;
typedef T value_type;
};
}}
|
module CardHelper
def <API key>(node, options = {})
{ class: dom_class(node, :card),
itemscope: '',
itemtype: 'http://schema.org/Thing',
itemid: node.uuid,
itemtype: node.class.schema_path }.merge(options)
end
def cardtec_header(node)
content_tag(:span, node.uuid, itemprop: :uuid) <<
content_tag(:span, node.ident, itemprop: :ident) <<
content_tag(:span, node.class.name, itemprop: :class_name) <<
content_tag(:span, node.path, itemprop: :path) <<
content_tag(:span, node.created_at, itemprop: :created_at) <<
content_tag(:span, node.updated_at, itemprop: :updated_at)
end
end
|
package org.ensor.robots.roboclawdriver;
/**
*
* @author jona
*/
class <API key> extends <API key> {
protected <API key>(RoboClaw aRoboClaw) {
super(aRoboClaw);
}
@Override
protected byte getCommandByte() {
return (byte)24;
}
@Override
protected void onResponse(double voltage) {
mRoboClaw.<API key>(voltage);
}
}
|
package org.kalnee.trivor.insights.web.rest;
import com.codahale.metrics.annotation.Timed;
import org.kalnee.trivor.insights.domain.insights.Insights;
import org.kalnee.trivor.insights.service.InsightService;
import org.kalnee.trivor.nlp.domain.ChunkFrequency;
import org.kalnee.trivor.nlp.domain.PhrasalVerbUsage;
import org.kalnee.trivor.nlp.domain.SentenceFrequency;
import org.kalnee.trivor.nlp.domain.WordUsage;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import java.util.Set;
@RestController
@RequestMapping(value = "/api/insights")
public class InsightsResource {
private final InsightService insightService;
public InsightsResource(InsightService insightService) {
this.insightService = insightService;
}
@GetMapping
public ResponseEntity<Page<Insights>> <API key>(@RequestParam("imdbId") String imdbId,
Pageable pageable) {
return ResponseEntity.ok().body(insightService.findByImdbId(imdbId, pageable));
}
@GetMapping("/summary")
@Timed
public ResponseEntity<Map<String, Object>> getInsightsSummary(@RequestParam("imdbId") String imdbId) {
return ResponseEntity.ok().body(insightService.getInsightsSummary(imdbId));
}
@GetMapping("/sentences/frequency")
@Timed
public ResponseEntity<List<SentenceFrequency>> <API key>(@RequestParam("imdbId") String imdbId,
@RequestParam(value = "limit", required = false) Integer limit) {
return ResponseEntity.ok().body(
insightService.<API key>(imdbId, limit)
);
}
@GetMapping("/chunks/frequency")
@Timed
public ResponseEntity<List<ChunkFrequency>> findChunksFrequency(@RequestParam("imdbId") String imdbId,
@RequestParam(value = "limit", required = false) Integer limit) {
return ResponseEntity.ok().body(
insightService.<API key>(imdbId, limit)
);
}
@GetMapping("/phrasal-verbs/usage")
@Timed
public ResponseEntity<List<PhrasalVerbUsage>> <API key>(@RequestParam("imdbId") String imdbId) {
return ResponseEntity.ok().body(insightService.<API key>(imdbId));
}
@GetMapping("/vocabulary/{vocabulary}/frequency")
@Timed
public ResponseEntity<Map<String, Integer>> <API key>(
@PathVariable("vocabulary") String vocabulary,
@RequestParam("imdbId") String imdbId,
@RequestParam(value = "limit", required = false) Integer limit) {
return ResponseEntity.ok().body(insightService.<API key>(vocabulary, imdbId, limit));
}
@GetMapping("/vocabulary/{vocabulary}/usage")
@Timed
public ResponseEntity<List<WordUsage>> <API key>(
@PathVariable("vocabulary") String vocabulary,
@RequestParam("imdbId") String imdbId,
@RequestParam(value = "season", required = false) Integer season,
@RequestParam(value = "episode", required = false) Integer episode) {
return ResponseEntity.ok().body(
insightService.<API key>(vocabulary, imdbId, season, episode)
);
}
@GetMapping("/{insight}/genres/{genre}")
@Timed
public ResponseEntity<List<Insights>> findInsightsByGenre(
@PathVariable("genre") String genre) {
return ResponseEntity.ok().body(insightService.<API key>(genre));
}
@GetMapping("/{insight}/keywords/{keyword}")
@Timed
public ResponseEntity<List<Insights>> <API key>(
@PathVariable("keyword") String keyword) {
return ResponseEntity.ok().body(insightService.<API key>(keyword));
}
}
|
// This file is used by Code Analysis to maintain SuppressMessage attributes that are applied to this
// project. Project-level suppressions either have no target or are given a specific target and
// scoped to a namespace, type, member, etc.
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0002:Simplify Member Access", Justification = "This is an auto-generated file.", Scope = "member", Target = "~P:Spritely.Foundations.WebApi.Messages.ResourceManager")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Spritely.Foundations.WebApi.WriteLog.Invoke(System.String)", Scope = "member", Target = "Spritely.Foundations.WebApi.<API key>.#.cctor()", Justification = "Colon is used as a separator for log file output - overkill to move this into resources.")]
|
#ifndef _VSARDUINO_H_
#define _VSARDUINO_H_
//Board = Arduino Nano w/ ATmega328
#define __AVR_ATmega328p__
#define __AVR_ATmega328P__
#define ARDUINO 105
#define ARDUINO_MAIN
#define __AVR__
#define __avr__
#define F_CPU 16000000L
#define __cplusplus
#define __inline__
#define __asm__(x)
#define __extension__
#define __ATTR_PURE__
#define __ATTR_CONST__
#define __inline__
#define __asm__
#define __volatile__
#define __builtin_va_list
#define __builtin_va_start
#define __builtin_va_end
#define __DOXYGEN__
#define __attribute__(x)
#define NOINLINE __attribute__((noinline))
#define prog_void
#define PGM_VOID_P int
typedef unsigned char byte;
extern "C" void __cxa_pure_virtual() {;}
int serial_putc(char c, FILE *);
void printf_begin(void);
static void dhcp_status_cb(int s, const uint16_t *dnsaddr);
static void resolv_found_cb(char *name, uint16_t *addr);
void ___dhcp_status(int s, const uint16_t *);
void <API key>(char *data, u16_t len);
void webclient_connected(void);
void webclient_timedout(void);
void webclient_aborted(void);
void webclient_closed(void);
#include "D:\arduino\arduino-1.0.5\hardware\arduino\cores\arduino\arduino.h"
#include "D:\arduino\arduino-1.0.5\hardware\arduino\variants\eightanaloginputs\pins_arduino.h"
#include "D:\Projects\<API key>\nrf24l01\<API key>\<API key>.ino"
#endif
|
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Network::Mgmt::V2018_04_01
module Models
# List of Vpn-Sites
class <API key>
include MsRestAzure
# @return [Array<SubResource>] List of resource-ids of the vpn-sites for
# which config is to be downloaded.
attr_accessor :vpn_sites
# @return [String] The sas-url to download the configurations for
# vpn-sites
attr_accessor :output_blob_sas_url
# Mapper for <API key> class as Ruby Hash.
# This will be used for serialization/deserialization.
def self.mapper()
{
<API key>: true,
required: false,
serialized_name: '<API key>',
type: {
name: 'Composite',
class_name: '<API key>',
model_properties: {
vpn_sites: {
<API key>: true,
required: false,
serialized_name: 'vpnSites',
type: {
name: 'Sequence',
element: {
<API key>: true,
required: false,
serialized_name: '<API key>',
type: {
name: 'Composite',
class_name: 'SubResource'
}
}
}
},
output_blob_sas_url: {
<API key>: true,
required: false,
serialized_name: 'outputBlobSasUrl',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
|
#pragma once
#include "messages.h"
#include "primitives/string_utils.h"
// Given pairs of pulse lens from 2 base stations, this class determines the phase for current cycle
// Phases are:
// 0) Base 1 (B), horizontal sweep
// 1) Base 1 (B), vertical sweep
// TODO: We might want to introduce a more thorough check for a fix, using the average_error_ value.
class <API key> {
public:
<API key>();
// Process the pulse lengths for current cycle (given by incrementing cycle_idx).
void <API key>(uint32_t cycle_idx, const TimeDelta (&pulse_lens)[num_base_stations]);
// Get current cycle phase. -1 if phase is not known (no fix achieved).
int get_phase(uint32_t cycle_idx);
// Reference to a pair of DataFrameBit-s
typedef DataFrameBit (&DataFrameBitPair)[num_base_stations];
// Get updated data bits from the pulse lens for current cycle.
// Both bits are always returned, but caller needs to make sure they were updated this cycle by
// checking DataFrameBit.cycle_idx == cycle_idx.
DataFrameBitPair get_data_bits(uint32_t cycle_idx, const TimeDelta (&pulse_lens)[num_base_stations]);
// Reset the state of this classifier - needs to be called if the cycle fix was lost.
void reset();
// Print debug information.
virtual bool debug_cmd(HashedWord *input_words);
virtual void debug_print(PrintStream &stream);
private:
float expected_pulse_len(bool skip, bool data, bool axis);
uint32_t <API key>;
uint32_t phase_history_;
int fix_level_;
uint32_t phase_shift_;
float pulse_base_len_;
DataFrameBit bits_[num_base_stations];
float average_error_;
bool debug_print_state_;
};
|
<?php
# MetInfo Enterprise Content Management System
require_once '../login/login_check.php';
if($action=='modify'){
$shortcut=array();
$query="select * from $met_language where value='$name' and lang='$lang'";
$lang_shortcut=$db->get_one($query);
$shortcut['name']=$lang_shortcut?'lang_'.$lang_shortcut['name']:urlencode($name);
$shortcut['url']=$url;
$shortcut['bigclass']=$bigclass;
$shortcut['field']=$field;
$shortcut['type']='2';
$shortcut['list_order']=$list_order;
$shortcut['protect']='0';
$shortcut['hidden']='0';
foreach($shortcut_list as $key=>$val){
$shortcut_list[$key][name]=$shortcut_list[$key][lang];
}
$shortcut_list[]=$shortcut;
change_met_cookie('<API key>',$shortcut_list);
save_met_cookie();
$query="update $met_admin_table set admin_shortcut='".json_encode($shortcut_list)."' where admin_id='$metinfo_admin_name'";
$db->query($query);
echo '<script type="text/javascript">parent.window.location.reload();</script>';
die();
//metsave('../system/shortcut.php?anyid='.$anyid.'&lang='.$lang.'&cs='.$cs);
}else{
$query="select * from $met_app where download=1";
$app=$db->get_all($query);
$css_url="../templates/".$met_skin."/css";
$img_url="../templates/".$met_skin."/images";
include template('system/shortcut_editor');
footer();
}
?>
|
layout: post
title:
date: 2017-05-13 10:54:37
categories: Java
# Java
````
*
java
import java.util.ArrayList;
import java.util.List;
/**
* <br>
* <font color="red"></font>
*
* @author rongzhisheng
*
* @param <E>
*/
public class CircleQueue<E> {
private static final int DEFAULT_CAPACITY = 10;
private int capacity;
private int head;
private int tail;
private List<E> queue;
private boolean isFull;// head==tail
public CircleQueue() {
this(DEFAULT_CAPACITY);
}
public CircleQueue(int capacity) {
this.capacity = capacity;
queue = new ArrayList<>(this.capacity);
head = tail = 0;
}
/**
*
*
* @param e
* @return
*/
public boolean add(E e) {
if (isFull) {
head = addIndex(head);
addOrSet(e, tail);
tail = head;
return true;
}
addOrSet(e, tail);
tail = addIndex(tail);
if (head == tail) {
isFull = true;
}
return false;
}
public E poll() {
if (!isFull && head == tail) {
return null;
}
E e = queue.get(head);
queue.set(head, null);
head = addIndex(head);
isFull = false;
return e;
}
public int size() {
if (!isFull && head == tail) {
return 0;
}
if (isFull) {
return capacity;
}
int i = 0;
int h = head;
while (h != tail) {
i++;
h = addIndex(h);
}
return i;
}
public int capacity() {
return capacity;
}
public E element(int index) {
if (index < 0 || index >= size()) {
throw new <API key>();
}
index = addIndex(head + index - 1);
return queue.get(index);
}
public boolean isEmpty() {
return size() == 0;
}
public List<E> getList() {
List<E> list = new ArrayList<>();
final int size = size();
for (int i = 0; i < size; i++) {
list.add(element(i));
}
return list;
}
public void clean() {
head = tail = 0;
isFull = false;
queue.clear();
}
public void grow(int newCapacity) {
if (newCapacity <= capacity) {
return;
}
List<E> data = getList();
queue.clear();
queue.addAll(data);
head = 0;
tail = head + queue.size();
capacity = newCapacity;
isFull = false;
}
@Override
public String toString() {
return getList().toString();
}
private void addOrSet(E e, int index) {
if (queue.size() > index) {
queue.set(index, e);
return;
}
if (queue.size() == index) {
queue.add(e);
return;
}
throw new <API key>();
}
private int addIndex(int i) {
return (i + 1) % capacity;
}
public static void main(String[] args) {
int a = 1;
CircleQueue<Integer> queue = new CircleQueue<Integer>(5);
queue.grow(8);
queue.grow(10);
for (int i = a; i < a + 6; i++) {
queue.add(i);
}
a += 6;
System.out.println(queue);
for (int i = a; i < a + 6; i++) {
queue.add(i);
}
a += 6;
System.out.println(queue);
queue.grow(10);
for (int i = a; i < a + 6; i++) {
queue.add(i);
}
a += 6;
System.out.println(queue);
for (int i = 0; i < 5; i++) {
System.out.println(queue.poll());
}
System.out.println(queue);
queue.clean();
for (int i = 0; i < 3; i++) {
queue.add(i);
}
System.out.println(queue);
}
}
|
'use strict';
exports.init = function(req, res){
//res.write("joder\n");
//res.write(req.csrfToken());
//res.end();
req.app.db.models.Experiment.find({})
.select("tableList name uploadedBy dateDevelopment id name neuronType")
.exec(function(err, exps) {
if(err) {
res.send("Error");
} else {
console.log(exps);
res.render('account/experiments/compare/stage1', {
code: req.csrfToken(),
experiments: exps
});
}
});
};
exports.second = function(req, res) {
console.log("BODY: " + req.body.fcbklist_value);
if(req.body.fcbklist_value.length < 2) {
res.redirect("/account/experiments/compare/");
} else {
//res.send(req.body);
var orArray = [];
req.body.fcbklist_value.forEach(function(idExp) {
orArray.push({_id: idExp});
});
console.log(orArray);
req.app.db.models.Experiment.find({$or: orArray})
.select("tableList name createdBy dateDevelopment id")
//.populate("tableList", "id")
.populate("createdBy", "username")
.exec(function(err, exps) {
console.log(err);
console.log(JSON.stringify(exps));
res.render("account/experiments/compare/stage2", {
experiments: exps,
code: req.csrfToken()
});
});
}
//["<API key>","<API key>"]
// Con esta lista de ids, lo que hacemos es sacar:
// 1. Cada experimento con:
// name uploadedBy dateDevelopment id
// y el identificador de cada tabla del experimento.
// 2. Con esos datos, montamos algo guay con radio button.
};
exports.third = function(req, res) {
var peticiones = req.body.tab;
console.log(peticiones);
var arr = [];
/*var mapMatch = {
"a": null,
"b": null,
"c": null,
"Datos2": null
}*/
var params = req.app.utility.variables;
var tabs = [];
var headersPaths = [];
var data = {}; // To save the return to view
var Set = req.app.utility.Set;
var commons = new Set();
var async = require('async');
async.series([
// First read data from database and save
function(callback){
console.log("ejecuto 1");
async.each(peticiones, function(tabid, call) {
console.log(tabid);
req.app.db.models.TableExperiment.findById(tabid).populate("assignedTo", "name neuronType createdBy dateDevelopment description").exec(function(err, tab) {
var username = "";
async.series({
first: function(call2) {
console.log("Paso 1");
console.log("Jodeeer, " + tab.assignedTo.createdBy);
/*console.log(tab);
async.each(tab, function(tab_, call3) {
console.log("Buscamos username " + tab_);
req.app.db.models.User.findById(tab_.createdBy._id).select("username").exec(function(err, user) {
console.log("USER : " + user);
tab.createdBy = user.username;
call3();
});
});*/
req.app.db.models.User.findById(tab.assignedTo.createdBy).select("username").exec(function(err, user) {
console.log("USER : " + user);
tab["username"] = user.username;
username = user.username;
//tab.username = user.username;
call2();
});
},
second: function(call2) {
console.log("Paso 2");
// TODO: Controlar "err"
var tab_ = {};
tab_.assignedTo = {
_id: tab.assignedTo._id,
username: username,
createdBy: tab.assignedTo.createdBy,
name: tab.assignedTo.name,
neuronType: tab.assignedTo.neuronType,
dateDevelopment: tab.assignedTo.dateDevelopment,
description: tab.assignedTo.description
};
tab_.id = tab._id;
tab_.matrix = tab.matrix;
tab_.headers = tab.headers;
/*
assignedTo:
{ _id: <API key>,
createdBy: <API key>,
name: 'Mi physiological',
neuronType: 'PHYSIOLOGICAL' },
_id: <API key>,
__v: 0,
matrix: */
console.log("SECOND : " + tab_);
tabs.push(tab_);
// Recorro las cabeceras y genero un mapa con k(header) y v(position)
var mapMatch = {};
console.log(tab.headers);
tab.headers.forEach(function(header, pos) {
if(params.contains(header)) {
mapMatch[header] = pos;
}
});
headersPaths.push(mapMatch); // Guardamos el mapeo
call2();
}
}, function(err, results) {
call();
});
});
}, function(err) {
callback();
});
},
// Filter columns that I use to compare table's experiment
function(callback) {
console.log("Tengo : " + tabs.length);
console.log("Tengo : " + headersPaths.length);
// Guardamos todos los valores de "params" en "data"
data.headers = {};
params.get().forEach(function(value) {
data.headers[value] = [];//undefined;
});
console.log(JSON.stringify(data));
// Creamos el attr "exps" dentro de "data"
data.exps = [];
// Ahora por cada experimento, cargamos los datos correspondientes
headersPaths.forEach(function(headerPath, index) {
console.log("
var posHeader = 0;
Object.keys(headerPath).forEach(function(key) {
console.log(key + " <=> " + headerPath[key]);
//tabs.forEach(function(tab, ii) {
tabs[index].matrix.forEach(function(matrix, area) {
data.headers[key][area] = data.headers[key][area] || [0];
data.headers[key][area].push(matrix.data[posHeader]);
});
/*var infoData = [];
tabs[index].matrix.forEach(function(matrix, area) {
infoData.push(matrix.data[posHeader]);
});
//console.log(infoData);
console.log("Inserta del index " + posHeader);
data.headers[key].push(infoData);*/
posHeader++;
});
data.exps.push(tabs[index].assignedTo);
});
console.log("
console.log("
//console.log(data);
console.log("
console.log("
/*async.each(arr, function(tab, call) {
tab.headers.forEach(function(header, position) {
//if(mapMatch[header] != undefined) {
if(header in tab.mapMatch) {
tab.mapMatch[header] = position;
}
});
// Remove all columns that not contains in mapMatch
//tab.mapMatch.forEach(function(position) {
//});
call();
});*/
callback();
}
],
// finish callback
function(err, results){
console.log("FIN: " + arr.length);
console.log(params.intersect(commons));
//res.send(data);
/*var ret = {
data: data
};
res.send(ret);*/
console.log("
console.log("
console.log("
console.log("
console.log(JSON.stringify(data));
res.render("account/experiments/compare/stage3", {
data: data,
code: req.csrfToken(),
id: 0
});
});
};
// TODO: No funciona bien T.T
|
#ifndef ECLAIR_DIRECTORY_H
# define ECLAIR_DIRECTORY_H
# include "eclair.h"
# include <sys/types.h>
# include <dirent.h>
namespace Eclair
{
struct DirectoryFile
{
std::string name;
bool is_directory;
bool is_regular_file;
};
class Directory
{
private:
std::string _dirname;
DIR *_dir = nullptr;
std::string _error_str;
DirectoryFile _file;
explicit Directory();
public:
explicit Directory(const std::string& dir);
virtual ~Directory() noexcept;
bool open() noexcept;
DirectoryFile *next() noexcept;
inline std::string error() const noexcept {
return (this->_error_str);
}
inline std::string path() const noexcept {
return (this->_dirname);
}
static inline std::string current() noexcept {
char str[1025];
return (getcwd(str, 1024));
}
};
}
#endif
|
import QUnit from 'qunit';
import { <API key> } from '@ember/debug';
let isRegistered = false;
let deprecations = new Set();
let <API key> = new Set();
// Ignore deprecations that are not caused by our own code, and which we cannot fix easily.
const ignoredDeprecations = [
/Versions of modifier manager capabilities prior to 3\.22 have been deprecated/,
/Usage of the Ember Global is deprecated./,
/import .* directly from/,
/Use of `assign` has been deprecated/,
];
export default function setupNoDeprecations({ beforeEach, afterEach }) {
beforeEach(function () {
deprecations.clear();
<API key>.clear();
if (!isRegistered) {
<API key>((message, options, next) => {
if (!ignoredDeprecations.some((regex) => message.match(regex))) {
deprecations.add(message);
}
next(message, options);
});
isRegistered = true;
}
});
afterEach(function (assert) {
// guard in if instead of using assert.equal(), to not make assert.expect() fail
if (deprecations.size > <API key>.size) {
assert.ok(
false,
`Expected ${<API key>.size} deprecations, found: ${[...deprecations]
.map((msg) => `"${msg}"`)
.join(', ')}`
);
}
});
QUnit.assert.deprecations = function (count) {
if (count === undefined) {
this.ok(deprecations.size, 'Expected deprecations during test.');
} else {
this.equal(deprecations.size, count, `Expected ${count} deprecation(s) during test.`);
}
deprecations.forEach((d) => <API key>.add(d));
};
QUnit.assert.deprecationsInclude = function (expected) {
let found = [...deprecations].find((deprecation) => deprecation.includes(expected));
this.pushResult({
result: !!found,
actual: deprecations,
message: `expected to find \`${expected}\` deprecation. Found ${[...deprecations]
.map((d) => `"${d}"`)
.join(', ')}`,
});
if (found) {
<API key>.add(found);
}
};
}
|
package com.manniwood.cl4pg.v1.exceptions;
public class <API key> extends Cl4pgException {
private static final long serialVersionUID = 1L;
public <API key>() {
super();
}
public <API key>(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public <API key>(String message, Throwable cause) {
super(message, cause);
}
public <API key>(String message) {
super(message);
}
public <API key>(Throwable cause) {
super(cause);
}
}
|
package com.cosium.spring.data.jpa.entity.graph.repository.support;
import com.google.common.base.MoreObjects;
import org.springframework.core.ResolvableType;
import org.springframework.data.jpa.repository.query.JpaEntityGraph;
import static java.util.Objects.requireNonNull;
/**
* Wrapper class allowing to hold a {@link JpaEntityGraph} with its associated domain class. Created
* on 23/11/16.
*
* @author Reda.Housni-Alaoui
*/
class EntityGraphBean {
private final JpaEntityGraph jpaEntityGraph;
private final Class<?> domainClass;
private final ResolvableType <API key>;
private final boolean optional;
private final boolean primary;
private final boolean valid;
public EntityGraphBean(
JpaEntityGraph jpaEntityGraph,
Class<?> domainClass,
ResolvableType <API key>,
boolean optional,
boolean primary) {
this.jpaEntityGraph = requireNonNull(jpaEntityGraph);
this.domainClass = requireNonNull(domainClass);
this.<API key> = requireNonNull(<API key>);
this.optional = optional;
this.primary = primary;
this.valid = computeValidity();
}
private boolean computeValidity() {
Class<?> resolvedReturnType = <API key>.resolve();
if (Void.TYPE.equals(resolvedReturnType) || domainClass.isAssignableFrom(resolvedReturnType)) {
return true;
}
for (Class genericType : <API key>.resolveGenerics()) {
if (domainClass.isAssignableFrom(genericType)) {
return true;
}
}
return false;
}
/** @return The jpa entity graph */
public JpaEntityGraph getJpaEntityGraph() {
return jpaEntityGraph;
}
/** @return The jpa entity class */
public Class<?> getDomainClass() {
return domainClass;
}
/** @return True if this entity graph is not mandatory */
public boolean isOptional() {
return optional;
}
/** @return True if this EntityGraph seems valid */
public boolean isValid() {
return valid;
}
/**
* @return True if this EntityGraph is a primary one. Default EntityGraph is an example of non
* primary EntityGraph.
*/
public boolean isPrimary() {
return primary;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("jpaEntityGraph", jpaEntityGraph)
.add("domainClass", domainClass)
.add("<API key>", <API key>)
.add("optional", optional)
.toString();
}
}
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Page',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('title', models.CharField(unique=True, max_length=150)),
('slug', models.SlugField(unique=True, max_length=150)),
('posted', models.DateTimeField(auto_now_add=True, db_index=True)),
],
options={
},
bases=(models.Model,),
),
]
|
module.exports = function(grunt) {
// Add our custom tasks.
grunt.loadTasks('../../../tasks');
// Project configuration.
grunt.initConfig({
mochaTest: {
options: {
reporter: 'spec',
grep: 'tests that match grep',
invert: true
},
all: {
src: ['*.js']
}
}
});
// Default task.
grunt.registerTask('default', ['mochaTest']);
};
|
<?php
namespace App\Service;
class Message {
public function get()
{
if (isset($_SESSION['message'])) {
$array = explode(',', $_SESSION['message']);
unset($_SESSION['message']);
return $array;
}
return '';
}
public function set($message, $type = null)
{
$_SESSION['message'] = implode(',', [$message, $type]);
}
}
|
package mqttpubsub
import (
"encoding/json"
"fmt"
"sync"
"time"
log "github.com/Sirupsen/logrus"
"github.com/brocaar/loraserver/api/gw"
"github.com/brocaar/lorawan"
"github.com/eclipse/paho.mqtt.golang"
)
// Backend implements a MQTT pub-sub backend.
type Backend struct {
conn mqtt.Client
txPacketChan chan gw.TXPacketBytes
gateways map[lorawan.EUI64]struct{}
mutex sync.RWMutex
}
// NewBackend creates a new Backend.
func NewBackend(server, username, password string) (*Backend, error) {
b := Backend{
txPacketChan: make(chan gw.TXPacketBytes),
gateways: make(map[lorawan.EUI64]struct{}),
}
opts := mqtt.NewClientOptions()
opts.AddBroker(server)
opts.SetUsername(username)
opts.SetPassword(password)
opts.SetOnConnectHandler(b.onConnected)
opts.<API key>(b.onConnectionLost)
log.WithField("server", server).Info("backend: connecting to mqtt broker")
b.conn = mqtt.NewClient(opts)
if token := b.conn.Connect(); token.Wait() && token.Error() != nil {
return nil, token.Error()
}
return &b, nil
}
// Close closes the backend.
func (b *Backend) Close() {
b.conn.Disconnect(250) // wait 250 milisec to complete pending actions
}
// TXPacketChan returns the TXPacketBytes channel.
func (b *Backend) TXPacketChan() chan gw.TXPacketBytes {
return b.txPacketChan
}
// SubscribeGatewayTX subscribes the backend to the gateway TXPacketBytes
// topic (packets the gateway needs to transmit).
func (b *Backend) SubscribeGatewayTX(mac lorawan.EUI64) error {
defer b.mutex.Unlock()
b.mutex.Lock()
topic := fmt.Sprintf("gateway/%s/tx", mac.String())
log.WithField("topic", topic).Info("backend: subscribing to topic")
if token := b.conn.Subscribe(topic, 0, b.txPacketHandler); token.Wait() && token.Error() != nil {
return token.Error()
}
b.gateways[mac] = struct{}{}
return nil
}
// <API key> unsubscribes the backend from the gateway TXPacketBytes
// topic.
func (b *Backend) <API key>(mac lorawan.EUI64) error {
defer b.mutex.Unlock()
b.mutex.Lock()
topic := fmt.Sprintf("gateway/%s/tx", mac.String())
log.WithField("topic", topic).Info("backend: unsubscribing from topic")
if token := b.conn.Unsubscribe(topic); token.Wait() && token.Error() != nil {
return token.Error()
}
delete(b.gateways, mac)
return nil
}
// PublishGatewayRX publishes a RX packet to the MQTT broker.
func (b *Backend) PublishGatewayRX(mac lorawan.EUI64, rxPacket gw.RXPacketBytes) error {
topic := fmt.Sprintf("gateway/%s/rx", mac.String())
return b.publish(topic, rxPacket)
}
// PublishGatewayStats publishes a GatewayStatsPacket to the MQTT broker.
func (b *Backend) PublishGatewayStats(mac lorawan.EUI64, stats gw.GatewayStatsPacket) error {
topic := fmt.Sprintf("gateway/%s/stats", mac.String())
return b.publish(topic, stats)
}
func (b *Backend) publish(topic string, v interface{}) error {
bytes, err := json.Marshal(v)
if err != nil {
return err
}
log.WithField("topic", topic).Info("backend: publishing packet")
if token := b.conn.Publish(topic, 0, false, bytes); token.Wait() && token.Error() != nil {
return token.Error()
}
return nil
}
func (b *Backend) txPacketHandler(c mqtt.Client, msg mqtt.Message) {
log.WithField("topic", msg.Topic()).Info("backend: packet received")
var txPacket gw.TXPacketBytes
if err := json.Unmarshal(msg.Payload(), &txPacket); err != nil {
log.Errorf("backend: decode tx packet error: %s", err)
return
}
b.txPacketChan <- txPacket
}
func (b *Backend) onConnected(c mqtt.Client) {
defer b.mutex.RUnlock()
b.mutex.RLock()
log.Info("backend: connected to mqtt broker")
if len(b.gateways) > 0 {
for {
log.WithField("topic_count", len(b.gateways)).Info("backend: re-registering to gateway topics")
topics := make(map[string]byte)
for k := range b.gateways {
topics[fmt.Sprintf("gateway/%s/tx", k)] = 0
}
if token := b.conn.SubscribeMultiple(topics, b.txPacketHandler); token.Wait() && token.Error() != nil {
log.WithField("topic_count", len(topics)).Errorf("backend: subscribe multiple failed: %s", token.Error())
time.Sleep(time.Second)
continue
}
return
}
}
}
func (b *Backend) onConnectionLost(c mqtt.Client, reason error) {
log.Errorf("backend: mqtt connection error: %s", reason)
}
|
package stage2;
public class DecafError {
int numErrors;
DecafError(){
}
public static String errorPos(Position p){
return "(L: " + p.startLine +
", Col: " + p.startCol +
") -- (L: " + p.endLine +
", Col: " + p.endCol +
")";
}
public void error(String s, Position p) {
System.out.println("Error found at location "+
errorPos(p) + ":\n"+s);
}
public boolean haveErrors() {
return (numErrors>0);
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>../plugins/plugins_2d/bar/bar.vlib.js</title>
<link rel="stylesheet" href="http://yui.yahooapis.com/3.9.1/build/cssgrids/cssgrids-min.css">
<link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
<link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
<link rel="shortcut icon" type="image/png" href="../assets/favicon.png">
<script src="http://yui.yahooapis.com/combo?3.9.1/build/yui/yui-min.js"></script>
</head>
<body class="yui3-skin-sam">
<div id="doc">
<div id="hd" class="yui3-g header">
<div class="yui3-u-3-4">
<h1><img src="../assets/css/logo.png" title=""></h1>
</div>
<div class="yui3-u-1-4 version">
<em>API Docs for: </em>
</div>
</div>
<div id="bd" class="yui3-g">
<div class="yui3-u-1-4">
<div id="docs-sidebar" class="sidebar apidocs">
<div id="api-list">
<h2 class="off-left">APIs</h2>
<div id="api-tabview" class="tabview">
<ul class="tabs">
<li><a href="#api-classes">Classes</a></li>
<li><a href="#api-modules">Modules</a></li>
</ul>
<div id="api-tabview-filter">
<input type="search" id="api-filter" placeholder="Type to filter APIs">
</div>
<div id="api-tabview-panel">
<ul id="api-classes" class="apis classes">
<li><a href="../classes/AbstractPlugin.html">AbstractPlugin</a></li>
<li><a href="../classes/Config.html">Config</a></li>
<li><a href="../classes/Controls.html">Controls</a></li>
<li><a href="../classes/Plot.html">Plot</a></li>
<li><a href="../classes/Plugin 3D.html">Plugin 3D</a></li>
<li><a href="../classes/Plugin Axes.html">Plugin Axes</a></li>
<li><a href="../classes/Plugin BasicMaterial.html">Plugin BasicMaterial</a></li>
<li><a href="../classes/Plugin CameraControl.html">Plugin CameraControl</a></li>
<li><a href="../classes/Plugin Color.html">Plugin Color</a></li>
<li><a href="../classes/Plugin Dataset.html">Plugin Dataset</a></li>
<li><a href="../classes/Plugin File.html">Plugin File</a></li>
<li><a href="../classes/Plugin Function.html">Plugin Function</a></li>
<li><a href="../classes/Plugin Heatmap.html">Plugin Heatmap</a></li>
<li><a href="../classes/Plugin Light.html">Plugin Light</a></li>
<li><a href="../classes/Plugin LinePlot.html">Plugin LinePlot</a></li>
<li><a href="../classes/Plugin Plane.html">Plugin Plane</a></li>
<li><a href="../classes/Plugin ScatterPlot.html">Plugin ScatterPlot</a></li>
<li><a href="../classes/Plugin SurfacePlot.html">Plugin SurfacePlot</a></li>
<li><a href="../classes/Plugin WireframeMaterial.html">Plugin WireframeMaterial</a></li>
<li><a href="../classes/SceneGraph.html">SceneGraph</a></li>
<li><a href="../classes/Templates.html">Templates</a></li>
<li><a href="../classes/Toolbox.html">Toolbox</a></li>
<li><a href="../classes/UTILS.html">UTILS</a></li>
<li><a href="../classes/VLib.html">VLib</a></li>
<li><a href="../classes/VMediator.html">VMediator</a></li>
</ul>
<ul id="api-modules" class="apis modules">
<li><a href="../modules/Controls.html">Controls</a></li>
<li><a href="../modules/main.html">main</a></li>
<li><a href="../modules/Plot.html">Plot</a></li>
<li><a href="../modules/SceneGraph.html">SceneGraph</a></li>
<li><a href="../modules/Templates.html">Templates</a></li>
<li><a href="../modules/Toolbox.html">Toolbox</a></li>
<li><a href="../modules/VLib.html">VLib</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="yui3-u-3-4">
<div id="api-options">
Show:
<label for="api-show-inherited">
<input type="checkbox" id="api-show-inherited" checked>
Inherited
</label>
<label for="api-show-protected">
<input type="checkbox" id="api-show-protected">
Protected
</label>
<label for="api-show-private">
<input type="checkbox" id="api-show-private">
Private
</label>
<label for="api-show-deprecated">
<input type="checkbox" id="api-show-deprecated">
Deprecated
</label>
</div>
<div class="apidocs">
<div id="docs-main">
<div class="content">
<h1 class="file-heading">File: ../plugins/plugins_2d/bar/bar.vlib.js</h1>
<div class="file">
<pre class="code prettyprint linenums">
define(['require','config'],function(require,Config) {
var plugin = (function() {
/** PUBLIC VARIABLES * */
this.context = Config.PLUGINTYPE.CONTEXT_2D;
this.type = Config.PLUGINTYPE.LINETYPE;
this.name = 'bar';
/** path to plugin-template file * */
this.accepts = {
predecessors : [ Config.PLUGINTYPE.DATA ],
successors : [ ]
}
this.icon = Config.absPlugins + '/plugins_2d/bar/icon.png';
this.description = 'Requires: [ '+this.accepts.predecessors.join(', ')+' ] Accepts: [ '+this.accepts.successors.join(', ')+' ]';
/** PUBLIC METHODS * */
|
<!DOCTYPE html>
<!DOCTYPE html>
<html lang=sl>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Kje lahko najdem datoteke katerih varnostno kopijo želim ustvariti?</title>
<script type="text/javascript" src="jquery.js"></script><script type="text/javascript" src="jquery.syntax.js"></script><script type="text/javascript" src="yelp.js"></script><link rel="shortcut icon" href="https:
<link rel="stylesheet" type="text/css" href="../vodnik_1404.css">
</head>
<body id="home"><div id="wrapper" class="hfeed">
<div id="header">
<div id="branding">
<div id="blog-title"><span><a rel="home" title="Ubuntu Slovenija | Uradna spletna stran slovenske skupnosti Linux distribucije Ubuntu" href="
<h1 id="blog-description"></h1>
</div>
<div id="access"><div id="loco-header-menu"><ul id="primary-header-menu"><li class="widget-container widget_nav_menu" id="nav_menu-3"><div class="<API key>"><ul class="menu" id="menu-glavni-meni">
<li id="menu-item-15" class="menu-item <API key> <API key> menu-item-15"><a href="
<li id="menu-item-2776" class="menu-item <API key> <API key> menu-item-2776"><a href="
<li id="menu-item-16" class="menu-item <API key> <API key> menu-item-16"><a href="
<li id="menu-item-19" class="menu-item <API key> <API key> menu-item-19"><a href="
<li id="menu-item-20" class="menu-item <API key> <API key> menu-item-20"><a href="
<li id="menu-item-17" class="menu-item <API key> <API key> menu-item-17"><a href="
<li id="menu-item-18" class="menu-item <API key> <API key> menu-item-18"><a href="
</ul></div></li></ul></div></div>
</div>
<div id="main"><div id="cwt-content" class="clearfix content-area"><div id="page">
<div class="trails" role="navigation"><div class="trail">
<span style="color:
<div id="content">
<div class="hgroup"><h1 class="title"><span class="title">Kje lahko najdem datoteke katerih varnostno kopijo želim ustvariti?</span></h1></div>
<div class="region">
<div class="contents">
<p class="p">Spodaj so izpisana najbolj pogosta mesta pomembnih datotek in nastavitev, ki si jih morda želite varnostno kopirati.</p>
<div class="list"><div class="inner"><div class="region"><ul class="list">
<li class="list">
<p class="p">Osebne datoteke (dokumenti, glasba, fotografije in videoposnetki)</p>
<p class="p">Te so ponavadi shranjene v vaši domači mapi (<span class="file">/home/vaše_ime</span>). Lahko so v podmapah kot je Namizje, Dokumenti, Slike, Glasba in Videi.</p>
<p class="p">Če je na vašem mediju varnostne kopije dovolj prostora (na primer če je to zunanji trdi disk), razmislite o ustvarjanju varnostne kopije celotne Domače mape. Koliko prostora zavzema Domača mapa lahko ugotovite z orodjem <span class="app">Preučevalnik porabe diska</span>.</p>
</li>
<li class="list">
<p class="p">Skrite datoteke</p>
<p class="p">Katerokoli ime datoteke ali mape, ki se začne s piko (.), je privzeto skrito. Za ogled skritih datotek kliknite <span class="guiseq"><span class="gui">Pogled</span> <span class="gui">Pokaži skrite datoteke</span></span> ali pritisnite <span class="keyseq"><span class="key"><kbd>Ctrl</kbd></span>+<span class="key"><kbd>H</kbd></span></span>.</p>
</li>
<li class="list">
<p class="p">Osebne nastavitve (možnosti namizja, teme in nastavitve programov)</p>
<p class="p">Večina programov shrani svoje nastavitve v skrite mape v vaši Domači mapi (glejte zgoraj za podrobnosti o skritih datotekah).</p>
<p class="p">Večina vaših nastavitev programov je shranjena v skritih mapah <span class="file">.config</span>, <span class="file">.gconf</span>, <span class="file">.gnome2</span> in <span class="file">.local</span> v vaši Domači mapi.</p>
</li>
<li class="list">
<p class="p">Sistemske nastavitve</p>
<p class="p">Nastavitve pomembnih delov sistema niso shranjene v Domači mapi. Obstajajo številna mesta, kjer so lahko shranjena, vendar jih je večina shranjena v mapi <span class="file">/etc</span>. V splošnem vam varnostne kopije teh datotek na domačem računalniku ni treba ustvariti. Če imate strežnik, je pametno ustvariti varnostno kopijo datotek za storitve, ki jih strežnik poganja.</p>
</li>
</ul></div></div></div>
</div>
<div class="sect sect-links" role="navigation">
<div class="hgroup"></div>
<div class="contents"><div class="links guidelinks"><div class="inner">
<div class="title"><h2><span class="title">Več podrobnosti</span></h2></div>
<div class="region"><ul><li class="links "><a href="files.html#backup" title="Ustvarjanje varnostnih kopij">Ustvarjanje varnostnih kopij</a></li></ul></div>
</div></div></div>
</div>
</div>
<div class="clear"></div>
</div>
</div></div></div>
<div id="footer">
<img src="https:
</div>
</div></body>
</html>
|
"use strict";
define("ace/mode/<API key>", ["require", "exports", "module", "ace/lib/oop", "ace/mode/<API key>"], function (require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextHighlightRules = require("./<API key>").TextHighlightRules;
var <API key> = function <API key>() {
var identifierRe = "[a-zA-Z\xA1-\uFFFF]+\\b";
this.$rules = {
"start": [{ token: "empty", regex: /$/ }, { token: "literal", regex: /^\.{4,}\s*$/, next: "listingBlock" }, { token: "literal", regex: /^-{4,}\s*$/, next: "literalBlock" }, { token: "string", regex: /^\+{4,}\s*$/, next: "passthroughBlock" }, { token: "keyword", regex: /^={4,}\s*$/ }, { token: "text", regex: /^\s*$/ }, { token: "empty", regex: "", next: "<API key>" }],
"<API key>": [{ include: "paragraphEnd" }, { token: "comment", regex: '^//.+$' }, { token: "keyword", regex: "^(?:NOTE|TIP|IMPORTANT|WARNING|CAUTION):" }, { include: "listStart" }, { token: "literal", regex: /^\s+.+$/, next: "indentedBlock" }, { token: "empty", regex: "", next: "text" }],
|
package cargaDoSistema;
import modelo.TipoUsuario;
import modelo.Usuario;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import service.<API key>;
import service.UsuarioAppService;
import service.controleTransacao.FabricaDeAppService;
import service.exception.AplicacaoException;
import util.JPAUtil;
public class CargaUsuario {
// Services
public <API key> tipoUsuarioService;
public UsuarioAppService usuarioService;
@BeforeClass
public void setupClass(){
try {
tipoUsuarioService = FabricaDeAppService.getAppService(<API key>.class);
usuarioService = FabricaDeAppService.getAppService(UsuarioAppService.class);
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void <API key>() {
TipoUsuario tipoUsuarioAdmin = new TipoUsuario();
TipoUsuario tipoUsuarioAluno = new TipoUsuario();
TipoUsuario tipoUsuarioGestor = new TipoUsuario();
TipoUsuario <API key> = new TipoUsuario();
tipoUsuarioAdmin.setTipoUsuario(TipoUsuario.ADMINISTRADOR);
tipoUsuarioAdmin.setDescricao("O usuário ADMINISTRADOR pode realizar qualquer operação no Sistema.");
tipoUsuarioAluno.setTipoUsuario(TipoUsuario.ALUNO);
tipoUsuarioAluno.setDescricao("O usuário ALUNO pode realizar apenas consultas e impressão de relatórios nas telas " +
"relativas ao Horizonte de Planejamento (HP,Periodo PMP, Periodo PAP) e não acessa " +
"Administração e Eng. Conhecimento");
tipoUsuarioGestor.setTipoUsuario(TipoUsuario.GESTOR);
tipoUsuarioGestor.setDescricao("O usuário GESTOR pode realizar qualquer operação no Sistema, porém não possui acesso" +
"as áreas de Administração e Engenharia de Conhecimento.");
<API key>.setTipoUsuario(TipoUsuario.<API key>);
<API key>.setDescricao("O usuário ENGENHEIRO pode realizar a parte de Logica Fuzzy (Engenharia de Conhecimento)" +
"no Sistema. Porém, não possui acesso a área Administrativa.");
tipoUsuarioService.inclui(tipoUsuarioAdmin);
tipoUsuarioService.inclui(tipoUsuarioAluno);
tipoUsuarioService.inclui(tipoUsuarioGestor);
tipoUsuarioService.inclui(<API key>);
Usuario usuarioAdmin = new Usuario();
Usuario usuarioAluno = new Usuario();
Usuario usuarioGestor = new Usuario();
Usuario usuarioEngenheiro = new Usuario();
usuarioAdmin.setNome("Administrador");
usuarioAdmin.setLogin("dgep");
usuarioAdmin.setSenha("admgesplan2@@8");
usuarioAdmin.setTipoUsuario(tipoUsuarioAdmin);
usuarioAluno.setNome("Alberto da Silva");
usuarioAluno.setLogin("alberto");
usuarioAluno.setSenha("alberto");
usuarioAluno.setTipoUsuario(tipoUsuarioAluno);
usuarioEngenheiro.setNome("Bernadete da Silva");
usuarioEngenheiro.setLogin("bernadete");
usuarioEngenheiro.setSenha("bernadete");
usuarioEngenheiro.setTipoUsuario(<API key>);
usuarioGestor.setNome("Carlos da Silva");
usuarioGestor.setLogin("carlos");
usuarioGestor.setSenha("carlos");
usuarioGestor.setTipoUsuario(tipoUsuarioGestor);
try {
usuarioService.inclui(usuarioAdmin, usuarioAdmin.getSenha());
usuarioService.inclui(usuarioEngenheiro, usuarioEngenheiro.getSenha());
usuarioService.inclui(usuarioGestor, usuarioGestor.getSenha());
usuarioService.inclui(usuarioAluno, usuarioAluno.getSenha());
} catch (AplicacaoException e) {
//e.printStackTrace();
System.out.println("Erro na inclusao do usuario: "+ e.getMessage());
}
}
}
|
import * as React from 'react'
import {Component, ComponentClass, createElement} from 'react'
import * as PropTypes from 'prop-types'
import {connect} from 'react-redux'
import {Store} from '../store'
import ComputedState from '../model/ComputedState'
function connectToStore<P>(component:ComponentClass<P>):ComponentClass<P> {
type PS = P & {store:Store}
const mapStateToProps = (state:ComputedState, ownProps:PS):P => ({
Object(ownProps),
state
})
const WrappedComponent = (props:P) => createElement(component, props)
const ConnectedComponent = connect(mapStateToProps)(WrappedComponent)
return class ConnectToStore extends Component<P, any> {
static contextTypes = {
rrnhStore: PropTypes.object.isRequired
}
render() {
const {rrnhStore} = this.context
return <ConnectedComponent store={rrnhStore} {...this.props} />
}
}
}
export default connectToStore
|
<!DOCTYPE HTML PUBLIC "-
<!--NewPage
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.4.2_05) on Thu Sep 30 22:16:01 GMT+01:00 2004 -->
<TITLE>
org.springframework.web.multipart.support Class Hierarchy (Spring Framework)
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="org.springframework.web.multipart.support Class Hierarchy (Spring Framework)";
}
</SCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<A NAME="navbar_top"></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../org/springframework/web/multipart/cos/package-tree.html"><B>PREV</B></A>
<A HREF="../../../../../org/springframework/web/servlet/package-tree.html"><B>NEXT</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<HR>
<CENTER>
<H2>
Hierarchy For Package org.springframework.web.multipart.support
</H2>
</CENTER>
<DL>
<DT><B>Package Hierarchies:</B><DD><A HREF="../../../../../overview-tree.html">All Packages</A></DL>
<HR>
<H2>
Class Hierarchy
</H2>
<UL>
<LI TYPE="circle">class java.lang.Object<UL>
<LI TYPE="circle">class org.springframework.web.filter.<A HREF="../../../../../org/springframework/web/filter/GenericFilterBean.html" title="class in org.springframework.web.filter"><B>GenericFilterBean</B></A> (implements javax.servlet.Filter)
<UL>
<LI TYPE="circle">class org.springframework.web.filter.<A HREF="../../../../../org/springframework/web/filter/<API key>.html" title="class in org.springframework.web.filter"><B><API key></B></A><UL>
<LI TYPE="circle">class org.springframework.web.multipart.support.<A HREF="../../../../../org/springframework/web/multipart/support/MultipartFilter.html" title="class in org.springframework.web.multipart.support"><B>MultipartFilter</B></A></UL>
</UL>
<LI TYPE="circle">class java.beans.<API key> (implements java.beans.PropertyEditor)
<UL>
<LI TYPE="circle">class org.springframework.web.multipart.support.<A HREF="../../../../../org/springframework/web/multipart/support/<API key>.html" title="class in org.springframework.web.multipart.support"><B><API key></B></A><LI TYPE="circle">class org.springframework.web.multipart.support.<A HREF="../../../../../org/springframework/web/multipart/support/<API key>.html" title="class in org.springframework.web.multipart.support"><B><API key></B></A></UL>
<LI TYPE="circle">class javax.servlet.<API key> (implements javax.servlet.ServletRequest)
<UL>
<LI TYPE="circle">class javax.servlet.http.<API key> (implements javax.servlet.http.HttpServletRequest)
<UL>
<LI TYPE="circle">class org.springframework.web.multipart.support.<A HREF="../../../../../org/springframework/web/multipart/support/<API key>.html" title="class in org.springframework.web.multipart.support"><B><API key></B></A> (implements org.springframework.web.multipart.<A HREF="../../../../../org/springframework/web/multipart/<API key>.html" title="interface in org.springframework.web.multipart"><API key></A>)
<UL>
<LI TYPE="circle">class org.springframework.web.multipart.support.<A HREF="../../../../../org/springframework/web/multipart/support/<API key>.html" title="class in org.springframework.web.multipart.support"><B><API key></B></A></UL>
</UL>
</UL>
</UL>
</UL>
<HR>
<A NAME="navbar_bottom"></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="<API key>"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../org/springframework/web/multipart/cos/package-tree.html"><B>PREV</B></A>
<A HREF="../../../../../org/springframework/web/servlet/package-tree.html"><B>NEXT</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<HR>
<i>Copyright (C) 2003-2004 The Spring Framework Project.</i>
</BODY>
</HTML>
|
import { <API key> } from '@angular/<API key>';
import { enableProdMode } from '@angular/core';
import { AppModule } from './app/app.module';
enableProdMode();
<API key>().bootstrapModule(AppModule);
|
from behave import given, when, then
from genosdb.models import User
from genosdb.exceptions import UserNotFound
# 'mongodb://localhost:27017/')
@given('a valid user with values {username}, {password}, {email}, {first_name}, {last_name}')
def step_impl(context, username, password, email, first_name, last_name):
context.base_user = User(username=username, email=email, password=password, first_name=first_name,
last_name=last_name)
@when('I add the user to the collection')
def step_impl(context):
context.user_service.save(context.base_user)
@then('I check {user_name} exists')
def step_impl(context, user_name):
user_exists = context.user_service.exists(user_name)
assert context.base_user.username == user_exists['username']
assert context.base_user.password == user_exists['password']
assert context.base_user.email == user_exists['email']
assert context.base_user.first_name == user_exists['first_name']
assert context.base_user.last_name == user_exists['last_name']
assert user_exists['_id'] is not None
@given('I update {username} {field} with {value}')
def step_impl(context, username, field, value):
user = context.user_service.exists(username)
if user is not None:
user[field] = value
context.user_service.update(user.to_json())
else:
raise UserNotFound(username, "User was not found")
@then('I check {username} {field} is {value}')
def step_impl(context, username, field, value):
user = context.user_service.exists(username)
if user is not None:
assert user[field] == value
else:
raise UserNotFound(username, "User was not found")
|
using Mokkosu.AST;
using System.Collections.Generic;
using System.Text;
namespace Mokkosu.ClosureConversion
{
class <API key>
{
public Dictionary<string, MExpr> FunctionTable { get; private set; }
public MExpr Main { get; private set; }
public <API key>(Dictionary<string, MExpr> table, MExpr main)
{
FunctionTable = table;
Main = main;
}
public override string ToString()
{
var sb = new StringBuilder();
foreach (var item in FunctionTable)
{
sb.AppendFormat("=== {0} ===\n", item.Key);
sb.Append(item.Value);
sb.Append("\n");
}
sb.Append("=== Main ===\n");
sb.Append(Main);
return sb.ToString();
}
}
}
|
package com.ov3rk1ll.kinocast.ui.util.glide;
import com.ov3rk1ll.kinocast.data.ViewModel;
public class <API key> {
private ViewModel viewModel;
private int screenWidthPx;
private String type;
public <API key>(ViewModel viewModel, int screenWidthPx, String type) {
this.viewModel = viewModel;
this.screenWidthPx = screenWidthPx;
this.type = type;
}
ViewModel getViewModel() {
return viewModel;
}
int getScreenWidthPx() {
return screenWidthPx;
}
public String getType() {
return type;
}
}
|
package stat
import (
"fmt"
"time"
// "encoding/json"
)
type RevStat struct {
RevId string `json:"RevId"`
UserName string `json:"UserName"`
WordCount int `json:"WordCount"`
ModDate string `json:"ModDate"`
WordFreq []WordPair `json:"WordFreq"`
}
type DocStat struct {
FileId string `json:"FileId"`
Title string `json:"Title"`
LastMod string `json:"LastMod"`
RevList []RevStat `json:"RevList"`
}
func (rev RevStat) GetTime() string {
x, _ := time.Parse("2006-01-02T15:04:05.000Z", rev.ModDate)
return x.Format("15:04")
}
func (rev RevStat) String() string {
return fmt.Sprintf("[%s %s] %d words by %s. \n\t Words [%s]", rev.ModDate, rev.RevId, rev.WordCount, rev.UserName, rev.WordFreq)
}
func (doc DocStat) String() string {
s := fmt.Sprintf("[%s] '%s' last mod on %s with revs\n", doc.FileId, doc.Title, doc.LastMod)
for i, v := range doc.RevList {
s += fmt.Sprintf("\t %d:%s\n", i, v)
}
return s
}
|
<html>
<head>
<meta charset="utf-8">
<title>Example React.js using NPM, Babel6 and Webpack</title>
</head>
<body>
<div id="app" />
<script src="public/bundle.js" type="text/javascript"></script>
</body>
</html>
|
package ru.lanbilling.webservice.wsdl;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"ret"
})
@XmlRootElement(name = "<API key>")
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
public class <API key> {
@XmlElement(required = true)
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
protected List<SoapDocument> ret;
/**
* Gets the value of the ret property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the ret property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getRet().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link SoapDocument }
*
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
public List<SoapDocument> getRet() {
if (ret == null) {
ret = new ArrayList<SoapDocument>();
}
return this.ret;
}
}
|
#include "ToolbarPanel.h"
#include "StagePanel.h"
#include "SelectSpritesOP.h"
#include "Context.h"
namespace coceditor
{
ToolbarPanel::ToolbarPanel(wxWindow* parent)
: ee::ToolbarPanel(parent, Context::Instance()->stage)
{
Context* context = Context::Instance();
// addChild(new ee::UniversalCMPT(this, wxT("paste"), context->stage,
// new ee::ArrangeSpriteOP<ee::SelectSpritesOP>(context->stage, context->stage)));
addChild(new ee::UniversalCMPT(this, wxT("paste"), context->stage,
new ee::ArrangeSpriteOP<SelectSpritesOP>(context->stage, context->stage, context->property)));
SetSizer(initLayout());
}
wxSizer* ToolbarPanel::initLayout()
{
wxBoxSizer* topSizer = new wxBoxSizer(wxVERTICAL);
topSizer->Add(initChildrenLayout());
return topSizer;
}
} // coceditor
|
using System.IO;
using System.Diagnostics;
using NDepend.Path;
namespace NDepend.Test.Unit {
public static class DirForTest {
public static <API key> <API key> {
get {
// If this following line doesn't work, it is because of ShadowCopyCache with NUnit
return System.Reflection.Assembly.<API key>().Location.ToAbsoluteFilePath().ParentDirectoryPath;
}
}
public static IAbsoluteFilePath <API key> {
get {
return <API key>.<API key>(<API key>);
}
}
private static string <API key> {
get {
string <API key> = System.Reflection.Assembly.<API key>().Location;
return System.IO.Path.GetFileName(<API key>);
}
}
public static <API key> DirAbsolute {
get {
return Dir.<API key>();
}
}
public static string Dir {
get {
return <API key>.<API key>("DirForTest").ToString();
}
}
public static <API key> <API key>(string unitTestName) {
<API key> ndependRootPath = <API key>.ParentDirectoryPath;
<API key> unitTestPath = ndependRootPath.<API key>("NDepend.Test.Dirs");
<API key> result = unitTestPath.<API key>(unitTestName);
Debug.Assert(result.Exists);
return result;
}
public static <API key> GetBinDebugDir() {
<API key> binDebug = DirAbsolute.ParentDirectoryPath.<API key>("Debug");
Debug.Assert(binDebug.Exists);
return binDebug;
}
public static void <API key>() {
string dir = Dir;
RETRY: // 29Nov2010: retry until it is ok!!
try {
// Clear the older dir
if (!Directory.Exists(dir)) {
Directory.CreateDirectory(dir);
} else {
var subDirs = Directory.GetDirectories(dir);
var subFiles = Directory.GetFiles(dir);
if (subFiles.Length > 0) {
foreach (var filePath in subFiles) {
File.Delete(filePath);
}
}
if (subDirs.Length > 0) {
foreach (var dirPath in subDirs) {
Directory.Delete(dirPath, true);
}
}
}
if (!Directory.Exists(dir)) { goto RETRY; }
if (Directory.GetDirectories(dir).Length > 0) { goto RETRY; }
if (Directory.GetFiles(dir).Length > 0) { goto RETRY; }
} catch {
goto RETRY;
}
var dirInfo = new DirectoryInfo(dir);
Debug.Assert(dirInfo.Exists);
Debug.Assert(dirInfo.GetFiles().Length == 0);
Debug.Assert(dirInfo.GetDirectories().Length == 0);
}
public static void Delete() {
string dir = Dir;
if (Directory.Exists(dir)) {
Directory.Delete(dir, true);
}
}
public static string <API key> {
get {
return Dir.<API key>().<API key>(<API key>).ToString();
}
}
public static void <API key>() {
File.Copy(<API key>.<API key>(<API key>).ToString(),
<API key>);
}
}
}
|
require 'statsample'
module Grid
class Row
attr_reader :top_y, :bottom_y
def initialize(item)
@data = []
self << item
end
def <<(item)
@data << item
@top_y = quartiles_meam(@data.map(&:y))
@bottom_y = quartiles_meam(@data.map{|item| item.y + item.height})
end
def inbound_y?(y)
@top_y <= y && y <= @bottom_y
end
def include?(item)
@data.include?(item)
end
def height
@bottom_y - @top_y
end
private
def quartiles_meam(array)
quartiles(array).to_scale.mean
end
def quartiles(array)
return array if array.size < 7
lower = (array.size - 3)/4
upper = lower * 3 + 3
array[lower..upper]
end
end
end
|
import unittest
from src.data_structures.mockdata import MockData
class TestMockData (unittest.TestCase):
def setUp(self):
self.data = MockData()
def test_random_data(self):
data = MockData()
a_set = data.get_random_elements(10)
self.assertTrue(len(a_set) == 10, "the data should have 10 elements!")
if __name__ == '__main__':
unittest.main()
|
// Person.h
// SJDBMapProject
#import <Foundation/Foundation.h>
#import "SJDBMapUseProtocol.h"
@class Book;
@class PersonTag;
@class Goods;
@class TestTest;
@interface Person : NSObject<SJDBMapUseProtocol>
@property (nonatomic, strong) Book *aBook;
@property (nonatomic, assign) NSInteger personID;
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSArray<PersonTag *> *tags;
@property (nonatomic, strong) NSString *test;
@property (nonatomic, strong) NSString *teet;
@property (nonatomic, strong) NSString *ttttt;
@property (nonatomic, strong) NSArray<Goods *> *goods;
@property (nonatomic, assign) NSInteger age;
@property (nonatomic, assign) NSInteger group;
@property (nonatomic, assign) NSInteger index;
@property (nonatomic, assign) NSInteger ID;
@property (nonatomic, assign) NSInteger unique;
@property (nonatomic, strong) NSURL *tessss;
@property (nonatomic, strong) NSString *teesssf;
@property (nonatomic, strong) TestTest *testTest;
@end
|
#include <bits/stdc++.h>
using namespace std;
#define REP(I,N) FOR(I,0,N)
#define FOR(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
#define ALL(A) (A).begin(), (A).end()
#define MSG(a) cout << #a << " == " << (a) << endl;
const int CLEAN = -1;
template <typename T>
string NumberToString ( T Number ) {
ostringstream ss;
ss << Number;
return ss.str();
}
#define ERR(args...) { vector<string> _v = split(#args, ','); err(_v.begin(), args); }
vector<string> split(const string& s, char c) {
vector<string> v;
stringstream ss(s);
string x;
while (getline(ss, x, c))
v.emplace_back(x);
return move(v);
}
void err(vector<string>::iterator it) {}
template<typename T, typename... Args>
void err(vector<string>::iterator it, T a, Args... args) {
cout << it -> substr((*it)[0] == ' ', it -> length()) << " = " << a << endl;
err(++it, args...);
}
int solve(int s) {
if (s < 10) {
return s;
}
int x = s - s % 10;
return x + solve(s - x + x / 10);
}
int main() {
int t;
cin >> t;
while (t
int s;
cin >> s;
cout << solve(s) << endl;
}
return 0;
}
|
# <API key>: true
module Wardrobe
module Plugins
module Validation
module Refinements
refine NilClass do
def filled?
'must be filled'
end
def empty?
# Nil is valid as empty
end
end
end
end
end
end
|
<!DOCTYPE html>
<html>
<head>
<title>Poet -- node.js blogging platform</title>
<link rel="stylesheet" href="styles/prettify.css">
<link rel="stylesheet" href="styles/poet.css">
<link href="http://fonts.googleapis.com/cs?family=La+Belle+Aurore" rel="stylesheet" type="text/css">
<script src="js/ga.js"></script>
</head>
<body>
<div class="header">
<div class="wrap"><a href="http://github.com/jsantell/poet">
<h1>Poet</h1>
<h2>write your code love poem</h2></a></div>
</div>
<div class="wrap">
<div class="cartoon"></div>
<h2 id="what-is-poet-">What is Poet?</h2>
<p><a href="http://github.com/jsantell/poet" title="Poet"><strong>Poet</strong></a> is a blog generator in
<a href="http://nodejs.org" title="node.js">node.js</a> to generate routing, render markdown/pug/whatever posts,
and get a blog up and running <em>fast</em>. Poet may not make you blog-famous,
and it may give you one less excuse for not having a blog,
but just imagine the insane hipster cred you get for having node power your blog.
<em>"Cool blog, is this Wordpress or something?"</em> your square friend asks.
<em>"Nah dude, this is in node,"</em> you respond,
while skateboarding off into the sunset, doing mad flips and stuff.
Little do they know you just used Poet's autoroute generation to get your content in, like, seconds, up on that internet.</p>
<h2 id="getting-started">Getting Started</h2>
<p>First thing first, throw <strong>Poet</strong> into your express app's package.json, or just install it locally with:</p>
<pre>
npm install poet
</pre>
<p>Once you have the <strong>Poet</strong> module in your app, just instantiate an instance with your Express app and options, and call the <code>init</code> method:</p>
<pre>
var
express = require('express'),
app = express(),
Poet = require('poet');
var poet = Poet(app, {
posts: './_posts/',
postsPerPage: 5,
metaFormat: 'json'
});
poet.init().then(function () {
// ready to go!
});
/* set up the rest of the express app */
</pre>
<p>If using Express 3, be sure to use Poet version <= <code>1.1.0</code>. For Express 4+, use Poet <code>2.0.0+</code>.</p>
<h2 id="posts">Posts</h2>
<p>Posts are constructed in <a href="http://daringfireball.net/projects/markdown/">markdown</a>/<a href="https://pugjs.org">pug</a>/<a href="
<pre>
{{{
"title": "Hello World!",
"tags": ["blog", "fun"],
"category": "javascript",
"date": "7-29-2013"
}}}
Here goes the content that belongs to the post...
</pre>
<h3 id="post-previews">Post Previews</h3>
<p>There are several ways of specifying the text of your post preview. <strong>Poet</strong> checks several properties and the first valid option is used. The order and ways to accomplish this are below.</p>
<ul>
<li>A <code>preview</code> property on a post. The text of this property runs through the appropriate template and be saved as the preview for a post</li>
<li>A <code>previewLength</code> property on a post, which will take the first <code>n</code> characters of your post (before running through a templating engine), becoming your preview.</li>
<li>The last, and most likely easiest, is specifying a <code>readMoreTag</code> option in your <strong>Poet</strong> configuration, which by default is <code><!--more--></code>. Whenever the <code>readMoreTag</code> is found int he post, anything proceeding it becomes the preview. You can set this globally in your <strong>Poet</strong> config, or specify a <code>readMoreTag</code> property for each post individually</li>
</ul>
<h2 id="options">Options</h2>
<ul>
<li><code>posts</code> path to directory of your files of posts (default: <code>./\_posts/</code>)</li>
<li><code>metaFormat</code> format of your front matter on every blog post. Can be <code>yaml</code> or <code>json</code> (default: <code>json</code>)</li>
<li><code>postsPerPage</code> How many posts are displayed per page in the page route (default: <code>5</code>)</li>
<li><code>readMoreLink</code> A function taking the post object as the only parameter, returning a string that is appended to the post's preview value. By default will be a function returning <code><a href="{post.link}">{post.title}</a></code></li>
<li><code>readMoreTag</code> A string in a post that is rendered as a read more link when parsed. (default: <code><!--more--></code>)</li>
<li><code>showDrafts</code> An option on whether or not to display posts that have <code>drafts</code> meta set to true (default: <code>process.env.NODE\_ENV !== 'production'</code>)</li>
<li><code>routes</code> A hash of route keys (ex: <code>'/post/:post'</code> and the related view file (ex: <code>'post'</code>). More information in the <a href="#Routes">routes</a> section below.</li>
</ul>
<h2 id="methods">Methods</h2>
<h3 id="poet-init-callback-">Poet::init([callback])</h3>
<p>The <code>init</code> method traverses the directory of posts and stores all the information in memory, sets up the internal structures for retrieval and returns a promise resolving to the instance upon completion. An optional callback may be provided for a node style callback with <code>err</code> and <code>poet</code> arguments passed in, called upon completion. This is used when initializing the application, or if reconstructing the internal storage is needed.</p>
<h3 id="poet-watch-callback-">Poet::watch([callback])</h3>
<p>Sets up the <strong>Poet</strong> instance to watch the posts directory for changes (a new post, updated post, etc.) and reinitializes the engine and storage. An optional <code>callback</code> may be provided to signify the completion of the reinitialization.</p>
<p>For an example of using <code>watch</code>, check out <a href="https://github.com/jsantell/poet/blob/master/examples/watcher.js">the watcher example</a></p>
<h3 id="poet-unwatch-">Poet::unwatch()</h3>
<p>Removes all watchers currently bound to the <strong>Poet</strong> instance.</p>
<h3 id="poet-clearcache-">Poet::clearCache()</h3>
<p>Used internally, this clears the <strong>Poet</strong> instance's internal cache, allowing it to be rebuilt on it's next use. This should not be used in most cases. Returns the <strong>Poet</strong> instance.</p>
<h3 id="Templates">Poet::addTemplate(data)</h3>
<p><strong>Poet</strong> comes with two templating engines by default (pug and markdown). To specify your own templating language, the <code>addTemplate</code> method may be used, taking a <code>data</code> object with two keys: <code>ext</code> and <code>fn</code>. <code>ext</code> may be a string or an array of strings, specifiying which extensions should use this templating engine, and <code>fn</code> does the rendering, where it is a function that passes an object with several properties: <code>source</code>, <code>filename</code> and <code>locals</code> for rendering engine local variables, and returns the formatted string. Here's an example of using your own YAML formatter:</p>
<pre>
var
express = require('express'),
app = express(),
yaml = require('yaml'),
Poet = require('poet');
var poet = Poet(app);
poet.addTemplate({
ext: 'yaml',
fn : function (options) { return yaml.eval(options.source); }
}).init();
</pre>
<p>This runs any post with the file extension <code>yaml</code> (ex: <code>my_post.yaml</code>) through the <code>fn</code> specified (by calling the <code>yaml</code> module's <code>eval</code> method.</p>
<h3 id="<API key>-">Poet::addRoute(route, handler)</h3>
<p><code>addRoute</code> allows you to specify the handler for a specific route type. Accepting a <code>route</code> string (ex: '/myposts/:post') and a function <code>handler</code>, the route is parsed based off of parameter name (<code>:post</code> for example in the route <code>/myposts/:post</code>), and the previously stored route for that route type (post) is replaced.</p>
<p>The below example uses all default routes except for the post route, and gives full control over how the request is handled. Obviously extra code is needed to specify this, but we can add arbitrary code here, for example, to do some sort of logging:</p>
<pre>
var
express = require('express'),
app = express(),
Poet = require('poet');
var poet = Poet(app);
poet.addRoute('/myposts/:post', function (req, res, next) {
var post = poet.helpers.getPost(req.params.post);
if (post) {
// Do some fancy logging here
res.render('post', { post: post });
} else {
res.send(404);
}
}).init();
</pre>
<p>For more examples on custom routing, check out the <a href="https://github.com/jsantell/poet/blob/master/examples/customRoutes.js">examples in the repository</a>.</p>
<h2 id="routing">Routing</h2>
<p>The default configuration uses the default routes with the view names below:</p>
<ul>
<li>'/post/:post': 'post'</li>
<li>'/page/:page': 'page'</li>
<li>'/tag/:tag': 'tag'</li>
<li>'/category/:category': 'category'</li>
</ul>
<p>For example, if your site root is <code>http://mysite.com</code>, going to the page <code>http://mysite.com/post/hello-world</code> will call the 'post' view in your view directory and render the appropriate post. The options passed into the instantiation of the <strong>Poet</strong> instance can have a <code>routes</code> key, with an object containing key/value pairs of strings mapping a route to a view. Based off of the paramter in the route (ex: <code>:post</code> in <code>/post/:post</code>), the previous route will be replaced.</p>
<p>For an example of customizing your route names and views, view the <a href="https://github.com/jsantell/poet/blob/master/examples/configuredSetup.js">example in the repository</a>. To override the default handlers of, check out the <code>Poet::addRoute(route, handler)</code> method.</p>
<h2 id="helpers">Helpers</h2>
<p>Built in helper methods are stored on the <strong>Poet</strong> instance's <code>helper</code> property. Used internally, and in the view locals, they can be used outside of <strong>Poet</strong> as well.</p>
<ul>
<li><code>getPosts(from, to)</code> - an array of reverse chronologically ordered post objects. May specify <code>from</code> and <code>to</code> based on their index, to limit which posts should be returned.</li>
<li><code>getTags()</code> - an array of tag names</li>
<li><code>getCategories</code> - an array of category names</li>
<li><code>tagURL(tag)</code> - a function that takes a name of a tag and returns the corresponding URL based off of the routing configuration</li>
<li><code>pageURL(page)</code> - a function that takes the number of a page and returns the corresponding URL based off of the routing configuration</li>
<li><code>categoryURL(category)</code> - a function that takes a name of a category and returns the corresponding URL based off of the routing configuration</li>
<li><code>getPostCount()</code> - a function that returns the number of total posts registered</li>
<li><code>getPost(title)</code> - a function that returns the corresponding post based off of <code>title</code></li>
<li><code>getPageCount()</code> - a function that returns the total number of pages, based off of number of posts registered and the <code>postsPerPage</code> option.</li>
<li><code>postsWithTag(tag)</code> - returns an array of posts that contain <code>tag</code></li>
<li><code>postsWithCategory(cat)</code> - returns an array of posts are in category `cat</li>
<li><code>options</code> - all of the option configurations</li>
</ul>
<h2 id="locals">Locals</h2>
<p>In addition to all of the helpers being available to each view, there are additional variables accessible inside specific views.</p>
<h3 id="post-locals">Post Locals</h3>
<ul>
<li><code>post.url</code> - the URL of the current post</li>
<li><code>post.content</code> - the content of the current post</li>
<li><code>post.preview</code> - the preview of the current post</li>
</ul>
<h3 id="page-locals">Page Locals</h3>
<ul>
<li><code>posts</code> - an array of post objects that are within the current post range</li>
<li><code>page</code> - the number of the current page</li>
</ul>
<h3 id="tag-locals">Tag Locals</h3>
<ul>
<li><code>posts</code> - an array of all post objects that contain the current tag</li>
<li><code>tag</code> - a string of the current tag's name</li>
</ul>
<h3 id="category-locals">Category Locals</h3>
<ul>
<li><code>posts</code> - an array of all post objects with the current category</li>
<li><code>category</code> - a string of the current category's name</li>
</ul>
<h2 id="additional-examples">Additional Examples</h2>
<p>Be sure to check out the examples in the repository</p>
<ul>
<li><a href="https://github.com/jsantell/poet/blob/master/examples/defaultSetup.js">Default configuration</a></li>
<li><a href="https://github.com/jsantell/poet/blob/master/examples/configuredSetup.js">Specifying some options</a></li>
<li><a href="https://github.com/jsantell/poet/blob/master/examples/customRoutes.js">Using your own custom routes</a></li>
<li><a href="https://github.com/jsantell/poet/blob/master/examples/rss.js">Setting up an RSS feed</a></li>
<li><a href="https://github.com/jsantell/poet/blob/master/examples/watcher.js">Using a watcher</a></li>
</ul>
<h2 id="get-bloggin-">Get Bloggin'!</h2>
<p>Time to start writing your sweet, beautiful words. For more development information, check out the <a href="https:
</div>
</div>
<script src="js/prettify.js"></script>
<script>
prettyPrint();
</script>
<a href="https:
</body>
</html>
|
from rest_framework.filters import (
FilterSet
)
from trialscompendium.trials.models import Treatment
class TreatmentListFilter(FilterSet):
"""
Filter query list from treatment database table
"""
class Meta:
model = Treatment
fields = {'id': ['exact', 'in'],
'no_replicate': ['exact', 'in', 'gte', 'lte'],
'nitrogen_treatment': ['iexact', 'in', 'icontains'],
'phosphate_treatment': ['iexact', 'in', 'icontains'],
'tillage_practice': ['iexact', 'in', 'icontains'],
'cropping_system': ['iexact', 'in', 'icontains'],
'crops_grown': ['iexact', 'in', 'icontains'],
'farm_yard_manure': ['iexact', 'in', 'icontains'],
'farm_residue': ['iexact', 'in', 'icontains'],
}
order_by = ['tillage_practice', 'cropping_system', 'crops_grown']
|
import React, { Component } from 'react';
class Main extends Component {
render() {
return (
<main className='Main'>
<h1 className='Main-headline'>Web solutions focused on<br/>Simplicity & Reliability.</h1>
<h2 className='Main-subhead'>Bleeding edge technology paired with amazing <em>talent</em> and <em>creativity</em>.</h2>
<a href='#' className='Main-button'>Work With Us</a>
</main>
);
}
}
export default Main;
|
<!DOCTYPE html>
<!--[if lt IE 9]><html class="no-js lt-ie9" lang="en" dir="ltr"><![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js" lang="en" dir="ltr">
<!--<![endif]-->
<!-- Usage: /eic/site/ccc-rec.nsf/tpl-eng/template-1col.html?Open&id=3 (optional: ?Open&page=filename.html&id=x) -->
<!-- Created: ; Product Code: 536; Server: stratnotes2.ic.gc.ca -->
<head>
<title>
Canada Custom Shutters Ltd. -
Complete profile - Canadian Company Capabilities - Industries and Business - Industry Canada
</title>
<!-- Title ends / Fin du titre -->
<meta charset="utf-8" />
<meta name="dcterms.language" title="ISO639-2" content="eng" />
<meta name="dcterms.title" content="" />
<meta name="description" content="" />
<meta name="dcterms.description" content="" />
<meta name="dcterms.type" content="report, data set" />
<meta name="dcterms.subject" content="businesses, industry" />
<meta name="dcterms.subject" content="businesses, industry" />
<meta name="dcterms.issued" title="W3CDTF" content="" />
<meta name="dcterms.modified" title="W3CDTF" content="" />
<meta name="keywords" content="" />
<meta name="dcterms.creator" content="" />
<meta name="author" content="" />
<meta name="dcterms.created" title="W3CDTF" content="" />
<meta name="dcterms.publisher" content="" />
<meta name="dcterms.audience" title="icaudience" content="" />
<meta name="dcterms.spatial" title="ISO3166-1" content="" />
<meta name="dcterms.spatial" title="gcgeonames" content="" />
<meta name="dcterms.format" content="HTML" />
<meta name="dcterms.identifier" title="ICsiteProduct" content="536" />
<!-- EPI-11240 -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- MCG-202 -->
<meta content="width=device-width,initial-scale=1" name="viewport">
<!-- EPI-11567 -->
<meta name = "format-detection" content = "telephone=no">
<!-- EPI-12603 -->
<meta name="robots" content="noarchive">
<!-- EPI-11190 - Webtrends -->
<script>
var startTime = new Date();
startTime = startTime.getTime();
</script>
<!--[if gte IE 9 | !IE ]><!-->
<link href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/favicon.ico" rel="icon" type="image/x-icon">
<link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/wet-boew.min.css">
<!--<![endif]-->
<link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/theme.min.css">
<!--[if lt IE 9]>
<link href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/favicon.ico" rel="shortcut icon" />
<link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/ie8-wet-boew.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/ie8-wet-boew.min.js"></script>
<![endif]
<!--[if lte IE 9]>
<![endif]
<noscript><link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/noscript.min.css" /></noscript>
<!-- Google Tag Manager DO NOT REMOVE OR MODIFY - NE PAS SUPPRIMER OU MODIFIER -->
<script>dataLayer1 = [];</script>
<!-- End Google Tag Manager -->
<!-- EPI-11235 -->
<link rel="stylesheet" href="/eic/home.nsf/css/<API key>.css">
<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
<link href="/app/ccc/srch/css/print.css" media="print" rel="stylesheet" type="text/css" />
</head>
<body class="home" vocab="http://schema.org/" typeof="WebPage">
<!-- EPIC HEADER BEGIN -->
<!-- Google Tag Manager DO NOT REMOVE OR MODIFY - NE PAS SUPPRIMER OU MODIFIER -->
<noscript><iframe title="Google Tag Manager" src="
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.<API key>(s)[0], j=d.createElement(s),dl=l!='dataLayer1'?'&l='+l:'';j.async=true;j.src='
<!-- End Google Tag Manager -->
<!-- EPI-12801 -->
<span typeof="Organization"><meta property="legalName" content="<API key>"></span>
<ul id="wb-tphp">
<li class="wb-slc">
<a class="wb-sl" href="#wb-cont">Skip to main content</a>
</li>
<li class="wb-slc visible-sm visible-md visible-lg">
<a class="wb-sl" href="#wb-info">Skip to "About this site"</a>
</li>
</ul>
<header role="banner">
<div id="wb-bnr" class="container">
<section id="wb-lng" class="visible-md visible-lg text-right">
<h2 class="wb-inv">Language selection</h2>
<div class="row">
<div class="col-md-12">
<ul class="list-inline mrgn-bttm-0">
<li><a href="nvgt.do?V_TOKEN=1492272358519&V_SEARCH.docsCount=3&V_DOCUMENT.docRank=7972&V_SEARCH.docsStart=7971&V_SEARCH.command=navigate&V_SEARCH.resultsJSP=/prfl.do&lang=fra&redirectUrl=/app/scr/imbs/ccc/rgstrtn/updt.sec?_flId?_flxKy=e1s1&estblmntNo=234567041301&profileId=61&_evId=bck&lang=eng&V_SEARCH.showStricts=false&prtl=1&_flId?_flId?_flxKy=e1s1" title="Français" lang="fr">Français</a></li>
</ul>
</div>
</div>
</section>
<div class="row">
<div class="brand col-xs-8 col-sm-9 col-md-6">
<a href="http:
</div>
<section class="wb-mb-links col-xs-4 col-sm-3 visible-sm visible-xs" id="wb-glb-mn">
<h2>Search and menus</h2>
<ul class="list-inline text-right chvrn">
<li><a href="#mb-pnl" title="Search and menus" aria-controls="mb-pnl" class="overlay-lnk" role="button"><span class="glyphicon glyphicon-search"><span class="glyphicon glyphicon-th-list"><span class="wb-inv">Search and menus</span></span></span></a></li>
</ul>
<div id="mb-pnl"></div>
</section>
<!-- Site Search Removed -->
</div>
</div>
<nav role="navigation" id="wb-sm" class="wb-menu visible-md visible-lg" data-trgt="mb-pnl" data-ajax-fetch="//cdn.canada.ca/gcweb-cdn-dev/sitemenu/sitemenu-en.html" typeof="<API key>">
<h2 class="wb-inv">Topics menu</h2>
<div class="container nvbar">
<div class="row">
<ul class="list-inline menu">
<li><a href="https:
<li><a href="http:
<li><a href="https://travel.gc.ca/">Travel</a></li>
<li><a href="https:
<li><a href="https:
<li><a href="http://healthycanadians.gc.ca/index-eng.php">Health</a></li>
<li><a href="https:
<li><a href="https:
</ul>
</div>
</div>
</nav>
<!-- EPIC BODY BEGIN -->
<nav role="navigation" id="wb-bc" class="" property="breadcrumb">
<h2 class="wb-inv">You are here:</h2>
<div class="container">
<div class="row">
<ol class="breadcrumb">
<li><a href="/eic/site/icgc.nsf/eng/home" title="Home">Home</a></li>
<li><a href="/eic/site/icgc.nsf/eng/h_07063.html" title="Industries and Business">Industries and Business</a></li>
<li><a href="/eic/site/ccc-rec.nsf/tpl-eng/../eng/home" >Canadian Company Capabilities</a></li>
</ol>
</div>
</div>
</nav>
</header>
<main id="wb-cont" role="main" property="mainContentOfPage" class="container">
<!-- End Header -->
<!-- Begin Body -->
<!-- Begin Body Title -->
<!-- End Body Title -->
<!-- Begin Body Head -->
<!-- End Body Head -->
<!-- Begin Body Content -->
<br>
<!-- Complete Profile -->
<!-- Company Information above tabbed area-->
<input id="showMore" type="hidden" value='more'/>
<input id="showLess" type="hidden" value='less'/>
<h1 id="wb-cont">
Company profile - Canadian Company Capabilities
</h1>
<div class="profileInfo hidden-print">
<ul class="list-inline">
<li><a href="cccSrch.do?lang=eng&profileId=&prtl=1&key.hitsPerPage=25&searchPage=%252Fapp%252Fccc%252Fsrch%252FcccBscSrch.do%253Flang%253Deng%2526amp%253Bprtl%253D1%2526amp%253Btagid%253D&V_SEARCH.scopeCategory=CCC.Root&V_SEARCH.depth=1&V_SEARCH.showStricts=false&V_SEARCH.sortSpec=title+asc&rstBtn.x=" class="btn btn-link">New Search</a> |</li>
<li><form name="searchForm" method="post" action="/app/ccc/srch/bscSrch.do">
<input type="hidden" name="lang" value="eng" />
<input type="hidden" name="profileId" value="" />
<input type="hidden" name="prtl" value="1" />
<input type="hidden" name="searchPage" value="%2Fapp%2Fccc%2Fsrch%2FcccBscSrch.do%3Flang%3Deng%26amp%3Bprtl%3D1%26amp%3Btagid%3D" />
<input type="hidden" name="V_SEARCH.scopeCategory" value="CCC.Root" />
<input type="hidden" name="V_SEARCH.depth" value="1" />
<input type="hidden" name="V_SEARCH.showStricts" value="false" />
<input id="repeatSearchBtn" class="btn btn-link" type="submit" value="Return to search results" />
</form></li>
<li>| <a href="nvgt.do?V_SEARCH.docsStart=7970&V_DOCUMENT.docRank=7971&V_SEARCH.docsCount=3&lang=eng&prtl=1&sbPrtl=&profile=cmpltPrfl&V_TOKEN=1492272390390&V_SEARCH.command=navigate&V_SEARCH.resultsJSP=%2fprfl.do&estblmntNo=234567090223&profileId=&key.newSearchLabel=">Previous Company</a></li>
<li>| <a href="nvgt.do?V_SEARCH.docsStart=7972&V_DOCUMENT.docRank=7973&V_SEARCH.docsCount=3&lang=eng&prtl=1&sbPrtl=&profile=cmpltPrfl&V_TOKEN=1492272390390&V_SEARCH.command=navigate&V_SEARCH.resultsJSP=%2fprfl.do&estblmntNo=234567009478&profileId=&key.newSearchLabel=">Next Company</a></li>
</ul>
</div>
<details>
<summary>Third-Party Information Liability Disclaimer</summary>
<p>Some of the information on this Web page has been provided by external sources. The Government of Canada is not responsible for the accuracy, reliability or currency of the information supplied by external sources. Users wishing to rely upon this information should consult directly with the source of the information. Content provided by external sources is not subject to official languages, privacy and accessibility requirements.</p>
</details>
<h2>
Canada Custom Shutters Ltd.
</h2>
<div class="row">
<div class="col-md-5">
<h2 class="h5 mrgn-bttm-0">Legal/Operating Name:</h2>
<p>Canada Custom Shutters Ltd.</p>
<div class="mrgn-tp-md"></div>
<p class="mrgn-bttm-0" ><a href="http:
target="_blank" title="Website URL">http:
<p><a href="mailto:goran@<API key>.com" title="goran@<API key>.com">goran@<API key>.com</a></p>
</div>
<div class="col-md-4 mrgn-sm-sm">
<h2 class="h5 mrgn-bttm-0">Mailing Address:</h2>
<address class="mrgn-bttm-md">
140 Toll Rd<br/>
HOLLAND LANDING,
Ontario<br/>
L9N 1G8
<br/>
</address>
<h2 class="h5 mrgn-bttm-0">Location Address:</h2>
<address class="mrgn-bttm-md">
140 Toll Rd<br/>
HOLLAND LANDING,
Ontario<br/>
L9N 1G8
<br/>
</address>
<p class="mrgn-bttm-0"><abbr title="Telephone">Tel.</abbr>:
(905) 953-0801
</p>
<p class="mrgn-bttm-0"><abbr title="Telephone">Tel.</abbr>:
(866) 532-5893</p>
<p class="mrgn-bttm-lg"><abbr title="Facsimile">Fax</abbr>:
(905) 953-8247</p>
</div>
<div class="col-md-3 mrgn-tp-md">
</div>
</div>
<div class="row mrgn-tp-md mrgn-bttm-md">
<div class="col-md-12">
</div>
</div>
<!-- <div class="wb-tabs ignore-session update-hash wb-eqht-off print-active"> -->
<div class="wb-tabs ignore-session">
<div class="tabpanels">
<details id="details-panel1">
<summary>
Full profile
</summary>
<!-- Tab 1 -->
<h2 class="wb-invisible">
Full profile
</h2>
<!-- Contact Information -->
<h3 class="page-header">
Contact information
</h3>
<section class="container-fluid">
<div class="row mrgn-tp-lg">
<div class="col-md-3">
<strong>
Milan
Gigic
</strong></div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Title:
</strong>
</div>
<div class="col-md-7">
<!--if client gender is not null or empty we use gender based job title
Manager
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Area of Responsibility:
</strong>
</div>
<div class="col-md-7">
Management Executive.
</div>
</div>
<div class="row mrgn-tp-lg">
<div class="col-md-3">
<strong>
Goran
Gigic
</strong></div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Title:
</strong>
</div>
<div class="col-md-7">
<!--if client gender is not null or empty we use gender based job title
Treasurer
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Telephone:
</strong>
</div>
<div class="col-md-7">
(905) 953-0801
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Facsimile:
</strong>
</div>
<div class="col-md-7">
(905) 953-8247
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Email:
</strong>
</div>
<div class="col-md-7">
goran@<API key>.com
</div>
</div>
</section>
<p class="mrgn-tp-lg text-right small hidden-print">
<a href="#wb-cont">top of page</a>
</p>
<!-- Company Description -->
<h3 class="page-header">
Company description
</h3>
<section class="container-fluid">
<div class="row">
<div class="col-md-5">
<strong>
Country of Ownership:
</strong>
</div>
<div class="col-md-7">
Canada
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Year Established:
</strong>
</div>
<div class="col-md-7">
1987
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Exporting:
</strong>
</div>
<div class="col-md-7">
Yes
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Primary Industry (NAICS):
</strong>
</div>
<div class="col-md-7">
321919 - Other Millwork
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Primary Business Activity:
</strong>
</div>
<div class="col-md-7">
Manufacturer / Processor / Producer
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Total Sales ($CDN):
</strong>
</div>
<div class="col-md-7">
$1,000,000 to $4,999,999
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Export Sales ($CDN):
</strong>
</div>
<div class="col-md-7">
$1 to $99,999
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Number of Employees:
</strong>
</div>
<div class="col-md-7">
20
</div>
</div>
</section>
<!-- Products / Services / Licensing -->
<h3 class="page-header">
Product / Service / Licensing
</h3>
<section class="container-fluid">
<div class="row mrgn-bttm-md">
<div class="col-md-3">
<strong>
Product Name:
</strong>
</div>
<div class="col-md-9">
SHUTTERS, WOODEN <br>
</div>
</div>
</section>
<p class="mrgn-tp-lg text-right small hidden-print">
<a href="#wb-cont">top of page</a>
</p>
<!-- Technology Profile -->
<!-- Market Profile -->
<h3 class="page-header">
Market profile
</h3>
<section class="container-fluid">
<h4>
Geographic markets:
</h4>
<h5>
Export experience:
</h5>
<ul>
<li>United States</li>
</ul>
</section>
<p class="mrgn-tp-lg text-right small hidden-print">
<a href="#wb-cont">top of page</a>
</p>
<!-- Sector Information -->
<details class="mrgn-tp-md mrgn-bttm-md">
<summary>
Third-Party Information Liability Disclaimer
</summary>
<p>
Some of the information on this Web page has been provided by external sources. The Government of Canada is not responsible for the accuracy, reliability or currency of the information supplied by external sources. Users wishing to rely upon this information should consult directly with the source of the information. Content provided by external sources is not subject to official languages, privacy and accessibility requirements.
</p>
</details>
</details>
<details id="details-panel2">
<summary>
Contacts
</summary>
<h2 class="wb-invisible">
Contact information
</h2>
<!-- Contact Information -->
<section class="container-fluid">
<div class="row mrgn-tp-lg">
<div class="col-md-3">
<strong>
Milan
Gigic
</strong></div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Title:
</strong>
</div>
<div class="col-md-7">
<!--if client gender is not null or empty we use gender based job title
Manager
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Area of Responsibility:
</strong>
</div>
<div class="col-md-7">
Management Executive.
</div>
</div>
<div class="row mrgn-tp-lg">
<div class="col-md-3">
<strong>
Goran
Gigic
</strong></div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Title:
</strong>
</div>
<div class="col-md-7">
<!--if client gender is not null or empty we use gender based job title
Treasurer
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Telephone:
</strong>
</div>
<div class="col-md-7">
(905) 953-0801
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Facsimile:
</strong>
</div>
<div class="col-md-7">
(905) 953-8247
</div>
</div>
<div class="row mrgn-lft-md">
<div class="col-md-5">
<strong>
Email:
</strong>
</div>
<div class="col-md-7">
goran@<API key>.com
</div>
</div>
</section>
</details>
<details id="details-panel3">
<summary>
Description
</summary>
<h2 class="wb-invisible">
Company description
</h2>
<section class="container-fluid">
<div class="row">
<div class="col-md-5">
<strong>
Country of Ownership:
</strong>
</div>
<div class="col-md-7">
Canada
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Year Established:
</strong>
</div>
<div class="col-md-7">
1987
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Exporting:
</strong>
</div>
<div class="col-md-7">
Yes
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Primary Industry (NAICS):
</strong>
</div>
<div class="col-md-7">
321919 - Other Millwork
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Primary Business Activity:
</strong>
</div>
<div class="col-md-7">
Manufacturer / Processor / Producer
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Total Sales ($CDN):
</strong>
</div>
<div class="col-md-7">
$1,000,000 to $4,999,999
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Export Sales ($CDN):
</strong>
</div>
<div class="col-md-7">
$1 to $99,999
</div>
</div>
<div class="row">
<div class="col-md-5">
<strong>
Number of Employees:
</strong>
</div>
<div class="col-md-7">
20
</div>
</div>
</section>
</details>
<details id="details-panel4">
<summary>
Products, services and licensing
</summary>
<h2 class="wb-invisible">
Product / Service / Licensing
</h2>
<section class="container-fluid">
<div class="row mrgn-bttm-md">
<div class="col-md-3">
<strong>
Product Name:
</strong>
</div>
<div class="col-md-9">
SHUTTERS, WOODEN <br>
</div>
</div>
</section>
</details>
<details id="details-panel6">
<summary>
Market
</summary>
<h2 class="wb-invisible">
Market profile
</h2>
<section class="container-fluid">
<h4>
Geographic markets:
</h4>
<h5>
Export experience:
</h5>
<ul>
<li>United States</li>
</ul>
</section>
</details>
</div>
</div>
<div class="row">
<div class="col-md-12 text-right">
Last Update Date 2017-03-06
</div>
</div>
<!
- Artifact ID: CBW - IMBS - CCC Search WAR
- Group ID: ca.gc.ic.strategis.imbs.ccc.search
- Version: 3.26
- Built-By: bamboo
- Build Timestamp: 2017-03-02T21:29:28Z
<!-- End Body Content -->
<!-- Begin Body Foot -->
<!-- End Body Foot -->
<!-- END MAIN TABLE -->
<!-- End body -->
<!-- Begin footer -->
<div class="row pagedetails">
<div class="col-sm-5 col-xs-12 datemod">
<dl id="wb-dtmd">
<dt class=" hidden-print">Date Modified:</dt>
<dd class=" hidden-print">
<span><time>2017-03-02</time></span>
</dd>
</dl>
</div>
<div class="clear visible-xs"></div>
<div class="col-sm-4 col-xs-6">
</div>
<div class="col-sm-3 col-xs-6 text-right">
</div>
<div class="clear visible-xs"></div>
</div>
</main>
<footer role="contentinfo" id="wb-info">
<nav role="navigation" class="container wb-navcurr">
<h2 class="wb-inv">About government</h2>
<!-- EPIC FOOTER BEGIN -->
<!-- EPI-11638 Contact us -->
<ul class="list-unstyled colcount-sm-2 colcount-md-3">
<li><a href="http://www.ic.gc.ca/eic/site/icgc.nsf/eng/h_07026.html#pageid=E048-H00000&from=Industries">Contact us</a></li>
<li><a href="https:
<li><a href="https:
<li><a href="https:
<li><a href="https:
<li><a href="https:
<li><a href="http://pm.gc.ca/eng">Prime Minister</a></li>
<li><a href="https:
<li><a href="http://open.canada.ca/en/">Open government</a></li>
</ul>
</nav>
<div class="brand">
<div class="container">
<div class="row">
<nav class="col-md-10 ftr-urlt-lnk">
<h2 class="wb-inv">About this site</h2>
<ul>
<li><a href="https:
<li><a href="https:
<li><a href="http://www1.canada.ca/en/newsite.html">About Canada.ca</a></li>
<li><a href="http:
<li><a href="http://www.ic.gc.ca/eic/site/icgc.nsf/eng/h_07033.html#p1">Privacy</a></li>
</ul>
</nav>
<div class="col-xs-6 visible-sm visible-xs tofpg">
<a href="#wb-cont">Top of Page <span class="glyphicon <API key>"></span></a>
</div>
<div class="col-xs-6 col-md-2 text-right">
<object type="image/svg+xml" tabindex="-1" role="img" data="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/wmms-blk.svg" aria-label="Symbol of the Government of Canada"></object>
</div>
</div>
</div>
</div>
</footer>
<!--[if gte IE 9 | !IE ]><!-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/wet-boew.min.js"></script>
<!--<![endif]-->
<!--[if lt IE 9]>
<script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/ie8-wet-boew2.min.js"></script>
<![endif]
<script src="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/js/theme.min.js"></script>
<!-- EPI-10519 -->
<span class="wb-sessto"
data-wb-sessto='{"inactivity": 1800000, "reactionTime": 180000, "sessionalive": 1800000, "logouturl": "/app/ccc/srch/cccSrch.do?lang=eng&prtl=1"}'></span>
<script src="/eic/home.nsf/js/jQuery.<API key>.js"></script>
<!-- EPI-11190 - Webtrends -->
<script src="/eic/home.nsf/js/webtrends.js"></script>
<script>var endTime = new Date();</script>
<noscript>
<div><img alt="" id="DCSIMG" width="1" height="1" src="
</noscript>
<!-- /Webtrends -->
<!-- JS deps -->
<script src="/eic/home.nsf/js/jquery.imagesloaded.js"></script>
<!-- EPI-11262 - Util JS -->
<script src="/eic/home.nsf/js/<API key>.min.js"></script>
<!-- EPI-11383 -->
<script src="/eic/home.nsf/js/jQuery.icValidationErrors.js"></script>
<span style="display:none;" id='app-info' <API key>='' <API key>='' <API key>='' <API key>='' data-issue-tracking='' data-scm-sha1='' <API key>='' data-scm-branch='' <API key>=''></span>
</body></html>
<!-- End Footer -->
<!
- Artifact ID: CBW - IMBS - CCC Search WAR
- Group ID: ca.gc.ic.strategis.imbs.ccc.search
- Version: 3.26
- Built-By: bamboo
- Build Timestamp: 2017-03-02T21:29:28Z
|
// SwiftMan.h
// SwiftMan
#import "TargetConditionals.h"
#if TARGET_OS_IPHONE
#import <UIKit/UIKit.h>
#elif TARGET_OS_MAC
#import <Cocoa/Cocoa.h>
#elif TARGET_OS_WATCH
#import <WatchKit/WatchKit.h>
#endif
//! Project version number for SwiftMan.
FOUNDATION_EXPORT double <API key>;
//! Project version string for SwiftMan.
FOUNDATION_EXPORT const unsigned char <API key>[];
// In this header, you should import all the public headers of your framework using statements like #import <SwiftMan/PublicHeader.h>
|
#include "board.h"
#include <stdint.h>
#include <string.h>
#include "usbd_rom_api.h"
#include "hid_keyboard.h"
#include "ms_timer.h"
/**
* @brief Structure to hold Keyboard data
*/
typedef struct {
USBD_HANDLE_T hUsb; /*!< Handle to USB stack. */
uint8_t report[<API key>]; /*!< Last report data */
uint8_t tx_busy; /*!< Flag indicating whether a report is pending in endpoint queue. */
ms_timer_t tmo; /*!< Timer to track when to send next report. */
} Keyboard_Ctrl_T;
/** Singleton instance of Keyboard control */
static Keyboard_Ctrl_T g_keyBoard;
extern const uint8_t <API key>[];
extern const uint16_t <API key>;
/* Routine to update keyboard state */
static void <API key>(void)
{
uint8_t joystick_status = Joystick_GetStatus();
<API key>(&g_keyBoard.report[0]);
switch (joystick_status) {
case JOY_PRESS:
<API key>(g_keyBoard.report, 0x53);
break;
case JOY_LEFT:
<API key>(g_keyBoard.report, 0x5C);
break;
case JOY_RIGHT:
<API key>(g_keyBoard.report, 0x5E);
break;
case JOY_UP:
<API key>(g_keyBoard.report, 0x60);
break;
case JOY_DOWN:
<API key>(g_keyBoard.report, 0x5A);
break;
}
}
/* HID Get Report Request Callback. Called automatically on HID Get Report Request */
static ErrorCode_t Keyboard_GetReport(USBD_HANDLE_T hHid,
USB_SETUP_PACKET *pSetup,
uint8_t * *pBuffer,
uint16_t *plength)
{
/* ReportID = SetupPacket.wValue.WB.L; */
switch (pSetup->wValue.WB.H) {
case HID_REPORT_INPUT:
<API key>();
memcpy(*pBuffer, &g_keyBoard.report[0], <API key>);
*plength = <API key>;
break;
case HID_REPORT_OUTPUT: /* Not Supported */
case HID_REPORT_FEATURE: /* Not Supported */
return ERR_USBD_STALL;
}
return LPC_OK;
}
/* HID Set Report Request Callback. Called automatically on HID Set Report Request */
static ErrorCode_t Keyboard_SetReport(USBD_HANDLE_T hHid, USB_SETUP_PACKET *pSetup, uint8_t * *pBuffer, uint16_t length)
{
/* we will reuse standard EP0Buf */
if (length == 0) {
return LPC_OK;
}
/* ReportID = SetupPacket.wValue.WB.L; */
switch (pSetup->wValue.WB.H) {
case HID_REPORT_OUTPUT:
/* If the USB host tells us to turn on the NUM LOCK LED,
* then turn on LED#2.
*/
if (**pBuffer & 0x01) {
Board_LED_Set(0, 1);
}
else {
Board_LED_Set(0, 0);
}
break;
case HID_REPORT_INPUT: /* Not Supported */
case HID_REPORT_FEATURE: /* Not Supported */
return ERR_USBD_STALL;
}
return LPC_OK;
}
/* HID interrupt IN endpoint handler */
static ErrorCode_t Keyboard_EpIN_Hdlr(USBD_HANDLE_T hUsb, void *data, uint32_t event)
{
switch (event) {
case USB_EVT_IN:
g_keyBoard.tx_busy = 0;
break;
}
return LPC_OK;
}
/* HID keyboard init routine */
ErrorCode_t Keyboard_init(USBD_HANDLE_T hUsb,
<API key> *pIntfDesc,
uint32_t *mem_base,
uint32_t *mem_size)
{
<API key> hid_param;
USB_HID_REPORT_T reports_data[1];
ErrorCode_t ret = LPC_OK;
/* Do a quick check of if the interface descriptor passed is the right one. */
if ((pIntfDesc == 0) || (pIntfDesc->bInterfaceClass != <API key>)) {
return ERR_FAILED;
}
/* init joystick control */
Board_Joystick_Init();
/* Init HID params */
memset((void *) &hid_param, 0, sizeof(<API key>));
hid_param.max_reports = 1;
hid_param.mem_base = *mem_base;
hid_param.mem_size = *mem_size;
hid_param.intf_desc = (uint8_t *) pIntfDesc;
/* user defined functions */
hid_param.HID_GetReport = Keyboard_GetReport;
hid_param.HID_SetReport = Keyboard_SetReport;
hid_param.HID_EpIn_Hdlr = Keyboard_EpIN_Hdlr;
/* Init reports_data */
reports_data[0].len = <API key>;
reports_data[0].idle_time = 0;
reports_data[0].desc = (uint8_t *) &<API key>[0];
hid_param.report_data = reports_data;
ret = USBD_API->hid->init(hUsb, &hid_param);
/* update memory variables */
*mem_base = hid_param.mem_base;
*mem_size = hid_param.mem_size;
/* store stack handle for later use. */
g_keyBoard.hUsb = hUsb;
/* start the mouse timer */
ms_timerInit(&g_keyBoard.tmo, <API key>);
return ret;
}
/* Keyboard tasks */
void Keyboard_Tasks(void)
{
/* check if moue report timer expired */
if (ms_timerExpired(&g_keyBoard.tmo)) {
/* reset timer */
ms_timerStart(&g_keyBoard.tmo);
/* check device is configured before sending report. */
if ( USB_IsConfigured(g_keyBoard.hUsb)) {
/* update report based on board state */
<API key>();
/* send report data */
if (g_keyBoard.tx_busy == 0) {
g_keyBoard.tx_busy = 1;
USBD_API->hw->WriteEP(g_keyBoard.hUsb, HID_EP_IN, &g_keyBoard.report[0], <API key>);
}
}
}
}
|
'use strict';
angular.module('main', ['ngRoute', 'ngResource', 'ui.route', 'main.system', 'main.index', 'main.events']);
angular.module('main.system', []);
angular.module('main.index', []);
angular.module('main.events', []);
'use strict';
//Setting HTML5 Location Mode
angular.module('main').config(['$locationProvider',
function ($locationProvider) {
$locationProvider.hashPrefix('!');
}
]);
'use strict';
angular.module('main.system')
.factory('Global', [
function () {
var obj = this;
obj._data = {
app: window.app || false
};
return obj._data;
}
]);
'use strict';
angular.element(document).ready(function() {
//Fixing facebook bug with redirect
if (window.location.hash === '#_=_') window.location.hash = '#!';
//Then init the app
angular.bootstrap(document, ['main']);
});
'use strict';
angular.module('main').config(['$routeProvider',
function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: '/views/index.html'
})
.otherwise({
redirectTo: '/'
});
}
]);
'use strict';
angular.module('main.index')
.controller('IndexCtrl', ['$scope', '$routeParams', '$http', '$location', 'Global', 'Event',
function ($scope, $routeParams, $http, $location, Global, Event) {
$scope.global = Global;
$scope.getEvents = function(){
Event.query(function(data){
$scope.events = data;
});
};
$scope.init = function(){
$scope.getEvents();
};
}
]);
'use strict';
angular.module('main.events')
.factory('Event', [
'$resource',
function ($resource) {
return $resource("/api/events/:id");
}
]);
|
/**
* StaticText.js
* Text that cannot be changed after loaded by the game
*/
import GamePiece from './GamePiece.js';
import Info from './Info.js';
import Text from './Text.js';
export default class StaticText extends Text {
constructor (config) {
super(config);
this.static = true;
}
}
|
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_101) on Mon Sep 19 15:00:46 UTC 2016 -->
<title>org.springframework.oxm.xmlbeans Class Hierarchy (Spring Framework 4.3.3.RELEASE API)</title><script>var _hmt = _hmt || [];(function() {var hm = document.createElement("script");hm.src = "//hm.baidu.com/hm.js?<API key>";var s = document.<API key>("script")[0];s.parentNode.insertBefore(hm, s);})();</script>
<meta name="date" content="2016-09-19">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="org.springframework.oxm.xmlbeans Class Hierarchy (Spring Framework 4.3.3.RELEASE API)";
}
}
catch(err) {
}
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="topNav"><a name="navbar.top">
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Spring Framework</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/springframework/oxm/support/package-tree.html">Prev</a></li>
<li><a href="../../../../org/springframework/oxm/xstream/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/springframework/oxm/xmlbeans/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip.navbar.top">
</a></div>
<div class="header">
<h1 class="title">Hierarchy For Package org.springframework.oxm.xmlbeans</h1>
<span class="<API key>">Package Hierarchies:</span>
<ul class="horizontal">
<li><a href="../../../../overview-tree.html">All Packages</a></li>
</ul>
</div>
<div class="contentContainer">
<h2 title="Class Hierarchy">Class Hierarchy</h2>
<ul>
<li type="circle">java.lang.<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">Object</span></a>
<ul>
<li type="circle">org.springframework.oxm.support.<a href="../../../../org/springframework/oxm/support/AbstractMarshaller.html" title="class in org.springframework.oxm.support"><span class="typeNameLink">AbstractMarshaller</span></a> (implements org.springframework.oxm.<a href="../../../../org/springframework/oxm/Marshaller.html" title="interface in org.springframework.oxm">Marshaller</a>, org.springframework.oxm.<a href="../../../../org/springframework/oxm/Unmarshaller.html" title="interface in org.springframework.oxm">Unmarshaller</a>)
<ul>
<li type="circle">org.springframework.oxm.xmlbeans.<a href="../../../../org/springframework/oxm/xmlbeans/XmlBeansMarshaller.html" title="class in org.springframework.oxm.xmlbeans"><span class="typeNameLink">XmlBeansMarshaller</span></a></li>
</ul>
</li>
<li type="circle">org.springframework.oxm.xmlbeans.<a href="../../../../org/springframework/oxm/xmlbeans/<API key>.html" title="class in org.springframework.oxm.xmlbeans"><span class="typeNameLink"><API key></span></a> (implements org.springframework.beans.factory.<a href="../../../../org/springframework/beans/factory/FactoryBean.html" title="interface in org.springframework.beans.factory">FactoryBean</a><T>)</li>
</ul>
</li>
</ul>
</div>
<div class="bottomNav"><a name="navbar.bottom">
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Spring Framework</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/springframework/oxm/support/package-tree.html">Prev</a></li>
<li><a href="../../../../org/springframework/oxm/xstream/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/springframework/oxm/xmlbeans/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip.navbar.bottom">
</a></div>
</body>
</html>
|
<?php
declare(strict_types=1);
namespace ApiPlatform\Core\Tests\Metadata\Property\Factory;
use ApiPlatform\Core\Metadata\Property\Factory\<API key>;
use ApiPlatform\Core\Metadata\Property\Factory\<API key>;
use ApiPlatform\Core\Metadata\Property\<API key>;
use ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity\Dummy;
use ApiPlatform\Core\Tests\ProphecyTrait;
use PHPUnit\Framework\TestCase;
use Psr\Cache\CacheException;
use Psr\Cache\CacheItemInterface;
use Psr\Cache\<API key>;
/**
* @author Baptiste Meyer <baptiste.meyer@gmail.com>
*/
class <API key> extends TestCase
{
use ProphecyTrait;
public function <API key>()
{
$cacheItem = $this->prophesize(CacheItemInterface::class);
$cacheItem->isHit()->willReturn(true)->shouldBeCalled();
$cacheItem->get()->willReturn(new <API key>(['id', 'name', 'description', 'dummy']))->shouldBeCalled();
$cacheItemPool = $this->prophesize(<API key>::class);
$cacheItemPool->getItem($this->generateCacheKey())->willReturn($cacheItem->reveal())->shouldBeCalled();
$<API key> = $this->prophesize(<API key>::class);
$<API key> = new <API key>($cacheItemPool->reveal(), $<API key>->reveal());
$<API key> = $<API key>->create(Dummy::class);
$expectedResult = new <API key>(['id', 'name', 'description', 'dummy']);
$this->assertEquals($expectedResult, $<API key>);
$this->assertEquals($expectedResult, $<API key>->create(Dummy::class), 'Trigger the local cache');
}
public function <API key>()
{
$<API key> = new <API key>(['id', 'name', 'description', 'dummy']);
$<API key> = $this->prophesize(<API key>::class);
$<API key>->create(Dummy::class, [])->willReturn($<API key>)->shouldBeCalled();
$cacheItem = $this->prophesize(CacheItemInterface::class);
$cacheItem->isHit()->willReturn(false)->shouldBeCalled();
$cacheItem->set($<API key>)->willReturn($cacheItem->reveal())->shouldBeCalled();
$cacheItemPool = $this->prophesize(<API key>::class);
$cacheItemPool->getItem($this->generateCacheKey())->willReturn($cacheItem->reveal())->shouldBeCalled();
$cacheItemPool->save($cacheItem->reveal())->willReturn(true)->shouldBeCalled();
$<API key> = new <API key>($cacheItemPool->reveal(), $<API key>->reveal());
$<API key> = $<API key>->create(Dummy::class);
$expectedResult = new <API key>(['id', 'name', 'description', 'dummy']);
$this->assertEquals($expectedResult, $<API key>);
$this->assertEquals($expectedResult, $<API key>->create(Dummy::class), 'Trigger the local cache');
}
public function <API key>()
{
$<API key> = $this->prophesize(<API key>::class);
$<API key>->create(Dummy::class, [])->willReturn(new <API key>(['id', 'name', 'description', 'dummy']))->shouldBeCalled();
$cacheException = new class() extends \Exception implements CacheException {};
$cacheItemPool = $this->prophesize(<API key>::class);
$cacheItemPool->getItem($this->generateCacheKey())->willThrow($cacheException)->shouldBeCalled();
$<API key> = new <API key>($cacheItemPool->reveal(), $<API key>->reveal());
$<API key> = $<API key>->create(Dummy::class);
$expectedResult = new <API key>(['id', 'name', 'description', 'dummy']);
$this->assertEquals($expectedResult, $<API key>);
$this->assertEquals($expectedResult, $<API key>->create(Dummy::class), 'Trigger the local cache');
}
private function generateCacheKey(string $resourceClass = Dummy::class, array $options = [])
{
return <API key>::CACHE_KEY_PREFIX.md5(serialize([$resourceClass, $options]));
}
}
|
<?php
namespace Tests\Behat\Mink;
use Behat\Mink\Session;
/**
* @group unittest
*/
class SessionTest extends \<API key>
{
private $driver;
private $selectorsHandler;
private $session;
protected function setUp()
{
$this->driver = $this->getMockBuilder('Behat\Mink\Driver\DriverInterface')->getMock();
$this->selectorsHandler = $this->getMockBuilder('Behat\Mink\Selector\SelectorsHandler')->getMock();
$this->session = new Session($this->driver, $this->selectorsHandler);
}
public function testGetDriver()
{
$this->assertSame($this->driver, $this->session->getDriver());
}
public function testGetPage()
{
$this->assertInstanceOf('Behat\Mink\Element\DocumentElement', $this->session->getPage());
}
public function <API key>()
{
$this->assertSame($this->selectorsHandler, $this->session->getSelectorsHandler());
}
public function testVisit()
{
$this->driver
->expects($this->once())
->method('visit')
->with($url = 'some_url');
$this->session->visit($url);
}
public function testReset()
{
$this->driver
->expects($this->once())
->method('reset');
$this->session->reset();
}
public function <API key>()
{
$this->driver
->expects($this->once())
->method('getResponseHeaders')
->will($this->returnValue($ret = array(2, 3, 4)));
$this->assertEquals($ret, $this->session->getResponseHeaders());
}
public function testGetStatusCode()
{
$this->driver
->expects($this->once())
->method('getStatusCode')
->will($this->returnValue($ret = 404));
$this->assertEquals($ret, $this->session->getStatusCode());
}
public function testGetCurrentUrl()
{
$this->driver
->expects($this->once())
->method('getCurrentUrl')
->will($this->returnValue($ret = 'http://some.url'));
$this->assertEquals($ret, $this->session->getCurrentUrl());
}
public function testExecuteScript()
{
$this->driver
->expects($this->once())
->method('executeScript')
->with($arg = 'JS');
$this->session->executeScript($arg);
}
public function testEvaluateScript()
{
$this->driver
->expects($this->once())
->method('evaluateScript')
->with($arg = 'JS func')
->will($this->returnValue($ret = '23'));
$this->assertEquals($ret, $this->session->evaluateScript($arg));
}
public function testWait()
{
$this->driver
->expects($this->once())
->method('wait')
->with(1000, 'function() {}');
$this->session->wait(1000, 'function() {}');
}
}
|
<?php
namespace DuxCms\Model;
use Think\Model;
class FieldDataModel extends Model {
public function setTable($name) {
$this->trueTableName = $this->tablePrefix.'ext_'.$name;
}
/**
*
* @return array
*/
public function loadList($where,$limit = 0,$order='data_id DESC'){
return $this->where($where)->limit($limit)->order($order)->select();
}
/**
*
* @return array
*/
public function countList($where){
return $this->where($where)->count();
}
/**
*
* @param int $dataId ID
* @return array
*/
public function getInfo($dataId)
{
$map = array();
$map['data_id'] = $dataId;
return $this->where($map)->find();
}
/**
*
* @param string $type
* @param array $fieldsetInfo
* @param bool $prefix POST
* @return bool
*/
public function saveData($type = 'add' , $fieldsetInfo){
$fieldList=D('DuxCms/Field')->loadList('fieldset_id='.$fieldsetInfo['fieldset_id']);
if(empty($fieldList)||!is_array($fieldList)){
return;
}
$valiRules = array();
$autoRules = array();
$data = array();
foreach ($fieldList as $value) {
$data[$value['field']] = I('Fieldset_'.$value['field']);
$verify_data = base64_decode($value['verify_data']);
if($verify_data){
$valiRules[] = array($value['field'], $verify_data ,$value['errormsg'],$value['verify_condition'],$value['verify_type'],3);
}
$autoRules[] = array($value['field'],'formatField',3,'callback',array($value['field'],$value['type']));
}
$data = $this->auto($autoRules)->validate($valiRules)->create($data);
if(!$data){
return false;
}
if($type == 'add'){
$this->tableName = $this->tableName;
return $this->add($data);
}
if($type == 'edit'){
$data['data_id'] = I('post.data_id');
if(empty($data['data_id'])){
return false;
}
$status = $this->where('data_id='.$data['data_id'])->save();
if($status === false){
return false;
}
return true;
}
return false;
}
/**
*
* @param int $dataId ID
* @return bool
*/
public function delData($dataId)
{
$map = array();
$map['data_id'] = $dataId;
return $this->where($map)->delete();
}
/**
*
* @param string $field
* @param int $type
* @return
*/
public function formatField($field,$type)
{
$data = $_POST['Fieldset_'.$field];
switch ($type) {
case '2':
case '3':
return $data;
break;
case '6':
$fileData=array();
if(is_array($data)){
foreach ($data['url'] as $key => $value) {
$fileData[$key]['url'] = $value;
$fileData[$key]['title'] = $data['title'][$key];
}
return serialize($fileData);
}
break;
case '7':
case '8':
return intval($data);
break;
case '10':
if(!empty($data)){
return strtotime($data);
}else{
return time();
}
break;
case '9':
if(!empty($data)&&is_array($data)){
return implode(',',$data);
}
break;
default:
return I('post.Fieldset_'.$field);
break;
}
}
/**
*
* @param string $field
* @param int $type
* @param int $type
* @return
*/
public function revertField($data,$type,$config)
{
switch ($type) {
case '6':
if(empty($data)){
return ;
}
$list=unserialize($data);
return $list;
break;
case '7':
case '8':
if(empty($config)){
return $data;
}
$list = explode(",",trim($config));
$data = array();
$i = 0;
foreach ($list as $value) {
$i++;
$data[$i] = $value;
}
return array(
'list' => $data,
'value' => intval($data),
);
break;
case '9':
if(empty($config)){
return $data;
}
$list = explode(",",trim($config));
$data = array();
$i = 0;
foreach ($list as $value) {
$i++;
$data[$i] = $value;
}
return array(
'list' => $data,
'value' => explode(",",trim($data)),
);
break;
case '11':
return number_format($data,2);
break;
default:
return html_out($data);
break;
}
}
/**
*
* @param int $type
* @return array
*/
public function showListField($data,$type,$config)
{
switch ($type) {
case '5':
if($data){
return '<img name="" src="'.$data.'" alt="" style="max-width:170px; max-height:90px;" />';
}else{
return '';
}
break;
case '6':
if(empty($data)){
return '';
}
$list=unserialize($data);
$html='';
if(!empty($list)){
foreach ($list as $key => $value) {
$html.=$value['url'].'<br>';
}
}
return $html;
break;
case '7':
case '8':
if(empty($config)){
return $data;
}
$list=explode(",",trim($config));
foreach ($list as $key => $vo) {
if($data==intval($key)+1){
return $vo;
}
}
break;
case '9':
if(empty($config)){
return $data;
}
$list = explode(",",trim($config));
$newList = array();
$i = 0;
foreach ($list as $value) {
$i++;
$newList[$i] = $value;
}
$data = explode(",",trim($data));
$html='';
foreach ($data as $key => $vo) {
$html.=' '.$newList[$vo].' |';
}
return substr($html,0,-1);
break;
case '10':
return date('Y-m-d H:i:s',$data);
break;
case '11':
return number_format($data,2);
break;
default:
return $data;
break;
}
}
}
|
# Install on Laravel Forge
1. Disable nginx with `sudo update-rc.d -f nginx disable`
2. Create a new site for your blog, and install this Git Repository
3. Execute `npm install --production` in `/home/forge/{<API key>}`.
4. Reboot your server
5. Add a daenom for the root user that executes `npm start /home/forge/{<API key>} --production`
6. Update your deploy script to look like this:
cd /home/forge/{<API key>}
git pull origin master
npm install --production
forge daemon:restart {YOUR_DAEMON_ID}
7. Ta da!
|
import os
from django.core.wsgi import <API key>
os.environ.setdefault("<API key>", "Carkinos.settings")
application = <API key>()
|
# Smallest Integer
# I worked on this challenge by myself.
# smallest_integer is a method that takes an array of integers as its input
# and returns the smallest integer in the array
# +list_of_nums+ is an array of integers
# smallest_integer(list_of_nums) should return the smallest integer in +list_of_nums+
# If +list_of_nums+ is empty the method should return nil
# Your Solution Below
def smallest_integer(list_of_nums)
if list_of_nums == []
return nil
else
smallest = list_of_nums[0]
list_of_nums.each do |num|
if num < smallest
smallest = num
end
end
return smallest
end
end
def smallest_integer(list_of_nums)
if list_of_nums.empty?
return nil
else
list_of_nums.sort[0]
end
end
|
require_relative 'spec_helper'
include LanguageSwitcher
I18n.available_locales = [:pt, :en]
describe "LanguageSwitcher" do
it "should be able to switch to a language" do
language(:pt){ I18n.locale.should == :pt }
language(:en){ I18n.locale.should == :en }
end
it "should not be able to switch to a language unless it is included in I18n.default_locales" do
lambda { language(:es) }.should raise_error
end
it "should pass thought each locale in I18n in order" do
i = 0
each_language do |l|
I18n.locale.should == I18n.available_locales[i]
I18n.locale.should == l
i+=1
end
end
# TODO: Add language_switcher view specs
end
|
import React from 'react';
import { string, node } from 'prop-types';
import classNames from 'classnames';
const TileAction = ({ children, className, ...rest }) => {
return (
<div className={classNames('tile-action', className)} {...rest}>
{children}
</div>
);
};
/**
* TileAction property types.
*/
TileAction.propTypes = {
className: string,
children: node
};
/**
* TileAction default properties.
*/
TileAction.defaultProps = {};
export default TileAction;
|
<?php
namespace tigrov\country;
/**
* This is the model class for table "city_translation".
*
* @property integer $geoname_id
* @property string $language_code
* @property string $value
*/
class CityTranslation extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return '{{%city_translation}}';
}
}
|
package com.mvas.webproxy.portals;
import com.mvas.webproxy.<API key>;
import com.mvas.webproxy.RequestData;
import com.mvas.webproxy.WebServer;
import com.mvas.webproxy.config.PortalConfiguration;
import org.apache.commons.io.IOUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.<API key>;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class <API key> implements <API key> {
private static final Logger logger = LoggerFactory.getLogger(<API key>.class);
public static final String GET_PARAM_DEVICE_ID = "device_id";
public static final String <API key> = "device_id2";
public static final String GET_PARAM_SIGNATURE = "signature";
public static final String GET_PARAM_SESSION = "session";
public static final String CONFIG_PORTAL_URL = "portal";
public static final String <API key> = "mac";
public static final String ACTION_HANDSHAKE = "action=handshake";
Pattern cookiePattern = Pattern.compile(".*mac=(([0-9A-F]{2}[:-]){5}([0-9A-F]{2})).*");
Pattern handshakePattern = Pattern.compile(ACTION_HANDSHAKE);
public static final String <API key> = "Authorization";
public static final class HeadersList {
public HashMap<String, String> getList() {
return list;
}
private HashMap<String, String> list = new HashMap<>();
}
public static final class ParamsList {
public HashMap<String, String> getList() {
return list;
}
private HashMap<String, String> list = new HashMap<>();
}
public HashMap<String, HeadersList> staticHeadersForMac = new HashMap<>();
public HashMap<String, ParamsList> staticParamsForMac = new HashMap<>();
<API key> <API key>;
static HashMap<String, Pattern> replacements = new HashMap<>();
static String[] configOptions;
static String[] getParamNames;
static {
getParamNames = new String[] {
GET_PARAM_DEVICE_ID, <API key>, GET_PARAM_SIGNATURE, GET_PARAM_SESSION
};
for (String name : getParamNames) {
replacements.put(name, Pattern.compile("([\\?&])?(" + name + ")=([a-zA-Z0-9/+]*)"));
}
configOptions = new String[] {
GET_PARAM_DEVICE_ID, <API key>, GET_PARAM_SIGNATURE, GET_PARAM_SESSION, CONFIG_PORTAL_URL, <API key>
};
}
private HeadersList <API key>(final RequestData requestData)
{
return staticHeadersForMac.get(requestData.getMacAddress());
}
private ParamsList getParamsForRequest(final RequestData requestData)
{
return staticParamsForMac.get(requestData.getMacAddress());
}
public <API key>(<API key> <API key>)
{
this.<API key> = <API key>;
}
@Override
public String getURL(final RequestData requestData) {
logger.debug("<API key>::getURL()");
String result = requestData.getRealUrl().toString();
HashMap<String, String> staticParams = getParamsForRequest(requestData).getList();
for(Map.Entry<String, Pattern> entry: replacements.entrySet())
{
Matcher matcher = entry.getValue().matcher(result);
if(matcher.find())
{
String name = matcher.group(2);
if(staticParams.get(name) == null)
{
String value = matcher.group(3);
staticParams.put(name, value);
logger.debug("set static param [" + name + "] to [" + value + "]");
if(name.equals(GET_PARAM_DEVICE_ID))
WebServer.<API key>().set(requestData.getConnectionName(), name, value);
if(name.equals(<API key>))
WebServer.<API key>().set(requestData.getConnectionName(), name, value);
}
}
}
for(Map.Entry<String, Pattern> rep: replacements.entrySet())
{
Pattern from = rep.getValue();
String to = rep.getKey();
result = result.replaceAll(from.pattern(), "$1$2=" + staticParams.get(to));
}
logger.debug("New query string: " + result);
return result;
}
@Override
public void onRequest(final RequestData requestData, final URLConnection urlConnection) {
logger.debug("<API key>::onRequest()");
HashMap<String, String> staticHeaders = <API key>(requestData).getList();
for(Map.Entry<String, String> header: requestData.getHeaders().entrySet())
{
String headerName = header.getKey();
String headerValue = header.getValue();
if(headerName.equals(<API key>))
{
if(staticHeaders.get(<API key>) == null)
staticHeaders.put(<API key>, headerValue);
else
{
String authorizationHeader = staticHeaders.get(<API key>);
if(headerValue.equals(authorizationHeader))
continue;
logger.debug("Overwriting [" + <API key> + "] from {" + headerValue + " } to {" + authorizationHeader + "}");
urlConnection.setRequestProperty(<API key>, authorizationHeader);
}
}
}
}
@Override
public InputStream onResponse(final RequestData requestData, final InputStream iStream) {
logger.debug("<API key>::onResponse()");
String target = requestData.getTarget();
if(!target.contains(".php"))
return iStream;
try {
String data = IOUtils.toString(iStream);
Matcher matcher = handshakePattern.matcher(requestData.getRealUrl().toString());
if(matcher.find())
{
processHandshake(requestData, data);
}
return IOUtils.toInputStream(data);
} catch (IOException e) {
e.printStackTrace();
}
return iStream;
}
@Override
public void onBeforeRequest(final RequestData requestData, final PortalConfiguration portalConfiguration) {
logger.debug("<API key>::onBeforeRequest()");
String macAddress = requestData.getMacAddress();
if(macAddress == null || macAddress.isEmpty())
{
String cookie = requestData.getCookie().replace("%3A", ":");
Matcher matcher = cookiePattern.matcher(cookie);
if(matcher.find())
{
requestData.setMacAddress(matcher.group(1));
macAddress = matcher.group(1);
logger.debug("MAC: " + matcher.group(1));
}
else
macAddress = "empty";
}
if(!staticHeadersForMac.containsKey(macAddress))
staticHeadersForMac.put(macAddress, new HeadersList());
HashMap<String, String> staticHeaders = <API key>(requestData).getList();
String <API key>.get(requestData.getConnectionName(), "token");
if(token != null)
staticHeaders.put(<API key>, "Bearer " + token);
if(!staticParamsForMac.containsKey(macAddress))
{
ParamsList params = new ParamsList();
HashMap<String, String> list = params.getList();
for(String name: configOptions)
{
String value = portalConfiguration.get(requestData.getConnectionName(), name);
if(value == null)
{
logger.debug("Skipping NULL config value [" + name + "]");
continue;
}
logger.debug("Loading {" + name + "} -> {" + value + "}");
list.put(name, value);
}
staticParamsForMac.put(macAddress, params);
}
try {
requestData.setRealUrl(new URL(getURL(requestData)));
} catch (<API key> e) {
e.printStackTrace();
}
}
public void processHandshake(final RequestData requestData, final String data)
{
logger.debug("<API key>::processHandshake()");
HashMap<String, String> staticHeaders = <API key>(requestData).getList();
JSONObject json;
try {
json = new JSONObject(data);
JSONObject js = json.getJSONObject("js");
String token = js.getString("token");
staticHeaders.put(<API key>, "Bearer " + token);
WebServer.<API key>().set(requestData.getConnectionName(), "token", token);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http:
<html>
<head>
:head
:fbthumb
</head>
<body>
<div id="wrapper">
<header>
<div class="container">
<h1 class="col four">
<a href="@root_path/" class="logo">@name</a>
</h1>
<div class="col six nav">
<div class=navItems>
:pages
</div>
</div>
</div>
</header>
<div id="content" class="container" role="main">
<div class="description col four">
<h1>@title</h1>
<p>@description</p>
</div>
<div class="col seven">
:media
@content
</div>
<hr class="push">
</div>
:footer
</div>
:analytics
</body>
</html>
|
package com.archimatetool.editor.actions;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.<API key>;
import java.net.URL;
import java.net.URLConnection;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.browser.IWebBrowser;
import org.eclipse.ui.browser.<API key>;
import com.archimatetool.editor.ArchiPlugin;
import com.archimatetool.editor.preferences.<API key>;
import com.archimatetool.editor.utils.StringUtils;
/**
* Check for New Action
*
* @author Phillip Beauvoir
*/
public class <API key> extends Action {
public <API key>() {
super(Messages.<API key>);
}
String getOnlineVersion(URL url) throws IOException {
URLConnection connection = url.openConnection();
connection.connect();
InputStream is = connection.getInputStream();
char[] buf = new char[32];
Reader r = new InputStreamReader(is, "UTF-8"); //$NON-NLS-1$
StringBuilder s = new StringBuilder();
while(true) {
int n = r.read(buf);
if(n < 0) {
break;
}
s.append(buf, 0, n);
}
is.close();
r.close();
return s.toString();
}
@Override
public void run() {
try {
String versionFile = ArchiPlugin.PREFERENCES.getString(<API key>.UPDATE_URL);
if(!StringUtils.isSet(versionFile)) {
return;
}
URL url = new URL(versionFile);
String newVersion = getOnlineVersion(url);
// Get this app's main version number
String thisVersion = ArchiPlugin.INSTANCE.getVersion();
if(StringUtils.<API key>(newVersion, thisVersion) > 0) {
String downloadURL = ArchiPlugin.PREFERENCES.getString(<API key>.DOWNLOAD_URL);
// No download URL
if(!StringUtils.isSet(downloadURL)) {
MessageDialog.openInformation(null, Messages.<API key>,
Messages.<API key> + " (" + newVersion + "). "); //$NON-NLS-1$ //$NON-NLS-2$
return;
}
// Does have download URL
boolean reply = MessageDialog.openQuestion(null, Messages.<API key>,
Messages.<API key> + " (" + newVersion + "). " + //$NON-NLS-1$ //$NON-NLS-2$
Messages.<API key>);
if(reply) {
<API key> support = PlatformUI.getWorkbench().getBrowserSupport();
IWebBrowser browser = support.getExternalBrowser();
if(browser != null) {
URL url2 = new URL(downloadURL);
browser.openURL(url2);
}
}
}
else {
MessageDialog.openInformation(null, Messages.<API key>, Messages.<API key>);
}
}
catch(<API key> ex) {
ex.printStackTrace();
}
catch(IOException ex) {
ex.printStackTrace();
showErrorMessage(Messages.<API key> + " " + ex.getMessage()); //$NON-NLS-1$
return;
}
catch(PartInitException ex) {
ex.printStackTrace();
}
};
@Override
public boolean isEnabled() {
String versionFile = ArchiPlugin.PREFERENCES.getString(<API key>.UPDATE_URL);
return StringUtils.isSet(versionFile);
}
private void showErrorMessage(String message) {
MessageDialog.openError(null, Messages.<API key>, message);
}
}
|
using System;
using System.Collections.Generic;
using EspaceClient.BackOffice.Domaine.Results;
using EspaceClient.BackOffice.Silverlight.Business.Depots;
using EspaceClient.BackOffice.Silverlight.Business.Interfaces;
using EspaceClient.BackOffice.Silverlight.Infrastructure.Services;
using EspaceClient.FrontOffice.Domaine;
using nRoute.Components.Composition;
using EspaceClient.BackOffice.Silverlight.Infrastructure.ServicePieceJointe;
namespace EspaceClient.BackOffice.Silverlight.Data.Depots
{
<summary>
Dépôt des pieces jointes
</summary>
[MapResource(typeof(IDepotPieceJointe), InstanceLifetime.Singleton)]
public class DepotPieceJointe : IDepotPieceJointe
{
private readonly <API key> _services;
private readonly IApplicationContext _applicationContext;
<summary>
Initialise une nouvelle instance du dépôt.
</summary>
<param name="services">Fournisseur de services.</param>
<param name="scheduler">Scheduler de tâches.</param>
[ResolveConstructor]
public DepotPieceJointe(IApplicationContext applicationContext, <API key> services)
{
_applicationContext = applicationContext;
_services = services;
}
public void <API key>(PieceJointeDto pieceJointe, Action<PieceJointeDto> callback, Action<Exception> error)
{
_services.ServicePieceJointe.Call<<API key>>(
s => s.<API key>(_applicationContext.Context, pieceJointe),
r =>
{
if (r.Error != null)
error(r.Error);
else
callback(r.Result);
});
}
public void <API key>(PieceJointeDto pieceJointe, Action<PieceJointeResult> callback, Action<Exception> error)
{
_services.ServicePieceJointe.Call<<API key>>(
s => s.<API key>(_applicationContext.Context, pieceJointe),
r =>
{
if (r.Error != null)
error(r.Error);
else
callback(r.Result);
});
}
public void AddLink(PieceJointeDto pieceJointe, Action<PieceJointeResult> callback, Action<Exception> error)
{
_services.ServicePieceJointe.Call<<API key>>(
s => s.AddLinkAsync(_applicationContext.Context, pieceJointe),
r =>
{
if (r.Error != null)
error(r.Error);
else
callback(r.Result);
});
}
public void UploadPieceJointe(PieceJointeDto pieceJointe, byte[] data, long part, Action<PieceJointeDto> callback, Action<Exception> error)
{
_services.ServicePieceJointe.Call<<API key>>(
s => s.<API key>(_applicationContext.Context, pieceJointe, data, part),
r =>
{
if (r.Error != null)
error(r.Error);
else
callback(r.Result);
});
}
public void GetPieceJointes(long vueId, long idFonctionnel, Action<IEnumerable<PieceJointeResult>> callback, Action<Exception> error)
{
_services.ServicePieceJointe.Call<<API key>>(
s => s.<API key>(_applicationContext.Context, vueId, idFonctionnel),
r =>
{
if (r.Error != null)
error(r.Error);
else
callback(r.Result);
});
}
public void <API key>(long pieceJointeId, Action<PieceJointeDto> callback, Action<Exception> error)
{
_services.ServicePieceJointe.Call<<API key>>(
s => s.<API key>(_applicationContext.Context, pieceJointeId),
r =>
{
if (r.Error != null)
error(r.Error);
else
callback(r.Result);
});
}
public void GetPieceJointesById(long pieceJointeId, long part, Action<byte[]> callback, Action<Exception> error)
{
_services.ServicePieceJointe.Call<<API key>>(
s => s.<API key>(_applicationContext.Context, pieceJointeId, part),
r =>
{
if (r.Error != null)
error(r.Error);
else
callback(r.Result);
});
}
public void DeletePieceJointe(long pieceJointeId, Action<bool> callback, Action<Exception> error)
{
_services.ServicePieceJointe.Call<<API key>>(
s => s.<API key>(_applicationContext.Context, pieceJointeId),
r =>
{
if (r.Error != null)
error(r.Error);
else
callback(r.Result);
});
}
}
}
|
from io import BytesIO
from django import forms
from django.http import HttpResponse
from django.template import Context, Template
from braces.views import LoginRequiredMixin
from django.views.generic import DetailView, ListView
from django.views.decorators.http import <API key>
from django.contrib import messages
from django.shortcuts import render, redirect
from django.conf import settings
from reportlab.pdfgen.canvas import Canvas
from reportlab.lib.units import inch
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.pagesizes import letter, landscape
from reportlab.platypus import Spacer
from reportlab.platypus import Frame
from reportlab.platypus import Paragraph
from reportlab.platypus import PageTemplate
from reportlab.platypus import BaseDocTemplate
from environ import Env
from members.models import Member
@<API key>(['GET', 'POST'])
def member_list(request):
env = Env()
MEMBERS_PASSWORD = env('MEMBERS_PASSWORD')
# handle form submission
if request.POST:
pw_form = PasswordForm(request.POST)
if pw_form.is_valid() and pw_form.cleaned_data['password'] == MEMBERS_PASSWORD:
request.session['password'] = pw_form.cleaned_data['password']
return redirect('members:member_list')
messages.error(request, "The password you entered was incorrect, please try again.")
# form not being submitted, check password
if (request.session.get('password') and request.session['password'] == MEMBERS_PASSWORD):
member_list = Member.objects.all()
return render(request, 'members/member_list.html', {
'member_list': member_list,
})
# password is wrong, render form
pw_form = PasswordForm()
return render(request, 'members/<API key>.html', {
'pw_form': pw_form,
})
class PasswordForm(forms.Form):
password = forms.CharField(max_length=20,
widget=forms.PasswordInput(attrs={
'class': 'form-control',
'placeholder': 'Enter Password',
}))
def build_frames(pwidth, pheight, ncols):
frames = []
for i in range(ncols):
f = Frame(x1=(i*((pwidth-30) / ncols)+15),
y1=0,
width=((pwidth-30) / ncols),
height=pheight+2,
leftPadding=15,
rightPadding=15,
topPadding=15,
bottomPadding=15,
showBoundary=True)
frames.append(f)
frames[0].showBoundary=False
frames[3].showBoundary=False
return frames
def member_list_pdf(request):
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="memberlist.pdf"'
buffer = BytesIO()
NCOLUMNS = 4
PAGE_WIDTH, PAGE_HEIGHT = landscape(letter)
styles = getSampleStyleSheet()
ptemplate = PageTemplate(frames=build_frames(PAGE_WIDTH, PAGE_HEIGHT, NCOLUMNS))
doc = BaseDocTemplate(
filename=buffer,
pagesize=landscape(letter),
pageTemplates=[ptemplate],
showBoundary=0,
leftMargin=inch,
rightMargin=inch,
topMargin=inch,
bottomMargin=inch,
allowSplitting=0,
title='SSIP209 Members Listing',
author='Max Shkurygin',
_pageBreakQuick=1,
encrypt=None)
template = Template("""
<font size="14"><strong>{{ member.last_name }}, {{ member.first_name }}</strong></font>
<br/>
{% if member.address or member.town %}
{{ member.address }}<br/>
{% if member.town %} {{ member.town }} NY <br/>{% endif %}
{% endif %}
{% if member.homephone %}
(Home) {{ member.homephone }}
<br/>
{% endif %}
{% if member.cellphone %}
(Cell) {{ member.cellphone }}
<br/>
{% endif %}
{% if member.email %}
Email: {{ member.email }}
<br/>
{% endif %}
{% if member.hobbies %}
<strong>My Hobbies</strong>: {{ member.hobbies }}
<br/>
{% endif %}
{% if member.canhelp %}
<strong>I can help with</strong>: {{ member.canhelp }}
<br/>
{% endif %}
{% if member.needhelp %}
<strong>I could use help with</strong>: {{ member.needhelp }}
<br/>
{% endif %}
""")
content = []
for member in Member.objects.all():
context = Context({"member": member})
p = Paragraph(template.render(context), styles["Normal"])
content.append(p)
content.append(Spacer(1, 0.3*inch))
doc.build(content)
pdf = buffer.getvalue()
buffer.close()
response.write(pdf)
return response
|
import {Component} from "@angular/core";
@Component({
moduleId: module.id,
selector: 'ptc-footer',
templateUrl: 'footer.component.html'
})
export class FooterComponent{
}
|
<?php
namespace Pinq\Iterators\Generators;
use Pinq\Iterators\Standard\IIterator;
/**
* Implementation of the adapter iterator for Pinq\Iterators\IIterator using the generator
*
* @author Elliot Levin <elliotlevin@hotmail.com>
*/
class IIteratorAdapter extends Generator
{
/**
* @var IIterator
*/
private $iterator;
public function __construct(IIterator $iterator)
{
parent::__construct();
$this->iterator = $iterator;
}
public function &getIterator()
{
$this->iterator->rewind();
while ($element = $this->iterator->fetch()) {
yield $element[0] => $element[1];
}
}
}
|
/*<API key>
<API key>
XX XX
XX ARM/ARM64 Code Generator Common Code XX
XX XX
<API key>
<API key>
*/
#include "jitpch.h"
#ifdef _MSC_VER
#pragma hdrstop
#endif
#ifndef LEGACY_BACKEND // This file is ONLY used for the RyuJIT backend that uses the linear scan register allocator
#ifdef _TARGET_ARMARCH_ // This file is ONLY used for ARM and ARM64 architectures
#include "codegen.h"
#include "lower.h"
#include "gcinfo.h"
#include "emit.h"
// genCodeForTreeNode Generate code for a single node in the tree.
// Preconditions:
// All operands have been evaluated.
void CodeGen::genCodeForTreeNode(GenTreePtr treeNode)
{
regNumber targetReg = treeNode->gtRegNum;
var_types targetType = treeNode->TypeGet();
emitter* emit = getEmitter();
#ifdef DEBUG
// Validate that all the operands for the current node are consumed in order.
// This is important because LSRA ensures that any necessary copies will be
// handled correctly.
lastConsumedNode = nullptr;
if (compiler->verbose)
{
unsigned seqNum = treeNode->gtSeqNum; // Useful for setting a conditional break in Visual Studio
compiler->gtDispLIRNode(treeNode, "Generating: ");
}
#endif // DEBUG
#ifdef _TARGET_ARM64_ // TODO-ARM: is this applicable to ARM32?
// Is this a node whose value is already in a register? LSRA denotes this by
// setting the GTF_REUSE_REG_VAL flag.
if (treeNode->IsReuseRegVal())
{
// For now, this is only used for constant nodes.
assert((treeNode->OperGet() == GT_CNS_INT) || (treeNode->OperGet() == GT_CNS_DBL));
JITDUMP(" TreeNode is marked ReuseReg\n");
return;
}
#endif // _TARGET_ARM64_
// contained nodes are part of their parents for codegen purposes
// ex : immediates, most LEAs
if (treeNode->isContained())
{
return;
}
switch (treeNode->gtOper)
{
case GT_START_NONGC:
getEmitter()->emitDisableGC();
break;
#ifdef _TARGET_ARM64_
case GT_PROF_HOOK:
// We should be seeing this only if profiler hook is needed
noway_assert(compiler-><API key>());
#ifdef PROFILING_SUPPORTED
// Right now this node is used only for tail calls. In future if
// we intend to use it for Enter or Leave hooks, add a data member
// to this node indicating the kind of profiler hook. For example,
// helper number can be used.
<API key>(<API key>);
#endif // PROFILING_SUPPORTED
break;
#endif // _TARGET_ARM64_
case GT_LCLHEAP:
genLclHeap(treeNode);
break;
case GT_CNS_INT:
case GT_CNS_DBL:
genSetRegToConst(targetReg, targetType, treeNode);
genProduceReg(treeNode);
break;
case GT_NOT:
case GT_NEG:
genCodeForNegNot(treeNode);
break;
case GT_MOD:
case GT_UMOD:
case GT_DIV:
case GT_UDIV:
genCodeForDivMod(treeNode->AsOp());
break;
case GT_OR:
case GT_XOR:
case GT_AND:
assert(<API key>(treeNode));
__fallthrough;
#if !defined(_TARGET_64BIT_)
case GT_ADD_LO:
case GT_ADD_HI:
case GT_SUB_LO:
case GT_SUB_HI:
#endif // !defined(_TARGET_64BIT_)
case GT_ADD:
case GT_SUB:
case GT_MUL:
genConsumeOperands(treeNode->AsOp());
genCodeForBinary(treeNode);
break;
case GT_LSH:
case GT_RSH:
case GT_RSZ:
// case GT_ROL: // No ROL instruction on ARM; it has been lowered to ROR.
case GT_ROR:
genCodeForShift(treeNode);
break;
#if !defined(_TARGET_64BIT_)
case GT_LSH_HI:
case GT_RSH_LO:
genCodeForShiftLong(treeNode);
break;
#endif // !defined(_TARGET_64BIT_)
case GT_CAST:
genCodeForCast(treeNode->AsOp());
break;
case GT_BITCAST:
{
GenTree* op1 = treeNode->gtOp.gtOp1;
if (varTypeIsFloating(treeNode) != varTypeIsFloating(op1))
{
#ifdef _TARGET_ARM64_
inst_RV_RV(INS_fmov, targetReg, genConsumeReg(op1), targetType);
#else // !_TARGET_ARM64_
if (varTypeIsFloating(treeNode))
{
NYI_ARM("genRegCopy from 'int' to 'float'");
}
else
{
assert(varTypeIsFloating(op1));
if (op1->TypeGet() == TYP_FLOAT)
{
inst_RV_RV(INS_vmov_f2i, targetReg, genConsumeReg(op1), targetType);
}
else
{
regNumber otherReg = (regNumber)treeNode->AsMultiRegOp()->gtOtherReg;
assert(otherReg != REG_NA);
inst_RV_RV_RV(INS_vmov_d2i, targetReg, otherReg, genConsumeReg(op1), EA_8BYTE);
}
}
#endif // !_TARGET_ARM64_
}
else
{
inst_RV_RV(ins_Copy(targetType), targetReg, genConsumeReg(op1), targetType);
}
}
break;
case GT_LCL_FLD_ADDR:
case GT_LCL_VAR_ADDR:
genCodeForLclAddr(treeNode);
break;
case GT_LCL_FLD:
genCodeForLclFld(treeNode->AsLclFld());
break;
case GT_LCL_VAR:
genCodeForLclVar(treeNode->AsLclVar());
break;
case GT_STORE_LCL_FLD:
<API key>(treeNode->AsLclFld());
break;
case GT_STORE_LCL_VAR:
<API key>(treeNode->AsLclVar());
break;
case GT_RETFILT:
case GT_RETURN:
genReturn(treeNode);
break;
case GT_LEA:
// If we are here, it is the case where there is an LEA that cannot be folded into a parent instruction.
genLeaInstruction(treeNode->AsAddrMode());
break;
case GT_INDEX_ADDR:
genCodeForIndexAddr(treeNode->AsIndexAddr());
break;
case GT_IND:
genCodeForIndir(treeNode->AsIndir());
break;
#ifdef _TARGET_ARM_
case GT_MUL_LONG:
genCodeForMulLong(treeNode->AsMultiRegOp());
break;
#endif // _TARGET_ARM_
#ifdef _TARGET_ARM64_
case GT_MULHI:
genCodeForMulHi(treeNode->AsOp());
break;
case GT_SWAP:
genCodeForSwap(treeNode->AsOp());
break;
#endif // _TARGET_ARM64_
case GT_JMP:
genJmpMethod(treeNode);
break;
case GT_CKFINITE:
genCkfinite(treeNode);
break;
case GT_INTRINSIC:
genIntrinsic(treeNode);
break;
#ifdef FEATURE_SIMD
case GT_SIMD:
genSIMDIntrinsic(treeNode->AsSIMD());
break;
#endif // FEATURE_SIMD
case GT_EQ:
case GT_NE:
case GT_LT:
case GT_LE:
case GT_GE:
case GT_GT:
case GT_CMP:
#ifdef _TARGET_ARM64_
case GT_TEST_EQ:
case GT_TEST_NE:
#endif // _TARGET_ARM64_
genCodeForCompare(treeNode->AsOp());
break;
case GT_JTRUE:
genCodeForJumpTrue(treeNode);
break;
#ifdef _TARGET_ARM64_
case GT_JCMP:
<API key>(treeNode->AsOp());
break;
#endif // _TARGET_ARM64_
case GT_JCC:
genCodeForJcc(treeNode->AsCC());
break;
case GT_SETCC:
genCodeForSetcc(treeNode->AsCC());
break;
case GT_RETURNTRAP:
<API key>(treeNode->AsOp());
break;
case GT_STOREIND:
genCodeForStoreInd(treeNode->AsStoreInd());
break;
case GT_COPY:
// This is handled at the time we call genConsumeReg() on the GT_COPY
break;
case GT_LIST:
case GT_FIELD_LIST:
// Should always be marked contained.
assert(!"LIST, FIELD_LIST nodes should always be marked contained.");
break;
case GT_PUTARG_STK:
genPutArgStk(treeNode->AsPutArgStk());
break;
case GT_PUTARG_REG:
genPutArgReg(treeNode->AsOp());
break;
#ifdef _TARGET_ARM_
case GT_PUTARG_SPLIT:
genPutArgSplit(treeNode->AsPutArgSplit());
break;
#endif
case GT_CALL:
genCallInstruction(treeNode->AsCall());
break;
case GT_LOCKADD:
case GT_XCHG:
case GT_XADD:
<API key>(treeNode->AsOp());
break;
case GT_MEMORYBARRIER:
<API key>();
break;
case GT_CMPXCHG:
NYI_ARM("GT_CMPXCHG");
#ifdef _TARGET_ARM64_
genCodeForCmpXchg(treeNode->AsCmpXchg());
#endif
break;
case GT_RELOAD:
// do nothing - reload is just a marker.
// The parent node will call genConsumeReg on this which will trigger the unspill of this node's child
// into the register specified in this node.
break;
case GT_NOP:
break;
case GT_NO_OP:
instGen(INS_nop);
break;
case GT_ARR_BOUNDS_CHECK:
#ifdef FEATURE_SIMD
case GT_SIMD_CHK:
#endif // FEATURE_SIMD
genRangeCheck(treeNode);
break;
case GT_PHYSREG:
genCodeForPhysReg(treeNode->AsPhysReg());
break;
case GT_NULLCHECK:
genCodeForNullCheck(treeNode->AsOp());
break;
case GT_CATCH_ARG:
noway_assert(handlerGetsXcptnObj(compiler->compCurBB->bbCatchTyp));
/* Catch arguments get passed in a register. genCodeForBBlist()
would have marked it as holding a GC object, but not used. */
noway_assert(gcInfo.gcRegGCrefSetCur & <API key>);
genConsumeReg(treeNode);
break;
case GT_PINVOKE_PROLOG:
noway_assert(((gcInfo.gcRegGCrefSetCur | gcInfo.gcRegByrefSetCur) & ~fullIntArgRegMask()) == 0);
// the runtime side requires the codegen here to be consistent
emit-><API key>();
break;
case GT_LABEL:
genPendingCallLabel = genCreateTempLabel();
treeNode->gtLabel.gtLabBB = genPendingCallLabel;
emit->emitIns_R_L(INS_adr, EA_PTRSIZE, genPendingCallLabel, targetReg);
break;
case GT_STORE_OBJ:
case GT_STORE_DYN_BLK:
case GT_STORE_BLK:
genCodeForStoreBlk(treeNode->AsBlk());
break;
case GT_JMPTABLE:
genJumpTable(treeNode);
break;
case GT_SWITCH_TABLE:
genTableBasedSwitch(treeNode);
break;
case GT_ARR_INDEX:
genCodeForArrIndex(treeNode->AsArrIndex());
break;
case GT_ARR_OFFSET:
genCodeForArrOffset(treeNode->AsArrOffs());
break;
#ifdef _TARGET_ARM_
case GT_CLS_VAR_ADDR:
emit->emitIns_R_C(INS_lea, EA_PTRSIZE, targetReg, treeNode->gtClsVar.gtClsVarHnd, 0);
genProduceReg(treeNode);
break;
case GT_LONG:
assert(treeNode->isUsedFromReg());
genConsumeRegs(treeNode);
break;
#endif // _TARGET_ARM_
case GT_IL_OFFSET:
// Do nothing; these nodes are simply markers for debug info.
break;
default:
{
#ifdef DEBUG
char message[256];
_snprintf_s(message, _countof(message), _TRUNCATE, "NYI: Unimplemented node type %s",
GenTree::OpName(treeNode->OperGet()));
NYIRAW(message);
#else
NYI("unimplemented node");
#endif
}
break;
}
}
// genSetRegToIcon: Generate code that will set the given register to the integer constant.
void CodeGen::genSetRegToIcon(regNumber reg, ssize_t val, var_types type, insFlags flags)
{
// Reg cannot be a FP reg
assert(!genIsValidFloatReg(reg));
// The only TYP_REF constant that can come this path is a managed 'null' since it is not
// relocatable. Other ref type constants (e.g. string objects) go through a different
// code path.
noway_assert(type != TYP_REF || val == 0);
<API key>(emitActualTypeSize(type), reg, val, flags);
}
// genIntrinsic - generate code for a given intrinsic
// Arguments
// treeNode - the GT_INTRINSIC node
// Return value:
// None
void CodeGen::genIntrinsic(GenTreePtr treeNode)
{
assert(treeNode->OperIs(GT_INTRINSIC));
// Both operand and its result must be of the same floating point type.
GenTreePtr srcNode = treeNode->gtOp.gtOp1;
assert(varTypeIsFloating(srcNode));
assert(srcNode->TypeGet() == treeNode->TypeGet());
// Right now only Abs/Ceiling/Floor/Round/Sqrt are treated as math intrinsics.
switch (treeNode->gtIntrinsic.gtIntrinsicId)
{
case <API key>:
genConsumeOperands(treeNode->AsOp());
getEmitter()->emitInsBinary(INS_ABS, emitActualTypeSize(treeNode), treeNode, srcNode);
break;
#ifdef _TARGET_ARM64_
case <API key>:
genConsumeOperands(treeNode->AsOp());
getEmitter()->emitInsBinary(INS_frintp, emitActualTypeSize(treeNode), treeNode, srcNode);
break;
case <API key>:
genConsumeOperands(treeNode->AsOp());
getEmitter()->emitInsBinary(INS_frintm, emitActualTypeSize(treeNode), treeNode, srcNode);
break;
#endif
case <API key>:
NYI_ARM("genIntrinsic for round - not implemented yet");
genConsumeOperands(treeNode->AsOp());
getEmitter()->emitInsBinary(INS_ROUND, emitActualTypeSize(treeNode), treeNode, srcNode);
break;
case <API key>:
genConsumeOperands(treeNode->AsOp());
getEmitter()->emitInsBinary(INS_SQRT, emitActualTypeSize(treeNode), treeNode, srcNode);
break;
default:
assert(!"genIntrinsic: Unsupported intrinsic");
unreached();
}
genProduceReg(treeNode);
}
// genPutArgStk - generate code for a GT_PUTARG_STK node
// Arguments
// treeNode - the GT_PUTARG_STK node
// Return value:
// None
void CodeGen::genPutArgStk(GenTreePutArgStk* treeNode)
{
assert(treeNode->OperIs(GT_PUTARG_STK));
GenTreePtr source = treeNode->gtOp1;
var_types targetType = source->TypeGet();
emitter* emit = getEmitter();
// This is the varNum for our store operations,
// typically this is the varNum for the Outgoing arg space
// When we are generating a tail call it will be the varNum for arg0
unsigned varNumOut = (unsigned)-1;
unsigned argOffsetMax = (unsigned)-1; // Records the maximum size of this area for assert checks
// Get argument offset to use with 'varNumOut'
// Here we cross check that argument offset hasn't changed from lowering to codegen since
// we are storing arg slot number in GT_PUTARG_STK node in lowering phase.
unsigned argOffsetOut = treeNode->gtSlotNum * TARGET_POINTER_SIZE;
#ifdef DEBUG
fgArgTabEntryPtr curArgTabEntry = compiler->gtArgEntryByNode(treeNode->gtCall, treeNode);
assert(curArgTabEntry);
assert(argOffsetOut == (curArgTabEntry->slotNum * TARGET_POINTER_SIZE));
#endif // DEBUG
// Whether to setup stk arg in incoming or out-going arg area?
// Fast tail calls implemented as epilog+jmp = stk arg is setup in incoming arg area.
// All other calls - stk arg is setup in out-going arg area.
if (treeNode-><API key>())
{
varNumOut = <API key>();
argOffsetMax = compiler->compArgSize;
#if <API key>
// This must be a fast tail call.
assert(treeNode->gtCall->IsFastTailCall());
// Since it is a fast tail call, the existence of first incoming arg is guaranteed
// because fast tail call requires that in-coming arg area of caller is >= out-going
// arg area required for tail call.
LclVarDsc* varDsc = &(compiler->lvaTable[varNumOut]);
assert(varDsc != nullptr);
#endif // <API key>
}
else
{
varNumOut = compiler-><API key>;
argOffsetMax = compiler-><API key>;
}
bool isStruct = (targetType == TYP_STRUCT) || (source->OperGet() == GT_FIELD_LIST);
if (!isStruct) // a normal non-Struct argument
{
instruction storeIns = ins_Store(targetType);
emitAttr storeAttr = emitTypeSize(targetType);
// If it is contained then source must be the integer constant zero
if (source->isContained())
{
#ifdef _TARGET_ARM64_
assert(source->OperGet() == GT_CNS_INT);
assert(source->AsIntConCommon()->IconValue() == 0);
emit->emitIns_S_R(storeIns, storeAttr, REG_ZR, varNumOut, argOffsetOut);
#else // !_TARGET_ARM64_
// There is no zero register on ARM32
unreached();
#endif // !_TARGET_ARM64
}
else
{
genConsumeReg(source);
emit->emitIns_S_R(storeIns, storeAttr, source->gtRegNum, varNumOut, argOffsetOut);
#ifdef _TARGET_ARM_
if (targetType == TYP_LONG)
{
// This case currently only occurs for double types that are passed as TYP_LONG;
// actual long types would have been decomposed by now.
assert(source->IsCopyOrReload());
regNumber otherReg = (regNumber)source->AsCopyOrReload()->GetRegNumByIdx(1);
assert(otherReg != REG_NA);
argOffsetOut += EA_4BYTE;
emit->emitIns_S_R(storeIns, storeAttr, otherReg, varNumOut, argOffsetOut);
}
#endif // _TARGET_ARM_
}
argOffsetOut += EA_SIZE_IN_BYTES(storeAttr);
assert(argOffsetOut <= argOffsetMax); // We can't write beyound the outgoing area area
}
else // We have some kind of a struct argument
{
assert(source->isContained()); // We expect that this node was marked as contained in Lower
if (source->OperGet() == GT_FIELD_LIST)
{
// Deal with the multi register passed struct args.
GenTreeFieldList* fieldListPtr = source->AsFieldList();
// Evaluate each of the GT_FIELD_LIST items into their register
// and store their register into the outgoing argument area
for (; fieldListPtr != nullptr; fieldListPtr = fieldListPtr->Rest())
{
GenTreePtr nextArgNode = fieldListPtr->gtOp.gtOp1;
genConsumeReg(nextArgNode);
regNumber reg = nextArgNode->gtRegNum;
var_types type = nextArgNode->TypeGet();
emitAttr attr = emitTypeSize(type);
// Emit store instructions to store the registers produced by the GT_FIELD_LIST into the outgoing
// argument area
emit->emitIns_S_R(ins_Store(type), attr, reg, varNumOut, argOffsetOut);
argOffsetOut += EA_SIZE_IN_BYTES(attr);
assert(argOffsetOut <= argOffsetMax); // We can't write beyound the outgoing area area
}
}
else // We must have a GT_OBJ or a GT_LCL_VAR
{
noway_assert((source->OperGet() == GT_LCL_VAR) || (source->OperGet() == GT_OBJ));
var_types targetType = source->TypeGet();
noway_assert(varTypeIsStruct(targetType));
// We will copy this struct to the stack, possibly using a ldp/ldr instruction
// in ARM64/ARM
// Setup loReg (and hiReg) from the internal registers that we reserved in lower.
regNumber loReg = treeNode->ExtractTempReg();
#ifdef _TARGET_ARM64_
regNumber hiReg = treeNode->GetSingleTempReg();
#endif // _TARGET_ARM64_
regNumber addrReg = REG_NA;
GenTreeLclVarCommon* varNode = nullptr;
GenTreePtr addrNode = nullptr;
if (source->OperGet() == GT_LCL_VAR)
{
varNode = source->AsLclVarCommon();
}
else // we must have a GT_OBJ
{
assert(source->OperGet() == GT_OBJ);
addrNode = source->gtOp.gtOp1;
// addrNode can either be a GT_LCL_VAR_ADDR or an address expression
if (addrNode->OperGet() == GT_LCL_VAR_ADDR)
{
// We have a GT_OBJ(GT_LCL_VAR_ADDR)
// We will treat this case the same as above
// (i.e if we just had this GT_LCL_VAR directly as the source)
// so update 'source' to point this GT_LCL_VAR_ADDR node
// and continue to the codegen for the LCL_VAR node below
varNode = addrNode->AsLclVarCommon();
addrNode = nullptr;
}
}
// Either varNode or addrNOde must have been setup above,
// the xor ensures that only one of the two is setup, not both
assert((varNode != nullptr) ^ (addrNode != nullptr));
BYTE gcPtrArray[MAX_ARG_REG_COUNT] = {}; // TYPE_GC_NONE = 0
BYTE* gcPtrs = gcPtrArray;
unsigned gcPtrCount; // The count of GC pointers in the struct
int structSize;
bool isHfa;
// This is the varNum for our load operations,
// only used when we have a multireg struct with a LclVar source
unsigned varNumInp = BAD_VAR_NUM;
#ifdef _TARGET_ARM_
// On ARM32, size of reference map can be larger than MAX_ARG_REG_COUNT
gcPtrs = treeNode->gtGcPtrs;
gcPtrCount = treeNode-><API key>;
#endif
// Setup the structSize, isHFa, and gcPtrCount
if (varNode != nullptr)
{
varNumInp = varNode->gtLclNum;
assert(varNumInp < compiler->lvaCount);
LclVarDsc* varDsc = &compiler->lvaTable[varNumInp];
// This struct also must live in the stack frame
// And it can't live in a register (SIMD)
assert(varDsc->lvType == TYP_STRUCT);
assert(varDsc->lvOnFrame && !varDsc->lvRegister);
structSize = varDsc->lvSize(); // This yields the roundUp size, but that is fine
// as that is how much stack is allocated for this LclVar
isHfa = varDsc->lvIsHfa();
#ifdef _TARGET_ARM64_
gcPtrCount = varDsc->lvStructGcCount;
for (unsigned i = 0; i < gcPtrCount; ++i)
gcPtrs[i] = varDsc->lvGcLayout[i];
#endif // _TARGET_ARM_
}
else // addrNode is used
{
assert(addrNode != nullptr);
// Generate code to load the address that we need into a register
genConsumeAddress(addrNode);
addrReg = addrNode->gtRegNum;
#ifdef _TARGET_ARM64_
// If addrReg equal to loReg, swap(loReg, hiReg)
// This reduces code complexity by only supporting one addrReg overwrite case
if (loReg == addrReg)
{
loReg = hiReg;
hiReg = addrReg;
}
#endif // _TARGET_ARM64_
<API key> objClass = source->gtObj.gtClass;
structSize = compiler->info.compCompHnd->getClassSize(objClass);
isHfa = compiler->IsHfa(objClass);
#ifdef _TARGET_ARM64_
gcPtrCount = compiler->info.compCompHnd->getClassGClayout(objClass, &gcPtrs[0]);
#endif
}
// If we have an HFA we can't have any GC pointers,
// if not then the max size for the the struct is 16 bytes
if (isHfa)
{
noway_assert(gcPtrCount == 0);
}
#ifdef _TARGET_ARM64_
else
{
noway_assert(structSize <= 2 * TARGET_POINTER_SIZE);
}
noway_assert(structSize <= <API key>);
#endif // _TARGET_ARM64_
int remainingSize = structSize;
unsigned structOffset = 0;
unsigned nextIndex = 0;
#ifdef _TARGET_ARM64_
// For a >= 16-byte structSize we will generate a ldp and stp instruction each loop
// ldp x2, x3, [x0]
// stp x2, x3, [sp,
while (remainingSize >= 2 * TARGET_POINTER_SIZE)
{
var_types type0 = compiler->getJitGCType(gcPtrs[nextIndex + 0]);
var_types type1 = compiler->getJitGCType(gcPtrs[nextIndex + 1]);
if (varNode != nullptr)
{
// Load from our varNumImp source
emit->emitIns_R_R_S_S(INS_ldp, emitTypeSize(type0), emitTypeSize(type1), loReg, hiReg, varNumInp,
0);
}
else
{
// check for case of destroying the addrRegister while we still need it
assert(loReg != addrReg);
noway_assert((remainingSize == 2 * TARGET_POINTER_SIZE) || (hiReg != addrReg));
// Load from our address expression source
emit->emitIns_R_R_R_I(INS_ldp, emitTypeSize(type0), loReg, hiReg, addrReg, structOffset,
INS_OPTS_NONE, emitTypeSize(type0));
}
// Emit stp instruction to store the two registers into the outgoing argument area
emit->emitIns_S_S_R_R(INS_stp, emitTypeSize(type0), emitTypeSize(type1), loReg, hiReg, varNumOut,
argOffsetOut);
argOffsetOut += (2 * TARGET_POINTER_SIZE); // We stored 16-bytes of the struct
assert(argOffsetOut <= argOffsetMax); // We can't write beyound the outgoing area area
remainingSize -= (2 * TARGET_POINTER_SIZE); // We loaded 16-bytes of the struct
structOffset += (2 * TARGET_POINTER_SIZE);
nextIndex += 2;
}
#else // _TARGET_ARM_
// For a >= 4 byte structSize we will generate a ldr and str instruction each loop
// ldr r2, [r0]
// str r2, [sp,
while (remainingSize >= TARGET_POINTER_SIZE)
{
var_types type = compiler->getJitGCType(gcPtrs[nextIndex]);
if (varNode != nullptr)
{
// Load from our varNumImp source
emit->emitIns_R_S(INS_ldr, emitTypeSize(type), loReg, varNumInp, structOffset);
}
else
{
// check for case of destroying the addrRegister while we still need it
assert(loReg != addrReg || remainingSize == TARGET_POINTER_SIZE);
// Load from our address expression source
emit->emitIns_R_R_I(INS_ldr, emitTypeSize(type), loReg, addrReg, structOffset);
}
// Emit str instruction to store the register into the outgoing argument area
emit->emitIns_S_R(INS_str, emitTypeSize(type), loReg, varNumOut, argOffsetOut);
argOffsetOut += TARGET_POINTER_SIZE; // We stored 4-bytes of the struct
assert(argOffsetOut <= argOffsetMax); // We can't write beyound the outgoing area area
remainingSize -= TARGET_POINTER_SIZE; // We loaded 4-bytes of the struct
structOffset += TARGET_POINTER_SIZE;
nextIndex += 1;
}
#endif // _TARGET_ARM_
// For a 12-byte structSize we will we will generate two load instructions
// ldr x2, [x0]
// ldr w3, [x0,
// str x2, [sp,
// str w3, [sp,
while (remainingSize > 0)
{
if (remainingSize >= TARGET_POINTER_SIZE)
{
var_types nextType = compiler->getJitGCType(gcPtrs[nextIndex]);
emitAttr nextAttr = emitTypeSize(nextType);
remainingSize -= TARGET_POINTER_SIZE;
if (varNode != nullptr)
{
// Load from our varNumImp source
emit->emitIns_R_S(ins_Load(nextType), nextAttr, loReg, varNumInp, structOffset);
}
else
{
assert(loReg != addrReg);
// Load from our address expression source
emit->emitIns_R_R_I(ins_Load(nextType), nextAttr, loReg, addrReg, structOffset);
}
// Emit a store instruction to store the register into the outgoing argument area
emit->emitIns_S_R(ins_Store(nextType), nextAttr, loReg, varNumOut, argOffsetOut);
argOffsetOut += EA_SIZE_IN_BYTES(nextAttr);
assert(argOffsetOut <= argOffsetMax); // We can't write beyound the outgoing area area
structOffset += TARGET_POINTER_SIZE;
nextIndex++;
}
else // (remainingSize < TARGET_POINTER_SIZE)
{
int loadSize = remainingSize;
remainingSize = 0;
// We should never have to do a non-pointer sized load when we have a LclVar source
assert(varNode == nullptr);
// the left over size is smaller than a pointer and thus can never be a GC type
assert(varTypeIsGC(compiler->getJitGCType(gcPtrs[nextIndex])) == false);
var_types loadType = TYP_UINT;
if (loadSize == 1)
{
loadType = TYP_UBYTE;
}
else if (loadSize == 2)
{
loadType = TYP_USHORT;
}
else
{
// Need to handle additional loadSize cases here
noway_assert(loadSize == 4);
}
instruction loadIns = ins_Load(loadType);
emitAttr loadAttr = emitAttr(loadSize);
assert(loReg != addrReg);
emit->emitIns_R_R_I(loadIns, loadAttr, loReg, addrReg, structOffset);
// Emit a store instruction to store the register into the outgoing argument area
emit->emitIns_S_R(ins_Store(loadType), loadAttr, loReg, varNumOut, argOffsetOut);
argOffsetOut += EA_SIZE_IN_BYTES(loadAttr);
assert(argOffsetOut <= argOffsetMax); // We can't write beyound the outgoing area area
}
}
}
}
}
// genPutArgReg - generate code for a GT_PUTARG_REG node
// Arguments
// tree - the GT_PUTARG_REG node
// Return value:
// None
void CodeGen::genPutArgReg(GenTreeOp* tree)
{
assert(tree->OperIs(GT_PUTARG_REG));
var_types targetType = tree->TypeGet();
regNumber targetReg = tree->gtRegNum;
assert(targetType != TYP_STRUCT);
GenTree* op1 = tree->gtOp1;
genConsumeReg(op1);
// If child node is not already in the register we need, move it
if (targetReg != op1->gtRegNum)
{
inst_RV_RV(ins_Copy(targetType), targetReg, op1->gtRegNum, targetType);
}
genProduceReg(tree);
}
#ifdef _TARGET_ARM_
// genPutArgSplit - generate code for a GT_PUTARG_SPLIT node
// Arguments
// tree - the GT_PUTARG_SPLIT node
// Return value:
// None
void CodeGen::genPutArgSplit(GenTreePutArgSplit* treeNode)
{
assert(treeNode->OperIs(GT_PUTARG_SPLIT));
GenTreePtr source = treeNode->gtOp1;
emitter* emit = getEmitter();
unsigned varNumOut = compiler-><API key>;
unsigned argOffsetMax = compiler-><API key>;
unsigned argOffsetOut = treeNode->gtSlotNum * TARGET_POINTER_SIZE;
if (source->OperGet() == GT_FIELD_LIST)
{
GenTreeFieldList* fieldListPtr = source->AsFieldList();
// Evaluate each of the GT_FIELD_LIST items into their register
// and store their register into the outgoing argument area
for (unsigned idx = 0; fieldListPtr != nullptr; fieldListPtr = fieldListPtr->Rest(), idx++)
{
GenTreePtr nextArgNode = fieldListPtr->gtGetOp1();
regNumber fieldReg = nextArgNode->gtRegNum;
genConsumeReg(nextArgNode);
if (idx >= treeNode->gtNumRegs)
{
var_types type = nextArgNode->TypeGet();
emitAttr attr = emitTypeSize(type);
// Emit store instructions to store the registers produced by the GT_FIELD_LIST into the outgoing
// argument area
emit->emitIns_S_R(ins_Store(type), attr, fieldReg, varNumOut, argOffsetOut);
argOffsetOut += EA_SIZE_IN_BYTES(attr);
assert(argOffsetOut <= argOffsetMax); // We can't write beyound the outgoing area area
}
else
{
var_types type = treeNode->GetRegType(idx);
regNumber argReg = treeNode->GetRegNumByIdx(idx);
// If child node is not already in the register we need, move it
if (argReg != fieldReg)
{
inst_RV_RV(ins_Copy(type), argReg, fieldReg, type);
}
}
}
}
else
{
var_types targetType = source->TypeGet();
assert(source->OperGet() == GT_OBJ);
assert(varTypeIsStruct(targetType));
regNumber baseReg = treeNode->ExtractTempReg();
regNumber addrReg = REG_NA;
GenTreeLclVarCommon* varNode = nullptr;
GenTreePtr addrNode = nullptr;
addrNode = source->gtOp.gtOp1;
// addrNode can either be a GT_LCL_VAR_ADDR or an address expression
if (addrNode->OperGet() == GT_LCL_VAR_ADDR)
{
// We have a GT_OBJ(GT_LCL_VAR_ADDR)
// We will treat this case the same as above
// (i.e if we just had this GT_LCL_VAR directly as the source)
// so update 'source' to point this GT_LCL_VAR_ADDR node
// and continue to the codegen for the LCL_VAR node below
varNode = addrNode->AsLclVarCommon();
addrNode = nullptr;
}
// Either varNode or addrNOde must have been setup above,
// the xor ensures that only one of the two is setup, not both
assert((varNode != nullptr) ^ (addrNode != nullptr));
// Setup the structSize, isHFa, and gcPtrCount
BYTE* gcPtrs = treeNode->gtGcPtrs;
unsigned gcPtrCount = treeNode-><API key>; // The count of GC pointers in the struct
int structSize = treeNode->getArgSize();
// This is the varNum for our load operations,
// only used when we have a struct with a LclVar source
unsigned srcVarNum = BAD_VAR_NUM;
if (varNode != nullptr)
{
srcVarNum = varNode->gtLclNum;
assert(srcVarNum < compiler->lvaCount);
// handle promote situation
LclVarDsc* varDsc = compiler->lvaTable + srcVarNum;
// This struct also must live in the stack frame
// And it can't live in a register (SIMD)
assert(varDsc->lvType == TYP_STRUCT);
assert(varDsc->lvOnFrame && !varDsc->lvRegister);
// We don't split HFA struct
assert(!varDsc->lvIsHfa());
}
else // addrNode is used
{
assert(addrNode != nullptr);
// Generate code to load the address that we need into a register
genConsumeAddress(addrNode);
addrReg = addrNode->gtRegNum;
// If addrReg equal to baseReg, we use the last target register as alternative baseReg.
// Because the candidate mask for the internal baseReg does not include any of the target register,
// we can ensure that baseReg, addrReg, and the last target register are not all same.
assert(baseReg != addrReg);
// We don't split HFA struct
assert(!compiler->IsHfa(source->gtObj.gtClass));
}
// Put on stack first
unsigned nextIndex = treeNode->gtNumRegs;
unsigned structOffset = nextIndex * TARGET_POINTER_SIZE;
int remainingSize = structSize - structOffset;
// remainingSize is always multiple of TARGET_POINTER_SIZE
assert(remainingSize % TARGET_POINTER_SIZE == 0);
while (remainingSize > 0)
{
var_types type = compiler->getJitGCType(gcPtrs[nextIndex]);
if (varNode != nullptr)
{
// Load from our varNumImp source
emit->emitIns_R_S(INS_ldr, emitTypeSize(type), baseReg, srcVarNum, structOffset);
}
else
{
// check for case of destroying the addrRegister while we still need it
assert(baseReg != addrReg);
// Load from our address expression source
emit->emitIns_R_R_I(INS_ldr, emitTypeSize(type), baseReg, addrReg, structOffset);
}
// Emit str instruction to store the register into the outgoing argument area
emit->emitIns_S_R(INS_str, emitTypeSize(type), baseReg, varNumOut, argOffsetOut);
argOffsetOut += TARGET_POINTER_SIZE; // We stored 4-bytes of the struct
assert(argOffsetOut <= argOffsetMax); // We can't write beyound the outgoing area area
remainingSize -= TARGET_POINTER_SIZE; // We loaded 4-bytes of the struct
structOffset += TARGET_POINTER_SIZE;
nextIndex += 1;
}
// We set up the registers in order, so that we assign the last target register `baseReg` is no longer in use,
// in case we had to reuse the last target register for it.
structOffset = 0;
for (unsigned idx = 0; idx < treeNode->gtNumRegs; idx++)
{
regNumber targetReg = treeNode->GetRegNumByIdx(idx);
var_types type = treeNode->GetRegType(idx);
if (varNode != nullptr)
{
// Load from our varNumImp source
emit->emitIns_R_S(INS_ldr, emitTypeSize(type), targetReg, srcVarNum, structOffset);
}
else
{
// check for case of destroying the addrRegister while we still need it
if (targetReg == addrReg && idx != treeNode->gtNumRegs - 1)
{
assert(targetReg != baseReg);
emit->emitIns_R_R(INS_mov, emitActualTypeSize(type), baseReg, addrReg);
addrReg = baseReg;
}
// Load from our address expression source
emit->emitIns_R_R_I(INS_ldr, emitTypeSize(type), targetReg, addrReg, structOffset);
}
structOffset += TARGET_POINTER_SIZE;
}
}
genProduceReg(treeNode);
}
#endif // _TARGET_ARM_
// <API key>: store multi-reg return value of a call node to a local
// Arguments:
// treeNode - Gentree of GT_STORE_LCL_VAR
// Return Value:
// None
// Assumption:
// The child of store is a multi-reg call node.
// genProduceReg() on treeNode is made by caller of this routine.
void CodeGen::<API key>(GenTreePtr treeNode)
{
assert(treeNode->OperGet() == GT_STORE_LCL_VAR);
#if defined(_TARGET_ARM_)
// Longs are returned in two return registers on Arm32.
// Structs are returned in four registers on ARM32 and HFAs.
assert(varTypeIsLong(treeNode) || varTypeIsStruct(treeNode));
#elif defined(_TARGET_ARM64_)
// Structs of size >=9 and <=16 are returned in two return registers on ARM64 and HFAs.
assert(varTypeIsStruct(treeNode));
#endif // _TARGET_*
// Assumption: current implementation requires that a multi-reg
// var in 'var = call' is flagged as lvIsMultiRegRet to prevent it from
// being promoted.
unsigned lclNum = treeNode->AsLclVarCommon()->gtLclNum;
LclVarDsc* varDsc = &(compiler->lvaTable[lclNum]);
noway_assert(varDsc->lvIsMultiRegRet);
GenTree* op1 = treeNode->gtGetOp1();
GenTree* actualOp1 = op1->gtSkipReloadOrCopy();
GenTreeCall* call = actualOp1->AsCall();
assert(call->HasMultiRegRetVal());
genConsumeRegs(op1);
ReturnTypeDesc* pRetTypeDesc = call->GetReturnTypeDesc();
unsigned regCount = pRetTypeDesc->GetReturnRegCount();
if (treeNode->gtRegNum != REG_NA)
{
// Right now the only enregistrable multi-reg return types supported are SIMD types.
assert(varTypeIsSIMD(treeNode));
NYI("GT_STORE_LCL_VAR of a SIMD enregisterable struct");
}
else
{
// Stack store
int offset = 0;
for (unsigned i = 0; i < regCount; ++i)
{
var_types type = pRetTypeDesc->GetReturnRegType(i);
regNumber reg = call->GetRegNumByIdx(i);
if (op1->IsCopyOrReload())
{
// GT_COPY/GT_RELOAD will have valid reg for those positions
// that need to be copied or reloaded.
regNumber reloadReg = op1->AsCopyOrReload()->GetRegNumByIdx(i);
if (reloadReg != REG_NA)
{
reg = reloadReg;
}
}
assert(reg != REG_NA);
getEmitter()->emitIns_S_R(ins_Store(type), emitTypeSize(type), reg, lclNum, offset);
offset += genTypeSize(type);
}
varDsc->lvRegNum = REG_STK;
}
}
// genRangeCheck: generate code for GT_ARR_BOUNDS_CHECK node.
void CodeGen::genRangeCheck(GenTreePtr oper)
{
#ifdef FEATURE_SIMD
noway_assert(oper->OperGet() == GT_ARR_BOUNDS_CHECK || oper->OperGet() == GT_SIMD_CHK);
#else // !FEATURE_SIMD
noway_assert(oper->OperGet() == GT_ARR_BOUNDS_CHECK);
#endif // !FEATURE_SIMD
GenTreeBoundsChk* bndsChk = oper->AsBoundsChk();
GenTreePtr arrLen = bndsChk->gtArrLen;
GenTreePtr arrIndex = bndsChk->gtIndex;
GenTreePtr arrRef = NULL;
int lenOffset = 0;
GenTree* src1;
GenTree* src2;
emitJumpKind jmpKind;
genConsumeRegs(arrIndex);
genConsumeRegs(arrLen);
if (arrIndex-><API key>())
{
// To encode using a cmp immediate, we place the
// constant operand in the second position
src1 = arrLen;
src2 = arrIndex;
jmpKind = genJumpKindForOper(GT_LE, CK_UNSIGNED);
}
else
{
src1 = arrIndex;
src2 = arrLen;
jmpKind = genJumpKindForOper(GT_GE, CK_UNSIGNED);
}
var_types bndsChkType = genActualType(src2->TypeGet());
#if DEBUG
// Bounds checks can only be 32 or 64 bit sized comparisons.
assert(bndsChkType == TYP_INT || bndsChkType == TYP_LONG);
// The type of the bounds check should always wide enough to compare against the index.
assert(emitTypeSize(bndsChkType) >= emitActualTypeSize(src1->TypeGet()));
#endif // DEBUG
getEmitter()->emitInsBinary(INS_cmp, emitActualTypeSize(bndsChkType), src1, src2);
<API key>(jmpKind, SCK_RNGCHK_FAIL, bndsChk->gtIndRngFailBB);
}
// genCodeForPhysReg - generate code for a GT_PHYSREG node
// Arguments
// tree - the GT_PHYSREG node
// Return value:
// None
void CodeGen::genCodeForPhysReg(GenTreePhysReg* tree)
{
assert(tree->OperIs(GT_PHYSREG));
var_types targetType = tree->TypeGet();
regNumber targetReg = tree->gtRegNum;
if (targetReg != tree->gtSrcReg)
{
inst_RV_RV(ins_Copy(targetType), targetReg, tree->gtSrcReg, targetType);
<API key>(targetReg, tree->gtSrcReg);
}
genProduceReg(tree);
}
// genCodeForNullCheck - generate code for a GT_NULLCHECK node
// Arguments
// tree - the GT_NULLCHECK node
// Return value:
// None
void CodeGen::genCodeForNullCheck(GenTreeOp* tree)
{
assert(tree->OperIs(GT_NULLCHECK));
assert(!tree->gtOp1->isContained());
regNumber addrReg = genConsumeReg(tree->gtOp1);
#ifdef _TARGET_ARM64_
regNumber targetReg = REG_ZR;
#else
regNumber targetReg = tree->GetSingleTempReg();
#endif
getEmitter()->emitIns_R_R_I(INS_ldr, EA_4BYTE, targetReg, addrReg, 0);
}
// <API key>: Returns the offset from the Array object to the
// lower bound for the given dimension.
// Arguments:
// elemType - the element type of the array
// rank - the rank of the array
// dimension - the dimension for which the lower bound offset will be returned.
// Return Value:
// The offset.
// TODO-Cleanup: move to CodeGenCommon.cpp
// static
unsigned CodeGen::<API key>(var_types elemType, unsigned rank, unsigned dimension)
{
// Note that the lower bound and length fields of the Array object are always TYP_INT
return compiler-><API key>(elemType) + genTypeSize(TYP_INT) * (dimension + rank);
}
// <API key>: Returns the offset from the Array object to the
// size for the given dimension.
// Arguments:
// elemType - the element type of the array
// rank - the rank of the array
// dimension - the dimension for which the lower bound offset will be returned.
// Return Value:
// The offset.
// TODO-Cleanup: move to CodeGenCommon.cpp
// static
unsigned CodeGen::<API key>(var_types elemType, unsigned rank, unsigned dimension)
{
// Note that the lower bound and length fields of the Array object are always TYP_INT
return compiler-><API key>(elemType) + genTypeSize(TYP_INT) * dimension;
}
// genCodeForArrIndex: Generates code to bounds check the index for one dimension of an array reference,
// producing the effective index by subtracting the lower bound.
// Arguments:
// arrIndex - the node for which we're generating code
// Return Value:
// None.
void CodeGen::genCodeForArrIndex(GenTreeArrIndex* arrIndex)
{
emitter* emit = getEmitter();
GenTreePtr arrObj = arrIndex->ArrObj();
GenTreePtr indexNode = arrIndex->IndexExpr();
regNumber arrReg = genConsumeReg(arrObj);
regNumber indexReg = genConsumeReg(indexNode);
regNumber tgtReg = arrIndex->gtRegNum;
noway_assert(tgtReg != REG_NA);
// We will use a temp register to load the lower bound and dimension size values.
regNumber tmpReg = arrIndex->GetSingleTempReg();
assert(tgtReg != tmpReg);
unsigned dim = arrIndex->gtCurrDim;
unsigned rank = arrIndex->gtArrRank;
var_types elemType = arrIndex->gtArrElemType;
unsigned offset;
offset = <API key>(elemType, rank, dim);
emit->emitIns_R_R_I(ins_Load(TYP_INT), EA_PTRSIZE, tmpReg, arrReg, offset); // a 4 BYTE sign extending load
emit->emitIns_R_R_R(INS_sub, EA_4BYTE, tgtReg, indexReg, tmpReg);
offset = <API key>(elemType, rank, dim);
emit->emitIns_R_R_I(ins_Load(TYP_INT), EA_PTRSIZE, tmpReg, arrReg, offset); // a 4 BYTE sign extending load
emit->emitIns_R_R(INS_cmp, EA_4BYTE, tgtReg, tmpReg);
emitJumpKind jmpGEU = genJumpKindForOper(GT_GE, CK_UNSIGNED);
<API key>(jmpGEU, SCK_RNGCHK_FAIL);
genProduceReg(arrIndex);
}
// genCodeForArrOffset: Generates code to compute the flattened array offset for
// one dimension of an array reference:
// result = (prevDimOffset * dimSize) + effectiveIndex
// where dimSize is obtained from the arrObj operand
// Arguments:
// arrOffset - the node for which we're generating code
// Return Value:
// None.
// Notes:
// dimSize and effectiveIndex are always non-negative, the former by design,
// and the latter because it has been normalized to be zero-based.
void CodeGen::genCodeForArrOffset(GenTreeArrOffs* arrOffset)
{
GenTreePtr offsetNode = arrOffset->gtOffset;
GenTreePtr indexNode = arrOffset->gtIndex;
regNumber tgtReg = arrOffset->gtRegNum;
noway_assert(tgtReg != REG_NA);
if (!offsetNode->IsIntegralConst(0))
{
emitter* emit = getEmitter();
regNumber offsetReg = genConsumeReg(offsetNode);
regNumber indexReg = genConsumeReg(indexNode);
regNumber arrReg = genConsumeReg(arrOffset->gtArrObj);
noway_assert(offsetReg != REG_NA);
noway_assert(indexReg != REG_NA);
noway_assert(arrReg != REG_NA);
regNumber tmpReg = arrOffset->GetSingleTempReg();
unsigned dim = arrOffset->gtCurrDim;
unsigned rank = arrOffset->gtArrRank;
var_types elemType = arrOffset->gtArrElemType;
unsigned offset = <API key>(elemType, rank, dim);
// Load tmpReg with the dimension size and evaluate
// tgtReg = offsetReg*tmpReg + indexReg.
emit->emitIns_R_R_I(ins_Load(TYP_INT), EA_PTRSIZE, tmpReg, arrReg, offset);
emit->emitIns_R_R_R_R(INS_MULADD, EA_PTRSIZE, tgtReg, tmpReg, offsetReg, indexReg);
}
else
{
regNumber indexReg = genConsumeReg(indexNode);
if (indexReg != tgtReg)
{
inst_RV_RV(INS_mov, tgtReg, indexReg, TYP_INT);
}
}
genProduceReg(arrOffset);
}
// indirForm: Make a temporary indir we can feed to pattern matching routines
// in cases where we don't want to instantiate all the indirs that happen.
GenTreeIndir CodeGen::indirForm(var_types type, GenTree* base)
{
GenTreeIndir i(GT_IND, type, base, nullptr);
i.gtRegNum = REG_NA;
i.SetContained();
// has to be nonnull (because contained nodes can't be the last in block)
// but don't want it to be a valid pointer
i.gtNext = (GenTree*)(-1);
return i;
}
// intForm: Make a temporary int we can feed to pattern matching routines
// in cases where we don't want to instantiate.
GenTreeIntCon CodeGen::intForm(var_types type, ssize_t value)
{
GenTreeIntCon i(type, value);
i.gtRegNum = REG_NA;
// has to be nonnull (because contained nodes can't be the last in block)
// but don't want it to be a valid pointer
i.gtNext = (GenTree*)(-1);
return i;
}
// genCodeForShift: Generates the code sequence for a GenTree node that
// represents a bit shift or rotate operation (<<, >>, >>>, rol, ror).
// Arguments:
// tree - the bit shift node (that specifies the type of bit shift to perform).
// Assumptions:
// a) All GenTrees are register allocated.
void CodeGen::genCodeForShift(GenTreePtr tree)
{
var_types targetType = tree->TypeGet();
genTreeOps oper = tree->OperGet();
instruction ins = genGetInsForOper(oper, targetType);
emitAttr size = emitActualTypeSize(tree);
assert(tree->gtRegNum != REG_NA);
genConsumeOperands(tree->AsOp());
GenTreePtr operand = tree->gtGetOp1();
GenTreePtr shiftBy = tree->gtGetOp2();
if (!shiftBy->IsCnsIntOrI())
{
getEmitter()->emitIns_R_R_R(ins, size, tree->gtRegNum, operand->gtRegNum, shiftBy->gtRegNum);
}
else
{
unsigned immWidth = emitter::getBitWidth(size); // For ARM64, immWidth will be set to 32 or 64
ssize_t shiftByImm = shiftBy->gtIntCon.gtIconVal & (immWidth - 1);
getEmitter()->emitIns_R_R_I(ins, size, tree->gtRegNum, operand->gtRegNum, shiftByImm);
}
genProduceReg(tree);
}
// genCodeForLclAddr: Generates the code for GT_LCL_FLD_ADDR/GT_LCL_VAR_ADDR.
// Arguments:
// tree - the node.
void CodeGen::genCodeForLclAddr(GenTree* tree)
{
assert(tree->OperIs(GT_LCL_FLD_ADDR, GT_LCL_VAR_ADDR));
var_types targetType = tree->TypeGet();
regNumber targetReg = tree->gtRegNum;
// Address of a local var.
noway_assert(targetType == TYP_BYREF);
inst_RV_TT(INS_lea, targetReg, tree, 0, EA_BYREF);
genProduceReg(tree);
}
// genCodeForLclFld: Produce code for a GT_LCL_FLD node.
// Arguments:
// tree - the GT_LCL_FLD node
void CodeGen::genCodeForLclFld(GenTreeLclFld* tree)
{
assert(tree->OperIs(GT_LCL_FLD));
var_types targetType = tree->TypeGet();
regNumber targetReg = tree->gtRegNum;
emitter* emit = getEmitter();
NYI_IF(targetType == TYP_STRUCT, "GT_LCL_FLD: struct load local field not supported");
assert(targetReg != REG_NA);
emitAttr size = emitTypeSize(targetType);
unsigned offs = tree->gtLclOffs;
unsigned varNum = tree->gtLclNum;
assert(varNum < compiler->lvaCount);
if (varTypeIsFloating(targetType))
{
emit->emitIns_R_S(ins_Load(targetType), size, targetReg, varNum, offs);
}
else
{
#ifdef _TARGET_ARM64_
size = EA_SET_SIZE(size, EA_8BYTE);
#endif // _TARGET_ARM64_
emit->emitIns_R_S(ins_Move_Extend(targetType, false), size, targetReg, varNum, offs);
}
genProduceReg(tree);
}
// genCodeForIndexAddr: Produce code for a GT_INDEX_ADDR node.
// Arguments:
// tree - the GT_INDEX_ADDR node
void CodeGen::genCodeForIndexAddr(GenTreeIndexAddr* node)
{
GenTree* const base = node->Arr();
GenTree* const index = node->Index();
genConsumeReg(base);
genConsumeReg(index);
// NOTE: `genConsumeReg` marks the consumed register as not a GC pointer, as it assumes that the input registers
// die at the first instruction generated by the node. This is not the case for `INDEX_ADDR`, however, as the
// base register is multiply-used. As such, we need to mark the base register as containing a GC pointer until
// we are finished generating the code for this node.
gcInfo.gcMarkRegPtrVal(base->gtRegNum, base->TypeGet());
assert(!varTypeIsGC(index->TypeGet()));
const regNumber tmpReg = node->GetSingleTempReg();
// Generate the bounds check if necessary.
if ((node->gtFlags & GTF_INX_RNGCHK) != 0)
{
// Create a GT_IND(GT_LEA)) tree for the array length access and load the length into a register.
GenTreeAddrMode arrLenAddr(base->TypeGet(), base, nullptr, 0, static_cast<unsigned>(node->gtLenOffset));
arrLenAddr.gtRegNum = REG_NA;
arrLenAddr.SetContained();
arrLenAddr.gtNext = (GenTree*)(-1);
GenTreeIndir arrLen = indirForm(TYP_INT, &arrLenAddr);
arrLen.gtRegNum = tmpReg;
arrLen.ClearContained();
getEmitter()->emitInsLoadStoreOp(ins_Load(TYP_INT), emitTypeSize(TYP_INT), arrLen.gtRegNum, &arrLen);
#ifdef _TARGET_64BIT_
// The CLI Spec allows an array to be indexed by either an int32 or a native int. In the case that the index
// is a native int on a 64-bit platform, we will need to widen the array length and the compare.
if (index->TypeGet() == TYP_I_IMPL)
{
// Extend the array length as needed.
getEmitter()->emitIns_R_R(ins_Move_Extend(TYP_INT, true), EA_8BYTE, arrLen.gtRegNum, arrLen.gtRegNum);
}
#endif
// Generate the range check.
getEmitter()->emitInsBinary(INS_cmp, emitActualTypeSize(TYP_I_IMPL), index, &arrLen);
<API key>(genJumpKindForOper(GT_GE, CK_UNSIGNED), SCK_RNGCHK_FAIL, node->gtIndRngFailBB);
}
// Compute the address of the array element.
switch (node->gtElemSize)
{
case 1:
// dest = base + index
getEmitter()->emitIns_R_R_R(INS_add, emitActualTypeSize(node), node->gtRegNum, base->gtRegNum,
index->gtRegNum);
break;
case 2:
case 4:
case 8:
case 16:
{
DWORD lsl;
BitScanForward(&lsl, node->gtElemSize);
// dest = base + index * scale
genScaledAdd(emitActualTypeSize(node), node->gtRegNum, base->gtRegNum, index->gtRegNum, lsl);
break;
}
default:
{
// tmp = scale
CodeGen::genSetRegToIcon(tmpReg, (ssize_t)node->gtElemSize, TYP_INT);
// dest = index * tmp + base
getEmitter()->emitIns_R_R_R_R(INS_MULADD, emitActualTypeSize(node), node->gtRegNum, index->gtRegNum, tmpReg,
base->gtRegNum);
break;
}
}
// dest = dest + elemOffs
getEmitter()->emitIns_R_R_I(INS_add, emitActualTypeSize(node), node->gtRegNum, node->gtRegNum, node->gtElemOffset);
gcInfo.gcMarkRegSetNpt(base->gtGetRegMask());
genProduceReg(node);
}
// genCodeForIndir: Produce code for a GT_IND node.
// Arguments:
// tree - the GT_IND node
void CodeGen::genCodeForIndir(GenTreeIndir* tree)
{
assert(tree->OperIs(GT_IND));
var_types targetType = tree->TypeGet();
regNumber targetReg = tree->gtRegNum;
emitter* emit = getEmitter();
emitAttr attr = emitTypeSize(tree);
instruction ins = ins_Load(targetType);
genConsumeAddress(tree->Addr());
if ((tree->gtFlags & GTF_IND_VOLATILE) != 0)
{
bool isAligned = ((tree->gtFlags & GTF_IND_UNALIGNED) == 0);
assert((attr != EA_1BYTE) || isAligned);
#ifdef _TARGET_ARM64_
GenTree* addr = tree->Addr();
bool useLoadAcquire = genIsValidIntReg(targetReg) && !addr->isContained() &&
(varTypeIsUnsigned(targetType) || varTypeIsI(targetType)) &&
!(tree->gtFlags & GTF_IND_UNALIGNED);
if (useLoadAcquire)
{
switch (EA_SIZE(attr))
{
case EA_1BYTE:
assert(ins == INS_ldrb);
ins = INS_ldarb;
break;
case EA_2BYTE:
assert(ins == INS_ldrh);
ins = INS_ldarh;
break;
case EA_4BYTE:
case EA_8BYTE:
assert(ins == INS_ldr);
ins = INS_ldar;
break;
default:
assert(false); // We should not get here
}
}
emit->emitInsLoadStoreOp(ins, attr, targetReg, tree);
if (!useLoadAcquire) // issue a INS_BARRIER_OSHLD after a volatile LdInd operation
<API key>(INS_BARRIER_OSHLD);
#else
emit->emitInsLoadStoreOp(ins, attr, targetReg, tree);
// issue a full memory barrier after a volatile LdInd operation
<API key>();
#endif // _TARGET_ARM64_
}
else
{
emit->emitInsLoadStoreOp(ins, attr, targetReg, tree);
}
genProduceReg(tree);
}
// Generate code for a CpBlk node by the means of the VM memcpy helper call
// Preconditions:
// a) The size argument of the CpBlk is not an integer constant
// b) The size argument is a constant but is larger than CPBLK_MOVS_LIMIT bytes.
void CodeGen::genCodeForCpBlk(GenTreeBlk* cpBlkNode)
{
// Make sure we got the arguments of the cpblk operation in the right registers
unsigned blockSize = cpBlkNode->Size();
GenTreePtr dstAddr = cpBlkNode->Addr();
assert(!dstAddr->isContained());
genConsumeBlockOp(cpBlkNode, REG_ARG_0, REG_ARG_1, REG_ARG_2);
#ifdef _TARGET_ARM64_
if (blockSize != 0)
{
assert(blockSize > CPBLK_UNROLL_LIMIT);
}
#endif // _TARGET_ARM64_
if (cpBlkNode->gtFlags & GTF_BLK_VOLATILE)
{
// issue a full memory barrier before a volatile CpBlk operation
<API key>();
}
genEmitHelperCall(CORINFO_HELP_MEMCPY, 0, EA_UNKNOWN);
if (cpBlkNode->gtFlags & GTF_BLK_VOLATILE)
{
#ifdef _TARGET_ARM64_
// issue a INS_BARRIER_ISHLD after a volatile CpBlk operation
<API key>(INS_BARRIER_ISHLD);
#else
// issue a full memory barrier after a volatile CpBlk operation
<API key>();
#endif // _TARGET_ARM64_
}
}
// <API key>: Generates CpBlk code by performing a loop unroll
// Arguments:
// cpBlkNode - Copy block node
// Return Value:
// None
// Assumption:
// The size argument of the CpBlk node is a constant and <= CPBLK_UNROLL_LIMIT bytes.
void CodeGen::<API key>(GenTreeBlk* cpBlkNode)
{
// Make sure we got the arguments of the cpblk operation in the right registers
unsigned size = cpBlkNode->Size();
GenTreePtr dstAddr = cpBlkNode->Addr();
GenTreePtr source = cpBlkNode->Data();
GenTreePtr srcAddr = nullptr;
assert((size != 0) && (size <= CPBLK_UNROLL_LIMIT));
emitter* emit = getEmitter();
if (dstAddr->isUsedFromReg())
{
genConsumeReg(dstAddr);
}
if (cpBlkNode->gtFlags & GTF_BLK_VOLATILE)
{
// issue a full memory barrier before a volatile CpBlkUnroll operation
<API key>();
}
if (source->gtOper == GT_IND)
{
srcAddr = source->gtGetOp1();
if (srcAddr->isUsedFromReg())
{
genConsumeReg(srcAddr);
}
}
else
{
noway_assert(source->IsLocal());
// TODO-Cleanup: Consider making the addrForm() method in Rationalize public, e.g. in GenTree.
// OR: transform source to GT_IND(GT_LCL_VAR_ADDR)
if (source->OperGet() == GT_LCL_VAR)
{
source->SetOper(GT_LCL_VAR_ADDR);
}
else
{
assert(source->OperGet() == GT_LCL_FLD);
source->SetOper(GT_LCL_FLD_ADDR);
}
srcAddr = source;
}
unsigned offset = 0;
// Grab the integer temp register to emit the loads and stores.
regNumber tmpReg = cpBlkNode->ExtractTempReg(RBM_ALLINT);
#ifdef _TARGET_ARM64_
if (size >= 2 * REGSIZE_BYTES)
{
regNumber tmp2Reg = cpBlkNode->ExtractTempReg(RBM_ALLINT);
size_t slots = size / (2 * REGSIZE_BYTES);
while (slots
{
// Load
<API key>(tmpReg, tmp2Reg, srcAddr, offset);
// Store
<API key>(tmpReg, tmp2Reg, dstAddr, offset);
offset += 2 * REGSIZE_BYTES;
}
}
// Fill the remainder (15 bytes or less) if there's one.
if ((size & 0xf) != 0)
{
if ((size & 8) != 0)
{
<API key>(INS_ldr, EA_8BYTE, tmpReg, srcAddr, offset);
<API key>(INS_str, EA_8BYTE, tmpReg, dstAddr, offset);
offset += 8;
}
if ((size & 4) != 0)
{
<API key>(INS_ldr, EA_4BYTE, tmpReg, srcAddr, offset);
<API key>(INS_str, EA_4BYTE, tmpReg, dstAddr, offset);
offset += 4;
}
if ((size & 2) != 0)
{
<API key>(INS_ldrh, EA_2BYTE, tmpReg, srcAddr, offset);
<API key>(INS_strh, EA_2BYTE, tmpReg, dstAddr, offset);
offset += 2;
}
if ((size & 1) != 0)
{
<API key>(INS_ldrb, EA_1BYTE, tmpReg, srcAddr, offset);
<API key>(INS_strb, EA_1BYTE, tmpReg, dstAddr, offset);
}
}
#else // !_TARGET_ARM64_
size_t slots = size / REGSIZE_BYTES;
while (slots
{
<API key>(INS_ldr, EA_4BYTE, tmpReg, srcAddr, offset);
<API key>(INS_str, EA_4BYTE, tmpReg, dstAddr, offset);
offset += REGSIZE_BYTES;
}
// Fill the remainder (3 bytes or less) if there's one.
if ((size & 0x03) != 0)
{
if ((size & 2) != 0)
{
<API key>(INS_ldrh, EA_2BYTE, tmpReg, srcAddr, offset);
<API key>(INS_strh, EA_2BYTE, tmpReg, dstAddr, offset);
offset += 2;
}
if ((size & 1) != 0)
{
<API key>(INS_ldrb, EA_1BYTE, tmpReg, srcAddr, offset);
<API key>(INS_strb, EA_1BYTE, tmpReg, dstAddr, offset);
}
}
#endif // !_TARGET_ARM64_
if (cpBlkNode->gtFlags & GTF_BLK_VOLATILE)
{
#ifdef _TARGET_ARM64_
// issue a INS_BARRIER_ISHLD after a volatile CpBlkUnroll operation
<API key>(INS_BARRIER_ISHLD);
#else
// issue a full memory barrier after a volatile CpBlk operation
<API key>();
#endif // !_TARGET_ARM64_
}
}
// Generates code for InitBlk by calling the VM memset helper function.
// Preconditions:
// a) The size argument of the InitBlk is not an integer constant.
// b) The size argument of the InitBlk is >= INITBLK_STOS_LIMIT bytes.
void CodeGen::genCodeForInitBlk(GenTreeBlk* initBlkNode)
{
unsigned size = initBlkNode->Size();
GenTreePtr dstAddr = initBlkNode->Addr();
GenTreePtr initVal = initBlkNode->Data();
if (initVal->OperIsInitVal())
{
initVal = initVal->gtGetOp1();
}
assert(!dstAddr->isContained());
assert(!initVal->isContained());
#ifdef _TARGET_ARM64_
if (size != 0)
{
assert(size > <API key>);
}
#endif // _TARGET_ARM64_
genConsumeBlockOp(initBlkNode, REG_ARG_0, REG_ARG_1, REG_ARG_2);
if (initBlkNode->gtFlags & GTF_BLK_VOLATILE)
{
// issue a full memory barrier before a volatile initBlock Operation
<API key>();
}
genEmitHelperCall(CORINFO_HELP_MEMSET, 0, EA_UNKNOWN);
}
// Generate code for a load from some address + offset
// base: tree node which can be either a local address or arbitrary node
// offset: distance from the base from which to load
void CodeGen::<API key>(instruction ins, emitAttr size, regNumber dst, GenTree* base, unsigned offset)
{
emitter* emit = getEmitter();
if (base->OperIsLocalAddr())
{
if (base->gtOper == GT_LCL_FLD_ADDR)
offset += base->gtLclFld.gtLclOffs;
emit->emitIns_R_S(ins, size, dst, base->gtLclVarCommon.gtLclNum, offset);
}
else
{
emit->emitIns_R_R_I(ins, size, dst, base->gtRegNum, offset);
}
}
// Generate code for a store to some address + offset
// base: tree node which can be either a local address or arbitrary node
// offset: distance from the base from which to load
void CodeGen::<API key>(instruction ins, emitAttr size, regNumber src, GenTree* base, unsigned offset)
{
emitter* emit = getEmitter();
if (base->OperIsLocalAddr())
{
if (base->gtOper == GT_LCL_FLD_ADDR)
offset += base->gtLclFld.gtLclOffs;
emit->emitIns_S_R(ins, size, src, base->gtLclVarCommon.gtLclNum, offset);
}
else
{
emit->emitIns_R_R_I(ins, size, src, base->gtRegNum, offset);
}
}
// genRegCopy: Generate a register copy.
void CodeGen::genRegCopy(GenTree* treeNode)
{
assert(treeNode->OperGet() == GT_COPY);
var_types targetType = treeNode->TypeGet();
regNumber targetReg = treeNode->gtRegNum;
assert(targetReg != REG_NA);
GenTree* op1 = treeNode->gtOp.gtOp1;
// Check whether this node and the node from which we're copying the value have the same
// register type.
// This can happen if (currently iff) we have a SIMD vector type that fits in an integer
// register, in which case it is passed as an argument, or returned from a call,
// in an integer register and must be copied if it's in an xmm register.
if (varTypeIsFloating(treeNode) != varTypeIsFloating(op1))
{
#ifdef _TARGET_ARM64_
inst_RV_RV(INS_fmov, targetReg, genConsumeReg(op1), targetType);
#else // !_TARGET_ARM64_
if (varTypeIsFloating(treeNode))
{
NYI_ARM("genRegCopy from 'int' to 'float'");
}
else
{
assert(varTypeIsFloating(op1));
if (op1->TypeGet() == TYP_FLOAT)
{
inst_RV_RV(INS_vmov_f2i, targetReg, genConsumeReg(op1), targetType);
}
else
{
regNumber otherReg = (regNumber)treeNode->AsCopyOrReload()->gtOtherRegs[0];
assert(otherReg != REG_NA);
inst_RV_RV_RV(INS_vmov_d2i, targetReg, otherReg, genConsumeReg(op1), EA_8BYTE);
}
}
#endif // !_TARGET_ARM64_
}
else
{
inst_RV_RV(ins_Copy(targetType), targetReg, genConsumeReg(op1), targetType);
}
if (op1->IsLocal())
{
// The lclVar will never be a def.
// If it is a last use, the lclVar will be killed by genConsumeReg(), as usual, and genProduceReg will
// appropriately set the gcInfo for the copied value.
// If not, there are two cases we need to handle:
// - If this is a TEMPORARY copy (indicated by the GTF_VAR_DEATH flag) the variable
// will remain live in its original register.
// genProduceReg() will appropriately set the gcInfo for the copied value,
// and genConsumeReg will reset it.
// - Otherwise, we need to update register info for the lclVar.
GenTreeLclVarCommon* lcl = op1->AsLclVarCommon();
assert((lcl->gtFlags & GTF_VAR_DEF) == 0);
if ((lcl->gtFlags & GTF_VAR_DEATH) == 0 && (treeNode->gtFlags & GTF_VAR_DEATH) == 0)
{
LclVarDsc* varDsc = &compiler->lvaTable[lcl->gtLclNum];
// If we didn't just spill it (in genConsumeReg, above), then update the register info
if (varDsc->lvRegNum != REG_STK)
{
// The old location is dying
genUpdateRegLife(varDsc, /*isBorn*/ false, /*isDying*/ true DEBUGARG(op1));
gcInfo.gcMarkRegSetNpt(genRegMask(op1->gtRegNum));
genUpdateVarReg(varDsc, treeNode);
// The new location is going live
genUpdateRegLife(varDsc, /*isBorn*/ true, /*isDying*/ false DEBUGARG(treeNode));
}
}
}
genProduceReg(treeNode);
}
// genCallInstruction: Produce code for a GT_CALL node
void CodeGen::genCallInstruction(GenTreeCall* call)
{
gtCallTypes callType = (gtCallTypes)call->gtCallType;
IL_OFFSETX ilOffset = BAD_IL_OFFSET;
// all virtuals should have been expanded into a control expression
assert(!call->IsVirtual() || call->gtControlExpr || call->gtCallAddr);
// Consume all the arg regs
for (GenTreePtr list = call->gtCallLateArgs; list; list = list->MoveNext())
{
assert(list->OperIsList());
GenTreePtr argNode = list->Current();
fgArgTabEntryPtr curArgTabEntry = compiler->gtArgEntryByNode(call, argNode);
assert(curArgTabEntry);
// GT_RELOAD/GT_COPY use the child node
argNode = argNode->gtSkipReloadOrCopy();
if (curArgTabEntry->regNum == REG_STK)
continue;
// Deal with multi register passed struct args.
if (argNode->OperGet() == GT_FIELD_LIST)
{
GenTreeArgList* argListPtr = argNode->AsArgList();
unsigned iterationNum = 0;
regNumber argReg = curArgTabEntry->regNum;
for (; argListPtr != nullptr; argListPtr = argListPtr->Rest(), iterationNum++)
{
GenTreePtr putArgRegNode = argListPtr->gtOp.gtOp1;
assert(putArgRegNode->gtOper == GT_PUTARG_REG);
genConsumeReg(putArgRegNode);
if (putArgRegNode->gtRegNum != argReg)
{
inst_RV_RV(ins_Move_Extend(putArgRegNode->TypeGet(), true), argReg, putArgRegNode->gtRegNum);
}
argReg = genRegArgNext(argReg);
#if defined(_TARGET_ARM_)
// A double register is modelled as an even-numbered single one
if (putArgRegNode->TypeGet() == TYP_DOUBLE)
{
argReg = genRegArgNext(argReg);
}
#endif // _TARGET_ARM_
}
}
#ifdef _TARGET_ARM_
else if (curArgTabEntry->isSplit)
{
assert(curArgTabEntry->numRegs >= 1);
<API key>(argNode->AsPutArgSplit());
for (unsigned idx = 0; idx < curArgTabEntry->numRegs; idx++)
{
regNumber argReg = (regNumber)((unsigned)curArgTabEntry->regNum + idx);
regNumber allocReg = argNode->AsPutArgSplit()->GetRegNumByIdx(idx);
if (argReg != allocReg)
{
inst_RV_RV(ins_Move_Extend(argNode->TypeGet(), true), argReg, allocReg);
}
}
}
#endif
else
{
regNumber argReg = curArgTabEntry->regNum;
genConsumeReg(argNode);
if (argNode->gtRegNum != argReg)
{
inst_RV_RV(ins_Move_Extend(argNode->TypeGet(), true), argReg, argNode->gtRegNum);
}
}
}
// Insert a null check on "this" pointer if asked.
if (call->NeedsNullCheck())
{
const regNumber regThis = genGetThisArgReg(call);
#if defined(_TARGET_ARM_)
const regNumber tmpReg = call->ExtractTempReg();
getEmitter()->emitIns_R_R_I(INS_ldr, EA_4BYTE, tmpReg, regThis, 0);
#elif defined(_TARGET_ARM64_)
getEmitter()->emitIns_R_R_I(INS_ldr, EA_4BYTE, REG_ZR, regThis, 0);
#endif // _TARGET_*
}
// Either gtControlExpr != null or gtCallAddr != null or it is a direct non-virtual call to a user or helper method.
<API key> methHnd;
GenTree* target = call->gtControlExpr;
if (callType == CT_INDIRECT)
{
assert(target == nullptr);
target = call->gtCallAddr;
methHnd = nullptr;
}
else
{
methHnd = call->gtCallMethHnd;
}
CORINFO_SIG_INFO* sigInfo = nullptr;
#ifdef DEBUG
// Pass the call signature information down into the emitter so the emitter can associate
// native call sites with the signatures they were generated from.
if (callType != CT_HELPER)
{
sigInfo = call->callSig;
}
#endif // DEBUG
// If fast tail call, then we are done. In this case we setup the args (both reg args
// and stack args in incoming arg area) and call target. Epilog sequence would
// generate "br <reg>".
if (call->IsFastTailCall())
{
// Don't support fast tail calling JIT helpers
assert(callType != CT_HELPER);
// Fast tail calls materialize call target either in gtControlExpr or in gtCallAddr.
assert(target != nullptr);
genConsumeReg(target);
// Use IP0 on ARM64 and R12 on ARM32 as the call target register.
if (target->gtRegNum != <API key>)
{
inst_RV_RV(INS_mov, <API key>, target->gtRegNum);
}
return;
}
// For a pinvoke to unmanaged code we emit a label to clear
// the GC pointer state before the callsite.
// We can't utilize the typical lazy killing of GC pointers
// at (or inside) the callsite.
if (compiler->killGCRefs(call))
{
genDefineTempLabel(genCreateTempLabel());
}
// Determine return value size(s).
ReturnTypeDesc* pRetTypeDesc = call->GetReturnTypeDesc();
emitAttr retSize = EA_PTRSIZE;
emitAttr secondRetSize = EA_UNKNOWN;
if (call->HasMultiRegRetVal())
{
retSize = emitTypeSize(pRetTypeDesc->GetReturnRegType(0));
secondRetSize = emitTypeSize(pRetTypeDesc->GetReturnRegType(1));
}
else
{
assert(!varTypeIsStruct(call));
if (call->gtType == TYP_REF || call->gtType == TYP_ARRAY)
{
retSize = EA_GCREF;
}
else if (call->gtType == TYP_BYREF)
{
retSize = EA_BYREF;
}
}
// We need to propagate the IL offset information to the call instruction, so we can emit
// an IL to native mapping record for the call, to support managed return value debugging.
// We don't want tail call helper calls that were converted from normal calls to get a record,
// so we skip this hash table lookup logic in that case.
if (compiler->opts.compDbgInfo && compiler-><API key> != nullptr && !call->IsTailCall())
{
(void)compiler-><API key>->Lookup(call, &ilOffset);
}
if (target != nullptr)
{
// A call target can not be a contained indirection
assert(!target->isContainedIndir());
genConsumeReg(target);
// We have already generated code for gtControlExpr evaluating it into a register.
// We just need to emit "call reg" in this case.
assert(genIsValidIntReg(target->gtRegNum));
genEmitCall(emitter::EC_INDIR_R, methHnd,
<API key>(sigInfo) nullptr, // addr
retSize <API key>(secondRetSize), ilOffset, target->gtRegNum);
}
else
{
// Generate a direct call to a non-virtual user defined or helper method
assert(callType == CT_HELPER || callType == CT_USER_FUNC);
void* addr = nullptr;
#ifdef <API key>
if (call->gtEntryPoint.addr != NULL)
{
assert(call->gtEntryPoint.accessType == IAT_VALUE);
addr = call->gtEntryPoint.addr;
}
else
#endif // <API key>
if (callType == CT_HELPER)
{
CorInfoHelpFunc helperNum = compiler->eeGetHelperNum(methHnd);
noway_assert(helperNum != CORINFO_HELP_UNDEF);
void* pAddr = nullptr;
addr = compiler->compGetHelperFtn(helperNum, (void**)&pAddr);
assert(pAddr == nullptr);
}
else
{
// Direct call to a non-virtual user function.
addr = call->gtDirectCallAddress;
}
assert(addr != nullptr);
// Non-virtual direct call to known addresses
#ifdef _TARGET_ARM_
if (!<API key>((ssize_t)addr))
{
regNumber tmpReg = call->GetSingleTempReg();
<API key>(EA_HANDLE_CNS_RELOC, tmpReg, (ssize_t)addr);
genEmitCall(emitter::EC_INDIR_R, methHnd, <API key>(sigInfo) NULL, retSize, ilOffset, tmpReg);
}
else
#endif // _TARGET_ARM_
{
genEmitCall(emitter::EC_FUNC_TOKEN, methHnd, <API key>(sigInfo) addr,
retSize <API key>(secondRetSize), ilOffset);
}
#if 0 && defined(_TARGET_ARM64_)
// Use this path if you want to load an absolute call target using
// a sequence of movs followed by an indirect call (blr instruction)
// Load the call target address in x16
<API key>(EA_8BYTE, REG_IP0, (ssize_t) addr);
// indirect call to constant address in IP0
genEmitCall(emitter::EC_INDIR_R,
methHnd,
<API key>(sigInfo)
nullptr, //addr
retSize,
secondRetSize,
ilOffset,
REG_IP0);
#endif
}
// if it was a pinvoke we may have needed to get the address of a label
if (genPendingCallLabel)
{
assert(call->IsUnmanaged());
genDefineTempLabel(genPendingCallLabel);
genPendingCallLabel = nullptr;
}
// Update GC info:
// All Callee arg registers are trashed and no longer contain any GC pointers.
// TODO-Bug?: As a matter of fact shouldn't we be killing all of callee trashed regs here?
// For now we will assert that other than arg regs gc ref/byref set doesn't contain any other
// registers from RBM_CALLEE_TRASH
assert((gcInfo.gcRegGCrefSetCur & (RBM_CALLEE_TRASH & ~RBM_ARG_REGS)) == 0);
assert((gcInfo.gcRegByrefSetCur & (RBM_CALLEE_TRASH & ~RBM_ARG_REGS)) == 0);
gcInfo.gcRegGCrefSetCur &= ~RBM_ARG_REGS;
gcInfo.gcRegByrefSetCur &= ~RBM_ARG_REGS;
var_types returnType = call->TypeGet();
if (returnType != TYP_VOID)
{
regNumber returnReg;
if (call->HasMultiRegRetVal())
{
assert(pRetTypeDesc != nullptr);
unsigned regCount = pRetTypeDesc->GetReturnRegCount();
// If regs allocated to call node are different from ABI return
// regs in which the call has returned its result, move the result
// to regs allocated to call node.
for (unsigned i = 0; i < regCount; ++i)
{
var_types regType = pRetTypeDesc->GetReturnRegType(i);
returnReg = pRetTypeDesc->GetABIReturnReg(i);
regNumber allocatedReg = call->GetRegNumByIdx(i);
if (returnReg != allocatedReg)
{
inst_RV_RV(ins_Copy(regType), allocatedReg, returnReg, regType);
}
}
}
else
{
#ifdef _TARGET_ARM_
if (call->IsHelperCall(compiler, <API key>))
{
// The <API key> helper uses a custom calling convention that returns with
// TCB in REG_PINVOKE_TCB. fgMorphCall() sets the correct argument registers.
returnReg = REG_PINVOKE_TCB;
}
else
#endif // _TARGET_ARM_
if (varTypeIsFloating(returnType) && !compiler->opts.compUseSoftFP)
{
returnReg = REG_FLOATRET;
}
else
{
returnReg = REG_INTRET;
}
if (call->gtRegNum != returnReg)
{
#ifdef _TARGET_ARM_
if (compiler->opts.compUseSoftFP && returnType == TYP_DOUBLE)
{
inst_RV_RV_RV(INS_vmov_i2d, call->gtRegNum, returnReg, genRegArgNext(returnReg), EA_8BYTE);
}
else if (compiler->opts.compUseSoftFP && returnType == TYP_FLOAT)
{
inst_RV_RV(INS_vmov_i2f, call->gtRegNum, returnReg, returnType);
}
else
#endif
{
inst_RV_RV(ins_Copy(returnType), call->gtRegNum, returnReg, returnType);
}
}
}
genProduceReg(call);
}
// If there is nothing next, that means the result is thrown away, so this value is not live.
// However, for minopts or debuggable code, we keep it live to support managed return value debugging.
if ((call->gtNext == nullptr) && !compiler->opts.MinOpts() && !compiler->opts.compDbgCode)
{
gcInfo.gcMarkRegSetNpt(RBM_INTRET);
}
}
// Produce code for a GT_JMP node.
// The arguments of the caller needs to be transferred to the callee before exiting caller.
// The actual jump to callee is generated as part of caller epilog sequence.
// Therefore the codegen of GT_JMP is to ensure that the callee arguments are correctly setup.
void CodeGen::genJmpMethod(GenTreePtr jmp)
{
assert(jmp->OperGet() == GT_JMP);
assert(compiler->compJmpOpUsed);
// If no arguments, nothing to do
if (compiler->info.compArgsCount == 0)
{
return;
}
// Make sure register arguments are in their initial registers
// and stack arguments are put back as well.
unsigned varNum;
LclVarDsc* varDsc;
// First move any en-registered stack arguments back to the stack.
// At the same time any reg arg not in correct reg is moved back to its stack location.
// We are not strictly required to spill reg args that are not in the desired reg for a jmp call
// But that would require us to deal with circularity while moving values around. Spilling
// to stack makes the implementation simple, which is not a bad trade off given Jmp calls
// are not frequent.
for (varNum = 0; (varNum < compiler->info.compArgsCount); varNum++)
{
varDsc = compiler->lvaTable + varNum;
if (varDsc->lvPromoted)
{
noway_assert(varDsc->lvFieldCnt == 1); // We only handle one field here
unsigned fieldVarNum = varDsc->lvFieldLclStart;
varDsc = compiler->lvaTable + fieldVarNum;
}
noway_assert(varDsc->lvIsParam);
if (varDsc->lvIsRegArg && (varDsc->lvRegNum != REG_STK))
{
// Skip reg args which are already in its right register for jmp call.
// If not, we will spill such args to their stack locations.
// If we need to generate a tail call profiler hook, then spill all
// arg regs to free them up for the callback.
if (!compiler-><API key>() && (varDsc->lvRegNum == varDsc->lvArgReg))
continue;
}
else if (varDsc->lvRegNum == REG_STK)
{
// Skip args which are currently living in stack.
continue;
}
// If we came here it means either a reg argument not in the right register or
// a stack argument currently living in a register. In either case the following
// assert should hold.
assert(varDsc->lvRegNum != REG_STK);
assert(varDsc->TypeGet() != TYP_STRUCT);
var_types storeType = genActualType(varDsc->TypeGet());
emitAttr storeSize = emitActualTypeSize(storeType);
#ifdef _TARGET_ARM_
if (varDsc->TypeGet() == TYP_LONG)
{
// long - at least the low half must be enregistered
getEmitter()->emitIns_S_R(ins_Store(TYP_INT), EA_4BYTE, varDsc->lvRegNum, varNum, 0);
// Is the upper half also enregistered?
if (varDsc->lvOtherReg != REG_STK)
{
getEmitter()->emitIns_S_R(ins_Store(TYP_INT), EA_4BYTE, varDsc->lvOtherReg, varNum, sizeof(int));
}
}
else
#endif // _TARGET_ARM_
{
getEmitter()->emitIns_S_R(ins_Store(storeType), storeSize, varDsc->lvRegNum, varNum, 0);
}
// Update lvRegNum life and GC info to indicate lvRegNum is dead and varDsc stack slot is going live.
// Note that we cannot modify varDsc->lvRegNum here because another basic block may not be expecting it.
// Therefore manually update life of varDsc->lvRegNum.
regMaskTP tempMask = genRegMask(varDsc->lvRegNum);
regSet.RemoveMaskVars(tempMask);
gcInfo.gcMarkRegSetNpt(tempMask);
if (compiler->lvaIsGCTracked(varDsc))
{
VarSetOps::AddElemD(compiler, gcInfo.gcVarPtrSetCur, varNum);
}
}
#ifdef PROFILING_SUPPORTED
// At this point all arg regs are free.
// Emit tail call profiler callback.
<API key>(<API key>);
#endif
// Next move any un-enregistered register arguments back to their register.
regMaskTP fixedIntArgMask = RBM_NONE; // tracks the int arg regs occupying fixed args in case of a vararg method.
unsigned firstArgVarNum = BAD_VAR_NUM; // varNum of the first argument in case of a vararg method.
for (varNum = 0; (varNum < compiler->info.compArgsCount); varNum++)
{
varDsc = compiler->lvaTable + varNum;
if (varDsc->lvPromoted)
{
noway_assert(varDsc->lvFieldCnt == 1); // We only handle one field here
unsigned fieldVarNum = varDsc->lvFieldLclStart;
varDsc = compiler->lvaTable + fieldVarNum;
}
noway_assert(varDsc->lvIsParam);
// Skip if arg not passed in a register.
if (!varDsc->lvIsRegArg)
continue;
// Register argument
noway_assert(isRegParamType(genActualType(varDsc->TypeGet())));
// Is register argument already in the right register?
// If not load it from its stack location.
regNumber argReg = varDsc->lvArgReg; // incoming arg register
regNumber argRegNext = REG_NA;
#ifdef _TARGET_ARM64_
if (varDsc->lvRegNum != argReg)
{
var_types loadType = TYP_UNDEF;
if (varTypeIsStruct(varDsc))
{
// Must be <= 16 bytes or else it wouldn't be passed in registers
noway_assert(EA_SIZE_IN_BYTES(varDsc->lvSize()) <= <API key>);
loadType = compiler->getJitGCType(varDsc->lvGcLayout[0]);
}
else
{
loadType = compiler->mangleVarArgsType(genActualType(varDsc->TypeGet()));
}
emitAttr loadSize = emitActualTypeSize(loadType);
getEmitter()->emitIns_R_S(ins_Load(loadType), loadSize, argReg, varNum, 0);
// Update argReg life and GC Info to indicate varDsc stack slot is dead and argReg is going live.
// Note that we cannot modify varDsc->lvRegNum here because another basic block may not be expecting it.
// Therefore manually update life of argReg. Note that GT_JMP marks the end of the basic block
// and after which reg life and gc info will be recomputed for the new block in genCodeForBBList().
regSet.AddMaskVars(genRegMask(argReg));
gcInfo.gcMarkRegPtrVal(argReg, loadType);
if (compiler->lvaIsMultiregStruct(varDsc))
{
if (varDsc->lvIsHfa())
{
NYI_ARM64("CodeGen::genJmpMethod with multireg HFA arg");
}
// Restore the second register.
argRegNext = genRegArgNext(argReg);
loadType = compiler->getJitGCType(varDsc->lvGcLayout[1]);
loadSize = emitActualTypeSize(loadType);
getEmitter()->emitIns_R_S(ins_Load(loadType), loadSize, argRegNext, varNum, TARGET_POINTER_SIZE);
regSet.AddMaskVars(genRegMask(argRegNext));
gcInfo.gcMarkRegPtrVal(argRegNext, loadType);
}
if (compiler->lvaIsGCTracked(varDsc))
{
VarSetOps::RemoveElemD(compiler, gcInfo.gcVarPtrSetCur, varNum);
}
}
// In case of a jmp call to a vararg method ensure only integer registers are passed.
if (compiler->info.compIsVarArgs)
{
assert((genRegMask(argReg) & RBM_ARG_REGS) != RBM_NONE);
fixedIntArgMask |= genRegMask(argReg);
if (compiler->lvaIsMultiregStruct(varDsc))
{
assert(argRegNext != REG_NA);
fixedIntArgMask |= genRegMask(argRegNext);
}
if (argReg == REG_ARG_0)
{
assert(firstArgVarNum == BAD_VAR_NUM);
firstArgVarNum = varNum;
}
}
#else
bool twoParts = false;
var_types loadType = TYP_UNDEF;
if (varDsc->TypeGet() == TYP_LONG)
{
twoParts = true;
}
else if (varDsc->TypeGet() == TYP_DOUBLE)
{
if (compiler->info.compIsVarArgs || compiler->opts.compUseSoftFP)
{
twoParts = true;
}
}
if (twoParts)
{
argRegNext = genRegArgNext(argReg);
if (varDsc->lvRegNum != argReg)
{
getEmitter()->emitIns_R_S(INS_ldr, EA_PTRSIZE, argReg, varNum, 0);
getEmitter()->emitIns_R_S(INS_ldr, EA_PTRSIZE, argRegNext, varNum, REGSIZE_BYTES);
}
if (compiler->info.compIsVarArgs)
{
fixedIntArgMask |= genRegMask(argReg);
fixedIntArgMask |= genRegMask(argRegNext);
}
}
else if (varDsc->lvIsHfaRegArg())
{
loadType = varDsc->GetHfaType();
regNumber fieldReg = argReg;
emitAttr loadSize = emitActualTypeSize(loadType);
unsigned maxSize = min(varDsc->lvSize(), (LAST_FP_ARGREG + 1 - argReg) * REGSIZE_BYTES);
for (unsigned ofs = 0; ofs < maxSize; ofs += (unsigned)loadSize)
{
if (varDsc->lvRegNum != argReg)
{
getEmitter()->emitIns_R_S(ins_Load(loadType), loadSize, fieldReg, varNum, ofs);
}
assert(genIsValidFloatReg(fieldReg)); // we don't use register tracking for FP
fieldReg = regNextOfType(fieldReg, loadType);
}
}
else if (varTypeIsStruct(varDsc))
{
regNumber slotReg = argReg;
unsigned maxSize = min(varDsc->lvSize(), (REG_ARG_LAST + 1 - argReg) * REGSIZE_BYTES);
for (unsigned ofs = 0; ofs < maxSize; ofs += REGSIZE_BYTES)
{
unsigned idx = ofs / REGSIZE_BYTES;
loadType = compiler->getJitGCType(varDsc->lvGcLayout[idx]);
if (varDsc->lvRegNum != argReg)
{
emitAttr loadSize = emitActualTypeSize(loadType);
getEmitter()->emitIns_R_S(ins_Load(loadType), loadSize, slotReg, varNum, ofs);
}
regSet.AddMaskVars(genRegMask(slotReg));
gcInfo.gcMarkRegPtrVal(slotReg, loadType);
if (genIsValidIntReg(slotReg) && compiler->info.compIsVarArgs)
{
fixedIntArgMask |= genRegMask(slotReg);
}
slotReg = genRegArgNext(slotReg);
}
}
else
{
loadType = compiler->mangleVarArgsType(genActualType(varDsc->TypeGet()));
if (varDsc->lvRegNum != argReg)
{
getEmitter()->emitIns_R_S(ins_Load(loadType), emitTypeSize(loadType), argReg, varNum, 0);
}
regSet.AddMaskVars(genRegMask(argReg));
gcInfo.gcMarkRegPtrVal(argReg, loadType);
if (genIsValidIntReg(argReg) && compiler->info.compIsVarArgs)
{
fixedIntArgMask |= genRegMask(argReg);
}
}
if (compiler->lvaIsGCTracked(varDsc))
{
VarSetOps::RemoveElemD(compiler, gcInfo.gcVarPtrSetCur, varNum);
}
#endif
}
// Jmp call to a vararg method - if the method has fewer than fixed arguments that can be max size of reg,
// load the remaining integer arg registers from the corresponding
// shadow stack slots. This is for the reason that we don't know the number and type
// of non-fixed params passed by the caller, therefore we have to assume the worst case
// of caller passing all integer arg regs that can be max size of reg.
// The caller could have passed gc-ref/byref type var args. Since these are var args
// the callee no way of knowing their gc-ness. Therefore, mark the region that loads
// remaining arg registers from shadow stack slots as non-gc interruptible.
if (fixedIntArgMask != RBM_NONE)
{
assert(compiler->info.compIsVarArgs);
assert(firstArgVarNum != BAD_VAR_NUM);
regMaskTP remainingIntArgMask = RBM_ARG_REGS & ~fixedIntArgMask;
if (remainingIntArgMask != RBM_NONE)
{
getEmitter()->emitDisableGC();
for (int argNum = 0, argOffset = 0; argNum < MAX_REG_ARG; ++argNum)
{
regNumber argReg = intArgRegs[argNum];
regMaskTP argRegMask = genRegMask(argReg);
if ((remainingIntArgMask & argRegMask) != 0)
{
remainingIntArgMask &= ~argRegMask;
getEmitter()->emitIns_R_S(INS_ldr, EA_PTRSIZE, argReg, firstArgVarNum, argOffset);
}
argOffset += REGSIZE_BYTES;
}
getEmitter()->emitEnableGC();
}
}
}
// genIntToIntCast: Generate code for an integer cast
// Arguments:
// treeNode - The GT_CAST node
// Return Value:
// None.
// Assumptions:
// The treeNode must have an assigned register.
// For a signed convert from byte, the source must be in a byte-addressable register.
// Neither the source nor target type can be a floating point type.
// TODO-ARM64-CQ: Allow castOp to be a contained node without an assigned register.
void CodeGen::genIntToIntCast(GenTreePtr treeNode)
{
assert(treeNode->OperGet() == GT_CAST);
GenTreePtr castOp = treeNode->gtCast.CastOp();
emitter* emit = getEmitter();
var_types dstType = treeNode->CastToType();
var_types srcType = genActualType(castOp->TypeGet());
emitAttr movSize = emitActualTypeSize(dstType);
bool movRequired = false;
#ifdef _TARGET_ARM_
if (varTypeIsLong(srcType))
{
genLongToIntCast(treeNode);
return;
}
#endif // _TARGET_ARM_
regNumber targetReg = treeNode->gtRegNum;
regNumber sourceReg = castOp->gtRegNum;
// For Long to Int conversion we will have a reserved integer register to hold the immediate mask
regNumber tmpReg = (treeNode-><API key>() == 0) ? REG_NA : treeNode->GetSingleTempReg();
assert(genIsValidIntReg(targetReg));
assert(genIsValidIntReg(sourceReg));
instruction ins = INS_invalid;
genConsumeReg(castOp);
Lowering::CastInfo castInfo;
// Get information about the cast.
Lowering::getCastDescription(treeNode, &castInfo);
if (castInfo.<API key>)
{
emitAttr cmpSize = EA_ATTR(genTypeSize(srcType));
if (castInfo.signCheckOnly)
{
// We only need to check for a negative value in sourceReg
emit->emitIns_R_I(INS_cmp, cmpSize, sourceReg, 0);
emitJumpKind jmpLT = genJumpKindForOper(GT_LT, CK_SIGNED);
<API key>(jmpLT, SCK_OVERFLOW);
noway_assert(genTypeSize(srcType) == 4 || genTypeSize(srcType) == 8);
// This is only interesting case to ensure zero-upper bits.
if ((srcType == TYP_INT) && (dstType == TYP_ULONG))
{
// cast to TYP_ULONG:
// We use a mov with size=EA_4BYTE
// which will zero out the upper bits
movSize = EA_4BYTE;
movRequired = true;
}
}
else if (castInfo.unsignedSource || castInfo.unsignedDest)
{
// When we are converting from/to unsigned,
// we only have to check for any bits set in 'typeMask'
noway_assert(castInfo.typeMask != 0);
#if defined(_TARGET_ARM_)
if (<API key>(INS_tst, castInfo.typeMask, INS_FLAGS_DONT_CARE))
{
emit->emitIns_R_I(INS_tst, cmpSize, sourceReg, castInfo.typeMask);
}
else
{
noway_assert(tmpReg != REG_NA);
<API key>(cmpSize, tmpReg, castInfo.typeMask);
emit->emitIns_R_R(INS_tst, cmpSize, sourceReg, tmpReg);
}
#elif defined(_TARGET_ARM64_)
emit->emitIns_R_I(INS_tst, cmpSize, sourceReg, castInfo.typeMask);
#endif // _TARGET_ARM*
emitJumpKind jmpNotEqual = genJumpKindForOper(GT_NE, CK_SIGNED);
<API key>(jmpNotEqual, SCK_OVERFLOW);
}
else
{
// For a narrowing signed cast
// We must check the value is in a signed range.
// Compare with the MAX
noway_assert((castInfo.typeMin != 0) && (castInfo.typeMax != 0));
#if defined(_TARGET_ARM_)
if (emitter::<API key>(castInfo.typeMax, INS_FLAGS_DONT_CARE))
#elif defined(_TARGET_ARM64_)
if (emitter::<API key>(castInfo.typeMax, cmpSize))
#endif // _TARGET_*
{
emit->emitIns_R_I(INS_cmp, cmpSize, sourceReg, castInfo.typeMax);
}
else
{
noway_assert(tmpReg != REG_NA);
<API key>(cmpSize, tmpReg, castInfo.typeMax);
emit->emitIns_R_R(INS_cmp, cmpSize, sourceReg, tmpReg);
}
emitJumpKind jmpGT = genJumpKindForOper(GT_GT, CK_SIGNED);
<API key>(jmpGT, SCK_OVERFLOW);
// Compare with the MIN
#if defined(_TARGET_ARM_)
if (emitter::<API key>(castInfo.typeMin, INS_FLAGS_DONT_CARE))
#elif defined(_TARGET_ARM64_)
if (emitter::<API key>(castInfo.typeMin, cmpSize))
#endif // _TARGET_*
{
emit->emitIns_R_I(INS_cmp, cmpSize, sourceReg, castInfo.typeMin);
}
else
{
noway_assert(tmpReg != REG_NA);
<API key>(cmpSize, tmpReg, castInfo.typeMin);
emit->emitIns_R_R(INS_cmp, cmpSize, sourceReg, tmpReg);
}
emitJumpKind jmpLT = genJumpKindForOper(GT_LT, CK_SIGNED);
<API key>(jmpLT, SCK_OVERFLOW);
}
ins = INS_mov;
}
else // Non-overflow checking cast.
{
if (genTypeSize(srcType) == genTypeSize(dstType))
{
ins = INS_mov;
}
else
{
var_types extendType = TYP_UNKNOWN;
if (genTypeSize(srcType) < genTypeSize(dstType))
{
// If we need to treat a signed type as unsigned
if ((treeNode->gtFlags & GTF_UNSIGNED) != 0)
{
extendType = genUnsignedType(srcType);
}
else
extendType = srcType;
#ifdef _TARGET_ARM_
movSize = emitTypeSize(extendType);
#endif // _TARGET_ARM_
if (extendType == TYP_UINT)
{
#ifdef _TARGET_ARM64_
// If we are casting from a smaller type to
// a larger type, then we need to make sure the
// higher 4 bytes are zero to gaurentee the correct value.
// Therefore using a mov with EA_4BYTE in place of EA_8BYTE
// will zero the upper bits
movSize = EA_4BYTE;
#endif // _TARGET_ARM64_
movRequired = true;
}
}
else // (genTypeSize(srcType) > genTypeSize(dstType))
{
// If we need to treat a signed type as unsigned
if ((treeNode->gtFlags & GTF_UNSIGNED) != 0)
{
extendType = genUnsignedType(dstType);
}
else
extendType = dstType;
#if defined(_TARGET_ARM_)
movSize = emitTypeSize(extendType);
#elif defined(_TARGET_ARM64_)
if (extendType == TYP_INT)
{
movSize = EA_8BYTE; // a sxtw instruction requires EA_8BYTE
}
#endif // _TARGET_*
}
ins = ins_Move_Extend(extendType, true);
}
}
// We should never be generating a load from memory instruction here!
assert(!emit->emitInsIsLoad(ins));
if ((ins != INS_mov) || movRequired || (targetReg != sourceReg))
{
emit->emitIns_R_R(ins, movSize, targetReg, sourceReg);
}
genProduceReg(treeNode);
}
// genFloatToFloatCast: Generate code for a cast between float and double
// Arguments:
// treeNode - The GT_CAST node
// Return Value:
// None.
// Assumptions:
// Cast is a non-overflow conversion.
// The treeNode must have an assigned register.
// The cast is between float and double.
void CodeGen::genFloatToFloatCast(GenTreePtr treeNode)
{
// float <--> double conversions are always non-overflow ones
assert(treeNode->OperGet() == GT_CAST);
assert(!treeNode->gtOverflow());
regNumber targetReg = treeNode->gtRegNum;
assert(genIsValidFloatReg(targetReg));
GenTreePtr op1 = treeNode->gtOp.gtOp1;
assert(!op1->isContained()); // Cannot be contained
assert(genIsValidFloatReg(op1->gtRegNum)); // Must be a valid float reg.
var_types dstType = treeNode->CastToType();
var_types srcType = op1->TypeGet();
assert(varTypeIsFloating(srcType) && varTypeIsFloating(dstType));
genConsumeOperands(treeNode->AsOp());
// treeNode must be a reg
assert(!treeNode->isContained());
#if defined(_TARGET_ARM_)
if (srcType != dstType)
{
instruction insVcvt = (srcType == TYP_FLOAT) ? INS_vcvt_f2d // convert Float to Double
: INS_vcvt_d2f; // convert Double to Float
getEmitter()->emitIns_R_R(insVcvt, emitTypeSize(treeNode), treeNode->gtRegNum, op1->gtRegNum);
}
else if (treeNode->gtRegNum != op1->gtRegNum)
{
getEmitter()->emitIns_R_R(INS_vmov, emitTypeSize(treeNode), treeNode->gtRegNum, op1->gtRegNum);
}
#elif defined(_TARGET_ARM64_)
if (srcType != dstType)
{
insOpts cvtOption = (srcType == TYP_FLOAT) ? INS_OPTS_S_TO_D // convert Single to Double
: INS_OPTS_D_TO_S; // convert Double to Single
getEmitter()->emitIns_R_R(INS_fcvt, emitActualTypeSize(treeNode), treeNode->gtRegNum, op1->gtRegNum, cvtOption);
}
else if (treeNode->gtRegNum != op1->gtRegNum)
{
// If double to double cast or float to float cast. Emit a move instruction.
getEmitter()->emitIns_R_R(INS_mov, emitActualTypeSize(treeNode), treeNode->gtRegNum, op1->gtRegNum);
}
#endif // _TARGET_*
genProduceReg(treeNode);
}
// <API key>: Create and record GC Info for the function.
void CodeGen::<API key>(unsigned codeSize,
unsigned prologSize,
unsigned epilogSize DEBUGARG(void* codePtr))
{
IAllocator* allowZeroAlloc = new (compiler, CMK_GC) AllowZeroAllocator(compiler->getAllocatorGC());
GcInfoEncoder* gcInfoEncoder = new (compiler, CMK_GC)
GcInfoEncoder(compiler->info.compCompHnd, compiler->info.compMethodInfo, allowZeroAlloc, NOMEM);
assert(gcInfoEncoder != nullptr);
// Follow the code pattern of the x86 gc info encoder (<API key>).
gcInfo.gcInfoBlockHdrSave(gcInfoEncoder, codeSize, prologSize);
// We keep the call count for the second call to gcMakeRegPtrTable() below.
unsigned callCnt = 0;
// First we figure out the encoder ID's for the stack slots and registers.
gcInfo.gcMakeRegPtrTable(gcInfoEncoder, codeSize, prologSize, GCInfo::<API key>, &callCnt);
// Now we've requested all the slots we'll need; "finalize" these (make more compact data structures for them).
gcInfoEncoder->FinalizeSlotIds();
// Now we can actually use those slot ID's to declare live ranges.
gcInfo.gcMakeRegPtrTable(gcInfoEncoder, codeSize, prologSize, GCInfo::<API key>, &callCnt);
#ifdef _TARGET_ARM64_
if (compiler->opts.compDbgEnC)
{
// what we have to preserve is called the "frame header" (see comments in VM\eetwain.cpp)
// which is:
// -return address
// -saved off RBP
// -saved 'this' pointer and bool for synchronized methods
// 4 slots for RBP + return address + RSI + RDI
int preservedAreaSize = 4 * REGSIZE_BYTES;
if (compiler->info.compFlags & CORINFO_FLG_SYNCH)
{
if (!(compiler->info.compFlags & CORINFO_FLG_STATIC))
preservedAreaSize += REGSIZE_BYTES;
preservedAreaSize += 1; // bool for synchronized methods
}
// Used to signal both that the method is compiled for EnC, and also the size of the block at the top of the
// frame
gcInfoEncoder-><API key>(preservedAreaSize);
}
#endif // _TARGET_ARM64_
gcInfoEncoder->Build();
// GC Encoder automatically puts the GC info in the right spot using ICorJitInfo::allocGCInfo(size_t)
// let's save the values anyway for debugging purposes
compiler->compInfoBlkAddr = gcInfoEncoder->Emit();
compiler->compInfoBlkSize = 0; // not exposed by the GCEncoder interface
}
// genJumpKindsForTree: Determine the number and kinds of conditional branches
// necessary to implement the given GT_CMP node
// Arguments:
// cmpTree - (input) The GenTree node that is used to set the Condition codes
// - The GenTree Relop node that was used to set the Condition codes
// jmpKind[2] - (output) One or two conditional branch instructions
// jmpToTrueLabel[2] - (output) On Arm64 both branches will always branch to the true label
// Return Value:
// Sets the proper values into the array elements of jmpKind[] and jmpToTrueLabel[]
// Assumptions:
// At least one conditional branch instruction will be returned.
// Typically only one conditional branch is needed
// and the second jmpKind[] value is set to EJ_NONE
void CodeGen::genJumpKindsForTree(GenTreePtr cmpTree, emitJumpKind jmpKind[2], bool jmpToTrueLabel[2])
{
// On ARM both branches will always branch to the true label
jmpToTrueLabel[0] = true;
jmpToTrueLabel[1] = true;
// For integer comparisons just use genJumpKindForOper
if (!varTypeIsFloating(cmpTree->gtOp.gtOp1))
{
CompareKind compareKind = ((cmpTree->gtFlags & GTF_UNSIGNED) != 0) ? CK_UNSIGNED : CK_SIGNED;
jmpKind[0] = genJumpKindForOper(cmpTree->gtOper, compareKind);
jmpKind[1] = EJ_NONE;
}
else // We have a Floating Point Compare operation
{
assert(cmpTree->OperIsCompare());
// For details on this mapping, see the ARM Condition Code table
// at section A8.3 in the ARMv7 architecture manual or
// at section C1.2.3 in the ARMV8 architecture manual.
// We must check the GTF_RELOP_NAN_UN to find out
// if we need to branch when we have a NaN operand.
if ((cmpTree->gtFlags & GTF_RELOP_NAN_UN) != 0)
{
// Must branch if we have an NaN, unordered
switch (cmpTree->gtOper)
{
case GT_EQ:
jmpKind[0] = EJ_eq; // branch or set when equal (and no NaN's)
jmpKind[1] = EJ_vs; // branch or set when we have a NaN
break;
case GT_NE:
jmpKind[0] = EJ_ne; // branch or set when not equal (or have NaN's)
jmpKind[1] = EJ_NONE;
break;
case GT_LT:
jmpKind[0] = EJ_lt; // branch or set when less than (or have NaN's)
jmpKind[1] = EJ_NONE;
break;
case GT_LE:
jmpKind[0] = EJ_le; // branch or set when less than or equal (or have NaN's)
jmpKind[1] = EJ_NONE;
break;
case GT_GT:
jmpKind[0] = EJ_hi; // branch or set when greater than (or have NaN's)
jmpKind[1] = EJ_NONE;
break;
case GT_GE:
jmpKind[0] = EJ_hs; // branch or set when greater than or equal (or have NaN's)
jmpKind[1] = EJ_NONE;
break;
default:
unreached();
}
}
else // ((cmpTree->gtFlags & GTF_RELOP_NAN_UN) == 0)
{
// Do not branch if we have an NaN, unordered
switch (cmpTree->gtOper)
{
case GT_EQ:
jmpKind[0] = EJ_eq; // branch or set when equal (and no NaN's)
jmpKind[1] = EJ_NONE;
break;
case GT_NE:
jmpKind[0] = EJ_gt; // branch or set when greater than (and no NaN's)
jmpKind[1] = EJ_lo; // branch or set when less than (and no NaN's)
break;
case GT_LT:
jmpKind[0] = EJ_lo; // branch or set when less than (and no NaN's)
jmpKind[1] = EJ_NONE;
break;
case GT_LE:
jmpKind[0] = EJ_ls; // branch or set when less than or equal (and no NaN's)
jmpKind[1] = EJ_NONE;
break;
case GT_GT:
jmpKind[0] = EJ_gt; // branch or set when greater than (and no NaN's)
jmpKind[1] = EJ_NONE;
break;
case GT_GE:
jmpKind[0] = EJ_ge; // branch or set when greater than or equal (and no NaN's)
jmpKind[1] = EJ_NONE;
break;
default:
unreached();
}
}
}
}
// genCodeForJumpTrue: Generates code for jmpTrue statement.
// Arguments:
// tree - The GT_JTRUE tree node.
// Return Value:
// None
void CodeGen::genCodeForJumpTrue(GenTreePtr tree)
{
GenTree* cmp = tree->gtOp.gtOp1;
assert(cmp->OperIsCompare());
assert(compiler->compCurBB->bbJumpKind == BBJ_COND);
// Get the "kind" and type of the comparison. Note that whether it is an unsigned cmp
// is governed by a flag NOT by the inherent type of the node
emitJumpKind jumpKind[2];
bool branchToTrueLabel[2];
genJumpKindsForTree(cmp, jumpKind, branchToTrueLabel);
assert(jumpKind[0] != EJ_NONE);
// On ARM the branches will always branch to the true label
assert(branchToTrueLabel[0]);
inst_JMP(jumpKind[0], compiler->compCurBB->bbJumpDest);
if (jumpKind[1] != EJ_NONE)
{
// the second conditional branch always has to be to the true label
assert(branchToTrueLabel[1]);
inst_JMP(jumpKind[1], compiler->compCurBB->bbJumpDest);
}
}
// genCodeForJcc: Produce code for a GT_JCC node.
// Arguments:
// tree - the node
void CodeGen::genCodeForJcc(GenTreeCC* tree)
{
assert(compiler->compCurBB->bbJumpKind == BBJ_COND);
CompareKind compareKind = ((tree->gtFlags & GTF_UNSIGNED) != 0) ? CK_UNSIGNED : CK_SIGNED;
emitJumpKind jumpKind = genJumpKindForOper(tree->gtCondition, compareKind);
inst_JMP(jumpKind, compiler->compCurBB->bbJumpDest);
}
// genCodeForSetcc: Generates code for a GT_SETCC node.
// Arguments:
// setcc - the GT_SETCC node
// Assumptions:
// The condition represents an integer comparison. This code doesn't
// have the necessary logic to deal with floating point comparisons,
// in fact it doesn't even know if the comparison is integer or floating
// point because SETCC nodes do not have any operands.
void CodeGen::genCodeForSetcc(GenTreeCC* setcc)
{
regNumber dstReg = setcc->gtRegNum;
CompareKind compareKind = setcc->IsUnsigned() ? CK_UNSIGNED : CK_SIGNED;
emitJumpKind jumpKind = genJumpKindForOper(setcc->gtCondition, compareKind);
assert(genIsValidIntReg(dstReg));
// Make sure nobody is setting GTF_RELOP_NAN_UN on this node as it is ignored.
assert((setcc->gtFlags & GTF_RELOP_NAN_UN) == 0);
#ifdef _TARGET_ARM64_
inst_SET(jumpKind, dstReg);
#else
// Emit code like that:
// bgt True
// movs rD,
// b Next
// True:
// movs rD,
// Next:
BasicBlock* labelTrue = genCreateTempLabel();
getEmitter()->emitIns_J(emitter::emitJumpKindToIns(jumpKind), labelTrue);
getEmitter()->emitIns_R_I(INS_mov, emitActualTypeSize(setcc->TypeGet()), dstReg, 0);
BasicBlock* labelNext = genCreateTempLabel();
getEmitter()->emitIns_J(INS_b, labelNext);
genDefineTempLabel(labelTrue);
getEmitter()->emitIns_R_I(INS_mov, emitActualTypeSize(setcc->TypeGet()), dstReg, 1);
genDefineTempLabel(labelNext);
#endif
genProduceReg(setcc);
}
// genCodeForStoreBlk: Produce code for a GT_STORE_OBJ/GT_STORE_DYN_BLK/GT_STORE_BLK node.
// Arguments:
// tree - the node
void CodeGen::genCodeForStoreBlk(GenTreeBlk* blkOp)
{
assert(blkOp->OperIs(GT_STORE_OBJ, GT_STORE_DYN_BLK, GT_STORE_BLK));
if (blkOp->OperIs(GT_STORE_OBJ) && blkOp->OperIsCopyBlkOp())
{
assert(blkOp->AsObj()->gtGcPtrCount != 0);
genCodeForCpObj(blkOp->AsObj());
return;
}
if (blkOp->gtBlkOpGcUnsafe)
{
getEmitter()->emitDisableGC();
}
bool isCopyBlk = blkOp->OperIsCopyBlkOp();
switch (blkOp->gtBlkOpKind)
{
case GenTreeBlk::BlkOpKindHelper:
if (isCopyBlk)
{
genCodeForCpBlk(blkOp);
}
else
{
genCodeForInitBlk(blkOp);
}
break;
case GenTreeBlk::BlkOpKindUnroll:
if (isCopyBlk)
{
<API key>(blkOp);
}
else
{
<API key>(blkOp);
}
break;
default:
unreached();
}
if (blkOp->gtBlkOpGcUnsafe)
{
getEmitter()->emitEnableGC();
}
}
// genScaledAdd: A helper for genLeaInstruction.
void CodeGen::genScaledAdd(emitAttr attr, regNumber targetReg, regNumber baseReg, regNumber indexReg, int scale)
{
emitter* emit = getEmitter();
#if defined(_TARGET_ARM_)
emit->emitIns_R_R_R_I(INS_add, attr, targetReg, baseReg, indexReg, scale, INS_FLAGS_DONT_CARE, INS_OPTS_LSL);
#elif defined(_TARGET_ARM64_)
emit->emitIns_R_R_R_I(INS_add, attr, targetReg, baseReg, indexReg, scale, INS_OPTS_LSL);
#endif
}
// genLeaInstruction: Produce code for a GT_LEA node.
// Arguments:
// lea - the node
void CodeGen::genLeaInstruction(GenTreeAddrMode* lea)
{
genConsumeOperands(lea);
emitter* emit = getEmitter();
emitAttr size = emitTypeSize(lea);
int offset = lea->Offset();
// In ARM we can only load addresses of the form:
// [Base + index*scale]
// [Base + Offset]
// [Literal] (PC-Relative)
// So for the case of a LEA node of the form [Base + Index*Scale + Offset] we will generate:
// destReg = baseReg + indexReg * scale;
// destReg = destReg + offset;
// TODO-ARM64-CQ: The purpose of the GT_LEA node is to directly reflect a single target architecture
// addressing mode instruction. Currently we're 'cheating' by producing one or more
// instructions to generate the addressing mode so we need to modify lowering to
// produce LEAs that are a 1:1 relationship to the ARM64 architecture.
if (lea->Base() && lea->Index())
{
GenTree* memBase = lea->Base();
GenTree* index = lea->Index();
DWORD lsl;
assert(isPow2(lea->gtScale));
BitScanForward(&lsl, lea->gtScale);
assert(lsl <= 4);
if (offset != 0)
{
regNumber tmpReg = lea->GetSingleTempReg();
if (emitter::<API key>(offset))
{
if (lsl > 0)
{
// Generate code to set tmpReg = base + index*scale
genScaledAdd(size, tmpReg, memBase->gtRegNum, index->gtRegNum, lsl);
}
else // no scale
{
// Generate code to set tmpReg = base + index
emit->emitIns_R_R_R(INS_add, size, tmpReg, memBase->gtRegNum, index->gtRegNum);
}
// Then compute target reg from [tmpReg + offset]
emit->emitIns_R_R_I(INS_add, size, lea->gtRegNum, tmpReg, offset);
}
else // large offset
{
// First load/store tmpReg with the large offset constant
<API key>(EA_PTRSIZE, tmpReg, offset);
// Then add the base register
// rd = rd + base
emit->emitIns_R_R_R(INS_add, size, tmpReg, tmpReg, memBase->gtRegNum);
noway_assert(tmpReg != index->gtRegNum);
// Then compute target reg from [tmpReg + index*scale]
genScaledAdd(size, lea->gtRegNum, tmpReg, index->gtRegNum, lsl);
}
}
else
{
if (lsl > 0)
{
// Then compute target reg from [base + index*scale]
genScaledAdd(size, lea->gtRegNum, memBase->gtRegNum, index->gtRegNum, lsl);
}
else
{
// Then compute target reg from [base + index]
emit->emitIns_R_R_R(INS_add, size, lea->gtRegNum, memBase->gtRegNum, index->gtRegNum);
}
}
}
else if (lea->Base())
{
GenTree* memBase = lea->Base();
if (emitter::<API key>(offset))
{
if (offset != 0)
{
// Then compute target reg from [memBase + offset]
emit->emitIns_R_R_I(INS_add, size, lea->gtRegNum, memBase->gtRegNum, offset);
}
else // offset is zero
{
if (lea->gtRegNum != memBase->gtRegNum)
{
emit->emitIns_R_R(INS_mov, size, lea->gtRegNum, memBase->gtRegNum);
}
}
}
else
{
// We require a tmpReg to hold the offset
regNumber tmpReg = lea->GetSingleTempReg();
// First load tmpReg with the large offset constant
<API key>(EA_PTRSIZE, tmpReg, offset);
// Then compute target reg from [memBase + tmpReg]
emit->emitIns_R_R_R(INS_add, size, lea->gtRegNum, memBase->gtRegNum, tmpReg);
}
}
else if (lea->Index())
{
// If we encounter a GT_LEA node without a base it means it came out
// when attempting to optimize an arbitrary arithmetic expression during lower.
// This is currently disabled in ARM64 since we need to adjust lower to account
// for the simpler instructions ARM64 supports.
// TODO-ARM64-CQ: Fix this and let LEA optimize arithmetic trees too.
assert(!"We shouldn't see a baseless address computation during CodeGen for ARM64");
}
genProduceReg(lea);
}
// isStructReturn: Returns whether the 'treeNode' is returning a struct.
// Arguments:
// treeNode - The tree node to evaluate whether is a struct return.
// Return Value:
// Returns true if the 'treeNode" is a GT_RETURN node of type struct.
// Otherwise returns false.
bool CodeGen::isStructReturn(GenTreePtr treeNode)
{
// This method could be called for 'treeNode' of GT_RET_FILT or GT_RETURN.
// For the GT_RET_FILT, the return is always
// a bool or a void, for the end of a finally block.
noway_assert(treeNode->OperGet() == GT_RETURN || treeNode->OperGet() == GT_RETFILT);
return varTypeIsStruct(treeNode);
}
// genStructReturn: Generates code for returning a struct.
// Arguments:
// treeNode - The GT_RETURN tree node.
// Return Value:
// None
// Assumption:
// op1 of GT_RETURN node is either GT_LCL_VAR or multi-reg GT_CALL
void CodeGen::genStructReturn(GenTreePtr treeNode)
{
assert(treeNode->OperGet() == GT_RETURN);
assert(isStructReturn(treeNode));
GenTreePtr op1 = treeNode->gtGetOp1();
if (op1->OperGet() == GT_LCL_VAR)
{
GenTreeLclVarCommon* lclVar = op1->AsLclVarCommon();
LclVarDsc* varDsc = &(compiler->lvaTable[lclVar->gtLclNum]);
var_types lclType = genActualType(varDsc->TypeGet());
// Currently only multireg TYP_STRUCT types such as HFA's(ARM32, ARM64) and 16-byte structs(ARM64) are supported
// In the future we could have FEATURE_SIMD types like TYP_SIMD16
assert(lclType == TYP_STRUCT);
assert(varDsc->lvIsMultiRegRet);
ReturnTypeDesc retTypeDesc;
unsigned regCount;
retTypeDesc.<API key>(compiler, varDsc->lvVerTypeInfo.GetClassHandle());
regCount = retTypeDesc.GetReturnRegCount();
assert(regCount >= 2);
assert(op1->isContained());
// Copy var on stack into ABI return registers
// TODO: It could be optimized by reducing two float loading to one double
int offset = 0;
for (unsigned i = 0; i < regCount; ++i)
{
var_types type = retTypeDesc.GetReturnRegType(i);
regNumber reg = retTypeDesc.GetABIReturnReg(i);
getEmitter()->emitIns_R_S(ins_Load(type), emitTypeSize(type), reg, lclVar->gtLclNum, offset);
offset += genTypeSize(type);
}
}
else // op1 must be multi-reg GT_CALL
{
assert(op1->IsMultiRegCall() || op1-><API key>());
genConsumeRegs(op1);
GenTree* actualOp1 = op1->gtSkipReloadOrCopy();
GenTreeCall* call = actualOp1->AsCall();
ReturnTypeDesc* pRetTypeDesc;
unsigned regCount;
unsigned matchingCount = 0;
pRetTypeDesc = call->GetReturnTypeDesc();
regCount = pRetTypeDesc->GetReturnRegCount();
var_types regType[MAX_RET_REG_COUNT];
regNumber returnReg[MAX_RET_REG_COUNT];
regNumber allocatedReg[MAX_RET_REG_COUNT];
regMaskTP srcRegsMask = 0;
regMaskTP dstRegsMask = 0;
bool needToShuffleRegs = false; // Set to true if we have to move any registers
for (unsigned i = 0; i < regCount; ++i)
{
regType[i] = pRetTypeDesc->GetReturnRegType(i);
returnReg[i] = pRetTypeDesc->GetABIReturnReg(i);
regNumber reloadReg = REG_NA;
if (op1->IsCopyOrReload())
{
// GT_COPY/GT_RELOAD will have valid reg for those positions
// that need to be copied or reloaded.
reloadReg = op1->AsCopyOrReload()->GetRegNumByIdx(i);
}
if (reloadReg != REG_NA)
{
allocatedReg[i] = reloadReg;
}
else
{
allocatedReg[i] = call->GetRegNumByIdx(i);
}
if (returnReg[i] == allocatedReg[i])
{
matchingCount++;
}
else // We need to move this value
{
// We want to move the value from allocatedReg[i] into returnReg[i]
// so record these two registers in the src and dst masks
srcRegsMask |= genRegMask(allocatedReg[i]);
dstRegsMask |= genRegMask(returnReg[i]);
needToShuffleRegs = true;
}
}
if (needToShuffleRegs)
{
assert(matchingCount < regCount);
unsigned remainingRegCount = regCount - matchingCount;
regMaskTP extraRegMask = treeNode->gtRsvdRegs;
while (remainingRegCount > 0)
{
// set 'available' to the 'dst' registers that are not currently holding 'src' registers
regMaskTP availableMask = dstRegsMask & ~srcRegsMask;
regMaskTP dstMask;
regNumber srcReg;
regNumber dstReg;
var_types curType = TYP_UNKNOWN;
regNumber freeUpReg = REG_NA;
if (availableMask == 0)
{
// Circular register dependencies
// So just free up the lowest register in dstRegsMask by moving it to the 'extra' register
assert(dstRegsMask == srcRegsMask); // this has to be true for us to reach here
assert(extraRegMask != 0); // we require an 'extra' register
assert((extraRegMask & ~dstRegsMask) != 0); // it can't be part of dstRegsMask
availableMask = extraRegMask & ~dstRegsMask;
regMaskTP srcMask = genFindLowestBit(srcRegsMask);
freeUpReg = genRegNumFromMask(srcMask);
}
dstMask = genFindLowestBit(availableMask);
dstReg = genRegNumFromMask(dstMask);
srcReg = REG_NA;
if (freeUpReg != REG_NA)
{
// We will free up the srcReg by moving it to dstReg which is an extra register
srcReg = freeUpReg;
// Find the 'srcReg' and set 'curType', change allocatedReg[] to dstReg
// and add the new register mask bit to srcRegsMask
for (unsigned i = 0; i < regCount; ++i)
{
if (allocatedReg[i] == srcReg)
{
curType = regType[i];
allocatedReg[i] = dstReg;
srcRegsMask |= genRegMask(dstReg);
}
}
}
else // The normal case
{
// Find the 'srcReg' and set 'curType'
for (unsigned i = 0; i < regCount; ++i)
{
if (returnReg[i] == dstReg)
{
srcReg = allocatedReg[i];
curType = regType[i];
}
}
// After we perform this move we will have one less registers to setup
remainingRegCount
}
assert(curType != TYP_UNKNOWN);
inst_RV_RV(ins_Copy(curType), dstReg, srcReg, curType);
// Clear the appropriate bits in srcRegsMask and dstRegsMask
srcRegsMask &= ~genRegMask(srcReg);
dstRegsMask &= ~genRegMask(dstReg);
} // while (remainingRegCount > 0)
} // (needToShuffleRegs)
} // op1 must be multi-reg GT_CALL
}
#endif // _TARGET_ARMARCH_
#endif // !LEGACY_BACKEND
|
<nav class="sr-only">
<div class="modal-header">
<div class="row">
<h1 class="h1 col-xs-10 col-sm-10 col-md-11 col-lg-11"><a href="/">WSJ Sections</a></h1>
<a href="" class=" col-xs-1 col-sm-1 col-md-1 col-lg-1" ng-click="NC.cancel()">close </a>
</div>
<div class="row">
<ul class="nav nav-pills nav-sections" >
<!-- <li ng-repeat="category in categories " ><a ng-click="NC.getNavSubCategories(category.slug)" href=""> {{NC.category.name}}</a></li>-->
</ul>
</div>
<div class="row">
<hr style="border-top: 1px solid #444;" />
<!-- <h2 class="text-center modal-title col-md-11">{{ subCategories.section }}</h2>-->
</div>
</div>
<div class="modal-body nav-section-stories">
<!-- <div ng-repeat="subCategory in subCategories" class="row sub-section" >-->
<!-- <article class="col-xs-3 col-sm-2 col-md-2" >-->
<!-- <a href="category/{{NC.subCategory.slug}}" class="story">-->
<!-- <h3> {{subCategory.name}}</h3>-->
<!-- </article>-->
<!-- <div class="col-xs-9 col-sm-10 col-md-10">-->
<!-- <section class="row">-->
<!-- <article ng-repeat="post in subCategory.posts" class="col-xs-12 col-sm-6 col-md-4" >-->
<!-- <!-- <img ng-if="getSource(NC.post.galleries)" class="img-responsive" src="{{NC.getSource(post.galleries)}}" alt="Powell Street"/>-->-->
<!-- <a href="/{{post.slug}}" class="story">-->
<!-- <!-- <h2>{{post.name | limitTo:letterLimitHeadline }}</h2>-->-->
<!-- <!-- {{post.content | limitTo:letterLimit }}-->-->
<!-- </article>-->
<!-- </section>-->
<!-- </div>-->
<!-- </div> <!-- End/ .row -->-->
</div>
<div class="modal-footer">
<article style="background-color: #a6e1ec; height: 5rem;" class="col-md-4">
Advertisement
</article>
Copyright WSJ
</div>
</nav>
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace AnalyzeThis
{
internal static class RegexExtensions
{
public static bool TryGetMatch(this Regex regex, string input, out Match match)
{
if (input == null)
{
match = null;
return false;
}
match = regex.Match(input);
return match.Success;
}
}
}
|
M.profile("generators");
function* forOfBlockScope() {
let a = [1, 2, 3, 4, 5, 6, 7, 8];
let b = [10, 11, 12, 13, 14, 15, 16];
const funs = [];
for (const i of a) {
let j = 0;
funs.push(function* iter() {
yield `fo1: ${i} ${j++}`;
});
}
for (var i of a) {
var j = 0;
funs.push(function* iter() {
yield `fo2: ${i} ${j++}`;
});
}
for (const i of a) {
for (let j of b) {
funs.push(function* iter() {
yield `fo3: ${i} ${j++}`;
});
}
}
for (const i of a) {
for (let j of b) {
yield `fo4: ${j}`;
funs.push(function* iter() {
yield `fo5: ${i} ${j++}`;
});
}
}
for (const i of a) {
yield `fo6: ${i}`;
for (let j of b) {
funs.push(function* iter() {
yield `fo7: ${i} ${j++}`;
});
}
}
for (const i of a) {
yield `fo8 ${i}`;
for (let j of b) {
yield `fo9: ${i}`;
funs.push(function* iter() {
yield `fo10: ${i} ${j++}`;
});
}
}
for (const i of funs) yield* i();
funs.length = 0;
for (const i of a) {
funs.push(function* iter() {
yield `fo11: ${i}`;
});
}
for (const i of a) {
yield `fo12 ${i}`;
funs.push(function* iter() {
yield `fo13 ${i}`;
});
}
let k = 0;
for (const i of a) {
yield `fo14 ${i} ${k} {m}`;
let m = k;
k++;
if (k === 3) continue;
if (k === 5) break;
funs.push(function* iter() {
yield `fo15 ${i} ${k} {m}`;
});
}
k = 0;
up1: for (const i of a) {
let m = k;
k++;
for (const j of b) {
let n = m;
m++;
if (k === 3) continue up1;
if (k === 5) break up1;
if (n === 3) continue;
if (n === 5) break;
funs.push(function* iter() {
n++;
yield `fo18: ${i} ${j} ${k} ${m} ${n}`;
});
}
}
k = 0;
up2: for (const i of a) {
let m = 0;
k++;
yield `fo16: ${i} ${k} ${m}`;
for (const j of b) {
let n = m;
m++;
if (k === 3) continue up2;
if (k === 5) break up2;
if (n === 3) continue;
if (n === 5) break;
funs.push(function* iter() {
n++;
yield `fo18: ${i} ${j} ${k} ${m} ${n}`;
});
}
}
k = 0;
up3: for (const i of a) {
let m = 0;
k++;
for (const j of b) {
let n = m;
m++;
yield `fo19 ${i} ${j} ${k} ${m} ${n}`;
if (k === 3) {
continue up3;
}
if (k === 5) break up3;
if (n === 3) continue;
if (n === 5) break;
funs.push(function* iter() {
n++;
yield `fo20: ${i} ${j} ${k} ${m} ${n}`;
});
}
}
bl1: {
let k = 0;
yield `fo21: ${i} ${k}`;
up4: for (const i of a) {
let m = 0;
k++;
yield `fo22: ${i} ${k} ${m}`;
for (const j of b) {
let n = m;
m++;
yield `fo23 ${i} ${j} ${k} ${m} ${n}`;
if (k === 3) continue up4;
if (k === 5) break bl1;
if (n === 3) continue;
if (n === 5) break;
funs.push(function* iter() {
n++;
yield `fo24: ${i} ${j} ${k} ${m} ${n}`;
});
}
}
}
bl2: {
let k = 0;
yield `fo25`;
up5: for (const i of a) {
let m = 0;
k++;
yield `fo26: ${i} ${k} ${m}`;
for (const j of b) {
let n = m;
m++;
yield `fo27 ${i} ${j} ${k} ${m} ${n}`;
if (k === 3) continue up5;
if (k === 5) break bl2;
if (n === 3) continue;
if (n === 5) break;
funs.push(function* iter() {
n++;
yield `fo28: ${i} ${j} ${k} ${m} ${n}`;
});
}
}
}
bl3: {
let k = 0;
up6: for (const i of a) {
let m = 0;
k++;
yield `fo29: ${i} ${k} ${m}`;
for (const j of b) {
let n = m;
m++;
yield `fo30 ${i} ${j} ${k} ${m} ${n}`;
if (k === 3) continue up6;
if (k === 5) {
for (const i of funs) yield* i();
return `r: ${i} ${j} ${k} ${m} ${n}`;
}
if (n === 3) continue;
if (n === 5) break;
funs.push(function* iter() {
n++;
yield `fo31: ${i} ${j} ${k} ${m} ${n}`;
});
}
}
}
}
|
<?php
namespace Neimheadh\Bundle\<API key>\Model\File;
use Symfony\Component\Filesystem\Exception\<API key>;
use Symfony\Component\Filesystem\Exception\IOException;
/**
* The files models interface.
*
* @author Neimheadh <contact@neimheadh.fr>
*/
interface FileInterface
{
/**
* Get path.
*
* @return string
*/
public function getPath();
/**
* Set path.
*
* @param string $path
* The file path.
* @return \Neimheadh\Bundle\<API key>\Model\File\FileInterface
*/
public function setPath(string $path);
/**
* Get access mode.
*
* @return string
*/
public function getAccessMode();
/**
* Set access mode.
*
* @param string $accessMode
* The access mode.
* @return \Neimheadh\Bundle\<API key>\Model\File\FileInterface
*/
public function setAccessMode(string $accessMode);
/**
* Check file access.
*
* @param bool $read
* Force read checking.
* @param bool $write
* Force write checking.
* @throws <API key> The file doesn't exist.
* @throws IOException The file cannot be accessed in read mode (code = 1).
* @throws IOException The file cannot be accessed in read mode (code = 2).
* @throws IOException Unknown access mode (code = 3).
*/
public function check(bool $read = false, bool $write = false);
/**
* Is the file existing?
*
* @return bool
*/
public function isExisting();
/**
* Is the file readable?
*
* @return bool
*/
public function isReadable();
/**
* Is the file writable?
*
* @return bool
*/
public function isWritable();
/**
* Process file line by line.
*
* @param callable $callback
* The callback.
*
*/
public function processLines($callback);
/**
* Append content in file.
*
* @param string $content
* Amended content.
* @param int|null $position
* Amend position
*/
public function amend(string $content, int $position = null);
}
|
<!DOCTYPE html>
<html>
<head>
<link href="css/awsdocs.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/awsdocs.min.js"></script>
<meta charset="utf-8">
</head>
<body>
<div id="content" style="padding: 10px 30px;">
<h1 class="topictitle" id="<API key>">AWS::Route53::HostedZone</h1><p>The <code class="code">AWS::Route53::HostedZone</code> resource creates a hosted zone, which can contain
a collection of record sets for a domain. You cannot create a hosted zone for a top-level
domain (TLD). For more information, see <a href="https:
(Private)</a> in the <em>Amazon Route 53 API Reference</em>.
</p><h2 id="<API key>">Syntax</h2><p>To declare this entity in your AWS CloudFormation template, use the following syntax:</p><div id="JSON" name="JSON" class="section langfilter">
<h3 id="<API key>.json">JSON</h3>
<pre class="programlisting"><div class="code-btn-container"><div class="btn-copy-code" title="Copy"></div><div class="btn-dark-theme" title="Dark theme" title-dark="Dark theme" title-light="Light theme"></div></div><code class="nohighlight">{
"Type" : "AWS::Route53::HostedZone",
"Properties" : {
"<a href="<API key>.html#<API key>">HostedZoneConfig</a>" : <a href="<API key>.html">HostedZoneConfig</a>,
"<a href="<API key>.html#<API key>">HostedZoneTags</a>" : [ <a href="<API key>.html">HostedZoneTags</a>, ... ],
"<a href="<API key>.html#<API key>">Name</a>" : <em class="replaceable"><code>String</code></em>,
"<a href="<API key>.html#<API key>">QueryLoggingConfig</a>" : <a href="<API key>.html">QueryLoggingConfig</a>,
"<a href="<API key>.html#<API key>">VPCs</a>" : [ <a href="<API key>.html">HostedZoneVPCs</a>, ... ]
}
}</code></pre>
</div><div id="YAML" name="YAML" class="section langfilter">
<h3 id="<API key>.yaml">YAML</h3>
<pre class="programlisting"><div class="code-btn-container"><div class="btn-copy-code" title="Copy"></div><div class="btn-dark-theme" title="Dark theme" title-dark="Dark theme" title-light="Light theme"></div></div><code class="nohighlight">Type: "AWS::Route53::HostedZone"
Properties:
<a href="<API key>.html#<API key>">HostedZoneConfig</a>:
<a href="<API key>.html">HostedZoneConfig</a>
<a href="<API key>.html#<API key>">HostedZoneTags</a>:
- <a href="<API key>.html">HostedZoneTags</a>
<a href="<API key>.html#<API key>">Name</a>: <em class="replaceable"><code>String</code></em>
<a href="<API key>.html#<API key>">QueryLoggingConfig</a>:
<a href="<API key>.html">QueryLoggingConfig</a>
<a href="<API key>.html#<API key>">VPCs</a>:
- <a href="<API key>.html">HostedZoneVPCs</a>
</code></pre>
</div><h2 id="<API key>">Properties</h2><div class="variablelist">
<dl>
<dt><a id="<API key>"></a><span class="term"><code class="code">HostedZoneConfig</code></span></dt>
<dd>
<p>A complex type that contains an optional comment about your hosted zone.</p>
<p><em>Required</em>: No
</p>
<p><em>Type</em>: <a href="<API key>.html">Route 53 HostedZoneConfig Property</a></p>
<p><em>Update requires</em>: <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#update-no-interrupt">No interruption</a></p>
</dd>
<dt><a id="<API key>"></a><span class="term"><code class="code">HostedZoneTags</code></span></dt>
<dd>
<p>An arbitrary set of tags (key–value pairs) for this hosted zone.</p>
<p><em>Required</em>: No
</p>
<p><em>Type</em>: List of <a href="<API key>.html">Amazon Route 53 HostedZoneTags</a></p>
<p><em>Update requires</em>: <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#update-no-interrupt">No interruption</a></p>
</dd>
<dt><a id="<API key>"></a><span class="term"><code class="code">Name</code></span></dt>
<dd>
<p>The name of the domain. For resource record types that include a domain name,
specify a fully qualified domain name.
</p>
<p><em>Required</em>: Yes
</p>
<p><em>Type</em>: String
</p>
<p><em>Update requires</em>: <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#update-replacement">Replacement</a></p>
</dd>
<dt><a id="<API key>"></a><span class="term"><code class="code">QueryLoggingConfig</code></span></dt>
<dd>
<p>The configuration for DNS query logging.</p>
<p><em>Required</em>: No
</p>
<p><em>Type</em>: <a href="<API key>.html">Route 53 QueryLoggingConfig</a></p>
<p><em>Update requires</em>: <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#update-no-interrupt">No interruption</a></p>
</dd>
<dt><a id="<API key>"></a><span class="term"><code class="code">VPCs</code></span></dt>
<dd>
<p>One or more VPCs that you want to associate with this hosted zone. When you
specify this property, AWS CloudFormation creates a private hosted zone.
</p>
<p><em>Required</em>: No
</p>
<p><em>Type</em>: List of <a href="<API key>.html">Route 53 HostedZoneVPCs</a></p>
<p>If this property was specified previously and you're modifying values, updates
require <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#update-no-interrupt">no interruption</a>. If this
property wasn't specified and you add values, updates require <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#update-replacement">replacement</a>. Also, if this property was
specified and you remove all values, updates require <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/<API key>.html#update-replacement">replacement</a>.
</p>
</dd>
</dl>
</div><h2 id="<API key>">Return Values</h2><h3 id="<API key>">Ref</h3><p>When the logical ID of this resource is provided to the <code class="code">Ref</code> intrinsic function, <code class="code">Ref</code> returns the hosted zone ID, such as
<code class="code">Z23ABC4XYZL05B</code>.
</p><p>For more information about using the <code class="code">Ref</code> function, see <a href="<API key>.html">Ref</a>.
</p><h3 id="<API key>">Fn::GetAtt</h3><p><code class="code">Fn::GetAtt</code> returns a value for a specified attribute of this type.
The following are the available attributes and sample return values.
</p><div class="variablelist">
<dl>
<dt><span class="term"><code class="literal">NameServers</code></span></dt>
<dd>
<p>Returns the set of name servers for the specific hosted zone. For example:
<code class="code">ns1.example.com</code>.
</p>
<p>This attribute is not supported for private hosted zones.</p>
</dd>
</dl>
</div><p>For more information about using
<code class="code">Fn::GetAtt</code>, see
<a href="<API key>.html">Fn::GetAtt</a>.
</p><h2 id="<API key>">Example</h2><p>The following template snippet creates a private hosted zone for the
<code class="code">example.com</code> domain.
</p><div id="JSON" name="JSON" class="section langfilter">
<h3 id="<API key>.json">JSON</h3>
<pre class="programlisting"><div class="code-btn-container"><div class="btn-copy-code" title="Copy"></div><div class="btn-dark-theme" title="Dark theme" title-dark="Dark theme" title-light="Light theme"></div></div><code class="nohighlight ">"DNS": {
"Type": "AWS::Route53::HostedZone",
"Properties": {
"HostedZoneConfig": {
"Comment": "My hosted zone for example.com"
},
"Name": "example.com",
"VPCs": [{
"VPCId": "vpc-abcd1234",
"VPCRegion": "ap-northeast-1"
},
{
"VPCId": "vpc-efgh5678",
"VPCRegion": "us-west-2"
}],
"HostedZoneTags" : [{
"Key": "SampleKey1",
"Value": "SampleValue1"
},
{
"Key": "SampleKey2",
"Value": "SampleValue2"
}]
}
}</code></pre>
</div><div id="YAML" name="YAML" class="section langfilter">
<h3 id="<API key>.yaml">YAML</h3>
<pre class="programlisting"><div class="code-btn-container"><div class="btn-copy-code" title="Copy"></div><div class="btn-dark-theme" title="Dark theme" title-dark="Dark theme" title-light="Light theme"></div></div><code class="nohighlight ">DNS:
Type: "AWS::Route53::HostedZone"
Properties:
HostedZoneConfig:
Comment: "My hosted zone for example.com"
Name: "example.com"
VPCs:
-
VPCId: "vpc-abcd1234"
VPCRegion: "ap-northeast-1"
-
VPCId: "vpc-efgh5678"
VPCRegion: "us-west-2"
HostedZoneTags:
-
Key: "SampleKey1"
Value: "SampleValue1"
-
Key: "SampleKey2"
Value: "SampleValue2"</code></pre>
</div></div>
</body>
</html>
|
package fPPPrograms;
import java.util.Scanner;
public class LeapYear {
public static void main(String[] args) {
System.out.println("Enter a year to determine whether it is a leap year or not?");
Scanner yourInput = new Scanner(System.in);
int year = yourInput.nextInt();
//String y = year%400 == 0? (year%4 == 0 ) && (year%100 !=0) ? "Yes" : "Not" : "Not" ;
String y = ((year%4 == 0) && (year%100 != 0) || (year%400 == 0)) ? "Yes" : "Not";
System.out.println("The Year You Entered is " + y + " a Leap Year");
}
}
|
<?php
namespace BigD\UbicacionBundle\Form\EventListener;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\EventDispatcher\<API key>;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\<API key>;
use Symfony\Component\PropertyAccess\PropertyAccess;
class <API key> implements <API key> {
private $factory;
public function __construct(<API key> $factory) {
$this->factory = $factory;
}
public static function getSubscribedEvents() {
return array(
FormEvents::PRE_SET_DATA => 'preSetData',
FormEvents::PRE_BIND => 'preBind'
);
}
private function addLocalidadForm($form, $city, $country) {
$form->add($this->factory->createNamed('city', 'entity', $city, array(
'class' => 'LocationBundle:City',
'auto_initialize' => false,
'empty_value' => 'Select',
'attr' => array(
'class' => 'city_selector',
),
'query_builder' => function (EntityRepository $repository) use ($country) {
$qb = $repository->createQueryBuilder('city')
->innerJoin('city.country', 'country');
if ($country instanceof Country) {
$qb->where('city.country = :country')
->setParameter('country', $country->getId());
} elseif (is_numeric($country)) {
$qb->where('country.id = :country')
->setParameter('country', $country);
} else {
$qb->where('country.name = :country')
->setParameter('country', null);
}
return $qb;
}
)));
}
public function preSetData(FormEvent $event) {
$data = $event->getData();
$form = $event->getForm();
if (null === $data) {
$this->addCityForm($form, null, null);
return;
}
$accessor = PropertyAccess::getPropertyAccessor();
$city = $accessor->getValue($data, 'city');
//$province = ($city) ? $city->getProvince() : null ;
//$this->addCityForm($form, $city, $province);
//$country = ($data->getCity()) ? $data->getCity()->getCountry() : null ;
$country = ($city) ? $city->getCountry() : null;
$this->addCityForm($form, $city, $country);
}
public function preBind(FormEvent $event) {
$data = $event->getData();
$form = $event->getForm();
if (null === $data) {
return;
}
// $city = array_key_exists('city', $data) ? $data['city'] : null;
// $this->addCityForm($form, $city, $province);
$country = array_key_exists('country', $data) ? $data['country'] : null;
$city = array_key_exists('city', $data) ? $data['city'] : null;
$this->addCityForm($form, $city, $country);
}
}
|
/*
* Webpack development server configuration
*
* This file is set up for serving the webpack-dev-server, which will watch for changes and recompile as required if
* the subfolder /webpack-dev-server/ is visited. Visiting the root will not automatically reload.
*/
'use strict';
import webpack from 'webpack';
import path from 'path';
import autoprefixer from 'autoprefixer';
const API_URL = process.env['__API_URL__'] || 'http://localhost:3001/'; //eslint-disable-line
export default {
output: {
path: path.join(__dirname, '.tmp'),
filename: 'bundle.js',
publicPath: '/static/'
},
devtool: 'eval-source-map',
entry: [
'whatwg-fetch',
'webpack-dev-server/client?http://0.0.0.0:3000',
'webpack/hot/only-dev-server',
'react-hot-loader/patch',
'./src/index.js'
],
module: {
preLoaders: [{
test: /\.(js|jsx)$/,
exclude: [/node_modules/, /vendor/],
loader: 'eslint-loader'
}],
loaders: [{
test: /\.(js|jsx)$/,
include: path.join(__dirname, 'src'),
loader: 'babel-loader'
},
{
test: /\.scss/,
loader: 'style-loader!css-loader!postcss-loader!sass-loader'
},
{
test: /\.json/,
loader: 'json-loader'
}, {
test: /\.(png|jpg|ttf|svg|eot|woff|woff2)/,
loader: 'url-loader?limit=8192'
}]
},
postcss: [
autoprefixer({ browsers: 'last 2 versions' })
],
plugins: [
new webpack.<API key>(),
new webpack.DefinePlugin({
__DEV__: true,
__DEVTOOLS__: false,
__API_URL__: `\'${API_URL}\'`
})
]
};
|
// This code will add an event listener to each anchor of the topbar after being dynamically replaced by "interchange"
$("body").on("click", function(event){
// If the active element is one of the topbar's links continues
if($(event.target).hasClass("topbarLink")) {
// The parent li element of the current active link is stored
var activeLink = $(event.target).parent();
// Takes each link and checks if its parent li element is active, removing "active" class if so.
$("#topNavContent li:not(.divider)").each(function(){
// If the li element has nested li's with links they are checked also.
if($(this).hasClass("has-dropdown")){
var dropdownList = $(this).children(".dropdown").children().not(".divider");
dropdownList.each(function(){
if($(this).hasClass("active")){
$(this).removeClass("active");
}
});
}
// The direct li element's "active" class is removed
if($(this).hasClass("active")){
$(this).removeClass("active");
}
});
// After having all topbar li elements deactivated, "active" class is added to the currently active link's li parent
if(!$(activeLink).hasClass("active")){
$(activeLink).addClass("active");
}
}
});
// This variable is used to know if this script will be loaded at the time of checking it in the JS manager
<API key> = true;
|
const elixir = require('laravel-elixir');
elixir((mix) => {
// Mix all Sass files into one
mix.sass('app.scss');
// Mix all vendor scripts together
mix.scripts(
[
'jquery/dist/jquery.min.js',
'bootstrap-sass/assets/javascripts/bootstrap.min.js',
'bootstrap-sass/assets/javascripts/bootstrap/dropdown.js'
],
'resources/assets/js/vendor.js',
'node_modules'
);
// Mix all script files into one
mix.scripts(
['vendor.js', 'app.js'],
'public/js/app.js'
);
// Copy vendor assets to public
mix.copy('node_modules/bootstrap-sass/assets/fonts/bootstrap/','public/fonts/bootstrap')
.copy('node_modules/font-awesome/fonts', 'public/fonts');
});
/*
var elixir = require('laravel-elixir');
elixir(function(mix) {
// Mix all scss files into one css file
mix.sass([
'charts.scss',
'app.scss'
], 'public/css/app.css');
// Mix all chart JS files into a master charts file
mix.scriptsIn(
'resources/assets/js/charts',
'public/js/charts.js'
);
// Mix common JS files into one file
mix.scripts([
'app.js'
], 'public/js/app.js');
});
*/
|
require 'spec_helper'
describe User do
context 'fields' do
it { should have_field(:email).of_type(String)}
it { should have_field(:encrypted_password).of_type(String)}
it { should have_field(:roles).of_type(Array)}
end
context 'Mass assignment' do
it { should <API key>(:email) }
it { should <API key>(:roles) }
it { should <API key>(:password) }
it { should <API key>(:<API key>) }
end
context 'Required fields' do
it { should <API key>(:roles)}
end
context 'Associations' do
it { should embed_one :profile }
end
end
|
import {Map} from 'immutable';
export function <API key>(mapStyle) {
let interactiveLayerIds = [];
if (Map.isMap(mapStyle) && mapStyle.has('layers')) {
interactiveLayerIds = mapStyle.get('layers')
.filter(l => l.get('interactive'))
.map(l => l.get('id'))
.toJS();
} else if (Array.isArray(mapStyle.layers)) {
interactiveLayerIds = mapStyle.layers.filter(l => l.interactive)
.map(l => l.id);
}
return interactiveLayerIds;
}
|
<!doctype html>
<html>
<head>
</head>
<body>
<h1>Milestones - Codenautas</h1>
<div id=milestones></div>
<script src=milestones.js></script>
</body>
</html>
|
package net.rlviana.pricegrabber.model.entity.common;
import net.rlviana.pricegrabber.context.<API key>;
import net.rlviana.pricegrabber.model.entity.<API key>;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.<API key>;
import org.springframework.test.context.junit4.<API key>;
import org.springframework.test.context.transaction.<API key>;
import org.springframework.transaction.annotation.Transactional;
/**
* @author ramon
*/
@RunWith(<API key>.class)
@<API key>(classes = {<API key>.class})
@<API key>(transactionManager = "transactionManager", defaultRollback = false)
@Transactional
public class CurrencyTest extends <API key><Currency, String> {
private static final Logger LOGGER = LoggerFactory.getLogger(CurrencyTest.class);
@Test
public void testFindAll() {
}
@Test
public void testFindByCriteria() {
}
/**
* @return
* @see net.rlviana.pricegrabber.model.entity.<API key>#getEntityPKFindOK()
*/
@Override
protected String getEntityPKFindOK() {
return "EU";
}
/**
* @return
* @see net.rlviana.pricegrabber.model.entity.<API key>#getEntityPKFindKO()
*/
@Override
protected String getEntityPKFindKO() {
return "NEU";
}
/**
* @return
* @see net.rlviana.pricegrabber.model.entity.<API key>#getTestClass()
*/
@Override
protected Class<Currency> getTestClass() {
return Currency.class;
}
}
|
package <API key>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
// AllocationState enumerates the values for allocation state.
type AllocationState string
const (
// <API key> ...
<API key> AllocationState = "Resizing"
// <API key> ...
<API key> AllocationState = "Steady"
)
// <API key> returns an array of possible values for the AllocationState const type.
func <API key>() []AllocationState {
return []AllocationState{<API key>, <API key>}
}
// <API key> enumerates the values for application sharing policy.
type <API key> string
const (
// <API key> ...
<API key> <API key> = "Personal"
// <API key> ...
<API key> <API key> = "Shared"
)
// <API key> returns an array of possible values for the <API key> const type.
func <API key>() []<API key> {
return []<API key>{<API key>, <API key>}
}
// ClusterPurpose enumerates the values for cluster purpose.
type ClusterPurpose string
const (
// <API key> ...
<API key> ClusterPurpose = "DenseProd"
// <API key> ...
<API key> ClusterPurpose = "DevTest"
// <API key> ...
<API key> ClusterPurpose = "FastProd"
)
// <API key> returns an array of possible values for the ClusterPurpose const type.
func <API key>() []ClusterPurpose {
return []ClusterPurpose{<API key>, <API key>, <API key>}
}
// <API key> enumerates the values for compute instance authorization type.
type <API key> string
const (
// ComputeInstance<API key> ...
ComputeInstance<API key> <API key> = "personal"
)
// <API key><API key> returns an array of possible values for the <API key> const type.
func <API key><API key>() []<API key> {
return []<API key>{ComputeInstance<API key>}
}
// <API key> enumerates the values for compute instance state.
type <API key> string
const (
// <API key> ...
<API key> <API key> = "CreateFailed"
// <API key> ...
<API key> <API key> = "Creating"
// <API key> ...
<API key> <API key> = "Deleting"
// <API key> ...
<API key> <API key> = "JobRunning"
// <API key> ...
<API key> <API key> = "Restarting"
// <API key> ...
<API key> <API key> = "Running"
// <API key> ...
<API key> <API key> = "SettingUp"
// <API key> ...
<API key> <API key> = "SetupFailed"
// <API key> ...
<API key> <API key> = "Starting"
// <API key> ...
<API key> <API key> = "Stopped"
// <API key> ...
<API key> <API key> = "Stopping"
// <API key> ...
<API key> <API key> = "Unknown"
// <API key> ...
<API key> <API key> = "Unusable"
// <API key> ...
<API key> <API key> = "UserSettingUp"
// <API key> ...
<API key> <API key> = "UserSetupFailed"
)
// <API key> returns an array of possible values for the <API key> const type.
func <API key>() []<API key> {
return []<API key>{<API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>}
}
// ComputeType enumerates the values for compute type.
type ComputeType string
const (
// ComputeTypeAKS ...
ComputeTypeAKS ComputeType = "AKS"
// <API key> ...
<API key> ComputeType = "AmlCompute"
// <API key> ...
<API key> ComputeType = "ComputeInstance"
// <API key> ...
<API key> ComputeType = "Databricks"
// <API key> ...
<API key> ComputeType = "DataFactory"
// <API key> ...
<API key> ComputeType = "DataLakeAnalytics"
// <API key> ...
<API key> ComputeType = "HDInsight"
// <API key> ...
<API key> ComputeType = "SynapseSpark"
// <API key> ...
<API key> ComputeType = "VirtualMachine"
)
// <API key> returns an array of possible values for the ComputeType const type.
func <API key>() []ComputeType {
return []ComputeType{ComputeTypeAKS, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>}
}
// <API key> enumerates the values for compute type basic compute.
type <API key> string
const (
// <API key> ...
<API key> <API key> = "AKS"
// <API key> ...
<API key> <API key> = "AmlCompute"
// <API key> ...
<API key> <API key> = "Compute"
// <API key> ...
<API key> <API key> = "ComputeInstance"
// <API key> ...
<API key> <API key> = "Databricks"
// <API key> ...
<API key> <API key> = "DataFactory"
// <API key> ...
<API key> <API key> = "DataLakeAnalytics"
// <API key> ...
<API key> <API key> = "HDInsight"
// <API key> ...
<API key> <API key> = "VirtualMachine"
)
// <API key> returns an array of possible values for the <API key> const type.
func <API key>() []<API key> {
return []<API key>{<API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>}
}
// <API key> enumerates the values for compute type basic compute nodes
// information.
type <API key> string
const (
// <API key> ...
<API key> <API key> = "AmlCompute"
// <API key> ...
<API key> <API key> = "<API key>"
)
// <API key> returns an array of possible values for the <API key> const type.
func <API key>() []<API key> {
return []<API key>{<API key>, <API key>}
}
// <API key> enumerates the values for compute type basic compute secrets.
type <API key> string
const (
// <API key> ...
<API key> <API key> = "AKS"
// <API key><API key> ...
<API key><API key> <API key> = "ComputeSecrets"
// <API key><API key> ...
<API key><API key> <API key> = "Databricks"
// <API key><API key> ...
<API key><API key> <API key> = "VirtualMachine"
)
// <API key> returns an array of possible values for the <API key> const type.
func <API key>() []<API key> {
return []<API key>{<API key>, <API key><API key>, <API key><API key>, <API key><API key>}
}
// <API key> enumerates the values for compute type basic create service request.
type <API key> string
const (
// <API key> ...
<API key> <API key> = "ACI"
// <API key> ...
<API key> <API key> = "AKS"
// <API key> ...
<API key> <API key> = "<API key>"
// <API key> ...
<API key> <API key> = "Custom"
)
// <API key> returns an array of possible values for the <API key> const type.
func <API key>() []<API key> {
return []<API key>{<API key>, <API key>, <API key>, <API key>}
}
// <API key> enumerates the values for compute type basic service response base.
type <API key> string
const (
// <API key> ...
<API key> <API key> = "ACI"
// <API key> ...
<API key> <API key> = "AKS"
// <API key> ...
<API key> <API key> = "Custom"
// <API key> ...
<API key> <API key> = "ServiceResponseBase"
)
// <API key> returns an array of possible values for the <API key> const type.
func <API key>() []<API key> {
return []<API key>{<API key>, <API key>, <API key>, <API key>}
}
// DeploymentType enumerates the values for deployment type.
type DeploymentType string
const (
// DeploymentTypeBatch ...
DeploymentTypeBatch DeploymentType = "Batch"
// <API key> ...
<API key> DeploymentType = "<API key>"
// <API key> ...
<API key> DeploymentType = "<API key>"
)
// <API key> returns an array of possible values for the DeploymentType const type.
func <API key>() []DeploymentType {
return []DeploymentType{DeploymentTypeBatch, <API key>, <API key>}
}
// EncryptionStatus enumerates the values for encryption status.
type EncryptionStatus string
const (
// <API key> ...
<API key> EncryptionStatus = "Disabled"
// <API key> ...
<API key> EncryptionStatus = "Enabled"
)
// <API key> returns an array of possible values for the EncryptionStatus const type.
func <API key>() []EncryptionStatus {
return []EncryptionStatus{<API key>, <API key>}
}
// IdentityType enumerates the values for identity type.
type IdentityType string
const (
// <API key> ...
<API key> IdentityType = "Application"
// IdentityTypeKey ...
IdentityTypeKey IdentityType = "Key"
// <API key> ...
<API key> IdentityType = "ManagedIdentity"
// IdentityTypeUser ...
IdentityTypeUser IdentityType = "User"
)
// <API key> returns an array of possible values for the IdentityType const type.
func <API key>() []IdentityType {
return []IdentityType{<API key>, IdentityTypeKey, <API key>, IdentityTypeUser}
}
// LoadBalancerType enumerates the values for load balancer type.
type LoadBalancerType string
const (
// <API key> ...
<API key> LoadBalancerType = "<API key>"
// <API key> ...
<API key> LoadBalancerType = "PublicIp"
)
// <API key> returns an array of possible values for the LoadBalancerType const type.
func <API key>() []LoadBalancerType {
return []LoadBalancerType{<API key>, <API key>}
}
// NodeState enumerates the values for node state.
type NodeState string
const (
// NodeStateIdle ...
NodeStateIdle NodeState = "idle"
// NodeStateLeaving ...
NodeStateLeaving NodeState = "leaving"
// NodeStatePreempted ...
NodeStatePreempted NodeState = "preempted"
// NodeStatePreparing ...
NodeStatePreparing NodeState = "preparing"
// NodeStateRunning ...
NodeStateRunning NodeState = "running"
// NodeStateUnusable ...
NodeStateUnusable NodeState = "unusable"
)
// <API key> returns an array of possible values for the NodeState const type.
func <API key>() []NodeState {
return []NodeState{NodeStateIdle, NodeStateLeaving, NodeStatePreempted, NodeStatePreparing, NodeStateRunning, NodeStateUnusable}
}
// OperationName enumerates the values for operation name.
type OperationName string
const (
// OperationNameCreate ...
OperationNameCreate OperationName = "Create"
// OperationNameDelete ...
OperationNameDelete OperationName = "Delete"
// <API key> ...
<API key> OperationName = "Reimage"
// <API key> ...
<API key> OperationName = "Restart"
// OperationNameStart ...
OperationNameStart OperationName = "Start"
// OperationNameStop ...
OperationNameStop OperationName = "Stop"
)
// <API key> returns an array of possible values for the OperationName const type.
func <API key>() []OperationName {
return []OperationName{OperationNameCreate, OperationNameDelete, <API key>, <API key>, OperationNameStart, OperationNameStop}
}
// OperationStatus enumerates the values for operation status.
type OperationStatus string
const (
// <API key> ...
<API key> OperationStatus = "CreateFailed"
// <API key> ...
<API key> OperationStatus = "DeleteFailed"
// <API key> ...
<API key> OperationStatus = "InProgress"
// <API key> ...
<API key> OperationStatus = "ReimageFailed"
// <API key> ...
<API key> OperationStatus = "RestartFailed"
// <API key> ...
<API key> OperationStatus = "StartFailed"
// <API key> ...
<API key> OperationStatus = "StopFailed"
// <API key> ...
<API key> OperationStatus = "Succeeded"
)
// <API key> returns an array of possible values for the OperationStatus const type.
func <API key>() []OperationStatus {
return []OperationStatus{<API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>}
}
// OrderString enumerates the values for order string.
type OrderString string
const (
// <API key> ...
<API key> OrderString = "CreatedAtAsc"
// <API key> ...
<API key> OrderString = "CreatedAtDesc"
// <API key> ...
<API key> OrderString = "UpdatedAtAsc"
// <API key> ...
<API key> OrderString = "UpdatedAtDesc"
)
// <API key> returns an array of possible values for the OrderString const type.
func <API key>() []OrderString {
return []OrderString{<API key>, <API key>, <API key>, <API key>}
}
// OsType enumerates the values for os type.
type OsType string
const (
// OsTypeLinux ...
OsTypeLinux OsType = "Linux"
// OsTypeWindows ...
OsTypeWindows OsType = "Windows"
)
// <API key> returns an array of possible values for the OsType const type.
func <API key>() []OsType {
return []OsType{OsTypeLinux, OsTypeWindows}
}
// <API key> enumerates the values for private endpoint connection
// provisioning state.
type <API key> string
const (
// <API key> ...
<API key> <API key> = "Creating"
// <API key> ...
<API key> <API key> = "Deleting"
// <API key> ...
<API key> <API key> = "Failed"
// <API key> ...
<API key> <API key> = "Succeeded"
)
// <API key> returns an array of possible values for the <API key> const type.
func <API key>() []<API key> {
return []<API key>{<API key>, <API key>, <API key>, <API key>}
}
// <API key> enumerates the values for private endpoint service connection status.
type <API key> string
const (
// <API key> ...
<API key> <API key> = "Approved"
// <API key> ...
<API key> <API key> = "Disconnected"
// <API key> ...
<API key> <API key> = "Pending"
// <API key> ...
<API key> <API key> = "Rejected"
// <API key> ...
<API key> <API key> = "Timeout"
)
// <API key> returns an array of possible values for the <API key> const type.
func <API key>() []<API key> {
return []<API key>{<API key>, <API key>, <API key>, <API key>, <API key>}
}
// ProvisioningState enumerates the values for provisioning state.
type ProvisioningState string
const (
// <API key> ...
<API key> ProvisioningState = "Canceled"
// <API key> ...
<API key> ProvisioningState = "Creating"
// <API key> ...
<API key> ProvisioningState = "Deleting"
// <API key> ...
<API key> ProvisioningState = "Failed"
// <API key> ...
<API key> ProvisioningState = "Succeeded"
// <API key> ...
<API key> ProvisioningState = "Unknown"
// <API key> ...
<API key> ProvisioningState = "Updating"
)
// <API key> returns an array of possible values for the ProvisioningState const type.
func <API key>() []ProvisioningState {
return []ProvisioningState{<API key>, <API key>, <API key>, <API key>, <API key>, <API key>, <API key>}
}
// QuotaUnit enumerates the values for quota unit.
type QuotaUnit string
const (
// QuotaUnitCount ...
QuotaUnitCount QuotaUnit = "Count"
)
// <API key> returns an array of possible values for the QuotaUnit const type.
func <API key>() []QuotaUnit {
return []QuotaUnit{QuotaUnitCount}
}
// ReasonCode enumerates the values for reason code.
type ReasonCode string
const (
// <API key> ...
<API key> ReasonCode = "<API key>"
// <API key> ...
<API key> ReasonCode = "<API key>"
// <API key> ...
<API key> ReasonCode = "NotSpecified"
)
// <API key> returns an array of possible values for the ReasonCode const type.
func <API key>() []ReasonCode {
return []ReasonCode{<API key>, <API key>, <API key>}
}
// <API key> enumerates the values for remote login port public access.
type <API key> string
const (
// <API key> ...
<API key> <API key> = "Disabled"
// <API key> ...
<API key> <API key> = "Enabled"
// <API key> ...
<API key> <API key> = "NotSpecified"
)
// <API key> returns an array of possible values for the <API key> const type.
func <API key>() []<API key> {
return []<API key>{<API key>, <API key>, <API key>}
}
// <API key> enumerates the values for resource identity type.
type <API key> string
const (
// <API key> ...
<API key> <API key> = "None"
// <API key> ...
<API key> <API key> = "SystemAssigned"
// <API key> ...
<API key> <API key> = "SystemAssigned,UserAssigned"
// <API key> ...
<API key> <API key> = "UserAssigned"
)
// <API key> returns an array of possible values for the <API key> const type.
func <API key>() []<API key> {
return []<API key>{<API key>, <API key>, <API key>, <API key>}
}
// SSHPublicAccess enumerates the values for ssh public access.
type SSHPublicAccess string
const (
// <API key> ...
<API key> SSHPublicAccess = "Disabled"
// <API key> ...
<API key> SSHPublicAccess = "Enabled"
)
// <API key> returns an array of possible values for the SSHPublicAccess const type.
func <API key>() []SSHPublicAccess {
return []SSHPublicAccess{<API key>, <API key>}
}
// Status enumerates the values for status.
type Status string
const (
// StatusFailure ...
StatusFailure Status = "Failure"
// <API key> ...
<API key> Status = "<API key>"
// <API key> ...
<API key> Status = "<API key>"
// <API key> ...
<API key> Status = "InvalidVMFamilyName"
// <API key> ...
<API key> Status = "<API key>"
// <API key> ...
<API key> Status = "<API key>"
// StatusSuccess ...
StatusSuccess Status = "Success"
// StatusUndefined ...
StatusUndefined Status = "Undefined"
)
// <API key> returns an array of possible values for the Status const type.
func <API key>() []Status {
return []Status{StatusFailure, <API key>, <API key>, <API key>, <API key>, <API key>, StatusSuccess, StatusUndefined}
}
// Status1 enumerates the values for status 1.
type Status1 string
const (
// Status1Auto ...
Status1Auto Status1 = "Auto"
// Status1Disabled ...
Status1Disabled Status1 = "Disabled"
// Status1Enabled ...
Status1Enabled Status1 = "Enabled"
)
// <API key> returns an array of possible values for the Status1 const type.
func <API key>() []Status1 {
return []Status1{Status1Auto, Status1Disabled, Status1Enabled}
}
// <API key> enumerates the values for underlying resource action.
type <API key> string
const (
// <API key> ...
<API key> <API key> = "Delete"
// <API key> ...
<API key> <API key> = "Detach"
)
// <API key> returns an array of possible values for the <API key> const type.
func <API key>() []<API key> {
return []<API key>{<API key>, <API key>}
}
// UsageUnit enumerates the values for usage unit.
type UsageUnit string
const (
// UsageUnitCount ...
UsageUnitCount UsageUnit = "Count"
)
// <API key> returns an array of possible values for the UsageUnit const type.
func <API key>() []UsageUnit {
return []UsageUnit{UsageUnitCount}
}
// ValueFormat enumerates the values for value format.
type ValueFormat string
const (
// ValueFormatJSON ...
ValueFormatJSON ValueFormat = "JSON"
)
// <API key> returns an array of possible values for the ValueFormat const type.
func <API key>() []ValueFormat {
return []ValueFormat{ValueFormatJSON}
}
// VariantType enumerates the values for variant type.
type VariantType string
const (
// VariantTypeControl ...
VariantTypeControl VariantType = "Control"
// <API key> ...
<API key> VariantType = "Treatment"
)
// <API key> returns an array of possible values for the VariantType const type.
func <API key>() []VariantType {
return []VariantType{VariantTypeControl, <API key>}
}
// VMPriceOSType enumerates the values for vm price os type.
type VMPriceOSType string
const (
// VMPriceOSTypeLinux ...
VMPriceOSTypeLinux VMPriceOSType = "Linux"
// <API key> ...
<API key> VMPriceOSType = "Windows"
)
// <API key> returns an array of possible values for the VMPriceOSType const type.
func <API key>() []VMPriceOSType {
return []VMPriceOSType{VMPriceOSTypeLinux, <API key>}
}
// VMPriority enumerates the values for vm priority.
type VMPriority string
const (
// VMPriorityDedicated ...
VMPriorityDedicated VMPriority = "Dedicated"
// <API key> ...
<API key> VMPriority = "LowPriority"
)
// <API key> returns an array of possible values for the VMPriority const type.
func <API key>() []VMPriority {
return []VMPriority{VMPriorityDedicated, <API key>}
}
// VMTier enumerates the values for vm tier.
type VMTier string
const (
// VMTierLowPriority ...
VMTierLowPriority VMTier = "LowPriority"
// VMTierSpot ...
VMTierSpot VMTier = "Spot"
// VMTierStandard ...
VMTierStandard VMTier = "Standard"
)
// <API key> returns an array of possible values for the VMTier const type.
func <API key>() []VMTier {
return []VMTier{VMTierLowPriority, VMTierSpot, VMTierStandard}
}
// WebServiceState enumerates the values for web service state.
type WebServiceState string
const (
// <API key> ...
<API key> WebServiceState = "Failed"
// <API key> ...
<API key> WebServiceState = "Healthy"
// <API key> ...
<API key> WebServiceState = "Transitioning"
// <API key> ...
<API key> WebServiceState = "Unhealthy"
// <API key> ...
<API key> WebServiceState = "Unschedulable"
)
// <API key> returns an array of possible values for the WebServiceState const type.
func <API key>() []WebServiceState {
return []WebServiceState{<API key>, <API key>, <API key>, <API key>, <API key>}
}
|
#include "utfgrid_encode.h"
#include <unordered_map>
#include <glog/logging.h>
#include <jsoncpp/json/value.h>
#include <mapnik/unicode.hpp>
struct <API key> {
Json::Value operator() (const mapnik::value_null& val) {return Json::Value();}
Json::Value operator() (const mapnik::value_bool& val) {return Json::Value(val);}
Json::Value operator() (const mapnik::value_integer& val) {return Json::Value(static_cast<uint>(val));}
Json::Value operator() (const mapnik::value_double& val) {return Json::Value(val);}
Json::Value operator() (const mapnik::<API key>& val) {
std::string utf8_str;
mapnik::to_utf8(val, utf8_str);
return Json::Value(utf8_str);
}
};
std::string encode_utfgrid(const mapnik::grid_view& utfgrid, uint size) {
Json::Value root(Json::objectValue);
Json::Value& jgrid = root["grid"];
jgrid = Json::Value(Json::arrayValue);
using lookup_type = mapnik::grid::lookup_type;
using value_type = mapnik::grid::value_type;
using feature_type = mapnik::grid::feature_type;
using keys_type = std::unordered_map<lookup_type, value_type>;
std::vector<lookup_type> key_order;
keys_type keys;
const mapnik::grid::feature_key_type& feature_keys = utfgrid.get_feature_keys();
std::uint16_t codepoint = 32;
for (uint y = 0; y < utfgrid.height(); y += size) {
std::string line;
const value_type* row = utfgrid.get_row(y);
for (uint x = 0; x < utfgrid.width(); x += size) {
value_type feature_id = row[x];
auto feature_itr = feature_keys.find(feature_id);
lookup_type val;
if (feature_itr == feature_keys.end()) {
feature_id = mapnik::grid::base_mask;
} else {
val = feature_itr->second;
}
auto key_iter = keys.find(val);
if (key_iter == keys.end()) {
// Create a new entry for this key. Skip the codepoints that
// can't be encoded directly in JSON.
if (codepoint == 34) ++codepoint; // Skip "
else if (codepoint == 92) ++codepoint; // Skip backslash
if (feature_id == mapnik::grid::base_mask) {
keys[""] = codepoint;
key_order.push_back("");
} else {
keys[val] = codepoint;
key_order.push_back(val);
}
line.append(reinterpret_cast<char*>(&codepoint), sizeof(codepoint));
++codepoint;
} else {
line.append(reinterpret_cast<char*>(&key_iter->second), sizeof(key_iter->second));
}
}
jgrid.append(Json::Value(line));
}
Json::Value& jkeys = root["keys"];
jkeys = Json::Value(Json::arrayValue);
for (const auto& key_id : key_order) {
jkeys.append(key_id);
}
Json::Value& jdata = root["data"];
const feature_type& g_features = utfgrid.get_grid_features();
const std::set<std::string>& attributes = utfgrid.get_fields();
feature_type::const_iterator feat_end = g_features.end();
for (const std::string& key_item : key_order)
{
if (key_item.empty()) {
continue;
}
feature_type::const_iterator feat_itr = g_features.find(key_item);
if (feat_itr == feat_end) {
continue;
}
bool found = false;
Json::Value jfeature(Json::objectValue);
mapnik::feature_ptr feature = feat_itr->second;
for (const std::string& attr : attributes) {
<API key> val_to_json;
if (attr == "__id__") {
jfeature[attr] = static_cast<uint>(feature->id());
} else if (feature->has_key(attr)) {
found = true;
jfeature[attr] = mapnik::util::apply_visitor(val_to_json, feature->get(attr));
}
}
if (found) {
jdata[feat_itr->first] = jfeature;
}
}
return root.toStyledString();
}
|
package me.moodcat.api;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
import lombok.Getter;
import me.moodcat.database.embeddables.VAVector;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
* A mood represents a vector in the valence-arousal plane which will be attached to song.
*/
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum Mood {
// CHECKSTYLE:OFF
ANGRY(new VAVector(-0.6, 0.6), "Angry"),
CALM(new VAVector(0.3, -0.9), "Calm"),
EXCITING(new VAVector(0.4, 0.8), "Exciting"),
HAPPY(new VAVector(0.7, 0.6), "Happy"),
NERVOUS(new VAVector(-0.7, 0.4), "Nervous"),
PLEASING(new VAVector(0.6, 0.3), "Pleasing"),
PEACEFUL(new VAVector(0.5, -0.7), "Peaceful"),
RELAXED(new VAVector(0.6, -0.3), "Relaxed"),
SAD(new VAVector(-0.7, -0.2), "Sad"),
SLEEPY(new VAVector(-0.2, -0.9), "Sleepy");
// CHECKSTYLE:ON
/**
* List of all names that represent moods. Used in {@link #nameRepresentsMood(String)}.
* By storing this once, we save a lot of unnecessary list creations.
*/
private static final List<String> MOOD_NAMES = Arrays.asList(Mood.values()).stream()
.map(moodValue -> moodValue.getName())
.collect(Collectors.toList());
/**
* The vector that represents this mood.
*
* @return The vector of this mood.
*/
@Getter
@JsonIgnore
private final VAVector vector;
/**
* Readable name for the frontend.
*
* @return The readable name of this mood.
*/
@Getter
private final String name;
private Mood(final VAVector vector, final String name) {
this.vector = vector;
this.name = name;
}
/**
* Get the mood that is closest to the given vector.
*
* @param vector
* The vector to determine the mood for.
* @return The Mood that is closest to the vector.
*/
public static Mood closestTo(final VAVector vector) {
double distance = Double.MAX_VALUE;
Mood mood = null;
for (final Mood m : Mood.values()) {
final double moodDistance = m.vector.distance(vector);
if (moodDistance < distance) {
distance = moodDistance;
mood = m;
}
}
return mood;
}
/**
* Get the vector that represents the average of the provided list of moods.
*
* @param moods
* The textual list of moods.
* @return The average vector, or the zero-vector if no moods were found.
*/
public static VAVector createTargetVector(final List<String> moods) {
final List<VAVector> actualMoods = moods.stream()
.filter(Mood::nameRepresentsMood)
.map(mood -> Mood.valueOf(mood.toUpperCase(Locale.ROOT)))
.map(mood -> mood.getVector())
.collect(Collectors.toList());
return VAVector.average(actualMoods);
}
private static boolean nameRepresentsMood(final String mood) {
return MOOD_NAMES.contains(mood);
}
}
|
<!-- CONTAINER BODY -->
<div class="panel-group" >
<div class="panel panel-default" >
<div class="panel-body">
<h4>Filmovi</h4>
<!-- Film List -->
<hr/>
<?php foreach($list as $row): ?>
<div class="row text-left">
<div class="col-sm-4 col-fix-140">
<?PHP
$id = $row['IDFilm'];
$path = $row['Poster'];
$link = site_url("index/film/$id");
echo "<a href="."$link"."><img src='"."$path"."' alt='Image' style='height:200px'></a>";
?>
</div>
<div class="col-sm-8">
<?php
$naslov = $row['Naziv'];
echo "<b>$naslov</b>";
?>
<table class="opis">
<tr>
<td><i>Ocena</i></td>
<td>
<?php
$ocena = $row['Ocena'];
echo "<div>";
for($k=0; $k<10; $k++){
if($k < $ocena)
echo "<span class='glyphicon glyphicon-star positiv-rate'></span>";
else
echo "<span class='glyphicon glyphicon-star negative-rate'></span>";
}
echo "</div>";
?>
</td>
</tr>
<?php
$original = $row['OriginalNaziv'];
echo "<tr>";
echo "<td><i>Originalni naslov</i></td>";
echo "<td><b>$original</b></td>";
echo "</tr>";
$datum = $row['PocetakPrikazivanja'];
echo "<tr>";
echo "<td><i>Pocetak prikazivanja</i></td>";
echo "<td><b>$datum</b></td>";
echo "</tr>";
$duzina = $row['Duzina'];
echo "<tr>";
echo "<td><i>Duzina trajanja</i></td>";
echo "<td><b>$duzina min</b></td>";
echo "</tr>";
$zanr = $row['Zanr'];
echo "<tr>";
echo "<td><i>Zanr</i></td>";
echo "<td><b>$zanr</b></td>";
echo "</tr>";
$reziser = $row['Reziser'];
echo "<tr>";
echo "<td><i>Reziser</i></td>";
echo "<td><b>$reziser</b></td>";
echo "</tr>";
$poreklo = $row['Poreklo'];
echo "<tr>";
echo "<td><i>Drzava</i></td>";
echo "<td><b>$poreklo</b></td>";
echo "</tr>";
?>
</table>
</div>
</div>
<hr/>
<?php endforeach; ?>
</div>
</div>
</div>
</div>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.