code
stringlengths 4
1.01M
| language
stringclasses 2
values |
---|---|
<?php
/* WebProfilerBundle:Profiler:toolbar_js.html.twig */
class __TwigTemplate_5c613b42836f9a825aea4138cba148e6 extends Twig_Template
{
protected function doGetParent(array $context)
{
return false;
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 1
echo "<div id=\"sfwdt";
echo twig_escape_filter($this->env, $this->getContext($context, "token"), "html", null, true);
echo "\" style=\"display: none\"></div>
<script type=\"text/javascript\">/*<![CDATA[*/
(function () {
var wdt, xhr;
wdt = document.getElementById('sfwdt";
// line 5
echo twig_escape_filter($this->env, $this->getContext($context, "token"), "html", null, true);
echo "');
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
xhr.open('GET', '";
// line 11
echo twig_escape_filter($this->env, $this->env->getExtension('routing')->getPath("_wdt", array("token" => $this->getContext($context, "token"))), "html", null, true);
echo "', true);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onreadystatechange = function(state) {
if (4 === xhr.readyState && 200 === xhr.status && -1 !== xhr.responseText.indexOf('sf-toolbarreset')) {
wdt.innerHTML = xhr.responseText;
wdt.style.display = 'block';
}
};
xhr.send('');
})();
/*]]>*/</script>
";
}
public function getTemplateName()
{
return "WebProfilerBundle:Profiler:toolbar_js.html.twig";
}
public function isTraitable()
{
return false;
}
}
| Java |
package utils
import (
"io/ioutil"
"net/http"
"encoding/json"
"fmt"
"github.com/juju/errors"
)
// GetRequestBody reads request and returns bytes
func GetRequestBody(r *http.Request) ([]byte, error) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, errors.Trace(err)
}
return body, nil
}
// Respond sends HTTP response
func Respond(w http.ResponseWriter, data interface{}, code int) error {
w.WriteHeader(code)
var resp []byte
var err error
resp, err = json.Marshal(data) // No need HAL, if input is not valid JSON
if err != nil {
return errors.Trace(err)
}
fmt.Fprintln(w, string(resp))
return nil
}
// UnmarshalRequest unmarshal HTTP request to given struct
func UnmarshalRequest(r *http.Request, v interface{}) error {
body, err := GetRequestBody(r)
if err != nil {
return errors.Trace(err)
}
if err := json.Unmarshal(body, v); err != nil {
return errors.Trace(err)
}
return nil
}
| Java |
---
author: jeffatwood
comments: true
date: 2010-12-17 06:28:45+00:00
layout: post
redirect_from: /2010/12/introducing-programmers-stackexchange-com
hero:
slug: introducing-programmers-stackexchange-com
title: Introducing programmers.stackexchange.com
wordpress_id: 6383
tags:
- company
- stackexchange
- community
---
One of the [more popular Stack Exchange beta sites](http://stackexchange.com/sites) just came out of beta with a final public design:
## [programmers.stackexchange.com](http://programmers.stackexchange.com)
[](http://programmers.stackexchange.com)
Now watch closely as I read your mind.
## I don't get it! What's the difference between Programmers and Stack Overflow?
I'm so glad you asked!
In a nutshell, **Stack Overflow is for when you're front of your compiler or editor** working through code issues. **Programmers is for when you're in front of a whiteboard** working through higher level conceptual programming issues. _Hence the (awesome) whiteboard inspired design!_
Stated another way, Stack Overflow questions almost all have **actual source code in the questions or answers**. It's much rarer (though certainly OK) for a Programmers question to contain source code.

Remember, these are just guidelines, not hard and fast arbitrary rules; refer to the [first few paragraphs of the FAQ](http://programmers.stackexchange.com/help/on-topic) if you want specifics about what Programmers is for:
>
Programmers - Stack Exchange is for expert programmers who are interested in subjective discussions on software development.
>
This can include topics such as:
>
>
> * Software engineering
> * Developer testing
> * Algorithm and data structure concepts
> * Design patterns
> * Architecture
> * Development methodologies
> * Quality assurance
> * Software law
> * Freelancing and business concerns
_Editorial note: the FAQ guidance has changed significantly over the years to better reflect the sorts of conceptual questions that actually **work** - please refer to [the latest version in the help center](http://programmers.stackexchange.com/help/on-topic) before asking._
Although I fully supported this site when it was just [a baby Area 51 site proposal](http://area51.stackexchange.com/proposals/3352/not-programming-related), we've endured a lot of angst over it -- mainly because **it veered so heavily into the realm of the subjective**. It forced us to think deeply about what makes a _useful_ subjective question, which we formalized into a set of 6 guidelines in [Good Subjective, Bad Subjective](http://blog.stackoverflow.com/2010/09/good-subjective-bad-subjective/). Constructive subjective questions …
1. inspire answers that explain “why” and “how”.
2. tend to have long, not short, answers.
3. have a constructive, fair, and impartial tone.
4. invite sharing experiences over opinions.
5. insist that opinion be backed up with facts and references.
6. are more than just mindless social fun.
Ultimately, with a little extra discipline and moderation, I think the site turned out great. So, go forth and ask your **high level, conceptual, software development questions** on [programmers.stackexchange.com](http://programmers.stackexchange.com)! Just make sure they're [professional and constructive](http://blog.stackoverflow.com/2010/09/good-subjective-bad-subjective), please - refer to [help center](http://programmers.stackexchange.com/help/on-topic) for more guidance there.
| Java |
# hookshot

"You found the *hookshot*! It's a spring-loaded chain that you can cast out to hook things."
## Intro
**hookshot** is a tiny library and companion CLI tool for handling [GitHub post-receive hooks](https://help.github.com/articles/post-receive-hooks).
## Examples
### Library
```javascript
var hookshot = require('hookshot');
hookshot('refs/heads/master', 'git pull && make').listen(3000)
```
### CLI Tool
```bash
hookshot -r refs/heads/master 'git pull && make'
```
## Usage
The library exposes a single function, `hookshot()`. When called, this functions returns an express instance configured to handle post-receive hooks from GitHub. You can react to pushes to specific branches by listening to specific events on the returned instance, or by providing optional arguments to the `hookshot()` function.
```javascript
hookshot()
.on('refs/heads/master', 'git pull && make')
.listen(3000)
```
```javascript
hookshot('refs/heads/master', 'git pull && make').listen(3000)
```
### Actions
Actions can either be shell commands or JavaScript functions.
```javascript
hookshot('refs/heads/master', 'git pull && make').listen(3000)
```
```javascript
hookshot('refs/heads/master', function(info) {
// do something with push info ...
}).listen(3000)
```
### Mounting to existing express servers
**hookshot** can be mounted to a custom route on your existing express server:
```javascript
// ...
app.use('/my-github-hook', hookshot('refs/heads/master', 'git pull && make'));
// ...
```
### Special Events
Special events are fired when branches/tags are created, deleted:
```javascript
hookshot()
.on('create', function(info) {
console.log('ref ' + info.ref + ' was created.')
})
.on('delete', function(info) {
console.log('ref ' + info.ref + ' was deleted.')
})
```
The `push` event is fired when a push is made to any ref:
```javascript
hookshot()
.on('push', function(info) {
console.log('ref ' + info.ref + ' was pushed.')
})
```
Finally, the `hook` event is fired for every post-receive hook that is send by GitHub.
```javascript
hookshot()
.on('push', function(info) {
console.log('ref ' + info.ref + ' was pushed.')
})
```
### CLI Tool
A companion CLI tool is provided for convenience. To use it, install **hookshot** via npm using the `-g` flag:
```bash
npm install -g hookshot
```
The CLI tool takes as argument a command to execute upon GitHub post-receive hook:
```bash
hookshot 'echo "PUSHED!"'
```
You can optionally specify an HTTP port via the `-p` flag (defaults to 3000) and a ref via the `-r` flag (defaults to all refs):
```bash
hookshot -r refs/heads/master -p 9001 'echo "pushed to master!"'
```
| Java |
#import <Cocoa/Cocoa.h>
#import "SpectacleShortcutRecorderDelegate.h"
@class SpectacleShortcutManager;
@interface SpectacleShortcutRecorderCell : NSCell
@property (nonatomic) SpectacleShortcutRecorder *shortcutRecorder;
@property (nonatomic) NSString *shortcutName;
@property (nonatomic) SpectacleShortcut *shortcut;
@property (nonatomic, assign) id<SpectacleShortcutRecorderDelegate> delegate;
@property (nonatomic) NSArray *additionalShortcutValidators;
@property (nonatomic) SpectacleShortcutManager *shortcutManager;
#pragma mark -
- (BOOL)resignFirstResponder;
#pragma mark -
- (BOOL)performKeyEquivalent:(NSEvent *)event;
- (void)flagsChanged:(NSEvent *)event;
@end
| Java |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>basic_datagram_socket::send (2 of 3 overloads)</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../../../boost_asio.html" title="Boost.Asio">
<link rel="up" href="../send.html" title="basic_datagram_socket::send">
<link rel="prev" href="overload1.html" title="basic_datagram_socket::send (1 of 3 overloads)">
<link rel="next" href="overload3.html" title="basic_datagram_socket::send (3 of 3 overloads)">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td>
<td align="center"><a href="../../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="overload1.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../send.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../boost_asio.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="overload3.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h5 class="title">
<a name="boost_asio.reference.basic_datagram_socket.send.overload2"></a><a class="link" href="overload2.html" title="basic_datagram_socket::send (2 of 3 overloads)">basic_datagram_socket::send
(2 of 3 overloads)</a>
</h5></div></div></div>
<p>
Send some data on a connected socket.
</p>
<pre class="programlisting"><span class="keyword">template</span><span class="special"><</span>
<span class="keyword">typename</span> <a class="link" href="../../ConstBufferSequence.html" title="Constant buffer sequence requirements">ConstBufferSequence</a><span class="special">></span>
<span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span> <span class="identifier">send</span><span class="special">(</span>
<span class="keyword">const</span> <span class="identifier">ConstBufferSequence</span> <span class="special">&</span> <span class="identifier">buffers</span><span class="special">,</span>
<span class="identifier">socket_base</span><span class="special">::</span><span class="identifier">message_flags</span> <span class="identifier">flags</span><span class="special">);</span>
</pre>
<p>
This function is used to send data on the datagram socket. The function
call will block until the data has been sent successfully or an error
occurs.
</p>
<h6>
<a name="boost_asio.reference.basic_datagram_socket.send.overload2.h0"></a>
<span><a name="boost_asio.reference.basic_datagram_socket.send.overload2.parameters"></a></span><a class="link" href="overload2.html#boost_asio.reference.basic_datagram_socket.send.overload2.parameters">Parameters</a>
</h6>
<div class="variablelist">
<p class="title"><b></b></p>
<dl>
<dt><span class="term">buffers</span></dt>
<dd><p>
One ore more data buffers to be sent on the socket.
</p></dd>
<dt><span class="term">flags</span></dt>
<dd><p>
Flags specifying how the send call is to be made.
</p></dd>
</dl>
</div>
<h6>
<a name="boost_asio.reference.basic_datagram_socket.send.overload2.h1"></a>
<span><a name="boost_asio.reference.basic_datagram_socket.send.overload2.return_value"></a></span><a class="link" href="overload2.html#boost_asio.reference.basic_datagram_socket.send.overload2.return_value">Return
Value</a>
</h6>
<p>
The number of bytes sent.
</p>
<h6>
<a name="boost_asio.reference.basic_datagram_socket.send.overload2.h2"></a>
<span><a name="boost_asio.reference.basic_datagram_socket.send.overload2.exceptions"></a></span><a class="link" href="overload2.html#boost_asio.reference.basic_datagram_socket.send.overload2.exceptions">Exceptions</a>
</h6>
<div class="variablelist">
<p class="title"><b></b></p>
<dl>
<dt><span class="term">boost::system::system_error</span></dt>
<dd><p>
Thrown on failure.
</p></dd>
</dl>
</div>
<h6>
<a name="boost_asio.reference.basic_datagram_socket.send.overload2.h3"></a>
<span><a name="boost_asio.reference.basic_datagram_socket.send.overload2.remarks"></a></span><a class="link" href="overload2.html#boost_asio.reference.basic_datagram_socket.send.overload2.remarks">Remarks</a>
</h6>
<p>
The send operation can only be used with a connected socket. Use the
send_to function to send data on an unconnected datagram socket.
</p>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2015 Christopher M.
Kohlhoff<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="overload1.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../send.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../boost_asio.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="overload3.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| Java |
// +build linux
// +build 386 amd64 arm arm64
package ras
import (
"database/sql"
"fmt"
"os"
"strconv"
"strings"
"time"
_ "modernc.org/sqlite" //to register SQLite driver
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/plugins/inputs"
)
// Ras plugin gathers and counts errors provided by RASDaemon
type Ras struct {
DBPath string `toml:"db_path"`
Log telegraf.Logger `toml:"-"`
db *sql.DB `toml:"-"`
latestTimestamp time.Time `toml:"-"`
cpuSocketCounters map[int]metricCounters `toml:"-"`
serverCounters metricCounters `toml:"-"`
}
type machineCheckError struct {
ID int
Timestamp string
SocketID int
ErrorMsg string
MciStatusMsg string
}
type metricCounters map[string]int64
const (
mceQuery = `
SELECT
id, timestamp, error_msg, mcistatus_msg, socketid
FROM mce_record
WHERE timestamp > ?
`
defaultDbPath = "/var/lib/rasdaemon/ras-mc_event.db"
dateLayout = "2006-01-02 15:04:05 -0700"
memoryReadCorrected = "memory_read_corrected_errors"
memoryReadUncorrected = "memory_read_uncorrectable_errors"
memoryWriteCorrected = "memory_write_corrected_errors"
memoryWriteUncorrected = "memory_write_uncorrectable_errors"
instructionCache = "cache_l0_l1_errors"
instructionTLB = "tlb_instruction_errors"
levelTwoCache = "cache_l2_errors"
upi = "upi_errors"
processorBase = "processor_base_errors"
processorBus = "processor_bus_errors"
internalTimer = "internal_timer_errors"
smmHandlerCode = "smm_handler_code_access_violation_errors"
internalParity = "internal_parity_errors"
frc = "frc_errors"
externalMCEBase = "external_mce_errors"
microcodeROMParity = "microcode_rom_parity_errors"
unclassifiedMCEBase = "unclassified_mce_errors"
)
// SampleConfig returns sample configuration for this plugin.
func (r *Ras) SampleConfig() string {
return `
## Optional path to RASDaemon sqlite3 database.
## Default: /var/lib/rasdaemon/ras-mc_event.db
# db_path = ""
`
}
// Description returns the plugin description.
func (r *Ras) Description() string {
return "RAS plugin exposes counter metrics for Machine Check Errors provided by RASDaemon (sqlite3 output is required)."
}
// Start initializes connection to DB, metrics are gathered in Gather
func (r *Ras) Start(telegraf.Accumulator) error {
err := validateDbPath(r.DBPath)
if err != nil {
return err
}
r.db, err = connectToDB(r.DBPath)
if err != nil {
return err
}
return nil
}
// Stop closes any existing DB connection
func (r *Ras) Stop() {
if r.db != nil {
err := r.db.Close()
if err != nil {
r.Log.Errorf("Error appeared during closing DB (%s): %v", r.DBPath, err)
}
}
}
// Gather reads the stats provided by RASDaemon and writes it to the Accumulator.
func (r *Ras) Gather(acc telegraf.Accumulator) error {
rows, err := r.db.Query(mceQuery, r.latestTimestamp)
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
mcError, err := fetchMachineCheckError(rows)
if err != nil {
return err
}
tsErr := r.updateLatestTimestamp(mcError.Timestamp)
if tsErr != nil {
return err
}
r.updateCounters(mcError)
}
addCPUSocketMetrics(acc, r.cpuSocketCounters)
addServerMetrics(acc, r.serverCounters)
return nil
}
func (r *Ras) updateLatestTimestamp(timestamp string) error {
ts, err := parseDate(timestamp)
if err != nil {
return err
}
if ts.After(r.latestTimestamp) {
r.latestTimestamp = ts
}
return nil
}
func (r *Ras) updateCounters(mcError *machineCheckError) {
if strings.Contains(mcError.ErrorMsg, "No Error") {
return
}
r.initializeCPUMetricDataIfRequired(mcError.SocketID)
r.updateSocketCounters(mcError)
r.updateServerCounters(mcError)
}
func newMetricCounters() *metricCounters {
return &metricCounters{
memoryReadCorrected: 0,
memoryReadUncorrected: 0,
memoryWriteCorrected: 0,
memoryWriteUncorrected: 0,
instructionCache: 0,
instructionTLB: 0,
processorBase: 0,
processorBus: 0,
internalTimer: 0,
smmHandlerCode: 0,
internalParity: 0,
frc: 0,
externalMCEBase: 0,
microcodeROMParity: 0,
unclassifiedMCEBase: 0,
}
}
func (r *Ras) updateServerCounters(mcError *machineCheckError) {
if strings.Contains(mcError.ErrorMsg, "CACHE Level-2") && strings.Contains(mcError.ErrorMsg, "Error") {
r.serverCounters[levelTwoCache]++
}
if strings.Contains(mcError.ErrorMsg, "UPI:") {
r.serverCounters[upi]++
}
}
func validateDbPath(dbPath string) error {
pathInfo, err := os.Stat(dbPath)
if os.IsNotExist(err) {
return fmt.Errorf("provided db_path does not exist: [%s]", dbPath)
}
if err != nil {
return fmt.Errorf("cannot get system information for db_path file: [%s] - %v", dbPath, err)
}
if mode := pathInfo.Mode(); !mode.IsRegular() {
return fmt.Errorf("provided db_path does not point to a regular file: [%s]", dbPath)
}
return nil
}
func connectToDB(dbPath string) (*sql.DB, error) {
return sql.Open("sqlite", dbPath)
}
func (r *Ras) initializeCPUMetricDataIfRequired(socketID int) {
if _, ok := r.cpuSocketCounters[socketID]; !ok {
r.cpuSocketCounters[socketID] = *newMetricCounters()
}
}
func (r *Ras) updateSocketCounters(mcError *machineCheckError) {
r.updateMemoryCounters(mcError)
r.updateProcessorBaseCounters(mcError)
if strings.Contains(mcError.ErrorMsg, "Instruction TLB") && strings.Contains(mcError.ErrorMsg, "Error") {
r.cpuSocketCounters[mcError.SocketID][instructionTLB]++
}
if strings.Contains(mcError.ErrorMsg, "BUS") && strings.Contains(mcError.ErrorMsg, "Error") {
r.cpuSocketCounters[mcError.SocketID][processorBus]++
}
if (strings.Contains(mcError.ErrorMsg, "CACHE Level-0") ||
strings.Contains(mcError.ErrorMsg, "CACHE Level-1")) &&
strings.Contains(mcError.ErrorMsg, "Error") {
r.cpuSocketCounters[mcError.SocketID][instructionCache]++
}
}
func (r *Ras) updateProcessorBaseCounters(mcError *machineCheckError) {
if strings.Contains(mcError.ErrorMsg, "Internal Timer error") {
r.cpuSocketCounters[mcError.SocketID][internalTimer]++
r.cpuSocketCounters[mcError.SocketID][processorBase]++
}
if strings.Contains(mcError.ErrorMsg, "SMM Handler Code Access Violation") {
r.cpuSocketCounters[mcError.SocketID][smmHandlerCode]++
r.cpuSocketCounters[mcError.SocketID][processorBase]++
}
if strings.Contains(mcError.ErrorMsg, "Internal parity error") {
r.cpuSocketCounters[mcError.SocketID][internalParity]++
r.cpuSocketCounters[mcError.SocketID][processorBase]++
}
if strings.Contains(mcError.ErrorMsg, "FRC error") {
r.cpuSocketCounters[mcError.SocketID][frc]++
r.cpuSocketCounters[mcError.SocketID][processorBase]++
}
if strings.Contains(mcError.ErrorMsg, "External error") {
r.cpuSocketCounters[mcError.SocketID][externalMCEBase]++
r.cpuSocketCounters[mcError.SocketID][processorBase]++
}
if strings.Contains(mcError.ErrorMsg, "Microcode ROM parity error") {
r.cpuSocketCounters[mcError.SocketID][microcodeROMParity]++
r.cpuSocketCounters[mcError.SocketID][processorBase]++
}
if strings.Contains(mcError.ErrorMsg, "Unclassified") || strings.Contains(mcError.ErrorMsg, "Internal unclassified") {
r.cpuSocketCounters[mcError.SocketID][unclassifiedMCEBase]++
r.cpuSocketCounters[mcError.SocketID][processorBase]++
}
}
func (r *Ras) updateMemoryCounters(mcError *machineCheckError) {
if strings.Contains(mcError.ErrorMsg, "Memory read error") {
if strings.Contains(mcError.MciStatusMsg, "Corrected_error") {
r.cpuSocketCounters[mcError.SocketID][memoryReadCorrected]++
} else {
r.cpuSocketCounters[mcError.SocketID][memoryReadUncorrected]++
}
}
if strings.Contains(mcError.ErrorMsg, "Memory write error") {
if strings.Contains(mcError.MciStatusMsg, "Corrected_error") {
r.cpuSocketCounters[mcError.SocketID][memoryWriteCorrected]++
} else {
r.cpuSocketCounters[mcError.SocketID][memoryWriteUncorrected]++
}
}
}
func addCPUSocketMetrics(acc telegraf.Accumulator, cpuSocketCounters map[int]metricCounters) {
for socketID, data := range cpuSocketCounters {
tags := map[string]string{
"socket_id": strconv.Itoa(socketID),
}
fields := make(map[string]interface{})
for errorName, count := range data {
fields[errorName] = count
}
acc.AddCounter("ras", fields, tags)
}
}
func addServerMetrics(acc telegraf.Accumulator, counters map[string]int64) {
fields := make(map[string]interface{})
for errorName, count := range counters {
fields[errorName] = count
}
acc.AddCounter("ras", fields, map[string]string{})
}
func fetchMachineCheckError(rows *sql.Rows) (*machineCheckError, error) {
mcError := &machineCheckError{}
err := rows.Scan(&mcError.ID, &mcError.Timestamp, &mcError.ErrorMsg, &mcError.MciStatusMsg, &mcError.SocketID)
if err != nil {
return nil, err
}
return mcError, nil
}
func parseDate(date string) (time.Time, error) {
return time.Parse(dateLayout, date)
}
func init() {
inputs.Add("ras", func() telegraf.Input {
defaultTimestamp, _ := parseDate("1970-01-01 00:00:01 -0700")
return &Ras{
DBPath: defaultDbPath,
latestTimestamp: defaultTimestamp,
cpuSocketCounters: map[int]metricCounters{
0: *newMetricCounters(),
},
serverCounters: map[string]int64{
levelTwoCache: 0,
upi: 0,
},
}
})
}
| Java |
using Marten.Testing.Documents;
namespace Marten.Testing.Linq.Compatibility.Support
{
public class DefaultQueryFixture: TargetSchemaFixture
{
public DefaultQueryFixture()
{
Store = provisionStore("linq_querying");
DuplicatedFieldStore = provisionStore("duplicate_fields", o =>
{
o.Schema.For<Target>()
.Duplicate(x => x.Number)
.Duplicate(x => x.Long)
.Duplicate(x => x.String)
.Duplicate(x => x.Date)
.Duplicate(x => x.Double)
.Duplicate(x => x.Flag)
.Duplicate(x => x.Color);
});
}
public DocumentStore DuplicatedFieldStore { get; set; }
public DocumentStore Store { get; set; }
}
}
| Java |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Linq;
using Cake.Core;
using Cake.Core.IO;
namespace Cake.Common.Tools.Chocolatey
{
/// <summary>
/// Contains Chocolatey path resolver functionality.
/// </summary>
public sealed class ChocolateyToolResolver : IChocolateyToolResolver
{
private readonly IFileSystem _fileSystem;
private readonly ICakeEnvironment _environment;
private IFile _cachedPath;
/// <summary>
/// Initializes a new instance of the <see cref="ChocolateyToolResolver" /> class.
/// </summary>
/// <param name="fileSystem">The file system.</param>
/// <param name="environment">The environment.</param>
public ChocolateyToolResolver(IFileSystem fileSystem, ICakeEnvironment environment)
{
_fileSystem = fileSystem;
_environment = environment;
if (fileSystem == null)
{
throw new ArgumentNullException(nameof(fileSystem));
}
if (environment == null)
{
throw new ArgumentNullException(nameof(environment));
}
}
/// <inheritdoc/>
public FilePath ResolvePath()
{
// Check if path already resolved
if (_cachedPath != null && _cachedPath.Exists)
{
return _cachedPath.Path;
}
// Check if path set to environment variable
var chocolateyInstallationFolder = _environment.GetEnvironmentVariable("ChocolateyInstall");
if (!string.IsNullOrWhiteSpace(chocolateyInstallationFolder))
{
var envFile = _fileSystem.GetFile(PathHelper.Combine(chocolateyInstallationFolder, "choco.exe"));
if (envFile.Exists)
{
_cachedPath = envFile;
return _cachedPath.Path;
}
}
// Last resort try path
var envPath = _environment.GetEnvironmentVariable("path");
if (!string.IsNullOrWhiteSpace(envPath))
{
var pathFile = envPath
.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
.Select(path => _fileSystem.GetDirectory(path))
.Where(path => path.Exists)
.Select(path => path.Path.CombineWithFilePath("choco.exe"))
.Select(_fileSystem.GetFile)
.FirstOrDefault(file => file.Exists);
if (pathFile != null)
{
_cachedPath = pathFile;
return _cachedPath.Path;
}
}
throw new CakeException("Could not locate choco.exe.");
}
}
} | Java |
#region Copyright
//
// DotNetNuke® - http://www.dnnsoftware.com
// Copyright (c) 2002-2018
// by DotNetNuke Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
using System;
namespace Dnn.ExportImport.Dto.Users
{
public class ExportUser : BasicExportImportDto
{
public int RowId { get; set; }
public int UserId { get; set; }
public string Username { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public bool IsSuperUser { get; set; }
public int? AffiliateId { get; set; }
public string Email { get; set; }
public string DisplayName { get; set; }
public bool UpdatePassword { get; set; }
public string LastIpAddress { get; set; }
public bool IsDeletedPortal { get; set; }
public int CreatedByUserId { get; set; } //How do we insert this value?
public string CreatedByUserName { get; set; }//This could be used to find "CreatedByUserId"
public DateTime? CreatedOnDate { get; set; }
public int LastModifiedByUserId { get; set; } //How do we insert this value?
public string LastModifiedByUserName { get; set; }//This could be used to find "LastModifiedByUserId"
public DateTime? LastModifiedOnDate { get; set; }
public Guid? PasswordResetToken { get; set; }
public DateTime? PasswordResetExpiration { get; set; }
}
}
| Java |
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<select multiple id="s">
<option value="1" id="one" selected>one</option>
<option id="two" selected>two</option>
</select>
<script>
alert(document.getElementById('s').value);
</script>
</body>
</html> | Java |
<?php
/*
* This file is part of PhpSpec, A php toolset to drive emergent
* design by specification.
*
* (c) Marcello Duarte <[email protected]>
* (c) Konstantin Kudryashov <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PhpSpec\CodeGenerator\Generator;
use PhpSpec\CodeGenerator\TemplateRenderer;
use ReflectionMethod;
class ExistingConstructorTemplate
{
private $templates;
private $class;
private $className;
private $arguments;
private $methodName;
public function __construct(TemplateRenderer $templates, string $methodName, array $arguments, string $className, string $class)
{
$this->templates = $templates;
$this->class = $class;
$this->className = $className;
$this->arguments = $arguments;
$this->methodName = $methodName;
}
public function getContent() : string
{
if (!$this->numberOfConstructorArgumentsMatchMethod()) {
return $this->getExceptionContent();
}
return $this->getCreateObjectContent();
}
private function numberOfConstructorArgumentsMatchMethod() : bool
{
$constructorArguments = 0;
$constructor = new ReflectionMethod($this->class, '__construct');
$params = $constructor->getParameters();
foreach ($params as $param) {
if (!$param->isOptional()) {
$constructorArguments++;
}
}
return $constructorArguments == \count($this->arguments);
}
private function getExceptionContent() : string
{
$values = $this->getValues();
if (!$content = $this->templates->render('named_constructor_exception', $values)) {
$content = $this->templates->renderString(
$this->getExceptionTemplate(),
$values
);
}
return $content;
}
private function getCreateObjectContent() : string
{
$values = $this->getValues(true);
if (!$content = $this->templates->render('named_constructor_create_object', $values)) {
$content = $this->templates->renderString(
$this->getCreateObjectTemplate(),
$values
);
}
return $content;
}
/**
* @return string[]
*/
private function getValues(bool $constructorArguments = false) : array
{
$argString = \count($this->arguments)
? '$argument'.implode(', $argument', range(1, \count($this->arguments)))
: ''
;
return array(
'%methodName%' => $this->methodName,
'%arguments%' => $argString,
'%returnVar%' => '$'.lcfirst($this->className),
'%className%' => $this->className,
'%constructorArguments%' => $constructorArguments ? $argString : ''
);
}
/**
* @return string
*/
private function getCreateObjectTemplate(): string
{
return file_get_contents(__DIR__.'/templates/named_constructor_create_object.template');
}
/**
* @return string
*/
private function getExceptionTemplate(): string
{
return file_get_contents(__DIR__.'/templates/named_constructor_exception.template');
}
}
| Java |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information
namespace DotNetNuke.Services.Connections
{
public enum ConnectorCategories
{
Social = 0,
FileSystem = 1,
Analytics = 2,
Marketting = 3,
Other = 4,
}
}
| Java |
package run_test
import (
"fmt"
"net/url"
"strings"
"testing"
"time"
)
var tests Tests
// Load all shared tests
func init() {
tests = make(map[string]Test)
tests["database_commands"] = Test{
queries: []*Query{
&Query{
name: "create database should succeed",
command: `CREATE DATABASE db0`,
exp: `{"results":[{"statement_id":0}]}`,
once: true,
},
&Query{
name: "create database with retention duration should succeed",
command: `CREATE DATABASE db0_r WITH DURATION 24h REPLICATION 2 NAME db0_r_policy`,
exp: `{"results":[{"statement_id":0}]}`,
once: true,
},
&Query{
name: "create database with retention policy should fail with invalid name",
command: `CREATE DATABASE db1 WITH NAME "."`,
exp: `{"results":[{"statement_id":0,"error":"invalid name"}]}`,
once: true,
},
&Query{
name: "create database should error with some unquoted names",
command: `CREATE DATABASE 0xdb0`,
exp: `{"error":"error parsing query: found 0xdb0, expected identifier at line 1, char 17"}`,
},
&Query{
name: "create database should error with invalid characters",
command: `CREATE DATABASE "."`,
exp: `{"results":[{"statement_id":0,"error":"invalid name"}]}`,
},
&Query{
name: "create database with retention duration should error with bad retention duration",
command: `CREATE DATABASE db0 WITH DURATION xyz`,
exp: `{"error":"error parsing query: found xyz, expected duration at line 1, char 35"}`,
},
&Query{
name: "create database with retention replication should error with bad retention replication number",
command: `CREATE DATABASE db0 WITH REPLICATION xyz`,
exp: `{"error":"error parsing query: found xyz, expected integer at line 1, char 38"}`,
},
&Query{
name: "create database with retention name should error with missing retention name",
command: `CREATE DATABASE db0 WITH NAME`,
exp: `{"error":"error parsing query: found EOF, expected identifier at line 1, char 31"}`,
},
&Query{
name: "show database should succeed",
command: `SHOW DATABASES`,
exp: `{"results":[{"statement_id":0,"series":[{"name":"databases","columns":["name"],"values":[["db0"],["db0_r"]]}]}]}`,
},
&Query{
name: "create database should not error with existing database",
command: `CREATE DATABASE db0`,
exp: `{"results":[{"statement_id":0}]}`,
},
&Query{
name: "create database should create non-existing database",
command: `CREATE DATABASE db1`,
exp: `{"results":[{"statement_id":0}]}`,
},
&Query{
name: "create database with retention duration should error if retention policy is different",
command: `CREATE DATABASE db1 WITH DURATION 24h`,
exp: `{"results":[{"statement_id":0,"error":"retention policy conflicts with an existing policy"}]}`,
},
&Query{
name: "create database should error with bad retention duration",
command: `CREATE DATABASE db1 WITH DURATION xyz`,
exp: `{"error":"error parsing query: found xyz, expected duration at line 1, char 35"}`,
},
&Query{
name: "show database should succeed",
command: `SHOW DATABASES`,
exp: `{"results":[{"statement_id":0,"series":[{"name":"databases","columns":["name"],"values":[["db0"],["db0_r"],["db1"]]}]}]}`,
},
&Query{
name: "drop database db0 should succeed",
command: `DROP DATABASE db0`,
exp: `{"results":[{"statement_id":0}]}`,
once: true,
},
&Query{
name: "drop database db0_r should succeed",
command: `DROP DATABASE db0_r`,
exp: `{"results":[{"statement_id":0}]}`,
once: true,
},
&Query{
name: "drop database db1 should succeed",
command: `DROP DATABASE db1`,
exp: `{"results":[{"statement_id":0}]}`,
once: true,
},
&Query{
name: "drop database should not error if it does not exists",
command: `DROP DATABASE db1`,
exp: `{"results":[{"statement_id":0}]}`,
},
&Query{
name: "drop database should not error with non-existing database db1",
command: `DROP DATABASE db1`,
exp: `{"results":[{"statement_id":0}]}`,
},
&Query{
name: "show database should have no results",
command: `SHOW DATABASES`,
exp: `{"results":[{"statement_id":0,"series":[{"name":"databases","columns":["name"]}]}]}`,
},
&Query{
name: "create database with shard group duration should succeed",
command: `CREATE DATABASE db0 WITH SHARD DURATION 61m`,
exp: `{"results":[{"statement_id":0}]}`,
},
&Query{
name: "create database with shard group duration and duration should succeed",
command: `CREATE DATABASE db1 WITH DURATION 60m SHARD DURATION 30m`,
exp: `{"results":[{"statement_id":0}]}`,
},
},
}
tests["drop_and_recreate_database"] = Test{
db: "db0",
rp: "rp0",
writes: Writes{
&Write{data: fmt.Sprintf(`cpu,host=serverA,region=uswest val=23.2 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano())},
},
queries: []*Query{
&Query{
name: "Drop database after data write",
command: `DROP DATABASE db0`,
exp: `{"results":[{"statement_id":0}]}`,
once: true,
},
&Query{
name: "Recreate database",
command: `CREATE DATABASE db0`,
exp: `{"results":[{"statement_id":0}]}`,
once: true,
},
&Query{
name: "Recreate retention policy",
command: `CREATE RETENTION POLICY rp0 ON db0 DURATION 365d REPLICATION 1 DEFAULT`,
exp: `{"results":[{"statement_id":0}]}`,
once: true,
},
&Query{
name: "Show measurements after recreate",
command: `SHOW MEASUREMENTS`,
exp: `{"results":[{"statement_id":0}]}`,
params: url.Values{"db": []string{"db0"}},
},
&Query{
name: "Query data after recreate",
command: `SELECT * FROM cpu`,
exp: `{"results":[{"statement_id":0}]}`,
params: url.Values{"db": []string{"db0"}},
},
},
}
tests["drop_database_isolated"] = Test{
db: "db0",
rp: "rp0",
writes: Writes{
&Write{data: fmt.Sprintf(`cpu,host=serverA,region=uswest val=23.2 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano())},
},
queries: []*Query{
&Query{
name: "Query data from 1st database",
command: `SELECT * FROM cpu`,
exp: `{"results":[{"statement_id":0,"series":[{"name":"cpu","columns":["time","host","region","val"],"values":[["2000-01-01T00:00:00Z","serverA","uswest",23.2]]}]}]}`,
params: url.Values{"db": []string{"db0"}},
},
&Query{
name: "Query data from 1st database with GROUP BY *",
command: `SELECT * FROM cpu GROUP BY *`,
exp: `{"results":[{"statement_id":0,"series":[{"name":"cpu","tags":{"host":"serverA","region":"uswest"},"columns":["time","val"],"values":[["2000-01-01T00:00:00Z",23.2]]}]}]}`,
params: url.Values{"db": []string{"db0"}},
},
&Query{
name: "Drop other database",
command: `DROP DATABASE db1`,
once: true,
exp: `{"results":[{"statement_id":0}]}`,
},
&Query{
name: "Query data from 1st database and ensure it's still there",
command: `SELECT * FROM cpu`,
exp: `{"results":[{"statement_id":0,"series":[{"name":"cpu","columns":["time","host","region","val"],"values":[["2000-01-01T00:00:00Z","serverA","uswest",23.2]]}]}]}`,
params: url.Values{"db": []string{"db0"}},
},
&Query{
name: "Query data from 1st database and ensure it's still there with GROUP BY *",
command: `SELECT * FROM cpu GROUP BY *`,
exp: `{"results":[{"statement_id":0,"series":[{"name":"cpu","tags":{"host":"serverA","region":"uswest"},"columns":["time","val"],"values":[["2000-01-01T00:00:00Z",23.2]]}]}]}`,
params: url.Values{"db": []string{"db0"}},
},
},
}
tests["delete_series"] = Test{
db: "db0",
rp: "rp0",
writes: Writes{
&Write{data: fmt.Sprintf(`cpu,host=serverA,region=uswest val=23.2 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano())},
&Write{data: fmt.Sprintf(`cpu,host=serverA,region=uswest val=100 %d`, mustParseTime(time.RFC3339Nano, "2000-01-02T00:00:00Z").UnixNano())},
&Write{data: fmt.Sprintf(`cpu,host=serverA,region=uswest val=200 %d`, mustParseTime(time.RFC3339Nano, "2000-01-03T00:00:00Z").UnixNano())},
&Write{db: "db1", data: fmt.Sprintf(`cpu,host=serverA,region=uswest val=23.2 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano())},
},
queries: []*Query{
&Query{
name: "Show series is present",
command: `SHOW SERIES`,
exp: `{"results":[{"statement_id":0,"series":[{"columns":["key"],"values":[["cpu,host=serverA,region=uswest"]]}]}]}`,
params: url.Values{"db": []string{"db0"}},
},
&Query{
name: "Delete series",
command: `DELETE FROM cpu WHERE time < '2000-01-03T00:00:00Z'`,
exp: `{"results":[{"statement_id":0}]}`,
params: url.Values{"db": []string{"db0"}},
once: true,
},
&Query{
name: "Show series still exists",
command: `SHOW SERIES`,
exp: `{"results":[{"statement_id":0,"series":[{"columns":["key"],"values":[["cpu,host=serverA,region=uswest"]]}]}]}`,
params: url.Values{"db": []string{"db0"}},
},
&Query{
name: "Make sure last point still exists",
command: `SELECT * FROM cpu`,
exp: `{"results":[{"statement_id":0,"series":[{"name":"cpu","columns":["time","host","region","val"],"values":[["2000-01-03T00:00:00Z","serverA","uswest",200]]}]}]}`,
params: url.Values{"db": []string{"db0"}},
},
&Query{
name: "Make sure data wasn't deleted from other database.",
command: `SELECT * FROM cpu`,
exp: `{"results":[{"statement_id":0,"series":[{"name":"cpu","columns":["time","host","region","val"],"values":[["2000-01-01T00:00:00Z","serverA","uswest",23.2]]}]}]}`,
params: url.Values{"db": []string{"db1"}},
},
},
}
tests["drop_and_recreate_series"] = Test{
db: "db0",
rp: "rp0",
writes: Writes{
&Write{data: fmt.Sprintf(`cpu,host=serverA,region=uswest val=23.2 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano())},
&Write{db: "db1", data: fmt.Sprintf(`cpu,host=serverA,region=uswest val=23.2 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano())},
},
queries: []*Query{
&Query{
name: "Show series is present",
command: `SHOW SERIES`,
exp: `{"results":[{"statement_id":0,"series":[{"columns":["key"],"values":[["cpu,host=serverA,region=uswest"]]}]}]}`,
params: url.Values{"db": []string{"db0"}},
},
&Query{
name: "Drop series after data write",
command: `DROP SERIES FROM cpu`,
exp: `{"results":[{"statement_id":0}]}`,
params: url.Values{"db": []string{"db0"}},
once: true,
},
&Query{
name: "Show series is gone",
command: `SHOW SERIES`,
exp: `{"results":[{"statement_id":0}]}`,
params: url.Values{"db": []string{"db0"}},
},
&Query{
name: "Make sure data wasn't deleted from other database.",
command: `SELECT * FROM cpu`,
exp: `{"results":[{"statement_id":0,"series":[{"name":"cpu","columns":["time","host","region","val"],"values":[["2000-01-01T00:00:00Z","serverA","uswest",23.2]]}]}]}`,
params: url.Values{"db": []string{"db1"}},
},
},
}
tests["drop_and_recreate_series_retest"] = Test{
db: "db0",
rp: "rp0",
writes: Writes{
&Write{data: fmt.Sprintf(`cpu,host=serverA,region=uswest val=23.2 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano())},
},
queries: []*Query{
&Query{
name: "Show series is present again after re-write",
command: `SHOW SERIES`,
exp: `{"results":[{"statement_id":0,"series":[{"columns":["key"],"values":[["cpu,host=serverA,region=uswest"]]}]}]}`,
params: url.Values{"db": []string{"db0"}},
},
},
}
tests["drop_series_from_regex"] = Test{
db: "db0",
rp: "rp0",
writes: Writes{
&Write{data: strings.Join([]string{
fmt.Sprintf(`a,host=serverA,region=uswest val=23.2 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()),
fmt.Sprintf(`aa,host=serverA,region=uswest val=23.2 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()),
fmt.Sprintf(`b,host=serverA,region=uswest val=23.2 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()),
fmt.Sprintf(`c,host=serverA,region=uswest val=30.2 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()),
}, "\n")},
},
queries: []*Query{
&Query{
name: "Show series is present",
command: `SHOW SERIES`,
exp: `{"results":[{"statement_id":0,"series":[{"columns":["key"],"values":[["a,host=serverA,region=uswest"],["aa,host=serverA,region=uswest"],["b,host=serverA,region=uswest"],["c,host=serverA,region=uswest"]]}]}]}`,
params: url.Values{"db": []string{"db0"}},
},
&Query{
name: "Drop series after data write",
command: `DROP SERIES FROM /a.*/`,
exp: `{"results":[{"statement_id":0}]}`,
params: url.Values{"db": []string{"db0"}},
once: true,
},
&Query{
name: "Show series is gone",
command: `SHOW SERIES`,
exp: `{"results":[{"statement_id":0,"series":[{"columns":["key"],"values":[["b,host=serverA,region=uswest"],["c,host=serverA,region=uswest"]]}]}]}`,
params: url.Values{"db": []string{"db0"}},
},
&Query{
name: "Drop series from regex that matches no measurements",
command: `DROP SERIES FROM /a.*/`,
exp: `{"results":[{"statement_id":0}]}`,
params: url.Values{"db": []string{"db0"}},
once: true,
},
&Query{
name: "make sure DROP SERIES doesn't delete anything when regex doesn't match",
command: `SHOW SERIES`,
exp: `{"results":[{"statement_id":0,"series":[{"columns":["key"],"values":[["b,host=serverA,region=uswest"],["c,host=serverA,region=uswest"]]}]}]}`,
params: url.Values{"db": []string{"db0"}},
},
&Query{
name: "Drop series with WHERE field should error",
command: `DROP SERIES FROM c WHERE val > 50.0`,
exp: `{"results":[{"statement_id":0,"error":"fields not supported in WHERE clause during deletion"}]}`,
params: url.Values{"db": []string{"db0"}},
},
&Query{
name: "make sure DROP SERIES with field in WHERE didn't delete data",
command: `SHOW SERIES`,
exp: `{"results":[{"statement_id":0,"series":[{"columns":["key"],"values":[["b,host=serverA,region=uswest"],["c,host=serverA,region=uswest"]]}]}]}`,
params: url.Values{"db": []string{"db0"}},
},
&Query{
name: "Drop series with WHERE time should error",
command: `DROP SERIES FROM c WHERE time > now() - 1d`,
exp: `{"results":[{"statement_id":0,"error":"DROP SERIES doesn't support time in WHERE clause"}]}`,
params: url.Values{"db": []string{"db0"}},
},
},
}
tests["retention_policy_commands"] = Test{
db: "db0",
queries: []*Query{
&Query{
name: "create retention policy with invalid name should return an error",
command: `CREATE RETENTION POLICY "." ON db0 DURATION 1d REPLICATION 1`,
exp: `{"results":[{"statement_id":0,"error":"invalid name"}]}`,
once: true,
},
&Query{
name: "create retention policy should succeed",
command: `CREATE RETENTION POLICY rp0 ON db0 DURATION 1h REPLICATION 1`,
exp: `{"results":[{"statement_id":0}]}`,
once: true,
},
&Query{
name: "show retention policy should succeed",
command: `SHOW RETENTION POLICIES ON db0`,
exp: `{"results":[{"statement_id":0,"series":[{"columns":["name","duration","shardGroupDuration","replicaN","default"],"values":[["rp0","1h0m0s","1h0m0s",1,false]]}]}]}`,
},
&Query{
name: "alter retention policy should succeed",
command: `ALTER RETENTION POLICY rp0 ON db0 DURATION 2h REPLICATION 3 DEFAULT`,
exp: `{"results":[{"statement_id":0}]}`,
once: true,
},
&Query{
name: "show retention policy should have new altered information",
command: `SHOW RETENTION POLICIES ON db0`,
exp: `{"results":[{"statement_id":0,"series":[{"columns":["name","duration","shardGroupDuration","replicaN","default"],"values":[["rp0","2h0m0s","1h0m0s",3,true]]}]}]}`,
},
&Query{
name: "show retention policy should still show policy",
command: `SHOW RETENTION POLICIES ON db0`,
exp: `{"results":[{"statement_id":0,"series":[{"columns":["name","duration","shardGroupDuration","replicaN","default"],"values":[["rp0","2h0m0s","1h0m0s",3,true]]}]}]}`,
},
&Query{
name: "create a second non-default retention policy",
command: `CREATE RETENTION POLICY rp2 ON db0 DURATION 1h REPLICATION 1`,
exp: `{"results":[{"statement_id":0}]}`,
once: true,
},
&Query{
name: "show retention policy should show both",
command: `SHOW RETENTION POLICIES ON db0`,
exp: `{"results":[{"statement_id":0,"series":[{"columns":["name","duration","shardGroupDuration","replicaN","default"],"values":[["rp0","2h0m0s","1h0m0s",3,true],["rp2","1h0m0s","1h0m0s",1,false]]}]}]}`,
},
&Query{
name: "dropping non-default retention policy succeed",
command: `DROP RETENTION POLICY rp2 ON db0`,
exp: `{"results":[{"statement_id":0}]}`,
once: true,
},
&Query{
name: "create a third non-default retention policy",
command: `CREATE RETENTION POLICY rp3 ON db0 DURATION 1h REPLICATION 1 SHARD DURATION 30m`,
exp: `{"results":[{"statement_id":0}]}`,
once: true,
},
&Query{
name: "create retention policy with default on",
command: `CREATE RETENTION POLICY rp3 ON db0 DURATION 1h REPLICATION 1 SHARD DURATION 30m DEFAULT`,
exp: `{"results":[{"statement_id":0,"error":"retention policy conflicts with an existing policy"}]}`,
once: true,
},
&Query{
name: "show retention policy should show both with custom shard",
command: `SHOW RETENTION POLICIES ON db0`,
exp: `{"results":[{"statement_id":0,"series":[{"columns":["name","duration","shardGroupDuration","replicaN","default"],"values":[["rp0","2h0m0s","1h0m0s",3,true],["rp3","1h0m0s","1h0m0s",1,false]]}]}]}`,
},
&Query{
name: "dropping non-default custom shard retention policy succeed",
command: `DROP RETENTION POLICY rp3 ON db0`,
exp: `{"results":[{"statement_id":0}]}`,
once: true,
},
&Query{
name: "show retention policy should show just default",
command: `SHOW RETENTION POLICIES ON db0`,
exp: `{"results":[{"statement_id":0,"series":[{"columns":["name","duration","shardGroupDuration","replicaN","default"],"values":[["rp0","2h0m0s","1h0m0s",3,true]]}]}]}`,
},
&Query{
name: "Ensure retention policy with unacceptable retention cannot be created",
command: `CREATE RETENTION POLICY rp4 ON db0 DURATION 1s REPLICATION 1`,
exp: `{"results":[{"statement_id":0,"error":"retention policy duration must be at least 1h0m0s"}]}`,
once: true,
},
&Query{
name: "Check error when deleting retention policy on non-existent database",
command: `DROP RETENTION POLICY rp1 ON mydatabase`,
exp: `{"results":[{"statement_id":0}]}`,
},
&Query{
name: "Ensure retention policy for non existing db is not created",
command: `CREATE RETENTION POLICY rp0 ON nodb DURATION 1h REPLICATION 1`,
exp: `{"results":[{"statement_id":0,"error":"database not found: nodb"}]}`,
once: true,
},
&Query{
name: "drop rp0",
command: `DROP RETENTION POLICY rp0 ON db0`,
exp: `{"results":[{"statement_id":0}]}`,
},
// INF Shard Group Duration will normalize to the Retention Policy Duration Default
&Query{
name: "create retention policy with inf shard group duration",
command: `CREATE RETENTION POLICY rpinf ON db0 DURATION INF REPLICATION 1 SHARD DURATION 0s`,
exp: `{"results":[{"statement_id":0}]}`,
once: true,
},
// 0s Shard Group Duration will normalize to the Replication Policy Duration
&Query{
name: "create retention policy with 0s shard group duration",
command: `CREATE RETENTION POLICY rpzero ON db0 DURATION 1h REPLICATION 1 SHARD DURATION 0s`,
exp: `{"results":[{"statement_id":0}]}`,
once: true,
},
// 1s Shard Group Duration will normalize to the MinDefaultRetentionPolicyDuration
&Query{
name: "create retention policy with 1s shard group duration",
command: `CREATE RETENTION POLICY rponesecond ON db0 DURATION 2h REPLICATION 1 SHARD DURATION 1s`,
exp: `{"results":[{"statement_id":0}]}`,
once: true,
},
&Query{
name: "show retention policy: validate normalized shard group durations are working",
command: `SHOW RETENTION POLICIES ON db0`,
exp: `{"results":[{"statement_id":0,"series":[{"columns":["name","duration","shardGroupDuration","replicaN","default"],"values":[["rpinf","0s","168h0m0s",1,false],["rpzero","1h0m0s","1h0m0s",1,false],["rponesecond","2h0m0s","1h0m0s",1,false]]}]}]}`,
},
},
}
tests["retention_policy_auto_create"] = Test{
queries: []*Query{
&Query{
name: "create database should succeed",
command: `CREATE DATABASE db0`,
exp: `{"results":[{"statement_id":0}]}`,
once: true,
},
&Query{
name: "show retention policies should return auto-created policy",
command: `SHOW RETENTION POLICIES ON db0`,
exp: `{"results":[{"statement_id":0,"series":[{"columns":["name","duration","shardGroupDuration","replicaN","default"],"values":[["autogen","0s","168h0m0s",1,true]]}]}]}`,
},
},
}
}
func (tests Tests) load(t *testing.T, key string) Test {
test, ok := tests[key]
if !ok {
t.Fatalf("no test %q", key)
}
return test.duplicate()
}
| Java |
<? header('Location: http://www.diridarek.com'); ?> | Java |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using Azure;
using Azure.Core;
namespace Azure.Storage.Files.DataLake
{
internal partial class FileSystemGetPropertiesHeaders
{
private readonly Response _response;
public FileSystemGetPropertiesHeaders(Response response)
{
_response = response;
}
/// <summary> The data and time the filesystem was last modified. Changes to filesystem properties update the last modified time, but operations on files and directories do not. </summary>
public DateTimeOffset? LastModified => _response.Headers.TryGetValue("Last-Modified", out DateTimeOffset? value) ? value : null;
/// <summary> The version of the REST protocol used to process the request. </summary>
public string Version => _response.Headers.TryGetValue("x-ms-version", out string value) ? value : null;
/// <summary> The user-defined properties associated with the filesystem. A comma-separated list of name and value pairs in the format "n1=v1, n2=v2, ...", where each value is a base64 encoded string. Note that the string may only contain ASCII characters in the ISO-8859-1 character set. </summary>
public string Properties => _response.Headers.TryGetValue("x-ms-properties", out string value) ? value : null;
/// <summary> A bool string indicates whether the namespace feature is enabled. If "true", the namespace is enabled for the filesystem. </summary>
public string NamespaceEnabled => _response.Headers.TryGetValue("x-ms-namespace-enabled", out string value) ? value : null;
}
}
| Java |
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
console.c
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Forrest Yu, 2005
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/*
回车键: 把光标移到第一列
换行键: 把光标前进到下一行
*/
#include "type.h"
#include "const.h"
#include "protect.h"
#include "string.h"
#include "proc.h"
#include "tty.h"
#include "console.h"
#include "global.h"
#include "keyboard.h"
#include "proto.h"
PRIVATE void set_cursor(unsigned int position);
/*======================================================================*
is_current_console
*======================================================================*/
PUBLIC int is_current_console(CONSOLE* p_con)
{
return (p_con == &console_table[nr_current_console]);
}
/*======================================================================*
out_char
*======================================================================*/
PUBLIC void out_char(CONSOLE* p_con, char ch)
{
u8* p_vmem = (u8*)(V_MEM_BASE + disp_pos);
*p_vmem++ = ch;
*p_vmem++ = DEFAULT_CHAR_COLOR;
disp_pos += 2;
set_cursor(disp_pos/2);
}
/*======================================================================*
set_cursor
*======================================================================*/
PRIVATE void set_cursor(unsigned int position)
{
disable_int();
out_byte(CRTC_ADDR_REG, CURSOR_H);
out_byte(CRTC_DATA_REG, (position >> 8) & 0xFF);
out_byte(CRTC_ADDR_REG, CURSOR_L);
out_byte(CRTC_DATA_REG, position & 0xFF);
enable_int();
}
| Java |
//
// NSDataAES.h
//
// Created by cheng on 15/12/25.
// Copyright © 2015年 cheng. All rights reserved.
//
#import <Foundation/Foundation.h>
extern NSString * kCryptorKey;
#pragma mark - @interface NSData (AES128)
@interface NSData (AES128)
+ (NSData *)dataFromBase64String:(NSString *)aString;
- (NSString *)base64EncodedString;
@end
#pragma mark - @interface NSString (Encrypt)
@interface NSString (Encrypt)
- (NSString *)AES128EncryptWithKey:(NSString *)key;
- (NSString *)AES128DecryptWithKey:(NSString *)key;
- (NSString *)stringByURLEncodingStringParameter;
- (NSString *)MD5String;
// base64 加密
- (NSString *)base64Encrypt;
// base64 解密
- (NSString *)base64Decrypt;
- (NSString *)sha1;
@end | Java |
from io import BytesIO
import tempfile
import os
import time
import shutil
from contextlib import contextmanager
import six
import sys
from netlib import utils, tcp, http
def treader(bytes):
"""
Construct a tcp.Read object from bytes.
"""
fp = BytesIO(bytes)
return tcp.Reader(fp)
@contextmanager
def tmpdir(*args, **kwargs):
orig_workdir = os.getcwd()
temp_workdir = tempfile.mkdtemp(*args, **kwargs)
os.chdir(temp_workdir)
yield temp_workdir
os.chdir(orig_workdir)
shutil.rmtree(temp_workdir)
def _check_exception(expected, actual, exc_tb):
if isinstance(expected, six.string_types):
if expected.lower() not in str(actual).lower():
six.reraise(AssertionError, AssertionError(
"Expected %s, but caught %s" % (
repr(expected), repr(actual)
)
), exc_tb)
else:
if not isinstance(actual, expected):
six.reraise(AssertionError, AssertionError(
"Expected %s, but caught %s %s" % (
expected.__name__, actual.__class__.__name__, repr(actual)
)
), exc_tb)
def raises(expected_exception, obj=None, *args, **kwargs):
"""
Assert that a callable raises a specified exception.
:exc An exception class or a string. If a class, assert that an
exception of this type is raised. If a string, assert that the string
occurs in the string representation of the exception, based on a
case-insenstivie match.
:obj A callable object.
:args Arguments to be passsed to the callable.
:kwargs Arguments to be passed to the callable.
"""
if obj is None:
return RaisesContext(expected_exception)
else:
try:
ret = obj(*args, **kwargs)
except Exception as actual:
_check_exception(expected_exception, actual, sys.exc_info()[2])
else:
raise AssertionError("No exception raised. Return value: {}".format(ret))
class RaisesContext(object):
def __init__(self, expected_exception):
self.expected_exception = expected_exception
def __enter__(self):
return
def __exit__(self, exc_type, exc_val, exc_tb):
if not exc_type:
raise AssertionError("No exception raised.")
else:
_check_exception(self.expected_exception, exc_val, exc_tb)
return True
test_data = utils.Data(__name__)
# FIXME: Temporary workaround during repo merge.
test_data.dirname = os.path.join(test_data.dirname, "..", "test", "netlib")
def treq(**kwargs):
"""
Returns:
netlib.http.Request
"""
default = dict(
first_line_format="relative",
method=b"GET",
scheme=b"http",
host=b"address",
port=22,
path=b"/path",
http_version=b"HTTP/1.1",
headers=http.Headers(((b"header", b"qvalue"), (b"content-length", b"7"))),
content=b"content"
)
default.update(kwargs)
return http.Request(**default)
def tresp(**kwargs):
"""
Returns:
netlib.http.Response
"""
default = dict(
http_version=b"HTTP/1.1",
status_code=200,
reason=b"OK",
headers=http.Headers(((b"header-response", b"svalue"), (b"content-length", b"7"))),
content=b"message",
timestamp_start=time.time(),
timestamp_end=time.time(),
)
default.update(kwargs)
return http.Response(**default)
| Java |
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#pragma once
class FunctionJITRuntimeInfo
{
public:
FunctionJITRuntimeInfo(FunctionJITRuntimeIDL * data);
intptr_t GetClonedInlineCache(uint index) const;
bool HasClonedInlineCaches() const;
private:
FunctionJITRuntimeIDL m_data;
};
| Java |
#ifndef __NET_IP_WRAPPER_H
#define __NET_IP_WRAPPER_H 1
#include_next <net/ip.h>
#include <linux/version.h>
#if LINUX_VERSION_CODE < KERNEL_VERSION(3,1,0)
static inline bool ip_is_fragment(const struct iphdr *iph)
{
return (iph->frag_off & htons(IP_MF | IP_OFFSET)) != 0;
}
#endif
#if LINUX_VERSION_CODE < KERNEL_VERSION(3,13,0)
static inline void rpl_inet_get_local_port_range(struct net *net, int *low,
int *high)
{
inet_get_local_port_range(low, high);
}
#define inet_get_local_port_range rpl_inet_get_local_port_range
#endif
#endif
| Java |
# Configure EPEL (Extra Repository for Enterprise Linux)
# Note
This is the last release that will support anything before Puppet 4.
# About
This module basically just mimics the epel-release rpm. The same repos are
enabled/disabled and the GPG key is imported. In the end you will end up with
the EPEL repos configured.
The following Repos will be setup and enabled by default:
* epel
Other repositories that will setup but disabled (as per the epel-release setup)
* epel-debuginfo
* epel-source
* epel-testing
* epel-testing-debuginfo
* epel-testing-source
# Usage
In nearly all cases, you can simply _include epel_ or classify your nodes with
the epel class. There are quite a few parameters available if you need to modify
the default settings for the epel repository such as having your own mirror, an
http proxy, or disable gpg checking.
You can also use a puppet one-liner to get epel onto a system.
puppet apply -e 'include epel'
# Proxy
If you have a http proxy required to access the internet, you can use either
a class parameter in the _epel_ class (epel_proxy), or edit the $proxy variable
in the params.pp file. By default no proxy is assumed.
# Why?
I am a big fan of EPEL. I actually was one of the people who helped get it
going. I am also the owner of the epel-release package, so in general this
module should stay fairly up to date with the official upstream package.
I just got sick of coding Puppet modules and basically having an assumption
that EPEL was setup or installed. I can now depend on this module instead.
I realize it is fairly trivial to get EPEL setup. Every now-and-then however
the path to epel-release changes because something changes in the package (mass
rebuild, rpm build macros updates, etc). This module will bypass the changing
URL and just setup the package mirrors.
This does mean that if you are looking for RPM macros that are normally
included with EPEL release, this will not have them.
# Further Information
* [EPEL Wiki](http://fedoraproject.org/wiki/EPEL)
* [epel-release package information](http://mirrors.servercentral.net/fedora/epel/6/i386/repoview/epel-release.html)
# ChangeLog
=======
1.3.0
* Add ability to disable and not define any resources from this module. This is useful if another module pulls in this module, but you already have epel managed another way.
* Ability to specify your own TLS certs
* repo files are now templated instead of sourced.
* properly use metalink vs mirrorlist
1.2.2
* Add dep on stdlib for getvar function call
1.2.1
* Minor fix that lets facter 1.6 still work
* Enforce strict variables
1.2.0
* Rework testing to use TravisCI
* If you specify a baseurl, disable mirrorlist
1.1.1
* Ensure that GPG keys are using short IDs (issue #33)
1.1.0
* Default URLs to be https
* Add ability to include/exclude packages
1.0.2
* Update README with usage section.
* Fix regression when os_maj_version fact was required
* Ready for 1.0 - replace Modulefile with metadata.json
* Replace os_maj_version custom fact with operatingsystemmajrelease
* Works for EPEL7 now as well.
# Testing
* This is commonly used on Puppet Enterprise 3.x
* This was tested using Puppet 3.3.0 on Centos5/6
* This was tested using Puppet 3.1.1 on Amazon's AWS Linux
* This was tested using Puppet 3.8 and Puppet 4 now as well!
* Note Ruby 2.2 and Puppet 3.8 are not yet friends.
* I assume it will work on any RHEL variant (Amazon Linux is debatable as a variant)
* Amazon Linux compatability not promised, as EPEL doesn't always work with it.
# Lifecycle
* No functionality has been introduced that should break Puppet 2.6 or 2.7, but I am no longer testing these versions of Puppet as they are end-of-lifed from Puppet Labs.
* This also assumes a facter of greater than 1.7.0 -- at least from a testing perspective.
* I'm not actively fixing bugs for anything in facter < 2 or puppet < 3.8
## Unit tests
Install the necessary gems
bundle install --path vendor --without system_tests
Run the RSpec and puppet-lint tests
bundle exec rake test
## System tests
If you have Vagrant >=1.1.0 you can also run system tests:
RSPEC_SET=centos-64-x64 bundle exec rake spec:system
Available RSPEC_SET options are in .nodeset.yml
# License
Apache Software License 2.0
# Author/Contributors
* Aaron <[email protected]>
* Alex Harvey <[email protected]>
* Chad Metcalf <[email protected]>
* Ewoud Kohl van Wijngaarden <[email protected]>
* Jeffrey Clark <[email protected]>
* Joseph Swick <[email protected]>
* Matthaus Owens <[email protected]>
* Michael Hanselmann <[email protected]>
* Michael Stahnke <[email protected]>
* Michael Stahnke <[email protected]>
* Michael Stahnke <[email protected]>
* Michael Stahnke <[email protected]>
* Mickaël Canévet <[email protected]>
* Nick Le Mouton <[email protected]>
* Pro Cabales <[email protected]>
* Proletaryo Cabales <[email protected]>
* Riccardo Calixte <[email protected]>
* Robert Story <rstory@localhost>
* Rob Nelson <[email protected]>
* Stefan Goethals <[email protected]>
* Tim Rupp <[email protected]>
* Toni Schmidbauer <[email protected]>
* Trey Dockendorf <[email protected]>
* Troy Bollinger <[email protected]>
* Vlastimil Holer <[email protected]>
# Alternatives
If you're on CentOS 7, you can just `yum install epel-release` as it's in centos-extras.
| Java |
import { rectangle } from 'leaflet';
import boundsType from './types/bounds';
import Path from './Path';
export default class Rectangle extends Path {
static propTypes = {
bounds: boundsType.isRequired,
};
componentWillMount() {
super.componentWillMount();
const { bounds, map, ...props } = this.props;
this.leafletElement = rectangle(bounds, props);
}
componentDidUpdate(prevProps) {
if (this.props.bounds !== prevProps.bounds) {
this.leafletElement.setBounds(this.props.bounds);
}
this.setStyleIfChanged(prevProps, this.props);
}
}
| Java |
/*
GWEN
Copyright (c) 2010 Facepunch Studios
See license in Gwen.h
*/
#pragma once
#ifndef GWEN_CONTROLS_CHECKBOX_H
#define GWEN_CONTROLS_CHECKBOX_H
#include "Gwen/Controls/Base.h"
#include "Gwen/Controls/Button.h"
#include "Gwen/Gwen.h"
#include "Gwen/Skin.h"
#include "Gwen/Controls/Symbol.h"
#include "Gwen/Controls/LabelClickable.h"
namespace Gwen
{
namespace Controls
{
class GWEN_EXPORT CheckBox : public Button
{
public:
GWEN_CONTROL(CheckBox, Button);
virtual void Render(Skin::Base* skin);
virtual void OnPress();
virtual void SetChecked(bool Checked);
virtual void Toggle() { SetChecked(!IsChecked()); }
virtual bool IsChecked() { return m_bChecked; }
Gwen::Event::Caller onChecked;
Gwen::Event::Caller onUnChecked;
Gwen::Event::Caller onCheckChanged;
private:
// For derived controls
virtual bool AllowUncheck() { return true; }
void OnCheckStatusChanged();
bool m_bChecked;
};
class GWEN_EXPORT CheckBoxWithLabel : public Base
{
public:
GWEN_CONTROL_INLINE(CheckBoxWithLabel, Base)
{
SetSize(200, 19);
m_Checkbox = new CheckBox(this);
m_Checkbox->Dock(Pos::Left);
m_Checkbox->SetMargin(Margin(0, 3, 3, 3));
m_Checkbox->SetTabable(false);
m_Label = new LabelClickable(this);
m_Label->Dock(Pos::Fill);
m_Label->onPress.Add(m_Checkbox, &CheckBox::ReceiveEventPress);
m_Label->SetTabable(false);
SetTabable(false);
}
virtual CheckBox* Checkbox() { return m_Checkbox; }
virtual LabelClickable* Label() { return m_Label; }
virtual bool OnKeySpace(bool bDown)
{
if (bDown) m_Checkbox->SetChecked(!m_Checkbox->IsChecked());
return true;
}
private:
CheckBox* m_Checkbox;
LabelClickable* m_Label;
};
} // namespace Controls
} // namespace Gwen
#endif
| Java |
require 'spec_helper'
require Rails.root.join('db', 'post_migrate', '20170921101004_normalize_ldap_extern_uids')
describe NormalizeLdapExternUids, :migration, :sidekiq do
let!(:identities) { table(:identities) }
around do |example|
Timecop.freeze { example.run }
end
before do
stub_const("Gitlab::Database::MigrationHelpers::BACKGROUND_MIGRATION_BATCH_SIZE", 2)
stub_const("Gitlab::Database::MigrationHelpers::BACKGROUND_MIGRATION_JOB_BUFFER_SIZE", 2)
# LDAP identities
(1..4).each do |i|
identities.create!(id: i, provider: 'ldapmain', extern_uid: " uid = foo #{i}, ou = People, dc = example, dc = com ", user_id: i)
end
# Non-LDAP identity
identities.create!(id: 5, provider: 'foo', extern_uid: " uid = foo 5, ou = People, dc = example, dc = com ", user_id: 5)
end
it 'correctly schedules background migrations' do
Sidekiq::Testing.fake! do
Timecop.freeze do
migrate!
expect(BackgroundMigrationWorker.jobs[0]['args']).to eq([described_class::MIGRATION, [1, 2]])
expect(BackgroundMigrationWorker.jobs[0]['at']).to eq(2.minutes.from_now.to_f)
expect(BackgroundMigrationWorker.jobs[1]['args']).to eq([described_class::MIGRATION, [3, 4]])
expect(BackgroundMigrationWorker.jobs[1]['at']).to eq(4.minutes.from_now.to_f)
expect(BackgroundMigrationWorker.jobs[2]['args']).to eq([described_class::MIGRATION, [5, 5]])
expect(BackgroundMigrationWorker.jobs[2]['at']).to eq(6.minutes.from_now.to_f)
expect(BackgroundMigrationWorker.jobs.size).to eq 3
end
end
end
it 'migrates the LDAP identities' do
perform_enqueued_jobs do
migrate!
identities.where(id: 1..4).each do |identity|
expect(identity.extern_uid).to eq("uid=foo #{identity.id},ou=people,dc=example,dc=com")
end
end
end
it 'does not modify non-LDAP identities' do
perform_enqueued_jobs do
migrate!
identity = identities.last
expect(identity.extern_uid).to eq(" uid = foo 5, ou = People, dc = example, dc = com ")
end
end
end
| Java |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\WebProfilerBundle\Csp;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Handles Content-Security-Policy HTTP header for the WebProfiler Bundle.
*
* @author Romain Neutron <[email protected]>
*
* @internal
*/
class ContentSecurityPolicyHandler
{
private $nonceGenerator;
private $cspDisabled = false;
public function __construct(NonceGenerator $nonceGenerator)
{
$this->nonceGenerator = $nonceGenerator;
}
/**
* Returns an array of nonces to be used in Twig templates and Content-Security-Policy headers.
*
* Nonce can be provided by;
* - The request - In case HTML content is fetched via AJAX and inserted in DOM, it must use the same nonce as origin
* - The response - A call to getNonces() has already been done previously. Same nonce are returned
* - They are otherwise randomly generated
*/
public function getNonces(Request $request, Response $response): array
{
if ($request->headers->has('X-SymfonyProfiler-Script-Nonce') && $request->headers->has('X-SymfonyProfiler-Style-Nonce')) {
return [
'csp_script_nonce' => $request->headers->get('X-SymfonyProfiler-Script-Nonce'),
'csp_style_nonce' => $request->headers->get('X-SymfonyProfiler-Style-Nonce'),
];
}
if ($response->headers->has('X-SymfonyProfiler-Script-Nonce') && $response->headers->has('X-SymfonyProfiler-Style-Nonce')) {
return [
'csp_script_nonce' => $response->headers->get('X-SymfonyProfiler-Script-Nonce'),
'csp_style_nonce' => $response->headers->get('X-SymfonyProfiler-Style-Nonce'),
];
}
$nonces = [
'csp_script_nonce' => $this->generateNonce(),
'csp_style_nonce' => $this->generateNonce(),
];
$response->headers->set('X-SymfonyProfiler-Script-Nonce', $nonces['csp_script_nonce']);
$response->headers->set('X-SymfonyProfiler-Style-Nonce', $nonces['csp_style_nonce']);
return $nonces;
}
/**
* Disables Content-Security-Policy.
*
* All related headers will be removed.
*/
public function disableCsp()
{
$this->cspDisabled = true;
}
/**
* Cleanup temporary headers and updates Content-Security-Policy headers.
*
* @return array Nonces used by the bundle in Content-Security-Policy header
*/
public function updateResponseHeaders(Request $request, Response $response): array
{
if ($this->cspDisabled) {
$this->removeCspHeaders($response);
return [];
}
$nonces = $this->getNonces($request, $response);
$this->cleanHeaders($response);
$this->updateCspHeaders($response, $nonces);
return $nonces;
}
private function cleanHeaders(Response $response)
{
$response->headers->remove('X-SymfonyProfiler-Script-Nonce');
$response->headers->remove('X-SymfonyProfiler-Style-Nonce');
}
private function removeCspHeaders(Response $response)
{
$response->headers->remove('X-Content-Security-Policy');
$response->headers->remove('Content-Security-Policy');
$response->headers->remove('Content-Security-Policy-Report-Only');
}
/**
* Updates Content-Security-Policy headers in a response.
*/
private function updateCspHeaders(Response $response, array $nonces = []): array
{
$nonces = array_replace([
'csp_script_nonce' => $this->generateNonce(),
'csp_style_nonce' => $this->generateNonce(),
], $nonces);
$ruleIsSet = false;
$headers = $this->getCspHeaders($response);
foreach ($headers as $header => $directives) {
foreach (['script-src' => 'csp_script_nonce', 'script-src-elem' => 'csp_script_nonce', 'style-src' => 'csp_style_nonce', 'style-src-elem' => 'csp_style_nonce'] as $type => $tokenName) {
if ($this->authorizesInline($directives, $type)) {
continue;
}
if (!isset($headers[$header][$type])) {
if (isset($headers[$header]['default-src'])) {
$headers[$header][$type] = $headers[$header]['default-src'];
} else {
// If there is no script-src/style-src and no default-src, no additional rules required.
continue;
}
}
$ruleIsSet = true;
if (!\in_array('\'unsafe-inline\'', $headers[$header][$type], true)) {
$headers[$header][$type][] = '\'unsafe-inline\'';
}
$headers[$header][$type][] = sprintf('\'nonce-%s\'', $nonces[$tokenName]);
}
}
if (!$ruleIsSet) {
return $nonces;
}
foreach ($headers as $header => $directives) {
$response->headers->set($header, $this->generateCspHeader($directives));
}
return $nonces;
}
/**
* Generates a valid Content-Security-Policy nonce.
*/
private function generateNonce(): string
{
return $this->nonceGenerator->generate();
}
/**
* Converts a directive set array into Content-Security-Policy header.
*/
private function generateCspHeader(array $directives): string
{
return array_reduce(array_keys($directives), function ($res, $name) use ($directives) {
return ('' !== $res ? $res.'; ' : '').sprintf('%s %s', $name, implode(' ', $directives[$name]));
}, '');
}
/**
* Converts a Content-Security-Policy header value into a directive set array.
*/
private function parseDirectives(string $header): array
{
$directives = [];
foreach (explode(';', $header) as $directive) {
$parts = explode(' ', trim($directive));
if (\count($parts) < 1) {
continue;
}
$name = array_shift($parts);
$directives[$name] = $parts;
}
return $directives;
}
/**
* Detects if the 'unsafe-inline' is prevented for a directive within the directive set.
*/
private function authorizesInline(array $directivesSet, string $type): bool
{
if (isset($directivesSet[$type])) {
$directives = $directivesSet[$type];
} elseif (isset($directivesSet['default-src'])) {
$directives = $directivesSet['default-src'];
} else {
return false;
}
return \in_array('\'unsafe-inline\'', $directives, true) && !$this->hasHashOrNonce($directives);
}
private function hasHashOrNonce(array $directives): bool
{
foreach ($directives as $directive) {
if ('\'' !== substr($directive, -1)) {
continue;
}
if ('\'nonce-' === substr($directive, 0, 7)) {
return true;
}
if (\in_array(substr($directive, 0, 8), ['\'sha256-', '\'sha384-', '\'sha512-'], true)) {
return true;
}
}
return false;
}
/**
* Retrieves the Content-Security-Policy headers (either X-Content-Security-Policy or Content-Security-Policy) from
* a response.
*/
private function getCspHeaders(Response $response): array
{
$headers = [];
if ($response->headers->has('Content-Security-Policy')) {
$headers['Content-Security-Policy'] = $this->parseDirectives($response->headers->get('Content-Security-Policy'));
}
if ($response->headers->has('Content-Security-Policy-Report-Only')) {
$headers['Content-Security-Policy-Report-Only'] = $this->parseDirectives($response->headers->get('Content-Security-Policy-Report-Only'));
}
if ($response->headers->has('X-Content-Security-Policy')) {
$headers['X-Content-Security-Policy'] = $this->parseDirectives($response->headers->get('X-Content-Security-Policy'));
}
return $headers;
}
}
| Java |
using System;
using Ionic.Zlib;
using UnityEngine;
namespace VoiceChat
{
public static class VoiceChatUtils
{
static void ToShortArray(this float[] input, short[] output)
{
if (output.Length < input.Length)
{
throw new System.ArgumentException("in: " + input.Length + ", out: " + output.Length);
}
for (int i = 0; i < input.Length; ++i)
{
output[i] = (short)Mathf.Clamp((int)(input[i] * 32767.0f), short.MinValue, short.MaxValue);
}
}
static void ToFloatArray(this short[] input, float[] output, int length)
{
if (output.Length < length || input.Length < length)
{
throw new System.ArgumentException();
}
for (int i = 0; i < length; ++i)
{
output[i] = input[i] / (float)short.MaxValue;
}
}
static byte[] ZlibCompress(byte[] input, int length)
{
using (var ms = new System.IO.MemoryStream())
{
using (var compressor = new Ionic.Zlib.ZlibStream(ms, CompressionMode.Compress, CompressionLevel.BestCompression))
{
compressor.Write(input, 0, length);
}
return ms.ToArray();
}
}
static byte[] ZlibDecompress(byte[] input, int length)
{
using (var ms = new System.IO.MemoryStream())
{
using (var compressor = new Ionic.Zlib.ZlibStream(ms, CompressionMode.Decompress, CompressionLevel.BestCompression))
{
compressor.Write(input, 0, length);
}
return ms.ToArray();
}
}
static byte[] ALawCompress(float[] input)
{
byte[] output = VoiceChatBytePool.Instance.Get();
for (int i = 0; i < input.Length; ++i)
{
int scaled = (int)(input[i] * 32767.0f);
short clamped = (short)Mathf.Clamp(scaled, short.MinValue, short.MaxValue);
output[i] = NAudio.Codecs.ALawEncoder.LinearToALawSample(clamped);
}
return output;
}
static float[] ALawDecompress(byte[] input, int length)
{
float[] output = VoiceChatFloatPool.Instance.Get();
for (int i = 0; i < length; ++i)
{
short alaw = NAudio.Codecs.ALawDecoder.ALawToLinearSample(input[i]);
output[i] = alaw / (float)short.MaxValue;
}
return output;
}
static NSpeex.SpeexEncoder speexEnc = new NSpeex.SpeexEncoder(NSpeex.BandMode.Narrow);
static byte[] SpeexCompress(float[] input, out int length)
{
short[] shortBuffer = VoiceChatShortPool.Instance.Get();
byte[] encoded = VoiceChatBytePool.Instance.Get();
input.ToShortArray(shortBuffer);
length = speexEnc.Encode(shortBuffer, 0, input.Length, encoded, 0, encoded.Length);
VoiceChatShortPool.Instance.Return(shortBuffer);
return encoded;
}
static float[] SpeexDecompress(NSpeex.SpeexDecoder speexDec, byte[] data, int dataLength)
{
float[] decoded = VoiceChatFloatPool.Instance.Get();
short[] shortBuffer = VoiceChatShortPool.Instance.Get();
speexDec.Decode(data, 0, dataLength, shortBuffer, 0, false);
shortBuffer.ToFloatArray(decoded, shortBuffer.Length);
VoiceChatShortPool.Instance.Return(shortBuffer);
return decoded;
}
public static VoiceChatPacket Compress(float[] sample)
{
VoiceChatPacket packet = new VoiceChatPacket();
packet.Compression = VoiceChatSettings.Instance.Compression;
switch (packet.Compression)
{
/*
case VoiceChatCompression.Raw:
{
short[] buffer = VoiceChatShortPool.Instance.Get();
packet.Length = sample.Length * 2;
sample.ToShortArray(shortBuffer);
Buffer.BlockCopy(shortBuffer, 0, byteBuffer, 0, packet.Length);
}
break;
case VoiceChatCompression.RawZlib:
{
packet.Length = sample.Length * 2;
sample.ToShortArray(shortBuffer);
Buffer.BlockCopy(shortBuffer, 0, byteBuffer, 0, packet.Length);
packet.Data = ZlibCompress(byteBuffer, packet.Length);
packet.Length = packet.Data.Length;
}
break;
*/
case VoiceChatCompression.Alaw:
{
packet.Length = sample.Length;
packet.Data = ALawCompress(sample);
}
break;
case VoiceChatCompression.AlawZlib:
{
byte[] alaw = ALawCompress(sample);
packet.Data = ZlibCompress(alaw, sample.Length);
packet.Length = packet.Data.Length;
VoiceChatBytePool.Instance.Return(alaw);
}
break;
case VoiceChatCompression.Speex:
{
packet.Data = SpeexCompress(sample, out packet.Length);
}
break;
}
return packet;
}
public static int Decompress(VoiceChatPacket packet, out float[] data)
{
return Decompress(null, packet, out data);
}
public static int Decompress(NSpeex.SpeexDecoder speexDecoder, VoiceChatPacket packet, out float[] data)
{
switch (packet.Compression)
{
/*
case VoiceChatCompression.Raw:
{
short[9 buffer
Buffer.BlockCopy(packet.Data, 0, shortBuffer, 0, packet.Length);
shortBuffer.ToFloatArray(data, packet.Length / 2);
return packet.Length / 2;
}
case VoiceChatCompression.RawZlib:
{
byte[] unzipedData = ZlibDecompress(packet.Data, packet.Length);
Buffer.BlockCopy(unzipedData, 0, shortBuffer, 0, unzipedData.Length);
shortBuffer.ToFloatArray(data, unzipedData.Length / 2);
return unzipedData.Length / 2;
}
*/
case VoiceChatCompression.Speex:
{
data = SpeexDecompress(speexDecoder, packet.Data, packet.Length);
return data.Length;
}
case VoiceChatCompression.Alaw:
{
data = ALawDecompress(packet.Data, packet.Length);
return packet.Length;
}
case VoiceChatCompression.AlawZlib:
{
byte[] alaw = ZlibDecompress(packet.Data, packet.Length);
data = ALawDecompress(alaw, alaw.Length);
return alaw.Length;
}
}
data = new float[0];
return 0;
}
public static int ClosestPowerOfTwo(int value)
{
int i = 1;
while (i < value)
{
i <<= 1;
}
return i;
}
}
} | Java |
/*
YUI 3.8.0pr2 (build 154)
Copyright 2012 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add("dd-drop-plugin",function(e,t){var n=function(e){e.node=e.host,n.superclass.constructor.apply(this,arguments)};n.NAME="dd-drop-plugin",n.NS="drop",e.extend(n,e.DD.Drop),e.namespace("Plugin"),e.Plugin.Drop=n},"3.8.0pr2",{requires:["dd-drop"]});
| Java |
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!-- template designed by Marco Von Ballmoos -->
<title>Docs for page smarty_internal_compile_extends.php</title>
<link rel="stylesheet" href="../../media/stylesheet.css" />
<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'/>
</head>
<body>
<div class="page-body">
<h2 class="file-name">/libs/sysplugins/smarty_internal_compile_extends.php</h2>
<a name="sec-description"></a>
<div class="info-box">
<div class="info-box-title">Description</div>
<div class="nav-bar">
<span class="disabled">Description</span> |
<a href="#sec-classes">Classes</a>
</div>
<div class="info-box-body">
<!-- ========== Info from phpDoc block ========= -->
<p class="short-description">Smarty Internal Plugin Compile extend</p>
<p class="description"><p>Compiles the {extends} tag</p></p>
<ul class="tags">
<li><span class="field">author:</span> Uwe Tews</li>
</ul>
</div>
</div>
<a name="sec-classes"></a>
<div class="info-box">
<div class="info-box-title">Classes</div>
<div class="nav-bar">
<a href="#sec-description">Description</a> |
<span class="disabled">Classes</span>
</div>
<div class="info-box-body">
<table cellpadding="2" cellspacing="0" class="class-table">
<tr>
<th class="class-table-header">Class</th>
<th class="class-table-header">Description</th>
</tr>
<tr>
<td style="padding-right: 2em; vertical-align: top">
<a href="../../Smarty/Compiler/Smarty_Internal_Compile_Extends.html">Smarty_Internal_Compile_Extends</a>
</td>
<td>
Smarty Internal Plugin Compile extend Class
</td>
</tr>
</table>
</div>
</div>
<p class="notes" id="credit">
Documentation generated on Sat, 24 Sep 2011 20:23:41 +0200 by <a href="http://www.phpdoc.org" target="_blank">phpDocumentor 1.4.1</a>
</p>
</div></body>
</html> | Java |
/* This file was generated by SableCC (http://www.sablecc.org/). */
package com.bju.cps450.node;
import com.bju.cps450.analysis.*;
@SuppressWarnings("nls")
public final class TPlus extends Token
{
public TPlus()
{
super.setText("+");
}
public TPlus(int line, int pos)
{
super.setText("+");
setLine(line);
setPos(pos);
}
@Override
public Object clone()
{
return new TPlus(getLine(), getPos());
}
@Override
public void apply(Switch sw)
{
((Analysis) sw).caseTPlus(this);
}
@Override
public void setText(@SuppressWarnings("unused") String text)
{
throw new RuntimeException("Cannot change TPlus text.");
}
}
| Java |
# https://github.com/plataformatec/devise#test-helpers
RSpec.configure do |config|
config.include Devise::TestHelpers, :type => :controller
end
| Java |
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>parse_extension_args (OpenID::SReg::Request)</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="../../../.././rdoc-style.css" type="text/css" media="screen" />
</head>
<body class="standalone-code">
<pre><span class="ruby-comment cmt"># File lib/openid/extensions/sreg.rb, line 126</span>
<span class="ruby-keyword kw">def</span> <span class="ruby-identifier">parse_extension_args</span>(<span class="ruby-identifier">args</span>, <span class="ruby-identifier">strict</span> = <span class="ruby-keyword kw">false</span>)
<span class="ruby-identifier">required_items</span> = <span class="ruby-identifier">args</span>[<span class="ruby-value str">'required'</span>]
<span class="ruby-keyword kw">unless</span> <span class="ruby-identifier">required_items</span>.<span class="ruby-identifier">nil?</span> <span class="ruby-keyword kw">or</span> <span class="ruby-identifier">required_items</span>.<span class="ruby-identifier">empty?</span>
<span class="ruby-identifier">required_items</span>.<span class="ruby-identifier">split</span>(<span class="ruby-value str">','</span>).<span class="ruby-identifier">each</span>{<span class="ruby-operator">|</span><span class="ruby-identifier">field_name</span><span class="ruby-operator">|</span>
<span class="ruby-keyword kw">begin</span>
<span class="ruby-identifier">request_field</span>(<span class="ruby-identifier">field_name</span>, <span class="ruby-keyword kw">true</span>, <span class="ruby-identifier">strict</span>)
<span class="ruby-keyword kw">rescue</span> <span class="ruby-constant">ArgumentError</span>
<span class="ruby-identifier">raise</span> <span class="ruby-keyword kw">if</span> <span class="ruby-identifier">strict</span>
<span class="ruby-keyword kw">end</span>
}
<span class="ruby-keyword kw">end</span>
<span class="ruby-identifier">optional_items</span> = <span class="ruby-identifier">args</span>[<span class="ruby-value str">'optional'</span>]
<span class="ruby-keyword kw">unless</span> <span class="ruby-identifier">optional_items</span>.<span class="ruby-identifier">nil?</span> <span class="ruby-keyword kw">or</span> <span class="ruby-identifier">optional_items</span>.<span class="ruby-identifier">empty?</span>
<span class="ruby-identifier">optional_items</span>.<span class="ruby-identifier">split</span>(<span class="ruby-value str">','</span>).<span class="ruby-identifier">each</span>{<span class="ruby-operator">|</span><span class="ruby-identifier">field_name</span><span class="ruby-operator">|</span>
<span class="ruby-keyword kw">begin</span>
<span class="ruby-identifier">request_field</span>(<span class="ruby-identifier">field_name</span>, <span class="ruby-keyword kw">false</span>, <span class="ruby-identifier">strict</span>)
<span class="ruby-keyword kw">rescue</span> <span class="ruby-constant">ArgumentError</span>
<span class="ruby-identifier">raise</span> <span class="ruby-keyword kw">if</span> <span class="ruby-identifier">strict</span>
<span class="ruby-keyword kw">end</span>
}
<span class="ruby-keyword kw">end</span>
<span class="ruby-ivar">@policy_url</span> = <span class="ruby-identifier">args</span>[<span class="ruby-value str">'policy_url'</span>]
<span class="ruby-keyword kw">end</span></pre>
</body>
</html> | Java |
class ChangeOrderAttributes < ActiveRecord::Migration
def up
change_column_default :orders, :front_end_change, nil
rename_column :orders, :front_end_change, :change
remove_column :orders, :refunded
remove_column :orders, :total_is_locked
remove_column :orders, :tax_is_locked
remove_column :orders, :subtotal_is_locked
remove_column :orders, :cash_register_daily_id
remove_column :orders, :by_card
remove_column :orders, :refunded_at
remove_column :orders, :refunded_by
remove_column :orders, :refunded_by_type
remove_column :orders, :discount_amount
remove_column :orders, :tax_free
change_column_default :orders, :qnr, nil
end
def down
end
end
| Java |
# extension imports
from _NetworKit import PageRankNibble, GCE | Java |
//= require d3/d3
//= require jquery.qtip.min
//= require simple_statistics
gfw.ui.model.CountriesEmbedOverview = cdb.core.Model.extend({
defaults: {
graph: 'total_loss',
years: true,
class: null
}
});
gfw.ui.view.CountriesEmbedOverview = cdb.core.View.extend({
el: document.body,
events: {
'click .graph_tab': '_updateGraph'
},
initialize: function() {
this.model = new gfw.ui.model.CountriesEmbedOverview();
this.$graph = $('.overview_graph__area');
this.$years = $('.overview_graph__years');
var m = this.m = 40,
w = this.w = this.$graph.width()+(m*2),
h = this.h = this.$graph.height(),
vertical_m = this.vertical_m = 20;
this.x_scale = d3.scale.linear()
.range([m, w-m])
.domain([2001, 2012]);
this.grid_scale = d3.scale.linear()
.range([vertical_m, h-vertical_m])
.domain([0, 1]);
this.model.bind('change:graph', this._redrawGraph, this);
this.model.bind('change:years', this._toggleYears, this);
this.model.bind('change:class', this._toggleClass, this);
this._initViews();
},
_initViews: function() {
this.tooltip = d3.select('body')
.append('div')
.attr('class', 'tooltip');
this._drawYears();
this._drawGraph();
},
_toggleYears: function() {
var that = this;
if(this.model.get('years') === false) {
this.$years.slideUp(250, function() {
$('.overview_graph__axis').slideDown();
});
} else {
$('.overview_graph__axis').slideUp(250, function() {
that.$years.slideDown();
});
}
},
_showYears: function() {
if (!this.model.get('years')) {
this.model.set('years', true);
}
},
_hideYears: function() {
if (this.model.get('years')) {
this.model.set('years', false);
}
},
_updateGraph: function(e) {
e.preventDefault();
var $target = $(e.target).closest('.graph_tab'),
graph = $target.attr('data-slug');
if (graph === this.model.get('graph')) {
return;
} else {
$('.graph_tab').removeClass('selected');
$target.addClass('selected');
this.model.set('graph', graph);
}
},
_redrawGraph: function() {
var graph = this.model.get('graph');
$('.overview_graph__title').html(config.GRAPHS[graph].title);
$('.overview_graph__legend p').html(config.GRAPHS[graph].subtitle);
$('.overview_graph__legend .info').attr('data-source', graph);
this.$graph.find('.'+graph);
this.$graph.find('.chart').hide();
this.$graph.find('.'+graph).fadeIn();
this._drawGraph();
},
_drawYears: function() {
var markup_years = '';
for (var y = 2001; y<=2012; y += 1) {
var y_ = this.x_scale(y);
if (y === 2001) {
y_ -= 25;
} else if (y === 2012) {
y_ -= 55;
} else {
y_ -= 40;
}
markup_years += '<span class="year" style="left:'+y_+'px">'+y+'</span>';
}
this.$years.html(markup_years);
},
_drawGraph: function() {
var that = this;
var w = this.w,
h = this.h,
vertical_m = this.vertical_m,
m = this.m,
x_scale = this.x_scale;
var grid_scale = d3.scale.linear()
.range([vertical_m, h-vertical_m])
.domain([1, 0]);
d3.select('#chart').remove();
var svg = d3.select('.overview_graph__area')
.append('svg:svg')
.attr('id', 'chart')
.attr('width', w)
.attr('height', h);
// grid
svg.selectAll('line.grid_h')
.data(grid_scale.ticks(4))
.enter()
.append('line')
.attr({
'class': 'grid grid_h',
'x1': 0,
'x2': w,
'y1': function(d, i) { return grid_scale(d); },
'y2': function(d, i) { return grid_scale(d); }
});
svg.selectAll('line.grid_v')
.data(x_scale.ticks(12))
.enter()
.append('line')
.attr({
'class': 'grid grid_v',
'y1': h,
'y2': 0,
'x1': function(d) { return x_scale(d); },
'x2': function(d) { return x_scale(d); }
});
var gradient = svg.append('svg:defs')
.append('svg:linearGradient')
.attr('id', 'gradient')
.attr('x1', '0%')
.attr('y1', '0%')
.attr('x2', '0%')
.attr('y2', '100%')
.attr('spreadMethod', 'pad');
gradient.append('svg:stop')
.attr('offset', '0%')
.attr('stop-color', '#CA46FF')
.attr('stop-opacity', .5);
gradient.append('svg:stop')
.attr('offset', '100%')
.attr('stop-color', '#D24DFF')
.attr('stop-opacity', 1);
if (this.model.get('graph') === 'total_loss') {
this._showYears();
svg.append('text')
.attr('class', 'axis')
.attr('id', 'axis_y')
.text('Mha')
.attr('x', -h/2)
.attr('y', 30)
.attr('transform', 'rotate(-90)');
var sql = 'SELECT ';
for(var y = 2001; y < 2012; y++) {
sql += 'SUM(y'+y+') as y'+y+', '
}
sql += 'SUM(y2012) as y2012, (SELECT SUM(y2001_y2012)\
FROM countries_gain) as gain\
FROM loss_gt_0';
d3.json('https://wri-01.cartodb.com/api/v2/sql?q='+sql, function(error, json) {
var data = json.rows[0];
var data_ = [],
gain = null;
_.each(data, function(val, key) {
if (key === 'gain') {
gain = val/12;
} else {
data_.push({
'year': key.replace('y',''),
'value': val
});
}
});
var y_scale = d3.scale.linear()
.range([vertical_m, h-vertical_m])
.domain([d3.max(data_, function(d) { return d.value; }), 0]);
// area
var area = d3.svg.area()
.x(function(d) { return x_scale(d.year); })
.y0(h)
.y1(function(d) { return y_scale(d.value); });
svg.append('path')
.datum(data_)
.attr('class', 'area')
.attr('d', area)
.style('fill', 'url(#gradient)');
// circles
svg.selectAll('circle')
.data(data_)
.enter()
.append('svg:circle')
.attr('class', 'linedot')
.attr('cx', function(d) {
return x_scale(d.year);
})
.attr('cy', function(d){
return y_scale(d.value);
})
.attr('r', 6)
.attr('name', function(d) {
return '<span>'+d.year+'</span>'+formatNumber(parseFloat(d.value/1000000).toFixed(1))+' Mha';
})
.on('mouseover', function(d) {
that.tooltip.html($(this).attr('name'))
.style('visibility', 'visible')
.style('top', $(this).offset().top-100+'px')
.style('left', $(this).offset().left-$('.tooltip').width()/2-4+'px')
.attr('class', 'tooltip');
d3.select(this)
.transition()
.duration(100)
.attr('r', 7);
// TODO: highlighting the legend
})
.on('mouseout', function(d) {
that.tooltip.style('visibility', 'hidden');
d3.select(this)
.transition()
.duration(100)
.attr('r', 6);
// TODO: highlighting the legend
});
var data_gain_ = [
{
year: 2001,
value: gain
},
{
year: 2012,
value: gain
}
];
// line
svg.selectAll('line.overview_line')
.data(data_gain_)
.enter()
.append('line')
.attr({
'class': 'overview_line',
'x1': m,
'x2': w-m,
'y1': function(d) { return y_scale(gain); },
'y2': function(d) { return y_scale(gain); }
});
svg.selectAll('circle.gain')
.data(data_gain_)
.enter()
.append('svg:circle')
.attr('class', 'linedot gain')
.attr('cx', function(d) {
return x_scale(d.year);
})
.attr('cy', function(d){
return y_scale(d.value);
})
.attr('r', 6)
.attr('name', function(d) {
return '<span>2001-2012</span>'+formatNumber(parseFloat(d.value/1000000).toFixed(1))+' Mha';
})
.on('mouseover', function(d) {
that.tooltip.html($(this).attr('name'))
.style('visibility', 'visible')
.style('top', $(this).offset().top-100+'px')
.style('left', $(this).offset().left-$('.tooltip').width()/2-4+'px')
.attr('class', 'tooltip gain_tooltip');
d3.select(this)
.transition()
.duration(100)
.attr('r', 7);
// TODO: highlighting the legend
})
.on('mouseout', function(d) {
that.tooltip.style('visibility', 'hidden');
d3.select(this)
.transition()
.duration(100)
.attr('r', 6);
// TODO: highlighting the legend
});
});
} else if (this.model.get('graph') === 'percent_loss') {
this._showYears();
svg.append('text')
.attr('class', 'axis')
.attr('id', 'axis_y')
.text('%')
.attr('x', -h/2)
.attr('y', 30)
.attr('transform', 'rotate(-90)');
var sql = 'WITH loss as (SELECT ';
for(var y = 2001; y < 2012; y++) {
sql += 'SUM(y'+y+') as sum_loss_y'+y+', ';
}
sql += 'SUM(y2012) as sum_loss_y2012\
FROM loss_gt_25), extent as (SELECT ';
for(var y = 2001; y < 2012; y++) {
sql += 'SUM(y'+y+') as sum_extent_y'+y+', ';
}
sql += 'SUM(y2012) as sum_extent_y2012\
FROM extent_gt_25)\
SELECT ';
for(var y = 2001; y < 2012; y++) {
sql += 'sum_loss_y'+y+'/sum_extent_y'+y+' as percent_loss_'+y+', ';
}
sql += 'sum_loss_y2012/sum_extent_y2012 as percent_loss_2012, (SELECT SUM(y2001_y2012)/(';
for(var y = 2001; y < 2012; y++) {
sql += 'sum_extent_y'+y+' + ';
}
sql += 'sum_extent_y2012)\
FROM countries_gain) as gain\
FROM loss, extent';
d3.json('https://wri-01.cartodb.com/api/v2/sql?q='+encodeURIComponent(sql), function(json) {
var data = json.rows[0];
var data_ = [],
gain = null;
_.each(data, function(val, key) {
if (key === 'gain') {
gain = val/12;
} else {
data_.push({
'year': key.replace('percent_loss_',''),
'value': val
});
}
});
var y_scale = grid_scale;
// area
var area = d3.svg.area()
.x(function(d) { return x_scale(d.year); })
.y0(h)
.y1(function(d) { return y_scale(d.value*100); });
svg.append('path')
.datum(data_)
.attr('class', 'area')
.attr('d', area)
.style('fill', 'url(#gradient)');
// circles
svg.selectAll('circle')
.data(data_)
.enter()
.append('svg:circle')
.attr('class', 'linedot')
.attr('cx', function(d) {
return x_scale(d.year);
})
.attr('cy', function(d){
return y_scale(d.value*100);
})
.attr('r', 6)
.attr('name', function(d) {
return '<span>'+d.year+'</span>'+parseFloat(d.value*100).toFixed(2)+' %';
})
.on('mouseover', function(d) {
that.tooltip.html($(this).attr('name'))
.style('visibility', 'visible')
.style('top', $(this).offset().top-100+'px')
.style('left', $(this).offset().left-$('.tooltip').width()/2-4+'px')
.attr('class', 'tooltip');
d3.select(this)
.transition()
.duration(100)
.attr('r', 7);
// TODO: highlighting the legend
})
.on('mouseout', function(d) {
that.tooltip.style('visibility', 'hidden');
d3.select(this)
.transition()
.duration(100)
.attr('r', 6);
// TODO: highlighting the legend
});
var data_gain_ = [
{
year: 2001,
value: gain
},
{
year: 2012,
value: gain
}
];
// line
svg.selectAll('line.overview_line')
.data(data_gain_)
.enter()
.append('line')
.attr({
'class': 'overview_line',
'x1': m,
'x2': w-m,
'y1': function(d) { return y_scale(gain*100); },
'y2': function(d) { return y_scale(gain*100); }
});
// circles
svg.selectAll('circle.gain')
.data(data_gain_)
.enter()
.append('svg:circle')
.attr('class', 'linedot gain')
.attr('cx', function(d) {
return x_scale(d.year);
})
.attr('cy', function(d){
return y_scale(d.value*100);
})
.attr('r', 6)
.attr('name', function(d) {
return '<span>2001-2012</span>'+parseFloat(d.value*100).toFixed(2)+' %';
})
.on('mouseover', function(d) {
that.tooltip.html($(this).attr('name'))
.style('visibility', 'visible')
.style('top', $(this).offset().top-100+'px')
.style('left', $(this).offset().left-$('.tooltip').width()/2-4+'px')
.attr('class', 'tooltip gain_tooltip');
d3.select(this)
.transition()
.duration(100)
.attr('r', 7);
// TODO: highlighting the legend
})
.on('mouseout', function(d) {
that.tooltip.style('visibility', 'hidden');
d3.select(this)
.transition()
.duration(100)
.attr('r', 6);
// TODO: highlighting the legend
});
});
} else if (this.model.get('graph') === 'total_extent') {
this._showYears();
svg.append('text')
.attr('class', 'axis')
.attr('id', 'axis_y')
.text('Mha')
.attr('x', -h/2)
.attr('y', 30)
.attr('transform', 'rotate(-90)');
var gradient_extent = svg.append('svg:defs')
.append('svg:linearGradient')
.attr('id', 'gradient_extent')
.attr('x1', '0%')
.attr('y1', '0%')
.attr('x2', '0%')
.attr('y2', '100%')
.attr('spreadMethod', 'pad');
gradient_extent.append('svg:stop')
.attr('offset', '0%')
.attr('stop-color', '#98BD17')
.attr('stop-opacity', .5);
gradient_extent.append('svg:stop')
.attr('offset', '100%')
.attr('stop-color', '#98BD17')
.attr('stop-opacity', 1);
var sql = 'SELECT ';
for(var y = 2001; y < 2012; y++) {
sql += 'SUM(loss.y'+y+') as loss_y'+y+', ';
}
sql += 'SUM(loss.y2012) as loss_y2012, ';
for(var y = 2001; y < 2012; y++) {
sql += 'SUM(extent.y'+y+') as extent_y'+y+', ';
}
sql += 'SUM(extent.y2012) as extent_y2012\
FROM loss_gt_25 loss, extent_gt_25 extent\
WHERE loss.iso = extent.iso';
d3.json('https://wri-01.cartodb.com/api/v2/sql?q='+encodeURIComponent(sql), function(json) {
var data = json.rows[0];
var data_ = [],
data_loss_ = [],
data_extent_ = [];
_.each(data, function(val, key) {
var year = key.split('_y')[1];
var obj = _.find(data_, function(obj) { return obj.year == year; });
if(obj === undefined) {
data_.push({ 'year': year });
}
if (key.indexOf('loss_y') != -1) {
data_loss_.push({
'year': key.split('_y')[1],
'value': val
});
}
if (key.indexOf('extent_y') != -1) {
data_extent_.push({
'year': key.split('extent_y')[1],
'value': val
});
}
});
_.each(data_, function(val) {
var loss = _.find(data_loss_, function(obj) { return obj.year == val.year; }),
extent = _.find(data_extent_, function(obj) { return obj.year == val.year; });
_.extend(val, { 'loss': loss.value, 'extent': extent.value });
});
var domain = [d3.max(data_, function(d) { return d.extent; }), 0];
var y_scale = d3.scale.linear()
.range([vertical_m, h-vertical_m])
.domain(domain);
// area
var area_loss = d3.svg.area()
.x(function(d) { return x_scale(d.year); })
.y0(h)
.y1(function(d) { return y_scale(d.loss); });
var area_extent = d3.svg.area()
.x(function(d) { return x_scale(d.year); })
.y0(function(d) { return y_scale(d.extent); })
.y1(function(d) { return y_scale(d.loss); });
svg.append('path')
.datum(data_)
.attr('class', 'area')
.attr('d', area_loss)
.style('fill', 'url(#gradient)');
svg.append('path')
.datum(data_)
.attr('class', 'area')
.attr('d', area_extent)
.style('fill', 'url(#gradient_extent)');
// circles
svg.selectAll('circle')
.data(data_loss_)
.enter()
.append('svg:circle')
.attr('class', 'linedot')
.attr('cx', function(d) {
return x_scale(d.year);
})
.attr('cy', function(d){
return y_scale(d.value);
})
.attr('r', 6)
.attr('name', function(d) {
return '<span>'+d.year+'</span>'+formatNumber(parseFloat(d.value/1000000).toFixed(1))+' Mha';
})
.on('mouseover', function(d) {
that.tooltip.html($(this).attr('name'))
.style('visibility', 'visible')
.style('top', $(this).offset().top-100+'px')
.style('left', $(this).offset().left-$('.tooltip').width()/2-4+'px')
.attr('class', 'tooltip');
d3.select(this)
.transition()
.duration(100)
.attr('r', 7);
// TODO: highlighting the legend
})
.on('mouseout', function(d) {
that.tooltip.style('visibility', 'hidden');
d3.select(this)
.transition()
.duration(100)
.attr('r', 6);
// TODO: highlighting the legend
});
svg.selectAll('circle.gain')
.data(data_extent_)
.enter()
.append('svg:circle')
.attr('class', 'linedot gain')
.attr('cx', function(d) {
return x_scale(d.year);
})
.attr('cy', function(d){
return y_scale(d.value);
})
.attr('r', 6)
.attr('name', function(d) {
return '<span>'+d.year+'</span>'+formatNumber(parseFloat(d.value/1000000).toFixed(1))+' Mha';
})
.on('mouseover', function(d) {
that.tooltip.html($(this).attr('name'))
.style('visibility', 'visible')
.style('top', $(this).offset().top-100+'px')
.style('left', $(this).offset().left-$('.tooltip').width()/2-4+'px')
.attr('class', 'tooltip gain_tooltip');
d3.select(this)
.transition()
.duration(100)
.attr('r', 7);
// TODO: highlighting the legend
})
.on('mouseout', function(d) {
that.tooltip.style('visibility', 'hidden');
d3.select(this)
.transition()
.duration(100)
.attr('r', 6);
// TODO: highlighting the legend
});
});
} else if (this.model.get('graph') === 'ratio') {
this._hideYears();
svg.append('text')
.attr('class', 'axis light')
.attr('id', 'axis_y')
.text('Cover gain 2001-2012')
.attr('x', -(h/2))
.attr('y', 30)
.attr('transform', 'rotate(-90)');
var shadow = svg.append('svg:defs')
.append('svg:filter')
.attr('id', 'shadow')
.attr('x', '0%')
.attr('y', '0%')
.attr('width', '200%')
.attr('height', '200%')
shadow.append('svg:feOffset')
.attr('result', 'offOut')
.attr('in', 'SourceAlpha')
.attr('dx', 0)
.attr('dy', 0);
shadow.append('svg:feGaussianBlur')
.attr('result', 'blurOut')
.attr('in', 'offOut')
.attr('stdDeviation', 1);
shadow.append('svg:feBlend')
.attr('in', 'SourceGraphic')
.attr('in2', 'blurOut')
.attr('mode', 'normal');
var sql = 'WITH loss as (SELECT iso, SUM(';
for(var y = 2001; y < 2012; y++) {
sql += 'loss.y'+y+' + ';
}
sql += 'loss.y2012) as sum_loss\
FROM loss_gt_50 loss\
GROUP BY iso), gain as (SELECT g.iso, SUM(y2001_y2012) as sum_gain\
FROM countries_gain g, loss_gt_50 loss\
WHERE loss.iso = g.iso\
GROUP BY g.iso), ratio as (';
sql += 'SELECT c.iso, c.name, c.enabled, loss.sum_loss as loss, gain.sum_gain as gain, loss.sum_loss/gain.sum_gain as ratio\
FROM loss, gain, gfw2_countries c\
WHERE sum_gain IS NOT null\
AND NOT sum_gain = 0\
AND c.iso = gain.iso\
AND c.iso = loss.iso\
ORDER BY loss.sum_loss DESC\
LIMIT 50) ';
sql += 'SELECT *\
FROM ratio\
WHERE ratio IS NOT null\
ORDER BY ratio DESC';
d3.json('https://wri-01.cartodb.com/api/v2/sql?q='+encodeURIComponent(sql), function(json) {
var data = json.rows;
var log_m = 50;
var y_scale = d3.scale.linear()
.range([h, 0])
.domain([0, d3.max(data, function(d) { return d.gain; })]);
var x_scale = d3.scale.linear()
.range([m, w-m])
.domain([d3.min(data, function(d) { return d.loss; }), d3.max(data, function(d) { return d.loss; })]);
var x_log_scale = d3.scale.log()
.range([m, w-m])
.domain([d3.min(data, function(d) { return d.loss; }), d3.max(data, function(d) { return d.loss; })]);
var y_log_scale = d3.scale.log()
.range([h-log_m, m])
.domain([d3.min(data, function(d) { return d.gain; }), d3.max(data, function(d) { return d.gain; })]);
var r_scale = d3.scale.linear()
.range(['yellow', 'red'])
.domain([0, d3.max(data, function(d) { return d.ratio; })]);
that.linearRegressionLine(svg, json, x_scale, y_scale);
// circles w/ magic numbers :(
var circle_attr = {
'cx': function(d) { return d.loss >= 1 ? x_log_scale(d.loss) : m; },
'cy': function(d) { return d.gain >= 1 ? y_log_scale(d.gain) : h-log_m; },
'r': '5',
'name': function(d) { return d.name; },
'class': function(d) { return d.enabled ? 'ball ball_link' : 'ball ball_nolink'; }
};
var data_ = [],
data_link_ = [],
exclude = ['Saint Barthélemy', 'Saint Kitts and Nevis',
'Saint Pierre and Miquelon', 'Virgin Islands', 'Oman',
'Gibraltar', 'Saudi Arabia', 'French Polynesia',
'Samoa', 'Western Sahara', 'United Arab Emirates'];
_.each(data, function(row) {
if (!_.contains(exclude, row.name)) {
if (row.enabled === true) {
data_link_.push(row);
} else {
data_.push(row);
}
}
});
var circles_link = svg.selectAll('circle.ball_link')
.data(data_link_)
.enter()
.append('a')
.attr('xlink:href', function(d) { return '/country/' + d.iso })
.attr('target', '_blank')
.append('svg:circle')
.attr(circle_attr)
.style('fill', function(d) {
return r_scale(d.ratio);
})
.style('filter', 'url(#shadow)')
.on('mouseover', function() {
d3.select(d3.event.target)
.transition()
.attr('r', '7')
.style('opacity', 1);
var t = $(this).offset().top - 80,
l = $(this).offset().left,
r = $(this).attr('r'),
tip = $('.tooltip').width()/2;
that.tooltip.html($(this).attr('name'))
.style('visibility', 'visible')
.style('top', parseInt(t, 10)+'px')
.style('left', parseInt(l, 10)+parseInt(r, 10)-parseInt(tip, 10)-10+'px')
.attr('class', 'tooltip gain_tooltip');
})
.on('mouseenter', function() {
d3.select(d3.event.target)
.transition()
.attr('r', '7')
.style('opacity', 1);
var t = $(this).offset().top - 80,
l = $(this).offset().left,
r = $(this).attr('r'),
tip = $('.tooltip').width()/2;
that.tooltip.html($(this).attr('name'))
.style('visibility', 'visible')
.style('top', parseInt(t, 10)+'px')
.style('left', parseInt(l, 10)+parseInt(r, 10)-parseInt(tip, 10)+'px')
.attr('class', 'tooltip gain_tooltip');
})
.on('mouseout', function() {
d3.select(d3.event.target)
.transition()
.attr('r', '5')
.style('opacity', .8);
that.tooltip.style('visibility', 'hidden');
});
var circles = svg.selectAll('circle.ball_nolink')
.data(data_)
.enter()
.append('svg:circle')
.attr(circle_attr)
.style('filter', 'url(#shadow)')
.on('mouseover', function() {
d3.select(d3.event.target)
.transition()
.attr('r', '7')
.style('opacity', 1);
var t = $(this).offset().top - 80,
l = $(this).offset().left,
r = $(this).attr('r'),
tip = $('.tooltip').width()/2;
that.tooltip.html($(this).attr('name'))
.style('visibility', 'visible')
.style('top', parseInt(t, 10)+'px')
.style('left', parseInt(l, 10)+parseInt(r, 10)-parseInt(tip, 10)-10+'px')
.attr('class', 'tooltip gain_tooltip');
})
.on('mouseenter', function() {
d3.select(d3.event.target)
.transition()
.attr('r', '7')
.style('opacity', 1);
var t = $(this).offset().top - 80,
l = $(this).offset().left,
r = $(this).attr('r'),
tip = $('.tooltip').width()/2;
that.tooltip.html($(this).attr('name'))
.style('visibility', 'visible')
.style('top', parseInt(t, 10)+'px')
.style('left', parseInt(l, 10)+parseInt(r, 10)-parseInt(tip, 10)+'px')
.attr('class', 'tooltip gain_tooltip');
})
.on('mouseout', function() {
d3.select(d3.event.target)
.transition()
.attr('r', '5')
.style('opacity', .8);
that.tooltip.style('visibility', 'hidden');
});
});
} else if (this.model.get('graph') === 'domains') {
this._showYears();
var sql = 'SELECT name, ';
for(var y = 2001; y < 2012; y++) {
sql += 'y'+y+', '
}
sql += 'y2012, GREATEST('
for(var y = 2001; y < 2012; y++) {
sql += 'y'+y+', '
}
sql += 'y2012) as max\
FROM countries_domains';
d3.json('https://wri-01.cartodb.com/api/v2/sql?q='+sql, function(error, json) {
var data = json.rows;
var r_scale = d3.scale.linear()
.range([5, 30]) // max ball radius
.domain([0, d3.max(data, function(d) { return d.max; })])
for(var j = 0; j < data.length; j++) {
var data_ = [],
domain = '';
_.each(data[j], function(val, key) {
if (key !== 'max') {
if (key === 'name') {
domain = val.toLowerCase();
} else {
data_.push({
'year': key.replace('y',''),
'value': val
});
}
}
});
svg.append('text')
.attr('class', 'label')
.attr('id', 'label_'+domain)
.text(domain)
.attr('x', function() {
var l = x_scale(2002) - $(this).width()/2;
return l;
})
.attr('y', (h/5)*(j+.6));
var circle_attr = {
'cx': function(d, i) { return x_scale(2001 + i); },
'cy': function(d) { return (h/5)*(j+1); },
'r': function(d) { return r_scale(d.value); },
'class': function(d) { return 'ball'; }
};
svg.selectAll('circle.domain_'+domain)
.data(data_)
.enter()
.append('svg:circle')
.attr(circle_attr)
.attr('data-slug', domain)
.attr('name', function(d) {
return '<span>'+d.year+'</span>'+formatNumber(parseFloat(d.value/1000000).toFixed(1))+' Mha';
})
.style('fill', function(d) { return config.GRAPHCOLORS[domain]; })
.on('mouseover', function() {
d3.select(d3.event.target)
.transition()
.attr('r', function(d) { return circle_attr.r(d) + 2; })
.style('opacity', 1);
var t = $(this).offset().top - 100,
l = $(this).offset().left,
r = $(this).attr('r'),
tip = $('.tooltip').width()/2,
slug = $(this).attr('data-slug');
that.tooltip.html($(this).attr('name'))
.style('visibility', 'visible')
.style('top', parseInt(t, 10)+'px')
.style('left', parseInt(l, 10)+parseInt(r, 10)-parseInt(tip, 10)-10+'px')
.attr('class', 'tooltip')
.attr('data-slug', 'tooltip')
.style('color', function() {
if (slug === 'subtropical') {
return '#FFC926'
} else {
return config.GRAPHCOLORS[slug];
}
});
})
.on('mouseenter', function() {
d3.select(d3.event.target)
.transition()
.attr('r', function(d) { return circle_attr.r(d) + 2; })
.style('opacity', 1);
var t = $(this).offset().top - 80,
l = $(this).offset().left,
r = $(this).attr('r'),
tip = $('.tooltip').width()/2,
slug = $(this).attr('data-slug');
that.tooltip.html($(this).attr('name'))
.style('visibility', 'visible')
.style('top', parseInt(t, 10)+'px')
.style('left', parseInt(l, 10)+parseInt(r, 10)-parseInt(tip, 10)-10+'px')
.attr('class', 'tooltip')
.attr('data-slug', 'tooltip')
.style('color', function() {
if (domain === 'subtropical') { return config.GRAPHCOLORS[domain]; }
});
})
.on('mouseout', function() {
d3.select(d3.event.target)
.transition()
.attr('r', function(d) { return circle_attr.r(d); })
.style('opacity', .8);
that.tooltip
.style('color', '')
.style('visibility', 'hidden');
});
}
});
}
},
linearRegressionLine: function(svg, dataset, x_log_scale, y_log_scale) {
var that = this;
// linear regresion line
var lr_line = ss.linear_regression()
.data(dataset.rows.map(function(d) { return [d.loss, d.gain]; }))
.line();
var line = d3.svg.line()
.x(x_log_scale)
.y(function(d) { return that.y_log_scale(lr_line(d));} )
var x0 = x_log_scale.domain()[0];
var x1 = x_log_scale.domain()[1];
var lr = svg.selectAll('.linear_regression').data([0]);
var attrs = {
"x1": x_log_scale(x0),
"y1": y_log_scale(lr_line(x0)),
"x2": x_log_scale(x1),
"y2": y_log_scale(lr_line(x1)),
"stroke-width": 1.3,
"stroke": "white",
"stroke-dasharray": "7,5"
};
lr.enter()
.append("line")
.attr('class', 'linear_regression')
.attr(attrs);
lr.transition().attr(attrs);
}
});
gfw.ui.view.CountriesEmbedShow = cdb.core.View.extend({
el: document.body,
events: {
'click .forma_dropdown-link': '_openDropdown',
'click .hansen_dropdown-link': '_openDropdown',
'click .hansen_dropdown-menu a': '_redrawCircle'
},
initialize: function() {
this.iso = this.options.iso;
this._initViews();
this._initHansenDropdown();
},
_initViews: function() {
this._drawCircle('forma', 'lines', { iso: this.iso });
this._drawCircle('forest_loss', 'bars', { iso: this.iso, dataset: 'loss' });
},
_initFormaDropdown: function() {
$('.forma_dropdown-link').qtip({
show: 'click',
hide: {
event: 'click unfocus'
},
content: {
text: $('.forma_dropdown-menu')
},
position: {
my: 'bottom right',
at: 'top right',
target: $('.forma_dropdown-link'),
adjust: {
x: -10
}
},
style: {
tip: {
corner: 'bottom right',
mimic: 'bottom center',
border: 1,
width: 10,
height: 6
}
}
});
},
_initHansenDropdown: function() {
this.dropdown = $('.hansen_dropdown-link').qtip({
show: 'click',
hide: {
event: 'click unfocus'
},
content: {
text: $('.hansen_dropdown-menu')
},
position: {
my: 'top right',
at: 'bottom right',
target: $('.hansen_dropdown-link'),
adjust: {
x: 10
}
},
style: {
tip: {
corner: 'top right',
mimic: 'top center',
border: 1,
width: 10,
height: 6
}
}
});
},
_openDropdown: function(e) {
e.preventDefault();
},
_redrawCircle: function(e) {
e.preventDefault();
var dataset = $(e.target).attr('data-slug'),
subtitle = $(e.target).text();
var api = this.dropdown.qtip('api');
api.hide();
$('.hansen_dropdown-link').html(subtitle);
if(dataset === 'countries_gain') {
this._drawCircle('forest_loss', 'comp', { iso: this.iso });
} else {
this._drawCircle('forest_loss', 'bars', { iso: this.iso, dataset: dataset });
}
},
_drawCircle: function(id, type, options) {
var that = this;
var $graph = $('.'+id),
$amount = $('.'+id+' .graph-amount'),
$date = $('.'+id+' .graph-date'),
$coming_soon = $('.'+id+' .coming_soon'),
$action = $('.'+id+' .action');
$('.graph.'+id+' .frame_bkg').empty();
$graph.addClass('ghost');
$amount.html('');
$date.html('');
$coming_soon.hide();
var width = options.width || 256,
height = options.height || width,
h = 100, // maxHeight
radius = width / 2;
var graph = d3.select('.graph.'+id+' .frame_bkg')
.append('svg:svg')
.attr('class', type)
.attr('width', width)
.attr('height', height);
var dashedLines = [
{ x1:17, y:height/4, x2:239, color: '#ccc' },
{ x1:0, y:height/2, x2:width, color: '#ccc' },
{ x1:17, y:3*height/4, x2:239, color: '#ccc' }
];
// Adds the dotted lines
_.each(dashedLines, function(line) {
graph.append('svg:line')
.attr('x1', line.x1)
.attr('y1', line.y)
.attr('x2', line.x2)
.attr('y2', line.y)
.style('stroke-dasharray', '2,2')
.style('stroke', line.color);
});
var sql = ["SELECT date_trunc('month', date) as date, COUNT(*) as alerts",
'FROM forma_api',
"WHERE iso = '"+options.iso+"'",
"GROUP BY date_trunc('month', date)",
"ORDER BY date_trunc('month', date) ASC"].join(' ');
if (type === 'lines') {
d3.json('https://wri-01.cartodb.com/api/v2/sql?q='+sql, function(json) {
if(json && json.rows.length > 0) {
$graph.removeClass('ghost');
$action.removeClass('disabled');
that._initFormaDropdown();
var data = json.rows.slice(1, json.rows.length - 1);
} else {
$coming_soon.show();
return;
}
var x_scale = d3.scale.linear()
.domain([0, data.length - 1])
.range([0, width - 80]);
var max = d3.max(data, function(d) { return parseFloat(d.alerts); });
if (max === d3.min(data, function(d) { return parseFloat(d.alerts); })) {
h = h/2;
}
var y_scale = d3.scale.linear()
.domain([0, max])
.range([0, h]);
var line = d3.svg.line()
.x(function(d, i) { return x_scale(i); })
.y(function(d, i) { return h - y_scale(d.alerts); })
.interpolate('basis');
var marginLeft = 40,
marginTop = radius - h/2;
$amount.html('<span>'+formatNumber(data[data.length - 1].alerts)+'</span>');
var date = new Date(data[data.length - 1].date),
form_date = 'Alerts in ' + config.MONTHNAMES[date.getMonth()] + ' ' + date.getFullYear();
$date.html(form_date);
graph.append('svg:path')
.attr('transform', 'translate(' + marginLeft + ',' + marginTop + ')')
.attr('d', line(data))
.on('mousemove', function(d) {
var index = Math.round(x_scale.invert(d3.mouse(this)[0]));
if (data[index]) { // if there's data
$amount.html('<span>'+formatNumber(data[index].alerts)+'</span>');
var date = new Date(data[index].date),
form_date = 'Alerts in ' + config.MONTHNAMES[date.getMonth()] + ' ' + date.getFullYear();
$date.html(form_date);
var cx = d3.mouse(this)[0] + marginLeft;
var cy = h - y_scale(data[index].alerts) + marginTop;
graph.select('.forma_marker')
.attr('cx', cx)
.attr('cy', cy);
}
});
graph.append('svg:circle')
.attr('class', 'forma_marker')
.attr('cx', -10000)
.attr('cy',100)
.attr('r', 5);
});
} else if (type === 'bars') {
var sql = "SELECT ";
if (options.dataset === 'loss') {
sql += "year, loss_gt_0 loss FROM umd WHERE iso='"+options.iso+"'";
} else if (options.dataset === 'extent') {
sql += "year, extent_gt_25 extent FROM umd WHERE iso='"+options.iso+"'";
}
d3.json('https://wri-01.cartodb.com/api/v2/sql?q='+sql, function(json) {
if(json) {
$graph.removeClass('ghost');
var data = json.rows;
} else {
$coming_soon.show();
return;
}
var data_ = [];
_.each(data, function(val, key) {
if (val.year >= 2001) {
data_.push({
'year': val.year,
'value': eval('val.'+options.dataset)
});
}
});
$amount.html('<span>'+formatNumber(parseInt(data_[data_.length - 1].value, 10))+'</span>');
$date.html('Hectares in ' + data_[data_.length - 1].year);
var marginLeft = 40,
marginTop = radius - h/2 + 5;
var y_scale = d3.scale.linear()
.domain([0, d3.max(data_, function(d) { return parseFloat(d.value); })])
.range([height, marginTop*2]);
var barWidth = (width - 80) / data_.length;
var bar = graph.selectAll('g')
.data(data_)
.enter()
.append('g')
.attr('transform', function(d, i) { return 'translate(' + (marginLeft + i * barWidth) + ','+ -marginTop+')'; });
bar.append('svg:rect')
.attr('class', function(d, i) {
if(i === 11) { // last year index
return 'last bar'
} else {
return 'bar'
}
})
.attr('y', function(d) { return y_scale(d.value); })
.attr('height', function(d) { return height - y_scale(d.value); })
.attr('width', barWidth - 1)
.on('mouseover', function(d) {
d3.selectAll('.bar').style('opacity', '.5');
d3.select(this).style('opacity', '1');
$amount.html('<span>'+formatNumber(parseInt(d.value, 10))+'</span>');
$date.html('Hectares in ' + d.year);
});
});
} else if (type === 'comp') {
var sql = "SELECT iso, sum(umd.loss_gt_0) loss, max(umd.gain) gain FROM umd WHERE iso='"+options.iso+"' GROUP BY iso";
d3.json('https://wri-01.cartodb.com/api/v2/sql?q='+encodeURIComponent(sql), function(json) {
if(json) {
$graph.removeClass('ghost');
var data = json.rows[0];
} else {
$coming_soon.show();
return;
}
var data_ = [{
'key': 'Tree cover gain',
'value': data.gain
}, {
'key': 'Tree cover loss',
'value': data.loss
}];
$amount.html('<span>'+formatNumber(parseInt(data_[data_.length - 1].value, 10))+'</span>');
$date.html('Ha '+data_[data_.length - 1].key);
var barWidth = (width - 80) / 12;
var marginLeft = 40 + barWidth*5,
marginTop = radius - h/2 + 5;
var y_scale = d3.scale.linear()
.domain([0, d3.max(data_, function(d) { return parseFloat(d.value); })])
.range([height, marginTop*2]);
var bar = graph.selectAll('g')
.data(data_)
.enter()
.append('g')
.attr('transform', function(d, i) { return 'translate(' + (marginLeft + i * barWidth) + ',' + -marginTop + ')'; });
bar.append('svg:rect')
.attr('class', function(d, i) {
if (i === 1) { // last bar index
return 'last bar'
} else {
return 'bar'
}
})
.attr('y', function(d) { return y_scale(d.value); })
.attr('height', function(d) { return height - y_scale(d.value); })
.attr('width', barWidth - 1)
.style('fill', '#FFC926')
.style('shape-rendering', 'crispEdges')
.on('mouseover', function(d) {
d3.selectAll('.bar').style('opacity', '.5');
d3.select(this).style('opacity', '1');
$amount.html('<span>'+formatNumber(parseFloat(d.value).toFixed(1))+'</span>');
$date.html('Ha '+d.key);
});
});
}
}
});
| Java |
/*
* @(#)LayouterSample.java
*
* Copyright (c) 1996-2010 by the original authors of JHotDraw and all its
* contributors. All rights reserved.
*
* You may not use, copy or modify this file, except in compliance with the
* license agreement you entered into with the copyright holders. For details
* see accompanying license terms.
*/
package org.jhotdraw.samples.mini;
import org.jhotdraw.draw.tool.DelegationSelectionTool;
import org.jhotdraw.draw.layouter.VerticalLayouter;
import javax.swing.*;
import org.jhotdraw.draw.*;
/**
* Example showing how to layout two editable text figures and a line figure
* within a graphical composite figure.
*
* @author Werner Randelshofer
* @version $Id: LayouterSample.java 718 2010-11-21 17:49:53Z rawcoder $
*/
public class LayouterSample {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
// Create a graphical composite figure.
GraphicalCompositeFigure composite = new GraphicalCompositeFigure();
// Add child figures to the composite figure
composite.add(new TextFigure("Above the line"));
composite.add(new LineFigure());
composite.add(new TextFigure("Below the line"));
// Set a layouter and perform the layout
composite.setLayouter(new VerticalLayouter());
composite.layout();
// Add the composite figure to a drawing
Drawing drawing = new DefaultDrawing();
drawing.add(composite);
// Create a frame with a drawing view and a drawing editor
JFrame f = new JFrame("My Drawing");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(400, 300);
DrawingView view = new DefaultDrawingView();
view.setDrawing(drawing);
f.getContentPane().add(view.getComponent());
DrawingEditor editor = new DefaultDrawingEditor();
editor.add(view);
editor.setTool(new DelegationSelectionTool());
f.setVisible(true);
}
});
}
}
| Java |
package com.iluwatar.front.controller;
/**
*
* Command for archers.
*
*/
public class ArcherCommand implements Command {
@Override
public void process() {
new ArcherView().display();
}
}
| Java |
declare module 'fast-memoize' {
declare type Cache<K, V> = {
get: (key: K) => V,
set: (key: K, value: V) => void,
has: (key: K) => boolean
}
declare type Options = {
cache?: Cache<*, *>;
serializer?: (...args: any[]) => any;
strategy?: <T>(fn: T, options?: Options) => T;
}
declare module.exports: <T>(fn: T, options?: Options) => T;
}
| Java |
angular.module('ualib.imageCarousel', ['angular-carousel'])
.constant('VIEW_IMAGES_URL', '//wwwdev2.lib.ua.edu/erCarousel/api/slides/active')
.factory('imageCarouselFactory', ['$http', 'VIEW_IMAGES_URL', function imageCarouselFactory($http, url){
return {
getData: function(){
return $http({method: 'GET', url: url, params: {}});
}
};
}])
.controller('imageCarouselCtrl', ['$scope', '$q', 'imageCarouselFactory',
function imageCarouselCtrl($scope, $q, imageCarouselFactory){
$scope.slides = null;
function loadImages(slides, i, len, deferred){
i = i ? i : 0;
len = len ? len : slides.length;
deferred = deferred ? deferred : $q.defer();
if (len < 1){
deferred.resolve(slides);
}
else{
var image = new Image();
image.onload = function(){
slides[i].styles = 'url('+this.src+')';
slides[i].image = this;
if (i+1 === len){
deferred.resolve(slides);
}
else {
i++;
loadImages(slides, i, len, deferred);
}
};
image.src = slides[i].image;
}
return deferred.promise;
}
imageCarouselFactory.getData()
.success(function(data) {
loadImages(data.slides).then(function(slides){
$scope.slides = slides;
});
})
.error(function(data, status, headers, config) {
console.log(data);
});
}])
.directive('ualibImageCarousel', [ function() {
return {
restrict: 'AC',
controller: 'imageCarouselCtrl',
link: function(scope, elm, attrs, Ctrl){
var toggleLock = false;
scope.isLocked = false;
scope.pause = function(){
toggleLock = true;
scope.isLocked = true;
};
scope.play = function(){
toggleLock = false;
scope.isLocked = false;
};
scope.mouseToggle = function(){
if (!toggleLock){
scope.isLocked = !scope.isLocked;
}
};
}
};
}]); | Java |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>basic_socket_streambuf::cancel (1 of 2 overloads)</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../../../boost_asio.html" title="Boost.Asio">
<link rel="up" href="../cancel.html" title="basic_socket_streambuf::cancel">
<link rel="prev" href="../cancel.html" title="basic_socket_streambuf::cancel">
<link rel="next" href="overload2.html" title="basic_socket_streambuf::cancel (2 of 2 overloads)">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td>
<td align="center"><a href="../../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../cancel.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../cancel.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../boost_asio.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="overload2.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h5 class="title">
<a name="boost_asio.reference.basic_socket_streambuf.cancel.overload1"></a><a class="link" href="overload1.html" title="basic_socket_streambuf::cancel (1 of 2 overloads)">basic_socket_streambuf::cancel
(1 of 2 overloads)</a>
</h5></div></div></div>
<p>
<span class="emphasis"><em>Inherited from basic_socket.</em></span>
</p>
<p>
Cancel all asynchronous operations associated with the socket.
</p>
<pre class="programlisting"><span class="keyword">void</span> <span class="identifier">cancel</span><span class="special">();</span>
</pre>
<p>
This function causes all outstanding asynchronous connect, send and receive
operations to finish immediately, and the handlers for cancelled operations
will be passed the <code class="computeroutput"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">asio</span><span class="special">::</span><span class="identifier">error</span><span class="special">::</span><span class="identifier">operation_aborted</span></code>
error.
</p>
<h6>
<a name="boost_asio.reference.basic_socket_streambuf.cancel.overload1.h0"></a>
<span><a name="boost_asio.reference.basic_socket_streambuf.cancel.overload1.exceptions"></a></span><a class="link" href="overload1.html#boost_asio.reference.basic_socket_streambuf.cancel.overload1.exceptions">Exceptions</a>
</h6>
<div class="variablelist">
<p class="title"><b></b></p>
<dl>
<dt><span class="term">boost::system::system_error</span></dt>
<dd><p>
Thrown on failure.
</p></dd>
</dl>
</div>
<h6>
<a name="boost_asio.reference.basic_socket_streambuf.cancel.overload1.h1"></a>
<span><a name="boost_asio.reference.basic_socket_streambuf.cancel.overload1.remarks"></a></span><a class="link" href="overload1.html#boost_asio.reference.basic_socket_streambuf.cancel.overload1.remarks">Remarks</a>
</h6>
<p>
Calls to <code class="computeroutput"><span class="identifier">cancel</span><span class="special">()</span></code>
will always fail with <code class="computeroutput"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">asio</span><span class="special">::</span><span class="identifier">error</span><span class="special">::</span><span class="identifier">operation_not_supported</span></code>
when run on Windows XP, Windows Server 2003, and earlier versions of
Windows, unless BOOST_ASIO_ENABLE_CANCELIO is defined. However, the CancelIo
function has two issues that should be considered before enabling its
use:
</p>
<div class="itemizedlist"><ul class="itemizedlist" type="disc">
<li class="listitem">
It will only cancel asynchronous operations that were initiated in
the current thread.
</li>
<li class="listitem">
It can appear to complete without error, but the request to cancel
the unfinished operations may be silently ignored by the operating
system. Whether it works or not seems to depend on the drivers that
are installed.
</li>
</ul></div>
<p>
For portable cancellation, consider using one of the following alternatives:
</p>
<div class="itemizedlist"><ul class="itemizedlist" type="disc">
<li class="listitem">
Disable asio's I/O completion port backend by defining BOOST_ASIO_DISABLE_IOCP.
</li>
<li class="listitem">
Use the <code class="computeroutput"><span class="identifier">close</span><span class="special">()</span></code>
function to simultaneously cancel the outstanding operations and
close the socket.
</li>
</ul></div>
<p>
When running on Windows Vista, Windows Server 2008, and later, the CancelIoEx
function is always used. This function does not have the problems described
above.
</p>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2015 Christopher M.
Kohlhoff<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../cancel.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../cancel.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../boost_asio.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="overload2.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| Java |
import { ListWrapper } from 'angular2/src/facade/collection';
import { stringify, isBlank } from 'angular2/src/facade/lang';
import { BaseException, WrappedException } from 'angular2/src/facade/exceptions';
function findFirstClosedCycle(keys) {
var res = [];
for (var i = 0; i < keys.length; ++i) {
if (ListWrapper.contains(res, keys[i])) {
res.push(keys[i]);
return res;
}
else {
res.push(keys[i]);
}
}
return res;
}
function constructResolvingPath(keys) {
if (keys.length > 1) {
var reversed = findFirstClosedCycle(ListWrapper.reversed(keys));
var tokenStrs = reversed.map(k => stringify(k.token));
return " (" + tokenStrs.join(' -> ') + ")";
}
else {
return "";
}
}
/**
* Base class for all errors arising from misconfigured providers.
*/
export class AbstractProviderError extends BaseException {
constructor(injector, key, constructResolvingMessage) {
super("DI Exception");
this.keys = [key];
this.injectors = [injector];
this.constructResolvingMessage = constructResolvingMessage;
this.message = this.constructResolvingMessage(this.keys);
}
addKey(injector, key) {
this.injectors.push(injector);
this.keys.push(key);
this.message = this.constructResolvingMessage(this.keys);
}
get context() { return this.injectors[this.injectors.length - 1].debugContext(); }
}
/**
* Thrown when trying to retrieve a dependency by `Key` from {@link Injector}, but the
* {@link Injector} does not have a {@link Provider} for {@link Key}.
*
* ### Example ([live demo](http://plnkr.co/edit/vq8D3FRB9aGbnWJqtEPE?p=preview))
*
* ```typescript
* class A {
* constructor(b:B) {}
* }
*
* expect(() => Injector.resolveAndCreate([A])).toThrowError();
* ```
*/
export class NoProviderError extends AbstractProviderError {
constructor(injector, key) {
super(injector, key, function (keys) {
var first = stringify(ListWrapper.first(keys).token);
return `No provider for ${first}!${constructResolvingPath(keys)}`;
});
}
}
/**
* Thrown when dependencies form a cycle.
*
* ### Example ([live demo](http://plnkr.co/edit/wYQdNos0Tzql3ei1EV9j?p=info))
*
* ```typescript
* var injector = Injector.resolveAndCreate([
* provide("one", {useFactory: (two) => "two", deps: [[new Inject("two")]]}),
* provide("two", {useFactory: (one) => "one", deps: [[new Inject("one")]]})
* ]);
*
* expect(() => injector.get("one")).toThrowError();
* ```
*
* Retrieving `A` or `B` throws a `CyclicDependencyError` as the graph above cannot be constructed.
*/
export class CyclicDependencyError extends AbstractProviderError {
constructor(injector, key) {
super(injector, key, function (keys) {
return `Cannot instantiate cyclic dependency!${constructResolvingPath(keys)}`;
});
}
}
/**
* Thrown when a constructing type returns with an Error.
*
* The `InstantiationError` class contains the original error plus the dependency graph which caused
* this object to be instantiated.
*
* ### Example ([live demo](http://plnkr.co/edit/7aWYdcqTQsP0eNqEdUAf?p=preview))
*
* ```typescript
* class A {
* constructor() {
* throw new Error('message');
* }
* }
*
* var injector = Injector.resolveAndCreate([A]);
* try {
* injector.get(A);
* } catch (e) {
* expect(e instanceof InstantiationError).toBe(true);
* expect(e.originalException.message).toEqual("message");
* expect(e.originalStack).toBeDefined();
* }
* ```
*/
export class InstantiationError extends WrappedException {
constructor(injector, originalException, originalStack, key) {
super("DI Exception", originalException, originalStack, null);
this.keys = [key];
this.injectors = [injector];
}
addKey(injector, key) {
this.injectors.push(injector);
this.keys.push(key);
}
get wrapperMessage() {
var first = stringify(ListWrapper.first(this.keys).token);
return `Error during instantiation of ${first}!${constructResolvingPath(this.keys)}.`;
}
get causeKey() { return this.keys[0]; }
get context() { return this.injectors[this.injectors.length - 1].debugContext(); }
}
/**
* Thrown when an object other then {@link Provider} (or `Type`) is passed to {@link Injector}
* creation.
*
* ### Example ([live demo](http://plnkr.co/edit/YatCFbPAMCL0JSSQ4mvH?p=preview))
*
* ```typescript
* expect(() => Injector.resolveAndCreate(["not a type"])).toThrowError();
* ```
*/
export class InvalidProviderError extends BaseException {
constructor(provider) {
super("Invalid provider - only instances of Provider and Type are allowed, got: " +
provider.toString());
}
}
/**
* Thrown when the class has no annotation information.
*
* Lack of annotation information prevents the {@link Injector} from determining which dependencies
* need to be injected into the constructor.
*
* ### Example ([live demo](http://plnkr.co/edit/rHnZtlNS7vJOPQ6pcVkm?p=preview))
*
* ```typescript
* class A {
* constructor(b) {}
* }
*
* expect(() => Injector.resolveAndCreate([A])).toThrowError();
* ```
*
* This error is also thrown when the class not marked with {@link Injectable} has parameter types.
*
* ```typescript
* class B {}
*
* class A {
* constructor(b:B) {} // no information about the parameter types of A is available at runtime.
* }
*
* expect(() => Injector.resolveAndCreate([A,B])).toThrowError();
* ```
*/
export class NoAnnotationError extends BaseException {
constructor(typeOrFunc, params) {
super(NoAnnotationError._genMessage(typeOrFunc, params));
}
static _genMessage(typeOrFunc, params) {
var signature = [];
for (var i = 0, ii = params.length; i < ii; i++) {
var parameter = params[i];
if (isBlank(parameter) || parameter.length == 0) {
signature.push('?');
}
else {
signature.push(parameter.map(stringify).join(' '));
}
}
return "Cannot resolve all parameters for " + stringify(typeOrFunc) + "(" +
signature.join(', ') + "). " + 'Make sure they all have valid type or annotations.';
}
}
/**
* Thrown when getting an object by index.
*
* ### Example ([live demo](http://plnkr.co/edit/bRs0SX2OTQiJzqvjgl8P?p=preview))
*
* ```typescript
* class A {}
*
* var injector = Injector.resolveAndCreate([A]);
*
* expect(() => injector.getAt(100)).toThrowError();
* ```
*/
export class OutOfBoundsError extends BaseException {
constructor(index) {
super(`Index ${index} is out-of-bounds.`);
}
}
// TODO: add a working example after alpha38 is released
/**
* Thrown when a multi provider and a regular provider are bound to the same token.
*
* ### Example
*
* ```typescript
* expect(() => Injector.resolveAndCreate([
* new Provider("Strings", {useValue: "string1", multi: true}),
* new Provider("Strings", {useValue: "string2", multi: false})
* ])).toThrowError();
* ```
*/
export class MixingMultiProvidersWithRegularProvidersError extends BaseException {
constructor(provider1, provider2) {
super("Cannot mix multi providers and regular providers, got: " + provider1.toString() + " " +
provider2.toString());
}
}
//# sourceMappingURL=exceptions.js.map | Java |
Map Navigation Hash (History)
======================
#### Overview
Uses dojo/router to enable zooming to next or previous extent using the browser forward and back buttons. The geographic map center and map zoom level is placed on the url.
#### CMV Configuration
Include the following code in js/config/viewer.js:
```javascript
navhash: {
include: true,
id: 'navhash',
type: 'invisible',
path: 'viewer/dijit/MapNavigationHash/MapNavigationHash',
title: 'Map Navigation Hash',
options: {
map: true
}
}
```
#### Usage Example
appurl.com/index.htlm#/_longitude_/_latitude_/_zoomLevel_
The application will automatically update the url hash on pan and zoom. Users may also manually edit the route to go to a specific long, lat, and zoom level. A user can bookmark the url in the browser and, on load, the app will zoom and pan to the bookmarked location.
[Click for demo](http://brianbunker.github.com/cmv-widgets)
Screen from Sample page:

| Java |
function SendItemsToOutput
{
Param
(
[parameter()]
[PSObject[]]$items,
[parameter(Mandatory=$true)]
[string[]]$typeName
)
foreach ($i in $items)
{
$i.PSObject.TypeNames.Insert(0, $typeName)
Write-Output $i
}
} | Java |
<?php
namespace Codeception\Command;
use Codeception\Configuration;
use Codeception\Lib\Generator\Snapshot as SnapshotGenerator;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Generates Snapshot.
* Snapshot can be used to test dynamical data.
* If suite name is provided, an actor class will be included into placeholder
*
* * `codecept g:snapshot UserEmails`
* * `codecept g:snapshot Products`
* * `codecept g:snapshot acceptance UserEmails`
*/
class GenerateSnapshot extends Command
{
use Shared\FileSystem;
use Shared\Config;
protected function configure()
{
$this->setDefinition([
new InputArgument('suite', InputArgument::REQUIRED, 'Suite name or snapshot name)'),
new InputArgument('snapshot', InputArgument::OPTIONAL, 'Name of snapshot'),
]);
parent::configure();
}
public function getDescription()
{
return 'Generates empty Snapshot class';
}
public function execute(InputInterface $input, OutputInterface $output)
{
$suite = $input->getArgument('suite');
$class = $input->getArgument('snapshot');
if (!$class) {
$class = $suite;
$suite = null;
}
$conf = $suite
? $this->getSuiteConfig($suite)
: $this->getGlobalConfig();
if ($suite) {
$suite = DIRECTORY_SEPARATOR . ucfirst($suite);
}
$path = $this->createDirectoryFor(Configuration::supportDir() . 'Snapshot' . $suite, $class);
$filename = $path . $this->getShortClassName($class) . '.php';
$output->writeln($filename);
$gen = new SnapshotGenerator($conf, ucfirst($suite) . '\\' . $class);
$res = $this->createFile($filename, $gen->produce());
if (!$res) {
$output->writeln("<error>Snapshot $filename already exists</error>");
exit;
}
$output->writeln("<info>Snapshot was created in $filename</info>");
}
}
| Java |
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ENTER} from '@angular/cdk/keycodes';
import {CommonModule} from '@angular/common';
import {NgModule} from '@angular/core';
import {
ErrorStateMatcher,
MatCommonModule,
MatRippleModule,
} from '@angular/material-experimental/mdc-core';
import {MatChip, MatChipCssInternalOnly} from './chip';
import {MAT_CHIPS_DEFAULT_OPTIONS, MatChipsDefaultOptions} from './chip-default-options';
import {MatChipEditInput} from './chip-edit-input';
import {MatChipGrid} from './chip-grid';
import {MatChipAvatar, MatChipRemove, MatChipTrailingIcon} from './chip-icons';
import {MatChipInput} from './chip-input';
import {MatChipListbox} from './chip-listbox';
import {MatChipRow} from './chip-row';
import {MatChipOption} from './chip-option';
import {MatChipSet} from './chip-set';
const CHIP_DECLARATIONS = [
MatChip,
MatChipAvatar,
MatChipCssInternalOnly,
MatChipEditInput,
MatChipGrid,
MatChipInput,
MatChipListbox,
MatChipOption,
MatChipRemove,
MatChipRow,
MatChipSet,
MatChipTrailingIcon,
];
@NgModule({
imports: [MatCommonModule, CommonModule, MatRippleModule],
exports: [MatCommonModule, CHIP_DECLARATIONS],
declarations: CHIP_DECLARATIONS,
providers: [
ErrorStateMatcher,
{
provide: MAT_CHIPS_DEFAULT_OPTIONS,
useValue: {
separatorKeyCodes: [ENTER]
} as MatChipsDefaultOptions
}
]
})
export class MatChipsModule {
}
| Java |
#region Copyright
//
// DotNetNuke® - http://www.dotnetnuke.com
// Copyright (c) 2002-2014
// by DotNetNuke Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Web;
using System.Web.Http;
using DotNetNuke.Application;
using DotNetNuke.Common;
using DotNetNuke.Entities.Controllers;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Services.Localization;
using DotNetNuke.Web.Api;
namespace DotNetNuke.Web.InternalServices
{
[RequireHost]
public class GettingStartedController : DnnApiController
{
private const string GettingStartedHideKey = "GettingStarted_Hide_{0}";
private const string GettingStartedDisplayKey = "GettingStarted_Display_{0}";
public class ClosePageDto
{
public bool IsHidden { get; set; }
}
public class EmailDto
{
public string Email { get; set; }
}
[HttpGet]
public HttpResponseMessage GetGettingStartedPageSettings()
{
var isHidden = HostController.Instance.GetBoolean(String.Format(GettingStartedHideKey, PortalSettings.UserId), false);
var userEmailAddress = PortalSettings.UserInfo.Email;
var request = HttpContext.Current.Request;
var builder = new UriBuilder
{
Scheme = request.Url.Scheme,
Host = "www.dnnsoftware.com",
Path = "Community/Download/Manuals",
Query = "src=dnn" // parameter to judge the effectiveness of this as a channel (i.e. the number of click through)
};
var userManualUrl = builder.Uri.AbsoluteUri;
return Request.CreateResponse(HttpStatusCode.OK, new { IsHidden = isHidden, EmailAddress = userEmailAddress, UserManualUrl = userManualUrl });
}
[HttpPost]
public HttpResponseMessage CloseGettingStartedPage(ClosePageDto dto)
{
HostController.Instance.Update(String.Format(GettingStartedHideKey, PortalSettings.UserId), dto.IsHidden.ToString());
HostController.Instance.Update(String.Format(GettingStartedDisplayKey, PortalSettings.UserId), "false");
return Request.CreateResponse(HttpStatusCode.OK, "Success");
}
[HttpPost]
public HttpResponseMessage SubscribeToNewsletter(EmailDto dto)
{
HostController.Instance.Update("NewsletterSubscribeEmail", dto.Email);
return Request.CreateResponse(HttpStatusCode.OK, "Success");
}
[HttpGet]
public HttpResponseMessage GetContentUrl()
{
var request = HttpContext.Current.Request;
var builder = new UriBuilder
{
Scheme = request.Url.Scheme,
Host = "www.dnnsoftware.com",
Path = String.Format("DesktopModules/DNNCorp/GettingStarted/{0}/{1}/index.html",
DotNetNukeContext.Current.Application.Name.Replace(".", "_"),
DotNetNukeContext.Current.Application.Version.ToString(3)),
Query = String.Format("locale={0}", Thread.CurrentThread.CurrentUICulture)
};
var contentUrl = builder.Uri.AbsoluteUri;
var fallbackUrl = Globals.AddHTTP(request.Url.Host + Globals.ResolveUrl("~/Portals/_default/GettingStartedFallback.htm"));
var isValid = IsValidUrl(contentUrl);
return Request.CreateResponse(HttpStatusCode.OK, new { Url = isValid ? contentUrl : fallbackUrl });
}
/// <summary>
/// Checks if url does not return server or protocol errors
/// </summary>
/// <param name="url">Url to check</param>
/// <returns></returns>
private static bool IsValidUrl(string url)
{
HttpWebResponse response = null;
try
{
var request = WebRequest.Create(url);
request.Timeout = 5000; // set the timeout to 5 seconds to keep the user from waiting too long for the page to load
request.Method = "HEAD"; // get only the header information - no need to download any content
response = request.GetResponse() as HttpWebResponse;
if (response == null)
{
return false;
}
var statusCode = (int)response.StatusCode;
if (statusCode >= 500 && statusCode <= 510) // server errors
{
return false;
}
}
catch
{
return false;
}
finally
{
if (response != null)
{
response.Close();
}
}
return true;
}
}
}
| Java |
// Help functions
/*
* Return a string with all helper functions whose name contains the 'substring';
* if the 'searchDescription' is true, then also search the function description");
*/
function getHelp(substring, searchDescription) {
return framework.getJavaScriptHelp(".*(?i:" + substring + ").*", searchDescription);
}
framework.addJavaScriptHelp("help", "substring, fileName",
"output all the helper functions whose name contains the given 'substring'");
function help(substring, fileName) {
if (arguments.length > 1) {
write(getHelp(substring, false), fileName);
} else if (arguments.length > 0) {
write(getHelp(substring, false));
} else {
write(getHelp("", false));
}
}
framework.addJavaScriptHelp("apropos", "substring, fileName",
"output all the helper functions whose name or description contains the given 'substring'");
function apropos(substring, fileName) {
if (arguments.length > 1) {
write(getHelp(substring, true), fileName);
} else if (arguments.length > 0) {
write(getHelp(substring, true));
} else {
write(getHelp("", true));
}
}
framework.addJavaScriptHelp("helpRegex", "regex, fileName",
"output all helper functions whose name matches 'regex'");
function helpRegex(regex, fileName) {
if (arguments.length > 1) {
write(framework.getJavaScriptHelp(regex, false), fileName);
} else if (arguments.length > 0) {
write(framework.getJavaScriptHelp(regex, false));
}
}
| Java |
FullCalendar.globalLocales.push(function () {
'use strict';
var it = {
code: 'it',
week: {
dow: 1, // Monday is the first day of the week.
doy: 4, // The week that contains Jan 4th is the first week of the year.
},
buttonText: {
prev: 'Prec',
next: 'Succ',
today: 'Oggi',
month: 'Mese',
week: 'Settimana',
day: 'Giorno',
list: 'Agenda',
},
weekText: 'Sm',
allDayText: 'Tutto il giorno',
moreLinkText(n) {
return '+altri ' + n
},
noEventsText: 'Non ci sono eventi da visualizzare',
};
return it;
}());
| Java |
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package get
import (
"errors"
"internal/testenv"
"io/ioutil"
"os"
"path"
"path/filepath"
"testing"
"cmd/go/internal/web"
)
// Test that RepoRootForImportPath creates the correct RepoRoot for a given importPath.
// TODO(cmang): Add tests for SVN and BZR.
func TestRepoRootForImportPath(t *testing.T) {
testenv.MustHaveExternalNetwork(t)
tests := []struct {
path string
want *repoRoot
}{
{
"github.com/golang/groupcache",
&repoRoot{
vcs: vcsGit,
repo: "https://github.com/golang/groupcache",
},
},
// Unicode letters in directories (issue 18660).
{
"github.com/user/unicode/испытание",
&repoRoot{
vcs: vcsGit,
repo: "https://github.com/user/unicode",
},
},
// IBM DevOps Services tests
{
"hub.jazz.net/git/user1/pkgname",
&repoRoot{
vcs: vcsGit,
repo: "https://hub.jazz.net/git/user1/pkgname",
},
},
{
"hub.jazz.net/git/user1/pkgname/submodule/submodule/submodule",
&repoRoot{
vcs: vcsGit,
repo: "https://hub.jazz.net/git/user1/pkgname",
},
},
{
"hub.jazz.net",
nil,
},
{
"hub2.jazz.net",
nil,
},
{
"hub.jazz.net/someotherprefix",
nil,
},
{
"hub.jazz.net/someotherprefix/user1/pkgname",
nil,
},
// Spaces are not valid in user names or package names
{
"hub.jazz.net/git/User 1/pkgname",
nil,
},
{
"hub.jazz.net/git/user1/pkg name",
nil,
},
// Dots are not valid in user names
{
"hub.jazz.net/git/user.1/pkgname",
nil,
},
{
"hub.jazz.net/git/user/pkg.name",
&repoRoot{
vcs: vcsGit,
repo: "https://hub.jazz.net/git/user/pkg.name",
},
},
// User names cannot have uppercase letters
{
"hub.jazz.net/git/USER/pkgname",
nil,
},
// OpenStack tests
{
"git.openstack.org/openstack/swift",
&repoRoot{
vcs: vcsGit,
repo: "https://git.openstack.org/openstack/swift",
},
},
// Trailing .git is less preferred but included for
// compatibility purposes while the same source needs to
// be compilable on both old and new go
{
"git.openstack.org/openstack/swift.git",
&repoRoot{
vcs: vcsGit,
repo: "https://git.openstack.org/openstack/swift.git",
},
},
{
"git.openstack.org/openstack/swift/go/hummingbird",
&repoRoot{
vcs: vcsGit,
repo: "https://git.openstack.org/openstack/swift",
},
},
{
"git.openstack.org",
nil,
},
{
"git.openstack.org/openstack",
nil,
},
// Spaces are not valid in package name
{
"git.apache.org/package name/path/to/lib",
nil,
},
// Should have ".git" suffix
{
"git.apache.org/package-name/path/to/lib",
nil,
},
{
"git.apache.org/package-name.git",
&repoRoot{
vcs: vcsGit,
repo: "https://git.apache.org/package-name.git",
},
},
{
"git.apache.org/package-name_2.x.git/path/to/lib",
&repoRoot{
vcs: vcsGit,
repo: "https://git.apache.org/package-name_2.x.git",
},
},
{
"chiselapp.com/user/kyle/repository/fossilgg",
&repoRoot{
vcs: vcsFossil,
repo: "https://chiselapp.com/user/kyle/repository/fossilgg",
},
},
{
// must have a user/$name/repository/$repo path
"chiselapp.com/kyle/repository/fossilgg",
nil,
},
{
"chiselapp.com/user/kyle/fossilgg",
nil,
},
}
for _, test := range tests {
got, err := repoRootForImportPath(test.path, web.Secure)
want := test.want
if want == nil {
if err == nil {
t.Errorf("repoRootForImportPath(%q): Error expected but not received", test.path)
}
continue
}
if err != nil {
t.Errorf("repoRootForImportPath(%q): %v", test.path, err)
continue
}
if got.vcs.name != want.vcs.name || got.repo != want.repo {
t.Errorf("repoRootForImportPath(%q) = VCS(%s) Repo(%s), want VCS(%s) Repo(%s)", test.path, got.vcs, got.repo, want.vcs, want.repo)
}
}
}
// Test that vcsFromDir correctly inspects a given directory and returns the right VCS and root.
func TestFromDir(t *testing.T) {
tempDir, err := ioutil.TempDir("", "vcstest")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tempDir)
for j, vcs := range vcsList {
dir := filepath.Join(tempDir, "example.com", vcs.name, "."+vcs.cmd)
if j&1 == 0 {
err := os.MkdirAll(dir, 0755)
if err != nil {
t.Fatal(err)
}
} else {
err := os.MkdirAll(filepath.Dir(dir), 0755)
if err != nil {
t.Fatal(err)
}
f, err := os.Create(dir)
if err != nil {
t.Fatal(err)
}
f.Close()
}
want := repoRoot{
vcs: vcs,
root: path.Join("example.com", vcs.name),
}
var got repoRoot
got.vcs, got.root, err = vcsFromDir(dir, tempDir)
if err != nil {
t.Errorf("FromDir(%q, %q): %v", dir, tempDir, err)
continue
}
if got.vcs.name != want.vcs.name || got.root != want.root {
t.Errorf("FromDir(%q, %q) = VCS(%s) Root(%s), want VCS(%s) Root(%s)", dir, tempDir, got.vcs, got.root, want.vcs, want.root)
}
}
}
func TestIsSecure(t *testing.T) {
tests := []struct {
vcs *vcsCmd
url string
secure bool
}{
{vcsGit, "http://example.com/foo.git", false},
{vcsGit, "https://example.com/foo.git", true},
{vcsBzr, "http://example.com/foo.bzr", false},
{vcsBzr, "https://example.com/foo.bzr", true},
{vcsSvn, "http://example.com/svn", false},
{vcsSvn, "https://example.com/svn", true},
{vcsHg, "http://example.com/foo.hg", false},
{vcsHg, "https://example.com/foo.hg", true},
{vcsGit, "ssh://[email protected]/foo.git", true},
{vcsGit, "user@server:path/to/repo.git", false},
{vcsGit, "user@server:", false},
{vcsGit, "server:repo.git", false},
{vcsGit, "server:path/to/repo.git", false},
{vcsGit, "example.com:path/to/repo.git", false},
{vcsGit, "path/that/contains/a:colon/repo.git", false},
{vcsHg, "ssh://[email protected]/path/to/repo.hg", true},
{vcsFossil, "http://example.com/foo", false},
{vcsFossil, "https://example.com/foo", true},
}
for _, test := range tests {
secure := test.vcs.isSecure(test.url)
if secure != test.secure {
t.Errorf("%s isSecure(%q) = %t; want %t", test.vcs, test.url, secure, test.secure)
}
}
}
func TestIsSecureGitAllowProtocol(t *testing.T) {
tests := []struct {
vcs *vcsCmd
url string
secure bool
}{
// Same as TestIsSecure to verify same behavior.
{vcsGit, "http://example.com/foo.git", false},
{vcsGit, "https://example.com/foo.git", true},
{vcsBzr, "http://example.com/foo.bzr", false},
{vcsBzr, "https://example.com/foo.bzr", true},
{vcsSvn, "http://example.com/svn", false},
{vcsSvn, "https://example.com/svn", true},
{vcsHg, "http://example.com/foo.hg", false},
{vcsHg, "https://example.com/foo.hg", true},
{vcsGit, "user@server:path/to/repo.git", false},
{vcsGit, "user@server:", false},
{vcsGit, "server:repo.git", false},
{vcsGit, "server:path/to/repo.git", false},
{vcsGit, "example.com:path/to/repo.git", false},
{vcsGit, "path/that/contains/a:colon/repo.git", false},
{vcsHg, "ssh://[email protected]/path/to/repo.hg", true},
// New behavior.
{vcsGit, "ssh://[email protected]/foo.git", false},
{vcsGit, "foo://example.com/bar.git", true},
{vcsHg, "foo://example.com/bar.hg", false},
{vcsSvn, "foo://example.com/svn", false},
{vcsBzr, "foo://example.com/bar.bzr", false},
}
defer os.Unsetenv("GIT_ALLOW_PROTOCOL")
os.Setenv("GIT_ALLOW_PROTOCOL", "https:foo")
for _, test := range tests {
secure := test.vcs.isSecure(test.url)
if secure != test.secure {
t.Errorf("%s isSecure(%q) = %t; want %t", test.vcs, test.url, secure, test.secure)
}
}
}
func TestMatchGoImport(t *testing.T) {
tests := []struct {
imports []metaImport
path string
mi metaImport
err error
}{
{
imports: []metaImport{
{Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"},
},
path: "example.com/user/foo",
mi: metaImport{Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"},
},
{
imports: []metaImport{
{Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"},
},
path: "example.com/user/foo/",
mi: metaImport{Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"},
},
{
imports: []metaImport{
{Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"},
{Prefix: "example.com/user/fooa", VCS: "git", RepoRoot: "https://example.com/repo/target"},
},
path: "example.com/user/foo",
mi: metaImport{Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"},
},
{
imports: []metaImport{
{Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"},
{Prefix: "example.com/user/fooa", VCS: "git", RepoRoot: "https://example.com/repo/target"},
},
path: "example.com/user/fooa",
mi: metaImport{Prefix: "example.com/user/fooa", VCS: "git", RepoRoot: "https://example.com/repo/target"},
},
{
imports: []metaImport{
{Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"},
{Prefix: "example.com/user/foo/bar", VCS: "git", RepoRoot: "https://example.com/repo/target"},
},
path: "example.com/user/foo/bar",
err: errors.New("should not be allowed to create nested repo"),
},
{
imports: []metaImport{
{Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"},
{Prefix: "example.com/user/foo/bar", VCS: "git", RepoRoot: "https://example.com/repo/target"},
},
path: "example.com/user/foo/bar/baz",
err: errors.New("should not be allowed to create nested repo"),
},
{
imports: []metaImport{
{Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"},
{Prefix: "example.com/user/foo/bar", VCS: "git", RepoRoot: "https://example.com/repo/target"},
},
path: "example.com/user/foo/bar/baz/qux",
err: errors.New("should not be allowed to create nested repo"),
},
{
imports: []metaImport{
{Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"},
{Prefix: "example.com/user/foo/bar", VCS: "git", RepoRoot: "https://example.com/repo/target"},
},
path: "example.com/user/foo/bar/baz/",
err: errors.New("should not be allowed to create nested repo"),
},
{
imports: []metaImport{
{Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"},
{Prefix: "example.com/user/foo/bar", VCS: "git", RepoRoot: "https://example.com/repo/target"},
},
path: "example.com",
err: errors.New("pathologically short path"),
},
{
imports: []metaImport{
{Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"},
},
path: "different.example.com/user/foo",
err: errors.New("meta tags do not match import path"),
},
}
for _, test := range tests {
mi, err := matchGoImport(test.imports, test.path)
if mi != test.mi {
t.Errorf("unexpected metaImport; got %v, want %v", mi, test.mi)
}
got := err
want := test.err
if (got == nil) != (want == nil) {
t.Errorf("unexpected error; got %v, want %v", got, want)
}
}
}
func TestValidateRepoRootScheme(t *testing.T) {
tests := []struct {
root string
err string
}{
{
root: "",
err: "no scheme",
},
{
root: "http://",
err: "",
},
{
root: "a://",
err: "",
},
{
root: "a#://",
err: "invalid scheme",
},
{
root: "-config://",
err: "invalid scheme",
},
}
for _, test := range tests {
err := validateRepoRootScheme(test.root)
if err == nil {
if test.err != "" {
t.Errorf("validateRepoRootScheme(%q) = nil, want %q", test.root, test.err)
}
} else if test.err == "" {
if err != nil {
t.Errorf("validateRepoRootScheme(%q) = %q, want nil", test.root, test.err)
}
} else if err.Error() != test.err {
t.Errorf("validateRepoRootScheme(%q) = %q, want %q", test.root, err, test.err)
}
}
}
| Java |
{% if site.staticman.repository and site.staticman.branch %}
<div class="staticman-comments">
<div class="page__comments">
<!-- Start static comments -->
<div class="js-comments">
{% if site.data.comments[page.slug] %}
<h3 class="page__comments-title">{{ site.data.ui-text[site.locale].comments_title | default: "Comments" }}</h3>
{% assign comments = site.data.comments[page.slug] | sort %}
{% for comment in comments %}
{% assign email = comment[1].email %}
{% assign name = comment[1].name %}
{% assign url = comment[1].url %}
{% assign date = comment[1].date %}
{% assign message = comment[1].message %}
{% include staticman-comment.html index=forloop.index email=email name=name url=url date=date message=message %}
{% endfor %}
{% endif %}
</div>
<!-- End static comments -->
<!-- Start new comment form -->
<div class="page__comments-form">
<h3 class="page__comments-title">{{ site.data.ui-text[site.locale].comments_label | default: "Leave a Comment" }}</h3>
<p class="small">{{ site.data.ui-text[site.locale].comment_form_info | default: "Your email address will not be published. Required fields are marked" }} <span class="required">*</span></p>
<form id="new_comment" class="page__comments-form js-form form" method="post">
<div class="form-group">
<label for="comment-form-message">{{ site.data.ui-text[site.locale].comment_form_comment_label | default: "Comment" }} <small class="required">*</small></label><br>
<textarea type="text" rows="12" cols="36" id="comment-form-message" name="fields[message]" tabindex="1"></textarea>
<div class="small help-block"><a href="https://daringfireball.net/projects/markdown/">{{ site.data.ui-text[site.locale].comment_form_md_info | default: "Markdown is supported." }}</a></div>
</div>
<div class="form-group">
<label for="comment-form-name">{{ site.data.ui-text[site.locale].comment_form_name_label | default: "Name" }} <small class="required">*</small></label>
<input type="text" id="comment-form-name" name="fields[name]" tabindex="2" />
</div>
<div class="form-group">
<label for="comment-form-email">{{ site.data.ui-text[site.locale].comment_form_email_label | default: "Email address" }} <small class="required">*</small></label>
<input type="email" id="comment-form-email" name="fields[email]" tabindex="3" />
</div>
<div class="form-group">
<label for="comment-form-url">{{ site.data.ui-text[site.locale].comment_form_website_label | default: "Website (optional)" }}</label>
<input type="url" id="comment-form-url" name="fields[url]" tabindex="4"/>
</div>
<div class="form-group hidden" style="display: none;">
<input type="hidden" name="options[origin]" value="{{ page.url | absolute_url }}">
<input type="hidden" name="options[slug]" value="{{ page.slug }}">
<label for="comment-form-location">Not used. Leave blank if you are a human.</label>
<input type="text" id="comment-form-location" name="fields[hidden]" autocomplete="off"/>
{% if site.staticman.reCaptcha.siteKey %}<input type="hidden" name="options[reCaptcha][siteKey]" value="{{ site.staticman.reCaptcha.siteKey }}">{% endif %}
{% if site.staticman.reCaptcha.secret %}<input type="hidden" name="options[reCaptcha][secret]" value="{{ site.staticman.reCaptcha.secret }}">{% endif %}
</div>
<!-- Start comment form alert messaging -->
<p class="hidden js-notice">
<strong class="js-notice-text-success hidden">{{ site.data.ui-text[site.locale].comment_success_msg | default: "Thanks for your comment! It will show on the site once it has been approved." }}</strong>
<strong class="js-notice-text-failure hidden">{{ site.data.ui-text[site.locale].comment_error_msg | default: "Sorry, there was an error with your submission. Please make sure all required fields have been completed and try again." }}</strong>
</p>
<!-- End comment form alert messaging -->
{% if site.staticman.reCaptcha.siteKey %}
<div class="form-group">
<div class="g-recaptcha" data-sitekey="{{ site.staticman.reCaptcha.siteKey }}"></div>
</div>
{% endif %}
<div class="form-group">
<button type="submit" id="comment-form-submit" tabindex="5" class="btn btn--primary btn--large">{{ site.data.ui-text[site.locale].comment_btn_submit | default: "Submit Comment" }}</button>
<button type="submit" id="comment-form-submitted" tabindex="5" class="btn btn--primary btn--large hidden" disabled>{{ site.data.ui-text[site.locale].comment_btn_submitted | default: "Submitted" }}</button>
</div>
</form>
</div>
<!-- End new comment form -->
<!-- Load reCaptcha if site key is set -->
{% if site.staticman.reCaptcha.siteKey %}
<script async src="https://www.google.com/recaptcha/api.js"></script>
{% endif %}
</div>
<!-- Load script to handle comment form submission -->
<!-- doing something a bit funky here because I want to be careful not to include JQuery twice! -->
<script>
if (typeof jQuery == 'undefined') {
document.write('<script src="{{ "/js/jquery-1.11.2.min.js" | relative_url }}"></scr' + 'ipt>');
}
</script>
<script src="{{ "/js/staticman.js" | relative_url }}"></script>
</div>
{% endif %}
| Java |
// Uncomment the following to provide samples for PageResult<T>. Must also add the Microsoft.AspNet.WebApi.OData
// package to your project.
////#define Handle_PageResultOfT
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net.Http.Headers;
using System.Reflection;
using System.Web;
using System.Web.Http;
#if Handle_PageResultOfT
using System.Web.Http.OData;
#endif
namespace TheBigCatProject.Server.Areas.HelpPage
{
/// <summary>
/// Use this class to customize the Help Page.
/// For example you can set a custom <see cref="System.Web.Http.Description.IDocumentationProvider"/> to supply the documentation
/// or you can provide the samples for the requests/responses.
/// </summary>
public static class HelpPageConfig
{
[SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters",
MessageId = "TheBigCatProject.Server.Areas.HelpPage.TextSample.#ctor(System.String)",
Justification = "End users may choose to merge this string with existing localized resources.")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly",
MessageId = "bsonspec",
Justification = "Part of a URI.")]
public static void Register(HttpConfiguration config)
{
//// Uncomment the following to use the documentation from XML documentation file.
//config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml")));
//// Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type.
//// Also, the string arrays will be used for IEnumerable<string>. The sample objects will be serialized into different media type
//// formats by the available formatters.
//config.SetSampleObjects(new Dictionary<Type, object>
//{
// {typeof(string), "sample string"},
// {typeof(IEnumerable<string>), new string[]{"sample 1", "sample 2"}}
//});
// Extend the following to provide factories for types not handled automatically (those lacking parameterless
// constructors) or for which you prefer to use non-default property values. Line below provides a fallback
// since automatic handling will fail and GeneratePageResult handles only a single type.
#if Handle_PageResultOfT
config.GetHelpPageSampleGenerator().SampleObjectFactories.Add(GeneratePageResult);
#endif
// Extend the following to use a preset object directly as the sample for all actions that support a media
// type, regardless of the body parameter or return type. The lines below avoid display of binary content.
// The BsonMediaTypeFormatter (if available) is not used to serialize the TextSample object.
config.SetSampleForMediaType(
new TextSample("Binary JSON content. See http://bsonspec.org for details."),
new MediaTypeHeaderValue("application/bson"));
//// Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format
//// and have IEnumerable<string> as the body parameter or return type.
//config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable<string>));
//// Uncomment the following to use "1234" directly as the request sample for media type "text/plain" on the controller named "Values"
//// and action named "Put".
//config.SetSampleRequest("1234", new MediaTypeHeaderValue("text/plain"), "Values", "Put");
//// Uncomment the following to use the image on "../images/aspNetHome.png" directly as the response sample for media type "image/png"
//// on the controller named "Values" and action named "Get" with parameter "id".
//config.SetSampleResponse(new ImageSample("../images/aspNetHome.png"), new MediaTypeHeaderValue("image/png"), "Values", "Get", "id");
//// Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent<string>.
//// The sample will be generated as if the controller named "Values" and action named "Get" were having string as the body parameter.
//config.SetActualRequestType(typeof(string), "Values", "Get");
//// Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent<string>.
//// The sample will be generated as if the controller named "Values" and action named "Post" were returning a string.
//config.SetActualResponseType(typeof(string), "Values", "Post");
}
#if Handle_PageResultOfT
private static object GeneratePageResult(HelpPageSampleGenerator sampleGenerator, Type type)
{
if (type.IsGenericType)
{
Type openGenericType = type.GetGenericTypeDefinition();
if (openGenericType == typeof(PageResult<>))
{
// Get the T in PageResult<T>
Type[] typeParameters = type.GetGenericArguments();
Debug.Assert(typeParameters.Length == 1);
// Create an enumeration to pass as the first parameter to the PageResult<T> constuctor
Type itemsType = typeof(List<>).MakeGenericType(typeParameters);
object items = sampleGenerator.GetSampleObject(itemsType);
// Fill in the other information needed to invoke the PageResult<T> constuctor
Type[] parameterTypes = new Type[] { itemsType, typeof(Uri), typeof(long?), };
object[] parameters = new object[] { items, null, (long)ObjectGenerator.DefaultCollectionSize, };
// Call PageResult(IEnumerable<T> items, Uri nextPageLink, long? count) constructor
ConstructorInfo constructor = type.GetConstructor(parameterTypes);
return constructor.Invoke(parameters);
}
}
return null;
}
#endif
}
} | Java |
<?php
namespace Hateoas\Tests\Expression;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Symfony\Component\ExpressionLanguage\Node\Node;
use Symfony\Component\ExpressionLanguage\ParsedExpression;
use Hateoas\Tests\TestCase;
use Hateoas\Expression\ExpressionEvaluator;
use Hateoas\Expression\ExpressionFunctionInterface;
class ExpressionEvaluatorTest extends TestCase
{
public function testNullEvaluate()
{
$expressionLanguageProphecy = $this->prophesize('Symfony\Component\ExpressionLanguage\ExpressionLanguage');
$expressionLanguageProphecy
->parse($this->arg->any())
->shouldNotBeCalled()
;
$expressionEvaluator = new ExpressionEvaluator($expressionLanguageProphecy->reveal());
$this
->string($expressionEvaluator->evaluate('hello', null))
->isEqualTo('hello')
;
}
public function testEvaluate()
{
$data = new \StdClass();
$expressionLanguageProphecy = $this->prophesize('Symfony\Component\ExpressionLanguage\ExpressionLanguage');
$expressionLanguageProphecy
->parse('"42"', array('object'))
->willReturn($parsedExpression = new ParsedExpression('', new Node()))
;
$expressionLanguageProphecy
->evaluate($parsedExpression, array('object' => $data))
->willReturn('42')
;
$expressionEvaluator = new ExpressionEvaluator($expressionLanguageProphecy->reveal());
$this
->string($expressionEvaluator->evaluate('expr("42")', $data))
->isEqualTo('42')
;
}
public function testEvaluateArray()
{
$parsedExpressions = array(
new ParsedExpression('a', new Node()),
new ParsedExpression('aa', new Node()),
new ParsedExpression('aaa', new Node()),
);
$data = new \StdClass();
$ELProphecy = $this->prophesize('Symfony\Component\ExpressionLanguage\ExpressionLanguage');
$ELProphecy->parse('a', array('object'))->willReturn($parsedExpressions[0])->shouldBeCalledTimes(1);
$ELProphecy->parse('aa', array('object'))->willReturn($parsedExpressions[1])->shouldBeCalledTimes(1);
$ELProphecy->parse('aaa', array('object'))->willReturn($parsedExpressions[2])->shouldBeCalledTimes(1);
$ELProphecy->evaluate($parsedExpressions[0], array('object' => $data))->willReturn(1);
$ELProphecy->evaluate($parsedExpressions[1], array('object' => $data))->willReturn(2);
$ELProphecy->evaluate($parsedExpressions[2], array('object' => $data))->willReturn(3);
$expressionEvaluator = new ExpressionEvaluator($ELProphecy->reveal());
$array = array(
'expr(a)' => 'expr(aa)',
'hello' => array('expr(aaa)'),
);
$this
->array($expressionEvaluator->evaluateArray($array, $data))
->isEqualTo(array(
1 => 2,
'hello' => array(3),
))
;
}
public function testSetContextVariable()
{
$data = new \StdClass();
$expressionLanguageProphecy = $this->prophesize('Symfony\Component\ExpressionLanguage\ExpressionLanguage');
$expressionLanguageProphecy
->parse('name', array('name', 'object'))
->willReturn($parsedExpression = new ParsedExpression('', new Node()))
->shouldBeCalledTimes(1)
;
$expressionLanguageProphecy
->evaluate($parsedExpression, array('object' => $data, 'name' => 'Adrien'))
->willReturn('Adrien')
->shouldBeCalledTimes(1)
;
$expressionEvaluator = new ExpressionEvaluator($expressionLanguageProphecy->reveal());
$expressionEvaluator->setContextVariable('name', 'Adrien');
$this
->string($expressionEvaluator->evaluate('expr(name)', $data))
->isEqualTo('Adrien')
;
}
public function testRegisterFunction()
{
$expressionEvaluator = new ExpressionEvaluator(new ExpressionLanguage());
$expressionEvaluator->registerFunction(new HelloExpressionFunction());
$this
->string($expressionEvaluator->evaluate('expr(hello("toto"))', null))
->isEqualTo('Hello, toto!')
;
}
}
class HelloExpressionFunction implements ExpressionFunctionInterface
{
public function getName()
{
return 'hello';
}
public function getCompiler()
{
return function ($value) {
return sprintf('$hello_helper->hello(%s)', $value);
};
}
public function getEvaluator()
{
return function (array $context, $value) {
return $context['hello_helper']->hello($value);
};
}
public function getContextVariables()
{
return array('hello_helper' => $this);
}
public function hello($name)
{
return sprintf('Hello, %s!', $name);
}
}
| Java |
<?php
/**
* Pro customizer section.
*
* @since 1.0.0
* @access public
*/
class Epsilon_Section_Pro extends WP_Customize_Section {
/**
* The type of customize section being rendered.
*
* @since 1.0.0
* @access public
* @var string
*/
public $type = 'epsilon-section-pro';
/**
* Custom pro button URL.
*
* @since 1.0.0
* @access public
* @var string
*/
public $button_url = '';
/**
* Custom pro button text.
*
* @since 1.0.0
* @access public
* @var string
*/
public $button_text = '';
/**
* Used to disable the upsells
*
* @var bool
*/
public $allowed = true;
/**
* Epsilon_Section_Pro constructor.
*
* @param WP_Customize_Manager $manager
* @param string $id
* @param array $args
*/
public function __construct( WP_Customize_Manager $manager, $id, array $args = array() ) {
$this->allowed = apply_filters( 'epsilon_upsell_section_display', true );
$manager->register_section_type( 'Epsilon_Section_Pro' );
parent::__construct( $manager, $id, $args );
}
/**
* Add custom parameters to pass to the JS via JSON.
*
* @since 1.0.0
* @access public
*/
public function json() {
$json = parent::json();
$json['button_url'] = $this->button_url;
$json['button_text'] = esc_html( $this->button_text );
$json['allowed'] = $this->allowed;
return $json;
}
/**
* Outputs the Underscore.js template.
*
* @since 1.0.0
* @access public
* @return void
*/
protected function render_template() {
?>
<?php if ( $this->allowed ) : //@formatter:off ?>
<li id="accordion-section-{{ data.id }}"
class="accordion-section control-section control-section-{{ data.type }} cannot-expand">
<h3 class="accordion-section-title epsilon-pro-section-title"> {{ data.title }}
<# if ( data.button_url ) { #>
<a href="{{ data.button_url }}" class="button alignright" target="_blank"> {{ data.button_text }}</a>
<# } #>
</h3>
</li>
<?php //@formatter:on ?>
<?php endif; ?>
<?php }
}
| Java |
/// <summary>
/// This class handles user ID, session ID, time stamp, and sends a user message, optionally including system specs, when the game starts
/// </summary>
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System;
using System.Net;
#if !UNITY_WEBPLAYER && !UNITY_NACL && !UNITY_FLASH && !UNITY_WP8 && !UNITY_METRO && !UNITY_PS3
using System.Net.NetworkInformation;
using System.Security.Cryptography;
using System.Text;
#endif
public class GA_GenericInfo
{
#region public values
/// <summary>
/// The ID of the user/player. A unique ID will be determined the first time the player plays. If an ID has already been created for a player this ID will be used.
/// </summary>
public string UserID
{
get {
if ((_userID == null || _userID == string.Empty) && !GA.SettingsGA.CustomUserID)
{
_userID = GetUserUUID();
}
return _userID;
}
}
/// <summary>
/// The ID of the current session. A unique ID will be determined when the game starts. This ID will be used for the remainder of the play session.
/// </summary>
public string SessionID
{
get {
if (_sessionID == null)
{
_sessionID = GetSessionUUID();
}
return _sessionID;
}
}
/// <summary>
/// The current UTC date/time in seconds
/// </summary>
/*public string TimeStamp
{
get {
return ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString();
}
}*/
#endregion
#region private values
private string _userID = string.Empty;
private string _sessionID;
private bool _settingUserID;
#endregion
#region public methods
/// <summary>
/// Gets generic system information at the beginning of a play session
/// </summary>
/// <param name="inclSpecs">
/// Determines if all the system specs should be included <see cref="System.Bool"/>
/// </param>
/// <returns>
/// The message to submit to the GA server is a dictionary of all the relevant parameters (containing user ID, session ID, system information, language information, date/time, build version) <see cref="Dictionary<System.String, System.Object>"/>
/// </returns>
public List<Hashtable> GetGenericInfo(string message)
{
List<Hashtable> systemspecs = new List<Hashtable>();
systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "unity_sdk " + GA_Settings.VERSION, message));
/*
* Apple does not allow tracking of device specific data:
* "You may not use analytics software in your application to collect and send device data to a third party"
* - iOS Developer Program License Agreement: http://www.scribd.com/doc/41213383/iOS-Developer-Program-License-Agreement
*/
#if !UNITY_IPHONE
systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "os:"+SystemInfo.operatingSystem, message));
systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "processor_type:"+SystemInfo.processorType, message));
systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_name:"+SystemInfo.graphicsDeviceName, message));
systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_version:"+SystemInfo.graphicsDeviceVersion, message));
// Unity provides lots of additional system info which might be worth tracking for some games:
//systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "process_count:"+SystemInfo.processorCount.ToString(), message));
//systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "sys_mem_size:"+SystemInfo.systemMemorySize.ToString(), message));
//systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_mem_size:"+SystemInfo.graphicsMemorySize.ToString(), message));
//systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_vendor:"+SystemInfo.graphicsDeviceVendor, message));
//systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_id:"+SystemInfo.graphicsDeviceID.ToString(), message));
//systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_vendor_id:"+SystemInfo.graphicsDeviceVendorID.ToString(), message));
//systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_shader_level:"+SystemInfo.graphicsShaderLevel.ToString(), message));
//systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_pixel_fillrate:"+SystemInfo.graphicsPixelFillrate.ToString(), message));
//systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "sup_shadows:"+SystemInfo.supportsShadows.ToString(), message));
//systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "sup_render_textures:"+SystemInfo.supportsRenderTextures.ToString(), message));
//systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "sup_image_effects:"+SystemInfo.supportsImageEffects.ToString(), message));
#else
systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "os:iOS", message));
#endif
return systemspecs;
}
/// <summary>
/// Gets a universally unique ID to represent the user. User ID should be device specific to allow tracking across different games on the same device:
/// -- Android uses deviceUniqueIdentifier.
/// -- iOS/PC/Mac uses the first MAC addresses available.
/// -- Webplayer uses deviceUniqueIdentifier.
/// Note: The unique user ID is based on the ODIN specifications. See http://code.google.com/p/odinmobile/ for more information on ODIN.
/// </summary>
/// <returns>
/// The generated UUID <see cref="System.String"/>
/// </returns>
public static string GetUserUUID()
{
#if UNITY_IPHONE && !UNITY_EDITOR
string uid = GA.SettingsGA.GetUniqueIDiOS();
if (uid == null)
{
return "";
}
else if (uid != "OLD")
{
if (uid.StartsWith("VENDOR-"))
return uid.Remove(0, 7);
else
return uid;
}
#endif
#if UNITY_ANDROID && !UNITY_EDITOR
string uid = GA.SettingsGA.GetAdvertisingIDAndroid();
if (!string.IsNullOrEmpty(uid))
{
return uid;
}
#endif
#if UNITY_WEBPLAYER || UNITY_NACL || UNITY_WP8 || UNITY_METRO || UNITY_PS3
return SystemInfo.deviceUniqueIdentifier;
#elif !UNITY_FLASH
try
{
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
string mac = "";
foreach (NetworkInterface adapter in nics)
{
PhysicalAddress address = adapter.GetPhysicalAddress();
if (address.ToString() != "" && mac == "")
{
mac = GA_Submit.CreateSha1Hash(address.ToString());
}
}
return mac;
}
catch
{
return SystemInfo.deviceUniqueIdentifier;
}
#else
return GetSessionUUID();
#endif
}
/// <summary>
/// Gets a universally unique ID to represent the session.
/// </summary>
/// <returns>
/// The generated UUID <see cref="System.String"/>
/// </returns>
public static string GetSessionUUID()
{
#if !UNITY_FLASH
return Guid.NewGuid().ToString();
#else
string returnValue = "";
for (int i = 0; i < 12; i++)
{
returnValue += UnityEngine.Random.Range(0, 10).ToString();
}
return returnValue;
#endif
}
/// <summary>
/// Sets the session ID. If newSessionID is null then a random UUID will be generated, otherwise newSessionID will be used as the session ID.
/// </summary>
/// <param name="newSessionID">New session I.</param>
public void SetSessionUUID(string newSessionID)
{
if (newSessionID == null)
{
_sessionID = GetSessionUUID();
}
else
{
_sessionID = newSessionID;
}
}
/// <summary>
/// Do not call this method (instead use GA_static_api.Settings.SetCustomUserID)! Only the GA class should call this method.
/// </summary>
/// <param name="customID">
/// The custom user ID - this should be unique for each user
/// </param>
public void SetCustomUserID(string customID)
{
_userID = customID;
}
#endregion
#region private methods
/// <summary>
/// Adds detailed system specifications regarding the users/players device to the parameters.
/// </summary>
/// <param name="parameters">
/// The parameters which will be sent to the server <see cref="Dictionary<System.String, System.Object>"/>
/// </param>
private Hashtable AddSystemSpecs(GA_Error.SeverityType severity, string type, string message)
{
string addmessage = "";
if (message != "")
addmessage = ": " + message;
Hashtable parameters = new Hashtable()
{
{ GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.Severity], severity.ToString() },
{ GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.Message], type + addmessage },
{ GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.Level], GA.SettingsGA.CustomArea.Equals(string.Empty)?Application.loadedLevelName:GA.SettingsGA.CustomArea }
};
return parameters;
}
/// <summary>
/// Gets the users system type
/// </summary>
/// <returns>
/// String determining the system the user is currently running <see cref="System.String"/>
/// </returns>
public static string GetSystem()
{
#if UNITY_STANDALONE_OSX
return "MAC";
#elif UNITY_STANDALONE_WIN
return "PC";
#elif UNITY_WEBPLAYER
return "WEBPLAYER";
#elif UNITY_WII
return "WII";
#elif UNITY_IPHONE
return "IPHONE";
#elif UNITY_ANDROID
return "ANDROID";
#elif UNITY_PS3
return "PS3";
#elif UNITY_XBOX360
return "XBOX";
#elif UNITY_FLASH
return "FLASH";
#elif UNITY_STANDALONE_LINUX
return "LINUX";
#elif UNITY_NACL
return "NACL";
#elif UNITY_DASHBOARD_WIDGET
return "DASHBOARD_WIDGET";
#elif UNITY_METRO
return "WINDOWS_STORE_APP";
#elif UNITY_WP8
return "WINDOWS_PHONE_8";
#elif UNITY_BLACKBERRY
return "BLACKBERRY";
#else
return "UNKNOWN";
#endif
}
#endregion
} | Java |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Bespin.
*
* The Initial Developer of the Original Code is Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Bespin Team ([email protected])
*
*
* ***** END LICENSE BLOCK ***** */
body {
padding: 0;
margin: 0;
background-color: #4f4e45;
font-family: Calibri, Arial, sans-serif;
}
#version {
float: left;
padding: 8px;
}
#version a {
text-decoration: none;
color: #aaa;
}
.versionnumber {
color: #777;
}
#loginbutton {
float: right;
padding: 9px 10px 0 7px;
cursor: pointer;
}
#logged_in > div {
float: right;
}
#loginpane {
height: 32px;
background-image: url("../images/splash_toolbar_bg.png");
background-repeat: repeat-x;
color: #4f4e45;
font-size: 10pt;
text-align: right;
}
#loginpane a {
color: #DAD4BA;
}
#loginpane #login-holder {
padding-top: 8px;
}
#loginpane #login-holder #psw-label {
padding-left: 12px;
}
#loginpane input#username,
#loginpane input#password {
border: none;
background-image: url("../images/splash_inputs.png");
background-repeat: no-repeat;
padding: 0px 4px;
height: 16px;
width: 81px;
color: #ddd;
}
#logo {
background-image: url("../images/splash_logo.jpg");
background-position: center;
height: 269px;
}
#welcome {
z-index: 30;
height: 269px;
background-image: url("../images/splash_logo_bg.jpg");
background-repeat: repeat-x;
}
#toolbar {
z-index: 40;
height: 24px;
margin-top: -9px;
padding-top: 12px;
background-image: url("../images/splash_lowertoolbar_bg.png");
background-repeat: repeat-x;
border-bottom: 1px solid black;
color: #dad4ba;
font-size: 12pt;
text-shadow: 1px 1px 1px #000;
}
#footer {
font-size: 8pt;
color: #7c7b74;
padding-bottom: 1em;
}
#main {
margin: 20px auto;
height: 181px;
width: 800px;
}
#main h3 {
font-size: 14px;
font-family: "Lucida Grande", Tahoma, Arial, sans-serif;
text-shadow: 1px 1px 1px #000;
}
#main p {
font-size: 12px;
font-family: "Lucida Grande", Tahoma, Arial, sans-serif;
}
#learnbespin {
float: left;
padding-left: 16px;
padding-right: 0;
padding-top: 10px;
width: 370px;
height: 356px;
background-image: url("../images/splash_contentarea_bg.png");
background-repeat: no-repeat;
text-align: left;
color: #dad4ba;
font-size: 10pt;
}
#learnbespin img {
cursor: pointer;
}
#main a {
font-family: "Lucida Grande", Tahoma, Arial, sans-serif;
font-size: 12px;
color: #ff9600;
}
#usebespin {
float: right;
margin-left: 0;
padding-left: 16px;
padding-right: 16px;
padding-top: 10px;
width: 353px;
height: 356px;
background-image: url("../images/splash_contentarea_bg.png");
background-repeat: no-repeat;
text-align: left;
color: #dad4ba;
font-size: 10pt;
}
#usebespin h2, #learnbespin h2 {
font-weight: normal;
margin: 0;
color: #ff9600;
font-family: "Lucida Grande", Tahoma, Arial, sans-serif;
font-size: 20px;
text-align: left;
text-shadow: 1px 1px 1px #000;
}
#usebespin input {
border: none;
background-image: url("../images/splash_editnow_input.png");
background-repeat: no-repeat;
padding-left: 4px;
padding-right: 4px;
width: 252px;
color: #ddd;
}
#usebespin img {
padding-right: 4px;
padding-top: 12px;
cursor: pointer;
}
#openid {
float: left;
padding-top: 9px;
padding-left: 1em;
color: #DDDDDD;
}
#newversion a {
color: #ff9600;
}
#overlay {
z-index: 10;
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
background-color: #000000;
opacity: 0.6;
}
#browser_not_compat {
z-index: 20;
background: url("../images/background_white_50.png");
position: absolute;
padding: 10px;
width: 400px;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
}
#inner_browser_not_compat {
border: 1px solid #000;
background: #d1cfc1;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
}
#browser_not_compat h3 {
background-color: #22211e;
background-image: url("../images/register_toolbar_background.png");
background-repeat: repeat-x;
margin: 0;
padding: 5px;
border: 0;
color: #eee;
height: 16px;
font-size: small;
}
#sorry_browser_text {
font-family: "Lucida Grande", Tahoma, Arial, sans-serif;
font-size: 12px;
padding: 10px;
}
#sorry_browser_cancel {
cursor: pointer;
}
#centerpopup {
z-index: 300;
background: url("../images/background_white_50.png");
position: absolute;
padding: 10px;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
}
.register_title {
background-color: #000;
background-image: url("../images/register_toolbar_background.png");
background-repeat: repeat-x;
padding: 5px;
border: 0;
color: #fff;
height: 16px;
}
.register_title p {
margin: 0;
}
.register_form {
border: 1px solid #000;
background: #d1cfc1;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
display: none;
}
.register_form .instructions {
font-size: 80%;
padding-left: 30px;
padding-right: 30px;
padding-bottom: 10px;
width: 200px;
}
#register_form table {
padding: 20px;
}
#register_form th {
text-align: right;
}
#register_form .darkButton {
border: 1px solid #DAD4BA;
}
#logged_in {
padding-top: 8px;
padding-right: 8px;
}
.register_error {
color: #f00;
font-size: 80%;
font-weight: bold;
text-align: right;
}
#learnbespin .darkButton {
font-size: 110%;
border: 1px solid #7c7b74;
}
#vcsurl {
background-image: url("../images/splash_editnow_input.png");
background-repeat: no-repeat;
}
.darkButton {
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
background: #111 repeat-x url("../images/button_background.png");
padding: 5px;
color: #FAF4DA;
}
#status {
color: #DDDDDD;
padding-top: 12px;
text-align: center;
font-family: Calibri, Arial, sans-serif;
font-size: 12pt;
overflow: hidden;
position: absolute;
top: 32px;
right: 0px;
height: 41px;
background-image: url("../images/targ-browser_bg.png");
width: 711px;
}
| Java |
import {OverlayRef, GlobalPositionStrategy} from '../core';
import {AnimationEvent} from '@angular/animations';
import {DialogPosition} from './dialog-config';
import {Observable} from 'rxjs/Observable';
import {Subject} from 'rxjs/Subject';
import {MdDialogContainer} from './dialog-container';
import 'rxjs/add/operator/filter';
// TODO(jelbourn): resizing
// TODO(jelbourn): afterOpen and beforeClose
/**
* Reference to a dialog opened via the MdDialog service.
*/
export class MdDialogRef<T> {
/** The instance of component opened into the dialog. */
componentInstance: T;
/** Subject for notifying the user that the dialog has finished closing. */
private _afterClosed: Subject<any> = new Subject();
/** Result to be passed to afterClosed. */
private _result: any;
constructor(private _overlayRef: OverlayRef, public _containerInstance: MdDialogContainer) {
_containerInstance._onAnimationStateChange
.filter((event: AnimationEvent) => event.toState === 'exit')
.subscribe(() => {
this._overlayRef.dispose();
this.componentInstance = null;
}, null, () => {
this._afterClosed.next(this._result);
this._afterClosed.complete();
});
}
/**
* Close the dialog.
* @param dialogResult Optional result to return to the dialog opener.
*/
close(dialogResult?: any): void {
this._result = dialogResult;
this._containerInstance._state = 'exit';
this._overlayRef.detachBackdrop(); // Transition the backdrop in parallel with the dialog.
}
/**
* Gets an observable that is notified when the dialog is finished closing.
*/
afterClosed(): Observable<any> {
return this._afterClosed.asObservable();
}
/**
* Updates the dialog's position.
* @param position New dialog position.
*/
updatePosition(position?: DialogPosition): this {
let strategy = this._getPositionStrategy();
if (position && (position.left || position.right)) {
position.left ? strategy.left(position.left) : strategy.right(position.right);
} else {
strategy.centerHorizontally();
}
if (position && (position.top || position.bottom)) {
position.top ? strategy.top(position.top) : strategy.bottom(position.bottom);
} else {
strategy.centerVertically();
}
this._overlayRef.updatePosition();
return this;
}
/**
* Updates the dialog's width and height.
* @param width New width of the dialog.
* @param height New height of the dialog.
*/
updateSize(width = 'auto', height = 'auto'): this {
this._getPositionStrategy().width(width).height(height);
this._overlayRef.updatePosition();
return this;
}
/** Fetches the position strategy object from the overlay ref. */
private _getPositionStrategy(): GlobalPositionStrategy {
return this._overlayRef.getState().positionStrategy as GlobalPositionStrategy;
}
}
| Java |
//
import java.util.Comparator;
abc.sort(Comparator.naturalOrder());
//
| Java |
module RR
module Errors
class SpyVerificationError < RRError
end
end
end | Java |
/*
LUFA Library
Copyright (C) Dean Camera, 2015.
dean [at] fourwalledcubicle [dot] com
www.lufa-lib.org
*/
/*
Copyright 2015 Dean Camera (dean [at] fourwalledcubicle [dot] com)
Permission to use, copy, modify, distribute, and sell this
software and its documentation for any purpose is hereby granted
without fee, provided that the above copyright notice appear in
all copies and that both that the copyright notice and this
permission notice and warranty disclaimer appear in supporting
documentation, and that the name of the author not be used in
advertising or publicity pertaining to distribution of the
software without specific, written prior permission.
The author disclaims all warranties with regard to this
software, including all implied warranties of merchantability
and fitness. In no event shall the author be liable for any
special, indirect or consequential damages or any damages
whatsoever resulting from loss of use, data or profits, whether
in an action of contract, negligence or other tortious action,
arising out of or in connection with the use or performance of
this software.
*/
#include "../../../Common/Common.h"
#if (ARCH == ARCH_XMEGA)
#define __INCLUDE_FROM_SERIAL_C
#include "../Serial.h"
FILE USARTSerialStream;
int Serial_putchar(char DataByte,
FILE *Stream)
{
USART_t* USART = fdev_get_udata(Stream);
Serial_SendByte(USART, DataByte);
return 0;
}
int Serial_getchar(FILE *Stream)
{
USART_t* USART = fdev_get_udata(Stream);
if (!(Serial_IsCharReceived(USART)))
return _FDEV_EOF;
return Serial_ReceiveByte(USART);
}
int Serial_getchar_Blocking(FILE *Stream)
{
USART_t* USART = fdev_get_udata(Stream);
while (!(Serial_IsCharReceived(USART)));
return Serial_ReceiveByte(USART);
}
void Serial_SendString_P(USART_t* const USART,
const char* FlashStringPtr)
{
uint8_t CurrByte;
while ((CurrByte = pgm_read_byte(FlashStringPtr)) != 0x00)
{
Serial_SendByte(USART, CurrByte);
FlashStringPtr++;
}
}
void Serial_SendString(USART_t* const USART,
const char* StringPtr)
{
uint8_t CurrByte;
while ((CurrByte = *StringPtr) != 0x00)
{
Serial_SendByte(USART, CurrByte);
StringPtr++;
}
}
void Serial_SendData(USART_t* const USART,
const void* Buffer,
uint16_t Length)
{
while (Length--)
Serial_SendByte(USART, *((uint8_t*)Buffer++));
}
void Serial_CreateStream(USART_t* USART, FILE* Stream)
{
if (!(Stream))
{
Stream = &USARTSerialStream;
stdin = Stream;
stdout = Stream;
}
*Stream = (FILE)FDEV_SETUP_STREAM(Serial_putchar, Serial_getchar, _FDEV_SETUP_RW);
fdev_set_udata(Stream, USART);
}
void Serial_CreateBlockingStream(USART_t* USART, FILE* Stream)
{
if (!(Stream))
{
Stream = &USARTSerialStream;
stdin = Stream;
stdout = Stream;
}
*Stream = (FILE)FDEV_SETUP_STREAM(Serial_putchar, Serial_getchar_Blocking, _FDEV_SETUP_RW);
fdev_set_udata(Stream, USART);
}
#endif
| Java |
<?php
/**
* This file is part of PHPWord - A pure PHP library for reading and writing
* word processing documents.
*
* PHPWord is free software distributed under the terms of the GNU Lesser
* General Public License version 3 as published by the Free Software Foundation.
*
* For the full copyright and license information, please read the LICENSE
* file that was distributed with this source code. For the full list of
* contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
*
* @see https://github.com/PHPOffice/PHPWord
* @copyright 2010-2018 PHPWord contributors
* @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
*/
namespace PhpOffice\PhpWord\Element;
/**
* Container abstract class
*
* @method Text addText(string $text, mixed $fStyle = null, mixed $pStyle = null)
* @method TextRun addTextRun(mixed $pStyle = null)
* @method Bookmark addBookmark(string $name)
* @method Link addLink(string $target, string $text = null, mixed $fStyle = null, mixed $pStyle = null, boolean $internal = false)
* @method PreserveText addPreserveText(string $text, mixed $fStyle = null, mixed $pStyle = null)
* @method void addTextBreak(int $count = 1, mixed $fStyle = null, mixed $pStyle = null)
* @method ListItem addListItem(string $txt, int $depth = 0, mixed $font = null, mixed $list = null, mixed $para = null)
* @method ListItemRun addListItemRun(int $depth = 0, mixed $listStyle = null, mixed $pStyle = null)
* @method Footnote addFootnote(mixed $pStyle = null)
* @method Endnote addEndnote(mixed $pStyle = null)
* @method CheckBox addCheckBox(string $name, $text, mixed $fStyle = null, mixed $pStyle = null)
* @method Title addTitle(mixed $text, int $depth = 1)
* @method TOC addTOC(mixed $fontStyle = null, mixed $tocStyle = null, int $minDepth = 1, int $maxDepth = 9)
* @method PageBreak addPageBreak()
* @method Table addTable(mixed $style = null)
* @method Image addImage(string $source, mixed $style = null, bool $isWatermark = false, $name = null)
* @method OLEObject addOLEObject(string $source, mixed $style = null)
* @method TextBox addTextBox(mixed $style = null)
* @method Field addField(string $type = null, array $properties = array(), array $options = array(), mixed $text = null)
* @method Line addLine(mixed $lineStyle = null)
* @method Shape addShape(string $type, mixed $style = null)
* @method Chart addChart(string $type, array $categories, array $values, array $style = null, $seriesName = null)
* @method FormField addFormField(string $type, mixed $fStyle = null, mixed $pStyle = null)
* @method SDT addSDT(string $type)
*
* @method \PhpOffice\PhpWord\Element\OLEObject addObject(string $source, mixed $style = null) deprecated, use addOLEObject instead
*
* @since 0.10.0
*/
abstract class AbstractContainer extends AbstractElement
{
/**
* Elements collection
*
* @var \PhpOffice\PhpWord\Element\AbstractElement[]
*/
protected $elements = array();
/**
* Container type Section|Header|Footer|Footnote|Endnote|Cell|TextRun|TextBox|ListItemRun|TrackChange
*
* @var string
*/
protected $container;
/**
* Magic method to catch all 'addElement' variation
*
* This removes addText, addTextRun, etc. When adding new element, we have to
* add the model in the class docblock with `@method`.
*
* Warning: This makes capitalization matters, e.g. addCheckbox or addcheckbox won't work.
*
* @param mixed $function
* @param mixed $args
* @return \PhpOffice\PhpWord\Element\AbstractElement
*/
public function __call($function, $args)
{
$elements = array(
'Text', 'TextRun', 'Bookmark', 'Link', 'PreserveText', 'TextBreak',
'ListItem', 'ListItemRun', 'Table', 'Image', 'Object', 'OLEObject',
'Footnote', 'Endnote', 'CheckBox', 'TextBox', 'Field',
'Line', 'Shape', 'Title', 'TOC', 'PageBreak',
'Chart', 'FormField', 'SDT', 'Comment',
);
$functions = array();
foreach ($elements as $element) {
$functions['add' . strtolower($element)] = $element == 'Object' ? 'OLEObject' : $element;
}
// Run valid `add` command
$function = strtolower($function);
if (isset($functions[$function])) {
$element = $functions[$function];
// Special case for TextBreak
// @todo Remove the `$count` parameter in 1.0.0 to make this element similiar to other elements?
if ($element == 'TextBreak') {
list($count, $fontStyle, $paragraphStyle) = array_pad($args, 3, null);
if ($count === null) {
$count = 1;
}
for ($i = 1; $i <= $count; $i++) {
$this->addElement($element, $fontStyle, $paragraphStyle);
}
} else {
// All other elements
array_unshift($args, $element); // Prepend element name to the beginning of args array
return call_user_func_array(array($this, 'addElement'), $args);
}
}
return null;
}
/**
* Add element
*
* Each element has different number of parameters passed
*
* @param string $elementName
* @return \PhpOffice\PhpWord\Element\AbstractElement
*/
protected function addElement($elementName)
{
$elementClass = __NAMESPACE__ . '\\' . $elementName;
$this->checkValidity($elementName);
// Get arguments
$args = func_get_args();
$withoutP = in_array($this->container, array('TextRun', 'Footnote', 'Endnote', 'ListItemRun', 'Field'));
if ($withoutP && ($elementName == 'Text' || $elementName == 'PreserveText')) {
$args[3] = null; // Remove paragraph style for texts in textrun
}
// Create element using reflection
$reflection = new \ReflectionClass($elementClass);
$elementArgs = $args;
array_shift($elementArgs); // Shift the $elementName off the beginning of array
/** @var \PhpOffice\PhpWord\Element\AbstractElement $element Type hint */
$element = $reflection->newInstanceArgs($elementArgs);
// Set parent container
$element->setParentContainer($this);
$element->setElementIndex($this->countElements() + 1);
$element->setElementId();
$this->elements[] = $element;
return $element;
}
/**
* Get all elements
*
* @return \PhpOffice\PhpWord\Element\AbstractElement[]
*/
public function getElements()
{
return $this->elements;
}
/**
* Returns the element at the requested position
*
* @param int $index
* @return \PhpOffice\PhpWord\Element\AbstractElement|null
*/
public function getElement($index)
{
if (array_key_exists($index, $this->elements)) {
return $this->elements[$index];
}
return null;
}
/**
* Removes the element at requested index
*
* @param int|\PhpOffice\PhpWord\Element\AbstractElement $toRemove
*/
public function removeElement($toRemove)
{
if (is_int($toRemove) && array_key_exists($toRemove, $this->elements)) {
unset($this->elements[$toRemove]);
} elseif ($toRemove instanceof \PhpOffice\PhpWord\Element\AbstractElement) {
foreach ($this->elements as $key => $element) {
if ($element->getElementId() === $toRemove->getElementId()) {
unset($this->elements[$key]);
return;
}
}
}
}
/**
* Count elements
*
* @return int
*/
public function countElements()
{
return count($this->elements);
}
/**
* Check if a method is allowed for the current container
*
* @param string $method
*
* @throws \BadMethodCallException
* @return bool
*/
private function checkValidity($method)
{
$generalContainers = array(
'Section', 'Header', 'Footer', 'Footnote', 'Endnote', 'Cell', 'TextRun', 'TextBox', 'ListItemRun', 'TrackChange',
);
$validContainers = array(
'Text' => $generalContainers,
'Bookmark' => $generalContainers,
'Link' => $generalContainers,
'TextBreak' => $generalContainers,
'Image' => $generalContainers,
'OLEObject' => $generalContainers,
'Field' => $generalContainers,
'Line' => $generalContainers,
'Shape' => $generalContainers,
'FormField' => $generalContainers,
'SDT' => $generalContainers,
'TrackChange' => $generalContainers,
'TextRun' => array('Section', 'Header', 'Footer', 'Cell', 'TextBox', 'TrackChange', 'ListItemRun'),
'ListItem' => array('Section', 'Header', 'Footer', 'Cell', 'TextBox'),
'ListItemRun' => array('Section', 'Header', 'Footer', 'Cell', 'TextBox'),
'Table' => array('Section', 'Header', 'Footer', 'Cell', 'TextBox'),
'CheckBox' => array('Section', 'Header', 'Footer', 'Cell', 'TextRun'),
'TextBox' => array('Section', 'Header', 'Footer', 'Cell'),
'Footnote' => array('Section', 'TextRun', 'Cell', 'ListItemRun'),
'Endnote' => array('Section', 'TextRun', 'Cell'),
'PreserveText' => array('Section', 'Header', 'Footer', 'Cell'),
'Title' => array('Section', 'Cell'),
'TOC' => array('Section'),
'PageBreak' => array('Section'),
'Chart' => array('Section', 'Cell'),
);
// Special condition, e.g. preservetext can only exists in cell when
// the cell is located in header or footer
$validSubcontainers = array(
'PreserveText' => array(array('Cell'), array('Header', 'Footer', 'Section')),
'Footnote' => array(array('Cell', 'TextRun'), array('Section')),
'Endnote' => array(array('Cell', 'TextRun'), array('Section')),
);
// Check if a method is valid for current container
if (isset($validContainers[$method])) {
if (!in_array($this->container, $validContainers[$method])) {
throw new \BadMethodCallException("Cannot add {$method} in {$this->container}.");
}
}
// Check if a method is valid for current container, located in other container
if (isset($validSubcontainers[$method])) {
$rules = $validSubcontainers[$method];
$containers = $rules[0];
$allowedDocParts = $rules[1];
foreach ($containers as $container) {
if ($this->container == $container && !in_array($this->getDocPart(), $allowedDocParts)) {
throw new \BadMethodCallException("Cannot add {$method} in {$this->container}.");
}
}
}
return true;
}
/**
* Create textrun element
*
* @deprecated 0.10.0
*
* @param mixed $paragraphStyle
*
* @return \PhpOffice\PhpWord\Element\TextRun
*
* @codeCoverageIgnore
*/
public function createTextRun($paragraphStyle = null)
{
return $this->addTextRun($paragraphStyle);
}
/**
* Create footnote element
*
* @deprecated 0.10.0
*
* @param mixed $paragraphStyle
*
* @return \PhpOffice\PhpWord\Element\Footnote
*
* @codeCoverageIgnore
*/
public function createFootnote($paragraphStyle = null)
{
return $this->addFootnote($paragraphStyle);
}
}
| Java |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Test unit filtering</title>
<link rel="stylesheet" href="../../boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../index.html" title="Boost.Test">
<link rel="up" href="../runtime_config.html" title="Runtime parameters">
<link rel="prev" href="../runtime_config.html" title="Runtime parameters">
<link rel="next" href="summary.html" title="Summary of run-time parameters">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td>
<td align="center"><a href="../../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../runtime_config.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../runtime_config.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="summary.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h3 class="title">
<a name="boost_test.runtime_config.test_unit_filtering"></a><a class="link" href="test_unit_filtering.html" title="Test unit filtering">Test unit
filtering</a>
</h3></div></div></div>
<p>
The <span class="emphasis"><em>Unit Test Framework</em></span> offers a number of ways to run
only a subset of all test cases registered in the test tree.
</p>
<a name="ref_default_run_status"></a><h4>
<a name="boost_test.runtime_config.test_unit_filtering.h0"></a>
<span class="phrase"><a name="boost_test.runtime_config.test_unit_filtering.default_run_status"></a></span><a class="link" href="test_unit_filtering.html#boost_test.runtime_config.test_unit_filtering.default_run_status">Default
run status</a>
</h4>
<p>
Each test unit (either test case or test suite) has an associated <span class="emphasis"><em>default
run status</em></span>. It can assume one of the three values:
</p>
<div class="orderedlist"><ol class="orderedlist" type="1">
<li class="listitem">
<span class="emphasis"><em>true</em></span> -- this means that, unless some runtime parameters
specify otherwise, the test unit is designated to be run.
</li>
<li class="listitem">
<span class="emphasis"><em>false</em></span> -- this means that, unless some runtime parameters
specify otherwise, the test unit is designated <span class="emphasis"><em>not</em></span>
to be run.
</li>
<li class="listitem">
<span class="emphasis"><em>inherit</em></span> -- this means that the test unit's default
run status is the same as that of its immediate parent test unit. This
is applied recursively.
</li>
</ol></div>
<p>
Initially, the master test suite has default run status set to <span class="emphasis"><em>true</em></span>.
All other test units have default run status set to <span class="emphasis"><em>inherit</em></span>.
This implies that, unless any additional configuration is applied, all tests
are designated to be run.
</p>
<p>
You can set a different default run status in any test unit by using <a class="link" href="../tests_organization/decorators.html" title="Decorators">decorators</a>: <a class="link" href="../utf_reference/test_org_reference/decorator_enabled.html" title="enabled / disabled (decorator)"><code class="computeroutput"><span class="identifier">disabled</span></code></a>, <a class="link" href="../utf_reference/test_org_reference/decorator_enabled.html" title="enabled / disabled (decorator)"><code class="computeroutput"><span class="identifier">enabled</span></code></a> and <a class="link" href="../utf_reference/test_org_reference/decorator_enable_if.html" title="enable_if (decorator)"><code class="computeroutput"><span class="identifier">enable_if</span></code></a>. The default run status
is set once, upon testing program initialization, and cannot be changed.
The disabled tests are not executed by default, but are still present in
the test tree, and are listed along with other tests when you use command-line
argument <a class="link" href="../utf_reference/rt_param_reference/list_content.html" title="list_content"><code class="computeroutput"><span class="identifier">list_content</span></code></a>.
</p>
<h6>
<a name="boost_test.runtime_config.test_unit_filtering.h1"></a>
<span class="phrase"><a name="boost_test.runtime_config.test_unit_filtering.example_descr"></a></span><a class="link" href="test_unit_filtering.html#boost_test.runtime_config.test_unit_filtering.example_descr">Example:
default run status</a>
</h6>
<div class="informaltable"><table class="table">
<colgroup><col></colgroup>
<thead><tr><th>
<p>
Code
</p>
</th></tr></thead>
<tbody><tr><td>
<pre xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="table-programlisting"><span class="preprocessor">#define</span> <span class="identifier">BOOST_TEST_MODULE</span> <span class="identifier">decorator_20</span>
<span class="preprocessor">#include</span> <span class="special"><</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">test</span><span class="special">/</span><span class="identifier">included</span><span class="special">/</span><span class="identifier">unit_test</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">></span>
<span class="keyword">namespace</span> <span class="identifier">utf</span> <span class="special">=</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">unit_test</span><span class="special">;</span>
<span class="keyword">const</span> <span class="keyword">bool</span> <span class="identifier">io_implemented</span> <span class="special">=</span> <span class="keyword">true</span><span class="special">;</span>
<span class="keyword">const</span> <span class="keyword">bool</span> <span class="identifier">db_implemented</span> <span class="special">=</span> <span class="keyword">false</span><span class="special">;</span>
<span class="identifier">BOOST_AUTO_TEST_SUITE</span><span class="special">(</span><span class="identifier">suite1</span><span class="special">,</span> <span class="special">*</span> <span class="identifier">utf</span><span class="special">::</span><span class="identifier">disabled</span><span class="special">());</span>
<span class="identifier">BOOST_AUTO_TEST_CASE</span><span class="special">(</span><span class="identifier">test_1</span><span class="special">)</span>
<span class="special">{</span>
<span class="identifier">BOOST_TEST</span><span class="special">(</span><span class="number">1</span> <span class="special">!=</span> <span class="number">1</span><span class="special">);</span>
<span class="special">}</span>
<span class="identifier">BOOST_AUTO_TEST_CASE</span><span class="special">(</span><span class="identifier">test_2</span><span class="special">,</span> <span class="special">*</span> <span class="identifier">utf</span><span class="special">::</span><span class="identifier">enabled</span><span class="special">())</span>
<span class="special">{</span>
<span class="identifier">BOOST_TEST</span><span class="special">(</span><span class="number">2</span> <span class="special">!=</span> <span class="number">2</span><span class="special">);</span>
<span class="special">}</span>
<span class="identifier">BOOST_AUTO_TEST_CASE</span><span class="special">(</span><span class="identifier">test_io</span><span class="special">,</span>
<span class="special">*</span> <span class="identifier">utf</span><span class="special">::</span><span class="identifier">enable_if</span><span class="special"><</span><span class="identifier">io_implemented</span><span class="special">>())</span>
<span class="special">{</span>
<span class="identifier">BOOST_TEST</span><span class="special">(</span><span class="number">3</span> <span class="special">!=</span> <span class="number">3</span><span class="special">);</span>
<span class="special">}</span>
<span class="identifier">BOOST_AUTO_TEST_CASE</span><span class="special">(</span><span class="identifier">test_db</span><span class="special">,</span>
<span class="special">*</span> <span class="identifier">utf</span><span class="special">::</span><span class="identifier">enable_if</span><span class="special"><</span><span class="identifier">db_implemented</span><span class="special">>())</span>
<span class="special">{</span>
<span class="identifier">BOOST_TEST</span><span class="special">(</span><span class="number">4</span> <span class="special">!=</span> <span class="number">4</span><span class="special">);</span>
<span class="special">}</span>
<span class="identifier">BOOST_AUTO_TEST_SUITE_END</span><span class="special">();</span>
</pre>
</td></tr></tbody>
</table></div>
<div class="informaltable"><table class="table">
<colgroup><col></colgroup>
<thead><tr><th>
<p>
Output
</p>
</th></tr></thead>
<tbody><tr><td>
<pre xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="table-programlisting"><span class="special">></span> <span class="identifier">decorator_20</span>
<span class="identifier">Running</span> <span class="number">2</span> <span class="identifier">test</span> <span class="identifier">cases</span><span class="special">...</span>
<span class="identifier">test</span><span class="special">.</span><span class="identifier">cpp</span><span class="special">(</span><span class="number">18</span><span class="special">):</span> <span class="identifier">error</span><span class="special">:</span> <span class="identifier">in</span> <span class="string">"suite1/test_2"</span><span class="special">:</span> <span class="identifier">check</span> <span class="number">2</span> <span class="special">!=</span> <span class="number">2</span> <span class="identifier">has</span> <span class="identifier">failed</span> <span class="special">[</span><span class="number">2</span> <span class="special">==</span> <span class="number">2</span><span class="special">]</span>
<span class="identifier">test</span><span class="special">.</span><span class="identifier">cpp</span><span class="special">(</span><span class="number">24</span><span class="special">):</span> <span class="identifier">error</span><span class="special">:</span> <span class="identifier">in</span> <span class="string">"suite1/test_io"</span><span class="special">:</span> <span class="identifier">check</span> <span class="number">3</span> <span class="special">!=</span> <span class="number">3</span> <span class="identifier">has</span> <span class="identifier">failed</span> <span class="special">[</span><span class="number">3</span> <span class="special">==</span> <span class="number">3</span><span class="special">]</span>
<span class="special">***</span> <span class="number">2</span> <span class="identifier">failures</span> <span class="identifier">are</span> <span class="identifier">detected</span> <span class="identifier">in</span> <span class="identifier">the</span> <span class="identifier">test</span> <span class="identifier">module</span> <span class="string">"decorator_20"</span>
<span class="special">></span> <span class="identifier">decorator_20</span> <span class="special">--</span><span class="identifier">list_content</span>
<span class="identifier">suite1</span><span class="special">*</span>
<span class="identifier">test_1</span>
<span class="identifier">test_2</span><span class="special">*</span>
<span class="identifier">test_io</span><span class="special">*</span>
<span class="identifier">test_db</span>
</pre>
</td></tr></tbody>
</table></div>
<a name="ref_dynamic_test_dependency"></a><h4>
<a name="boost_test.runtime_config.test_unit_filtering.h2"></a>
<span class="phrase"><a name="boost_test.runtime_config.test_unit_filtering.dynamic_test_dependencies"></a></span><a class="link" href="test_unit_filtering.html#boost_test.runtime_config.test_unit_filtering.dynamic_test_dependencies">Dynamic
test dependencies</a>
</h4>
<p>
Additionally, it is possible to statically associate a test unit with a condition.
This associated condition is evaluated immediately before executing the test
unit. If the condition is met, the test unit is executed. Otherwise, the
test unit is <span class="emphasis"><em>skipped</em></span>. It is possible to add two dependencies:
</p>
<div class="orderedlist"><ol class="orderedlist" type="1">
<li class="listitem">
Upon another test unit. In this case the decorated test case is skipped
if the test unit specified in the dependency is either failed or skipped
or disabled. This can be declared with decorator <a class="link" href="../utf_reference/test_org_reference/decorator_depends_on.html" title="depends_on (decorator)"><code class="computeroutput"><span class="identifier">depends_on</span></code></a>.
</li>
<li class="listitem">
Upon an arbitrary predicate. This can be declared with decorator <a class="link" href="../utf_reference/test_org_reference/decorator_precondition.html" title="precondition (decorator)"><code class="computeroutput"><span class="identifier">precondition</span></code></a>.
</li>
</ol></div>
<a name="ref_command_line_control"></a><h4>
<a name="boost_test.runtime_config.test_unit_filtering.h3"></a>
<span class="phrase"><a name="boost_test.runtime_config.test_unit_filtering.command_line_control"></a></span><a class="link" href="test_unit_filtering.html#boost_test.runtime_config.test_unit_filtering.command_line_control">Command-line
control</a>
</h4>
<p>
Static configuration of the test-case filtering is used by default, unless
command-line filtering is applied. With command-line argument <a class="link" href="../utf_reference/rt_param_reference/run_test.html" title="run_test"><code class="computeroutput"><span class="identifier">run_test</span></code></a> it is possible to alter
the static pre-set in a number of ways:
</p>
<div class="orderedlist"><ol class="orderedlist" type="1">
<li class="listitem">
Ignore the static configuration and manually specify test cases to be
run.
</li>
<li class="listitem">
Augment the statically defined set by enabling the disabled test cases.
</li>
<li class="listitem">
Shrink the statically defined set by disabling some of the enabled test
cases.
</li>
</ol></div>
<a name="ref_command_line_control_absolute"></a><h5>
<a name="boost_test.runtime_config.test_unit_filtering.h4"></a>
<span class="phrase"><a name="boost_test.runtime_config.test_unit_filtering.absolute_specification"></a></span><a class="link" href="test_unit_filtering.html#boost_test.runtime_config.test_unit_filtering.absolute_specification">Absolute
specification</a>
</h5>
<p>
Term 'absolute' in this context means that the default run status of the
test units, which has been statically set up, is completely ignored and the
tests to be run are specified manually from scratch. First, in order to learn
what test units are registered in the test tree the user needs to use command-line
argument <a class="link" href="../utf_reference/rt_param_reference/list_content.html" title="list_content"><code class="computeroutput"><span class="identifier">list_content</span></code></a>. Next, in order to
specify a set of test cases, the user needs to use command-line argument
<a class="link" href="../utf_reference/rt_param_reference/run_test.html" title="run_test"><code class="computeroutput"><span class="identifier">run_test</span></code></a> with absolute value:
</p>
<pre class="programlisting"><span class="special">></span> <span class="identifier">test_program</span> <span class="special">--</span><a class="link" href="../utf_reference/rt_param_reference/run_test.html" title="run_test"><code class="computeroutput"><span class="identifier">run_test</span></code></a><span class="special">=<</span><span class="identifier">test_set</span><span class="special">></span>
</pre>
<p>
The format of <code class="computeroutput"><span class="special"><</span><span class="identifier">test_set</span><span class="special">></span></code> value can assume a number of forms. Given
the following program:
</p>
<pre class="programlisting"><span class="preprocessor">#define</span> <a class="link" href="../utf_reference/link_references/link_boost_test_module_macro.html" title="BOOST_TEST_MODULE"><code class="computeroutput"><span class="identifier">BOOST_TEST_MODULE</span></code></a> <span class="identifier">example</span>
<span class="preprocessor">#include</span> <span class="special"><</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">test</span><span class="special">/</span><span class="identifier">included</span><span class="special">/</span><span class="identifier">unit_test</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">></span>
<span class="keyword">using</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">unit_test</span><span class="special">::</span><a class="link" href="../utf_reference/test_org_reference/decorator_label.html" title="label (decorator)"><code class="computeroutput"><span class="identifier">label</span></code></a><span class="special">;</span>
<a class="link" href="../utf_reference/test_org_reference/test_org_boost_auto_test_case.html" title="BOOST_AUTO_TEST_CASE"><code class="computeroutput"><span class="identifier">BOOST_AUTO_TEST_CASE</span></code></a><span class="special">(</span><span class="identifier">test_1</span><span class="special">,</span> <span class="special">*</span><span class="identifier">label</span><span class="special">(</span><span class="string">"L1"</span><span class="special">))</span> <span class="special">{}</span>
<span class="identifier">BOOST_AUTO_TEST_CASE</span><span class="special">(</span><span class="identifier">test_2</span><span class="special">,</span> <span class="special">*</span><span class="identifier">label</span><span class="special">(</span><span class="string">"L1"</span><span class="special">))</span> <span class="special">{}</span>
<a class="link" href="../utf_reference/test_org_reference/test_org_boost_auto_test_suite.html" title="BOOST_AUTO_TEST_SUITE"><code class="computeroutput"><span class="identifier">BOOST_AUTO_TEST_SUITE</span></code></a><span class="special">(</span><span class="identifier">suite_1</span><span class="special">)</span>
<span class="identifier">BOOST_AUTO_TEST_SUITE</span><span class="special">(</span><span class="identifier">suite_1</span><span class="special">)</span>
<span class="identifier">BOOST_AUTO_TEST_CASE</span><span class="special">(</span><span class="identifier">test_1</span><span class="special">)</span> <span class="special">{}</span>
<span class="identifier">BOOST_AUTO_TEST_CASE</span><span class="special">(</span><span class="identifier">test_2</span><span class="special">)</span> <span class="special">{}</span>
<span class="identifier">BOOST_AUTO_TEST_SUITE_END</span><span class="special">()</span>
<span class="identifier">BOOST_AUTO_TEST_SUITE</span><span class="special">(</span><span class="identifier">suite_2</span><span class="special">)</span>
<span class="identifier">BOOST_AUTO_TEST_CASE</span><span class="special">(</span><span class="identifier">test_1</span><span class="special">,</span> <span class="special">*</span><span class="identifier">label</span><span class="special">(</span><span class="string">"L2"</span><span class="special">))</span> <span class="special">{}</span>
<span class="identifier">BOOST_AUTO_TEST_CASE</span><span class="special">(</span><span class="identifier">test_2</span><span class="special">,</span> <span class="special">*</span><span class="identifier">label</span><span class="special">(</span><span class="string">"L2"</span><span class="special">))</span> <span class="special">{}</span>
<span class="identifier">BOOST_AUTO_TEST_SUITE_END</span><span class="special">()</span>
<span class="identifier">BOOST_AUTO_TEST_CASE</span><span class="special">(</span><span class="identifier">test_1</span><span class="special">,</span> <span class="special">*</span><span class="identifier">label</span><span class="special">(</span><span class="string">"L1"</span><span class="special">))</span> <span class="special">{}</span>
<span class="identifier">BOOST_AUTO_TEST_CASE</span><span class="special">(</span><span class="identifier">test_2</span><span class="special">)</span> <span class="special">{}</span>
<span class="identifier">BOOST_AUTO_TEST_CASE</span><span class="special">(</span><span class="identifier">test_2A</span><span class="special">)</span> <span class="special">{}</span>
<span class="identifier">BOOST_AUTO_TEST_SUITE_END</span><span class="special">()</span>
</pre>
<p>
The following table illustrates how different values of <code class="computeroutput"><span class="special"><</span><span class="identifier">test_set</span><span class="special">></span></code>
control which test cases ware run.
</p>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Description
</p>
</th>
<th>
<p>
Parameter value
</p>
</th>
<th>
<p>
Test cases run
</p>
</th>
</tr></thead>
<tbody>
<tr>
<td>
<p>
Run single top-level test case by name
</p>
</td>
<td>
<pre xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="table-programlisting"><a class="link" href="../utf_reference/rt_param_reference/run_test.html" title="run_test"><code class="computeroutput"><span class="identifier">run_test</span></code></a>=test_1</pre>
</td>
<td>
<pre xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="table-programlisting">test_1
</pre>
</td>
</tr>
<tr>
<td>
<p>
Run single nested test case by name
</p>
</td>
<td>
<pre xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="table-programlisting"><a class="link" href="../utf_reference/rt_param_reference/run_test.html" title="run_test"><code class="computeroutput"><span class="identifier">run_test</span></code></a>=suite_1/suite_1/test_1</pre>
</td>
<td>
<pre xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="table-programlisting">suite_1/suite_1/test_1
</pre>
</td>
</tr>
<tr>
<td>
<p>
Run single test suite by name
</p>
</td>
<td>
<pre xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="table-programlisting"><a class="link" href="../utf_reference/rt_param_reference/run_test.html" title="run_test"><code class="computeroutput"><span class="identifier">run_test</span></code></a>=suite_1/suite_2
<a class="link" href="../utf_reference/rt_param_reference/run_test.html" title="run_test"><code class="computeroutput"><span class="identifier">run_test</span></code></a>=suite_1/suite_2/*
</pre>
</td>
<td>
<pre xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="table-programlisting">suite_1/suite_2/test_1
suite_1/suite_2/test_2
</pre>
</td>
</tr>
<tr>
<td>
<p>
Run multiple test units residing in the same test suite
</p>
</td>
<td>
<pre xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="table-programlisting"><a class="link" href="../utf_reference/rt_param_reference/run_test.html" title="run_test"><code class="computeroutput"><span class="identifier">run_test</span></code></a>=suite_1/test_1,suite_2</pre>
</td>
<td>
<pre xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="table-programlisting">suite_1/suite_2/test_1
suite_1/suite_2/test_2
suite_1/test_1
</pre>
</td>
</tr>
<tr>
<td>
<p>
Run all tests matching to a given label
</p>
</td>
<td>
<pre xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="table-programlisting"><a class="link" href="../utf_reference/rt_param_reference/run_test.html" title="run_test"><code class="computeroutput"><span class="identifier">run_test</span></code></a>=@L1</pre>
</td>
<td>
<pre xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="table-programlisting">test_1
test_2
suite_1/test_1
</pre>
</td>
</tr>
<tr>
<td>
<p>
Run every test case in the test tree
</p>
</td>
<td>
<pre xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="table-programlisting"><a class="link" href="../utf_reference/rt_param_reference/run_test.html" title="run_test"><code class="computeroutput"><span class="identifier">run_test</span></code></a>=*</pre>
</td>
<td>
<pre xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="table-programlisting">test_1
test_2
suite_1/suite_1/test_1
suite_1/suite_1/test_2
suite_1/suite_2/test_1
suite_1/suite_2/test_2
suite_1/test_1
suite_1/test_2
suite_1/test_2A
</pre>
</td>
</tr>
<tr>
<td>
<p>
Run every test unit in a given suite with a given prefix
</p>
</td>
<td>
<pre xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="table-programlisting"><a class="link" href="../utf_reference/rt_param_reference/run_test.html" title="run_test"><code class="computeroutput"><span class="identifier">run_test</span></code></a>=suite_1/test*</pre>
</td>
<td>
<pre xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="table-programlisting">suite_1/test_1
suite_1/test_2
suite_1/test_2A
</pre>
</td>
</tr>
<tr>
<td>
<p>
Run every test unit in a given suite with a given suffix
</p>
</td>
<td>
<pre xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="table-programlisting"><a class="link" href="../utf_reference/rt_param_reference/run_test.html" title="run_test"><code class="computeroutput"><span class="identifier">run_test</span></code></a>=suite_1/*_1</pre>
</td>
<td>
<pre xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="table-programlisting">suite_1/suite_1/test_1
suite_1/suite_1/test_2
suite_1/test_1
</pre>
</td>
</tr>
<tr>
<td>
<p>
Run every test unit in a given suite with a given infix
</p>
</td>
<td>
<pre xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="table-programlisting"><a class="link" href="../utf_reference/rt_param_reference/run_test.html" title="run_test"><code class="computeroutput"><span class="identifier">run_test</span></code></a>=suite_1/*_2*</pre>
</td>
<td>
<pre xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="table-programlisting">suite_1/suite_2/test_1
suite_1/suite_2/test_2
suite_1/test_2
suite_1/test_2A
</pre>
</td>
</tr>
<tr>
<td>
<p>
Run test(s) with given name in any N-level suite
</p>
</td>
<td>
<pre xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="table-programlisting"><a class="link" href="../utf_reference/rt_param_reference/run_test.html" title="run_test"><code class="computeroutput"><span class="identifier">run_test</span></code></a>=*/*/test_2</pre>
</td>
<td>
<pre xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="table-programlisting">suite_1/suite_1/test_2
suite_1/suite_2/test_2
</pre>
</td>
</tr>
</tbody>
</table></div>
<p>
For the syntax productions describing the structure of <code class="computeroutput"><span class="special"><</span><span class="identifier">test_set</span><span class="special">></span></code>
value see <a class="link" href="../utf_reference/rt_param_reference/run_test.html" title="run_test">here</a>.
</p>
<p>
While using manual absolute test case specification ignores the default run
status, it does not ignore the dynamic test dependencies. If test unit <code class="computeroutput"><span class="identifier">B</span></code> depends on test unit <code class="computeroutput"><span class="identifier">A</span></code>
and test <code class="computeroutput"><span class="identifier">B</span></code> is specified to
be run by <a class="link" href="../utf_reference/rt_param_reference/run_test.html" title="run_test"><code class="computeroutput"><span class="identifier">run_test</span></code></a>, <code class="computeroutput"><span class="identifier">A</span></code>
is also run, even if it is not specified, and its failure may cause the execution
of <code class="computeroutput"><span class="identifier">B</span></code> to be skipped. Similarly,
the failed check of the <a class="link" href="../utf_reference/test_org_reference/decorator_precondition.html" title="precondition (decorator)"><code class="computeroutput"><span class="identifier">precondition</span></code></a> may cause the test
selected test to be skipped.
</p>
<h6>
<a name="boost_test.runtime_config.test_unit_filtering.h5"></a>
<span class="phrase"><a name="boost_test.runtime_config.test_unit_filtering.example_descr0"></a></span><a class="link" href="test_unit_filtering.html#boost_test.runtime_config.test_unit_filtering.example_descr0">Example:
run_test and dynamic dependencies</a>
</h6>
<div class="informaltable"><table class="table">
<colgroup><col></colgroup>
<thead><tr><th>
<p>
Code
</p>
</th></tr></thead>
<tbody><tr><td>
<pre xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="table-programlisting"><span class="preprocessor">#define</span> <span class="identifier">BOOST_TEST_MODULE</span> <span class="identifier">decorator_21</span>
<span class="preprocessor">#include</span> <span class="special"><</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">test</span><span class="special">/</span><span class="identifier">included</span><span class="special">/</span><span class="identifier">unit_test</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">></span>
<span class="keyword">namespace</span> <span class="identifier">utf</span> <span class="special">=</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">unit_test</span><span class="special">;</span>
<span class="keyword">namespace</span> <span class="identifier">tt</span> <span class="special">=</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">test_tools</span><span class="special">;</span>
<span class="identifier">tt</span><span class="special">::</span><span class="identifier">assertion_result</span> <span class="identifier">fail</span><span class="special">(</span><span class="identifier">utf</span><span class="special">::</span><span class="identifier">test_unit_id</span><span class="special">)</span>
<span class="special">{</span>
<span class="identifier">tt</span><span class="special">::</span><span class="identifier">assertion_result</span> <span class="identifier">ans</span><span class="special">(</span><span class="keyword">false</span><span class="special">);</span>
<span class="identifier">ans</span><span class="special">.</span><span class="identifier">message</span><span class="special">()</span> <span class="special"><<</span> <span class="string">"precondition failed"</span><span class="special">;</span>
<span class="keyword">return</span> <span class="identifier">ans</span><span class="special">;</span>
<span class="special">}</span>
<span class="identifier">BOOST_AUTO_TEST_CASE</span><span class="special">(</span><span class="identifier">test_1</span><span class="special">)</span>
<span class="special">{</span>
<span class="identifier">BOOST_TEST</span><span class="special">(</span><span class="keyword">false</span><span class="special">);</span>
<span class="special">}</span>
<span class="identifier">BOOST_AUTO_TEST_CASE</span><span class="special">(</span><span class="identifier">test_2</span><span class="special">,</span>
<span class="special">*</span> <span class="identifier">utf</span><span class="special">::</span><span class="identifier">depends_on</span><span class="special">(</span><span class="string">"test_1"</span><span class="special">))</span>
<span class="special">{</span>
<span class="identifier">BOOST_TEST</span><span class="special">(</span><span class="keyword">true</span><span class="special">);</span>
<span class="special">}</span>
<span class="identifier">BOOST_AUTO_TEST_CASE</span><span class="special">(</span><span class="identifier">test_3</span><span class="special">,</span>
<span class="special">*</span> <span class="identifier">utf</span><span class="special">::</span><span class="identifier">precondition</span><span class="special">(</span><span class="identifier">fail</span><span class="special">))</span>
<span class="special">{</span>
<span class="identifier">BOOST_TEST</span><span class="special">(</span><span class="keyword">true</span><span class="special">);</span>
<span class="special">}</span>
</pre>
</td></tr></tbody>
</table></div>
<div class="informaltable"><table class="table">
<colgroup><col></colgroup>
<thead><tr><th>
<p>
Output
</p>
</th></tr></thead>
<tbody><tr><td>
<pre xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="table-programlisting"><span class="special">></span> <span class="identifier">decorator_21</span> <span class="special">--</span><span class="identifier">log_level</span><span class="special">=</span><span class="identifier">test_suite</span> <span class="special">--</span><span class="identifier">run_test</span><span class="special">=</span><span class="identifier">test_2</span><span class="special">,</span><span class="identifier">test_3</span>
<span class="identifier">Including</span> <span class="identifier">test</span> <span class="keyword">case</span> <span class="identifier">test_1</span> <span class="identifier">as</span> <span class="identifier">a</span> <span class="identifier">dependency</span> <span class="identifier">of</span> <span class="identifier">test</span> <span class="keyword">case</span> <span class="identifier">test_2</span>
<span class="identifier">Running</span> <span class="number">3</span> <span class="identifier">test</span> <span class="identifier">cases</span><span class="special">...</span>
<span class="identifier">Entering</span> <span class="identifier">test</span> <span class="identifier">module</span> <span class="string">"decorator_21"</span>
<span class="identifier">test</span><span class="special">.</span><span class="identifier">cpp</span><span class="special">(</span><span class="number">14</span><span class="special">):</span> <span class="identifier">Entering</span> <span class="identifier">test</span> <span class="keyword">case</span> <span class="string">"test_1"</span>
<span class="identifier">test</span><span class="special">.</span><span class="identifier">cpp</span><span class="special">(</span><span class="number">16</span><span class="special">):</span> <span class="identifier">error</span><span class="special">:</span> <span class="identifier">in</span> <span class="string">"test_1"</span><span class="special">:</span> <span class="identifier">check</span> <span class="keyword">false</span> <span class="identifier">has</span> <span class="identifier">failed</span>
<span class="identifier">test</span><span class="special">.</span><span class="identifier">cpp</span><span class="special">(</span><span class="number">14</span><span class="special">):</span> <span class="identifier">Leaving</span> <span class="identifier">test</span> <span class="keyword">case</span> <span class="string">"test_1"</span><span class="special">;</span> <span class="identifier">testing</span> <span class="identifier">time</span><span class="special">:</span> <span class="number">3</span><span class="identifier">ms</span>
<span class="identifier">test</span><span class="special">.</span><span class="identifier">cpp</span><span class="special">(</span><span class="number">26</span><span class="special">):</span> <span class="identifier">Test</span> <span class="keyword">case</span> <span class="string">"test_3"</span> <span class="identifier">is</span> <span class="identifier">skipped</span> <span class="identifier">because</span> <span class="identifier">precondition</span> <span class="identifier">failed</span>
<span class="identifier">test</span><span class="special">.</span><span class="identifier">cpp</span><span class="special">(</span><span class="number">20</span><span class="special">):</span> <span class="identifier">Test</span> <span class="keyword">case</span> <span class="string">"test_2"</span> <span class="identifier">is</span> <span class="identifier">skipped</span> <span class="identifier">because</span> <span class="identifier">dependency</span> <span class="identifier">test</span> <span class="keyword">case</span> <span class="string">"test_1"</span> <span class="identifier">has</span> <span class="identifier">failed</span>
<span class="identifier">Leaving</span> <span class="identifier">test</span> <span class="identifier">module</span> <span class="string">"decorator_21"</span><span class="special">;</span> <span class="identifier">testing</span> <span class="identifier">time</span><span class="special">:</span> <span class="number">17</span><span class="identifier">ms</span>
<span class="special">***</span> <span class="number">1</span> <span class="identifier">failure</span> <span class="identifier">is</span> <span class="identifier">detected</span> <span class="identifier">in</span> <span class="identifier">the</span> <span class="identifier">test</span> <span class="identifier">module</span> <span class="string">"decorator_21"</span>
</pre>
</td></tr></tbody>
</table></div>
<a name="ref_command_line_control_enablers"></a><h5>
<a name="boost_test.runtime_config.test_unit_filtering.h6"></a>
<span class="phrase"><a name="boost_test.runtime_config.test_unit_filtering.relative_specification"></a></span><a class="link" href="test_unit_filtering.html#boost_test.runtime_config.test_unit_filtering.relative_specification">Relative
specification</a>
</h5>
<p>
Term 'relative' in this context means that the configuration is based on
either the default run status of the test units or by the command-line override
specified by the <span class="emphasis"><em>absolute specification</em></span>; and atop of
this, we additionally either enable some disabled test units or disable some
enabled tests units. The relative specification is controlled by command-line
argument <a class="link" href="../utf_reference/rt_param_reference/run_test.html" title="run_test"><code class="computeroutput"><span class="identifier">run_test</span></code></a>, with the value using similar
syntax as in the absolute specification, but preceded with either character
<code class="computeroutput"><span class="char">'!'</span></code> for disabling enabled test
units or with character <code class="computeroutput"><span class="char">'+'</span></code> for
enabling the disabled test units. this can be summarized with the following
table:
</p>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
command
</p>
</th>
<th>
<p>
specification type
</p>
</th>
<th>
<p>
semantics
</p>
</th>
</tr></thead>
<tbody>
<tr>
<td>
<pre xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="table-programlisting">> test_program --<a class="link" href="../utf_reference/rt_param_reference/run_test.html" title="run_test"><code class="computeroutput"><span class="identifier">run_test</span></code></a>=!<absolute_spec></pre>
</td>
<td>
<p>
disabler
</p>
</td>
<td>
<p>
Enabled test units that match <code class="computeroutput"><span class="special"><</span><span class="identifier">absolute_spec</span><span class="special">></span></code>
become disabled.
</p>
</td>
</tr>
<tr>
<td>
<pre xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="table-programlisting">> test_program --<a class="link" href="../utf_reference/rt_param_reference/run_test.html" title="run_test"><code class="computeroutput"><span class="identifier">run_test</span></code></a>=+<absolute_spec></pre>
</td>
<td>
<p>
enabler
</p>
</td>
<td>
<p>
Disabled test units that match <code class="computeroutput"><span class="special"><</span><span class="identifier">absolute_spec</span><span class="special">></span></code>
as well as their upstream dependencies become enabled.
</p>
</td>
</tr>
</tbody>
</table></div>
<p>
The <span class="emphasis"><em>enabler</em></span> specification is used to enable a set of
test units which are initially disabled.
</p>
<h6>
<a name="boost_test.runtime_config.test_unit_filtering.h7"></a>
<span class="phrase"><a name="boost_test.runtime_config.test_unit_filtering.example_descr1"></a></span><a class="link" href="test_unit_filtering.html#boost_test.runtime_config.test_unit_filtering.example_descr1">Example:
command-line enabler</a>
</h6>
<div class="informaltable"><table class="table">
<colgroup><col></colgroup>
<thead><tr><th>
<p>
Code
</p>
</th></tr></thead>
<tbody><tr><td>
<pre xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="table-programlisting"><span class="preprocessor">#define</span> <span class="identifier">BOOST_TEST_MODULE</span> <span class="identifier">decorator_22</span>
<span class="preprocessor">#include</span> <span class="special"><</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">test</span><span class="special">/</span><span class="identifier">included</span><span class="special">/</span><span class="identifier">unit_test</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">></span>
<span class="keyword">namespace</span> <span class="identifier">utf</span> <span class="special">=</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">unit_test</span><span class="special">;</span>
<span class="identifier">BOOST_AUTO_TEST_CASE</span><span class="special">(</span><span class="identifier">test_1</span><span class="special">)</span>
<span class="special">{</span>
<span class="identifier">BOOST_TEST</span><span class="special">(</span><span class="keyword">true</span><span class="special">);</span>
<span class="special">}</span>
<span class="identifier">BOOST_AUTO_TEST_CASE</span><span class="special">(</span><span class="identifier">test_net</span><span class="special">,</span>
<span class="special">*</span> <span class="identifier">utf</span><span class="special">::</span><span class="identifier">disabled</span><span class="special">()</span>
<span class="special">*</span> <span class="identifier">utf</span><span class="special">::</span><span class="identifier">description</span><span class="special">(</span><span class="string">"requires network"</span><span class="special">))</span>
<span class="special">{</span>
<span class="identifier">BOOST_TEST</span><span class="special">(</span><span class="keyword">true</span><span class="special">);</span>
<span class="special">}</span>
</pre>
</td></tr></tbody>
</table></div>
<div class="informaltable"><table class="table">
<colgroup><col></colgroup>
<thead><tr><th>
<p>
Output
</p>
</th></tr></thead>
<tbody><tr><td>
<pre xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="table-programlisting"><span class="special">></span> <span class="identifier">decorator_22</span> <span class="special">--</span><span class="identifier">list_content</span>
<span class="identifier">test_1</span><span class="special">*</span>
<span class="identifier">test_net</span> <span class="special">:</span> <span class="identifier">requires</span> <span class="identifier">network</span>
<span class="special">></span> <span class="identifier">decorator_22</span> <span class="special">--</span><span class="identifier">log_level</span><span class="special">=</span><span class="identifier">test_suite</span>
<span class="identifier">Running</span> <span class="number">1</span> <span class="identifier">test</span> <span class="keyword">case</span><span class="special">...</span>
<span class="identifier">Entering</span> <span class="identifier">test</span> <span class="identifier">module</span> <span class="string">"decorator_22"</span>
<span class="identifier">test</span><span class="special">.</span><span class="identifier">cpp</span><span class="special">(</span><span class="number">6</span><span class="special">):</span> <span class="identifier">Entering</span> <span class="identifier">test</span> <span class="keyword">case</span> <span class="string">"test_1"</span>
<span class="identifier">test</span><span class="special">.</span><span class="identifier">cpp</span><span class="special">(</span><span class="number">6</span><span class="special">):</span> <span class="identifier">Leaving</span> <span class="identifier">test</span> <span class="keyword">case</span> <span class="string">"test_1"</span>
<span class="identifier">Leaving</span> <span class="identifier">test</span> <span class="identifier">module</span> <span class="string">"decorator_22"</span><span class="special">;</span> <span class="identifier">testing</span> <span class="identifier">time</span><span class="special">:</span> <span class="number">5</span><span class="identifier">ms</span>
<span class="special">***</span> <span class="identifier">No</span> <span class="identifier">errors</span> <span class="identifier">detected</span>
<span class="special">></span> <span class="identifier">decorator_22</span> <span class="special">--</span><span class="identifier">log_level</span><span class="special">=</span><span class="identifier">test_suite</span> <span class="special">--</span><span class="identifier">run_test</span><span class="special">=+</span><span class="identifier">test_net</span>
<span class="identifier">Running</span> <span class="number">2</span> <span class="identifier">test</span> <span class="identifier">cases</span><span class="special">...</span>
<span class="identifier">Entering</span> <span class="identifier">test</span> <span class="identifier">module</span> <span class="string">"decorator_22"</span>
<span class="identifier">test</span><span class="special">.</span><span class="identifier">cpp</span><span class="special">(</span><span class="number">6</span><span class="special">):</span> <span class="identifier">Entering</span> <span class="identifier">test</span> <span class="keyword">case</span> <span class="string">"test_1"</span>
<span class="identifier">test</span><span class="special">.</span><span class="identifier">cpp</span><span class="special">(</span><span class="number">6</span><span class="special">):</span> <span class="identifier">Leaving</span> <span class="identifier">test</span> <span class="keyword">case</span> <span class="string">"test_1"</span><span class="special">;</span> <span class="identifier">testing</span> <span class="identifier">time</span><span class="special">:</span> <span class="number">1</span><span class="identifier">ms</span>
<span class="identifier">test</span><span class="special">.</span><span class="identifier">cpp</span><span class="special">(</span><span class="number">13</span><span class="special">):</span> <span class="identifier">Entering</span> <span class="identifier">test</span> <span class="keyword">case</span> <span class="string">"test_net"</span>
<span class="identifier">test</span><span class="special">.</span><span class="identifier">cpp</span><span class="special">(</span><span class="number">13</span><span class="special">):</span> <span class="identifier">Leaving</span> <span class="identifier">test</span> <span class="keyword">case</span> <span class="string">"test_net"</span><span class="special">;</span> <span class="identifier">testing</span> <span class="identifier">time</span><span class="special">:</span> <span class="number">1</span><span class="identifier">ms</span>
<span class="identifier">Leaving</span> <span class="identifier">test</span> <span class="identifier">module</span> <span class="string">"decorator_22"</span><span class="special">;</span> <span class="identifier">testing</span> <span class="identifier">time</span><span class="special">:</span> <span class="number">16</span><span class="identifier">ms</span>
<span class="special">***</span> <span class="identifier">No</span> <span class="identifier">errors</span> <span class="identifier">detected</span>
</pre>
</td></tr></tbody>
</table></div>
<p>
Conversely, the <span class="emphasis"><em>disabler</em></span> specification is used to disable
a set of test units which are initially enabled.
</p>
<h6>
<a name="boost_test.runtime_config.test_unit_filtering.h8"></a>
<span class="phrase"><a name="boost_test.runtime_config.test_unit_filtering.example_descr2"></a></span><a class="link" href="test_unit_filtering.html#boost_test.runtime_config.test_unit_filtering.example_descr2">Example:
command-line disabler</a>
</h6>
<div class="informaltable"><table class="table">
<colgroup><col></colgroup>
<thead><tr><th>
<p>
Code
</p>
</th></tr></thead>
<tbody><tr><td>
<pre xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="table-programlisting"><span class="preprocessor">#define</span> <span class="identifier">BOOST_TEST_MODULE</span> <span class="identifier">decorator_23</span>
<span class="preprocessor">#include</span> <span class="special"><</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">test</span><span class="special">/</span><span class="identifier">included</span><span class="special">/</span><span class="identifier">unit_test</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">></span>
<span class="keyword">namespace</span> <span class="identifier">utf</span> <span class="special">=</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">unit_test</span><span class="special">;</span>
<span class="identifier">BOOST_AUTO_TEST_CASE</span><span class="special">(</span><span class="identifier">test_1</span><span class="special">)</span>
<span class="special">{</span>
<span class="identifier">BOOST_TEST</span><span class="special">(</span><span class="keyword">true</span><span class="special">);</span>
<span class="special">}</span>
<span class="identifier">BOOST_AUTO_TEST_CASE</span><span class="special">(</span><span class="identifier">test_net</span><span class="special">,</span>
<span class="special">*</span> <span class="identifier">utf</span><span class="special">::</span><span class="identifier">description</span><span class="special">(</span><span class="string">"requires network"</span><span class="special">))</span>
<span class="special">{</span>
<span class="identifier">BOOST_TEST</span><span class="special">(</span><span class="keyword">true</span><span class="special">);</span>
<span class="special">}</span>
</pre>
</td></tr></tbody>
</table></div>
<div class="informaltable"><table class="table">
<colgroup><col></colgroup>
<thead><tr><th>
<p>
Output
</p>
</th></tr></thead>
<tbody><tr><td>
<pre xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="table-programlisting"><span class="special">></span> <span class="identifier">decorator_23</span> <span class="special">--</span><span class="identifier">list_content</span>
<span class="identifier">test_1</span><span class="special">*</span>
<span class="identifier">test_net</span><span class="special">*:</span> <span class="identifier">requires</span> <span class="identifier">network</span>
<span class="special">></span> <span class="identifier">decorator_23</span> <span class="special">--</span><span class="identifier">log_level</span><span class="special">=</span><span class="identifier">test_suite</span>
<span class="identifier">Running</span> <span class="number">2</span> <span class="identifier">test</span> <span class="identifier">cases</span><span class="special">...</span>
<span class="identifier">Entering</span> <span class="identifier">test</span> <span class="identifier">module</span> <span class="string">"decorator_23"</span>
<span class="identifier">test</span><span class="special">.</span><span class="identifier">cpp</span><span class="special">(</span><span class="number">6</span><span class="special">):</span> <span class="identifier">Entering</span> <span class="identifier">test</span> <span class="keyword">case</span> <span class="string">"test_1"</span>
<span class="identifier">test</span><span class="special">.</span><span class="identifier">cpp</span><span class="special">(</span><span class="number">6</span><span class="special">):</span> <span class="identifier">Leaving</span> <span class="identifier">test</span> <span class="keyword">case</span> <span class="string">"test_1"</span>
<span class="identifier">test</span><span class="special">.</span><span class="identifier">cpp</span><span class="special">(</span><span class="number">12</span><span class="special">):</span> <span class="identifier">Entering</span> <span class="identifier">test</span> <span class="keyword">case</span> <span class="string">"test_net"</span>
<span class="identifier">test</span><span class="special">.</span><span class="identifier">cpp</span><span class="special">(</span><span class="number">12</span><span class="special">):</span> <span class="identifier">Leaving</span> <span class="identifier">test</span> <span class="keyword">case</span> <span class="string">"test_net"</span>
<span class="identifier">Leaving</span> <span class="identifier">test</span> <span class="identifier">module</span> <span class="string">"decorator_23"</span><span class="special">;</span> <span class="identifier">testing</span> <span class="identifier">time</span><span class="special">:</span> <span class="number">14</span><span class="identifier">ms</span>
<span class="special">***</span> <span class="identifier">No</span> <span class="identifier">errors</span> <span class="identifier">detected</span>
<span class="special">></span> <span class="identifier">decorator_23</span> <span class="special">--</span><span class="identifier">log_level</span><span class="special">=</span><span class="identifier">test_suite</span> <span class="special">--</span><span class="identifier">run_test</span><span class="special">=!</span><span class="identifier">test_net</span>
<span class="identifier">Running</span> <span class="number">1</span> <span class="identifier">test</span> <span class="keyword">case</span><span class="special">...</span>
<span class="identifier">Entering</span> <span class="identifier">test</span> <span class="identifier">module</span> <span class="string">"decorator_23"</span>
<span class="identifier">test</span><span class="special">.</span><span class="identifier">cpp</span><span class="special">(</span><span class="number">6</span><span class="special">):</span> <span class="identifier">Entering</span> <span class="identifier">test</span> <span class="keyword">case</span> <span class="string">"test_1"</span>
<span class="identifier">test</span><span class="special">.</span><span class="identifier">cpp</span><span class="special">(</span><span class="number">6</span><span class="special">):</span> <span class="identifier">Leaving</span> <span class="identifier">test</span> <span class="keyword">case</span> <span class="string">"test_1"</span>
<span class="identifier">Leaving</span> <span class="identifier">test</span> <span class="identifier">module</span> <span class="string">"decorator_23"</span><span class="special">;</span> <span class="identifier">testing</span> <span class="identifier">time</span><span class="special">:</span> <span class="number">5</span><span class="identifier">ms</span>
</pre>
</td></tr></tbody>
</table></div>
<p>
If there are both an enabler and disabler on one command line that specify
the same test, the test becomes disabled. I.e., the disabler takes the precedence
over the enabler.
</p>
<div class="note"><table border="0" summary="Note">
<tr>
<td rowspan="2" align="center" valign="top" width="25"><img alt="[Note]" src="../../../../../../doc/src/images/note.png"></td>
<th align="left">Note</th>
</tr>
<tr><td align="left" valign="top"><p>
While enabler additionally enables the upstream dependencies (introduced
with decorator <a class="link" href="../utf_reference/test_org_reference/decorator_depends_on.html" title="depends_on (decorator)"><code class="computeroutput"><span class="identifier">depends_on</span></code></a>), disabler does not
disable them. Therefore when you enable and then disable the same test,
you do not disable its upstream dependencies.
</p></td></tr>
</table></div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2001-2015 Boost.Test team<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../runtime_config.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../runtime_config.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="summary.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| Java |
using OfficeDevPnP.MSGraphAPIDemo.Components;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using OfficeDevPnP.MSGraphAPIDemo.Models;
using System.Threading;
namespace OfficeDevPnP.MSGraphAPIDemo.Controllers
{
public class FilesController : Controller
{
// GET: Files
public ActionResult Index()
{
return View();
}
public ActionResult PlayWithFiles()
{
var drive = FilesHelper.GetUserPersonalDrive();
var root = FilesHelper.GetUserPersonalDriveRoot();
var childrenItems = FilesHelper.ListFolderChildren(drive.Id, root.Id);
var newFileOnRoot = UploadSampleFile(drive, root, Server.MapPath("~/AppIcon.png"));
// Collect information about children items in the root folder
StringBuilder sb = new StringBuilder();
String oneFolderId = null;
foreach (var item in childrenItems)
{
if (item.Folder != null)
{
sb.AppendFormat("Found folder {0} with {1} child items.\n", item.Name, item.Folder.ChildCount);
if (item.Name == "One Folder")
{
oneFolderId = item.Id;
}
}
else
{
sb.AppendFormat("Found file {0}.\n", item.Name);
}
}
var filesLog = sb.ToString();
// Create a new folder in the root folder
var newFolder = FilesHelper.CreateFolder(drive.Id, root.Id,
new Models.DriveItem
{
Name = $"Folder Created via API - {DateTime.Now.GetHashCode()}",
Folder = new Models.Folder { },
});
var newFile = UploadSampleFile(drive, newFolder, Server.MapPath("~/AppIcon.png"));
UpdateSampleFile(drive, newFile, Server.MapPath("~/SP2016-MinRoles.jpg"));
// Create another folder in the root folder
var anotherFolder = FilesHelper.CreateFolder(drive.Id, root.Id,
new Models.DriveItem
{
Name = $"Folder Created via API - {DateTime.Now.GetHashCode()}",
Folder = new Models.Folder { },
});
var movedItem = FilesHelper.MoveDriveItem(drive.Id, newFile.Id, "moved.jpg", anotherFolder.Name);
var movedFolder = FilesHelper.MoveDriveItem(drive.Id, anotherFolder.Id, "Moved Folder", newFolder.Name);
var searchResult = FilesHelper.Search("PnPLogo", drive.Id, root.Id);
if (searchResult != null && searchResult.Count > 0)
{
var firstFileResult = searchResult.FirstOrDefault(i => i.File != null);
try
{
var thumbnails = FilesHelper.GetFileThumbnails(drive.Id, firstFileResult.Id);
var thumbnailMedium = FilesHelper.GetFileThumbnail(drive.Id, firstFileResult.Id, Models.ThumbnailSize.Medium);
var thumbnailImage = FilesHelper.GetFileThumbnailImage(drive.Id, firstFileResult.Id, Models.ThumbnailSize.Medium);
}
catch (Exception)
{
// Something wrong while getting the thumbnail,
// We will have to handle it properly ...
}
}
if (newFileOnRoot != null)
{
var permission = FilesHelper.GetDriveItemPermission(newFileOnRoot.Id, "0");
FilesHelper.DeleteFile(drive.Id, newFileOnRoot.Id);
}
try
{
var sharingPermission = FilesHelper.CreateSharingLink(newFolder.Id,
SharingLinkType.View, SharingLinkScope.Anonymous);
}
catch (Exception)
{
// Something wrong while getting the sharing link,
// We will have to handle it properly ...
}
if (!String.IsNullOrEmpty(oneFolderId))
{
var newFolderChildren = FilesHelper.ListFolderChildren(drive.Id, newFolder.Id);
var file = newFolderChildren.FirstOrDefault(f => f.Name == "moved.jpg");
if (file != null)
{
String jpegContentType = "image/jpeg";
Stream fileContent = FilesHelper.GetFileContent(drive.Id, file.Id, jpegContentType);
return (base.File(fileContent, jpegContentType, file.Name));
}
}
return View("Index");
}
private Models.DriveItem UploadSampleFile(Models.Drive drive, Models.DriveItem newFolder, String filePath)
{
Models.DriveItem result = null;
Stream memPhoto = getFileContent(filePath);
try
{
if (memPhoto.Length > 0)
{
String contentType = "image/png";
result = FilesHelper.UploadFile(drive.Id, newFolder.Id,
new Models.DriveItem
{
File = new Models.File { },
Name = "PnPLogo.png",
ConflictBehavior = "rename",
},
memPhoto,
contentType);
}
}
catch (Exception ex)
{
// Handle the exception
}
return (result);
}
private void UpdateSampleFile(Drive drive, DriveItem newFile, String filePath)
{
FilesHelper.RenameFile(drive.Id, newFile.Id, "SP2016-MinRoles.jpg");
Stream memPhoto = getFileContent(filePath);
try
{
if (memPhoto.Length > 0)
{
String contentType = "image/jpeg";
FilesHelper.UpdateFileContent(
drive.Id,
newFile.Id,
memPhoto,
contentType);
}
}
catch (Exception ex)
{
// Handle the exception
}
}
private static Stream getFileContent(String filePath)
{
MemoryStream memPhoto = new MemoryStream();
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
Byte[] newPhoto = new Byte[fs.Length];
fs.Read(newPhoto, 0, (Int32)(fs.Length - 1));
memPhoto.Write(newPhoto, 0, newPhoto.Length);
memPhoto.Position = 0;
}
return memPhoto;
}
}
} | Java |
/* @flow */
/*eslint-disable no-undef, no-unused-vars, no-console*/
import _, {
compose,
pipe,
curry,
filter,
find,
isNil,
repeat,
replace,
zipWith
} from "ramda";
import { describe, it } from 'flow-typed-test';
const ns: Array<number> = [1, 2, 3, 4, 5];
const ss: Array<string> = ["one", "two", "three", "four"];
const obj: { [k: string]: number } = { a: 1, c: 2 };
const objMixed: { [k: string]: mixed } = { a: 1, c: "d" };
const os: Array<{ [k: string]: * }> = [{ a: 1, c: "d" }, { b: 2 }];
const str: string = "hello world";
// Math
{
const partDiv: (a: number) => number = _.divide(6);
const div: number = _.divide(6, 2);
//$FlowExpectedError
const div2: number = _.divide(6, true);
}
// String
{
const ss: Array<string | void> = _.match(/h/, "b");
describe('replace', () => {
it('should supports replace by string', () => {
const r1: string = replace(",", "|", "b,d,d");
const r2: string = replace(",")("|", "b,d,d");
const r3: string = replace(",")("|")("b,d,d");
const r4: string = replace(",", "|")("b,d,d");
});
it('should supports replace by RegExp', () => {
const r1: string = replace(/[,]/, "|", "b,d,d");
const r2: string = replace(/[,]/)("|", "b,d,d");
const r3: string = replace(/[,]/)("|")("b,d,d");
const r4: string = replace(/[,]/, "|")("b,d,d");
});
it('should supports replace by RegExp with replacement fn', () => {
const fn = (match: string, g1: string): string => g1;
const r1: string = replace(/([,])d/, fn, "b,d,d");
const r2: string = replace(/([,])d/)(fn, "b,d,d");
const r3: string = replace(/([,])d/)(fn)("b,d,d");
const r4: string = replace(/([,])d/, fn)("b,d,d");
});
});
const ss2: Array<string> = _.split(",", "b,d,d");
const ss1: boolean = _.test(/h/, "b");
const s: string = _.trim("s");
const x: string = _.head("one");
const sss: string = _.concat("H", "E");
const sss1: string = _.concat("H")("E");
const ssss: string = _.drop(1, "EF");
const ssss1: string = _.drop(1)("E");
const ssss2: string = _.dropLast(1, "EF");
const ys: string = _.nth(2, "curry");
const ys1: string = _.nth(2)("curry");
}
//Type
{
const x: boolean = _.is(Number, 1);
const x1: boolean = isNil(1);
// should refine type
const x1a: ?{ a: number } = { a: 1 };
//$FlowExpectedError
x1a.a;
if (!isNil(x1a)) {
x1a.a;
}
const x2: boolean = _.propIs(1, "num", { num: 1 });
}
| Java |
"""
A directive for including a matplotlib plot in a Sphinx document.
By default, in HTML output, `plot` will include a .png file with a
link to a high-res .png and .pdf. In LaTeX output, it will include a
.pdf.
The source code for the plot may be included in one of three ways:
1. **A path to a source file** as the argument to the directive::
.. plot:: path/to/plot.py
When a path to a source file is given, the content of the
directive may optionally contain a caption for the plot::
.. plot:: path/to/plot.py
This is the caption for the plot
Additionally, one my specify the name of a function to call (with
no arguments) immediately after importing the module::
.. plot:: path/to/plot.py plot_function1
2. Included as **inline content** to the directive::
.. plot::
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
img = mpimg.imread('_static/stinkbug.png')
imgplot = plt.imshow(img)
3. Using **doctest** syntax::
.. plot::
A plotting example:
>>> import matplotlib.pyplot as plt
>>> plt.plot([1,2,3], [4,5,6])
Options
-------
The ``plot`` directive supports the following options:
format : {'python', 'doctest'}
Specify the format of the input
include-source : bool
Whether to display the source code. The default can be changed
using the `plot_include_source` variable in conf.py
encoding : str
If this source file is in a non-UTF8 or non-ASCII encoding,
the encoding must be specified using the `:encoding:` option.
The encoding will not be inferred using the ``-*- coding -*-``
metacomment.
context : bool
If provided, the code will be run in the context of all
previous plot directives for which the `:context:` option was
specified. This only applies to inline code plot directives,
not those run from files.
nofigs : bool
If specified, the code block will be run, but no figures will
be inserted. This is usually useful with the ``:context:``
option.
Additionally, this directive supports all of the options of the
`image` directive, except for `target` (since plot will add its own
target). These include `alt`, `height`, `width`, `scale`, `align` and
`class`.
Configuration options
---------------------
The plot directive has the following configuration options:
plot_include_source
Default value for the include-source option
plot_pre_code
Code that should be executed before each plot.
plot_basedir
Base directory, to which ``plot::`` file names are relative
to. (If None or empty, file names are relative to the
directoly where the file containing the directive is.)
plot_formats
File formats to generate. List of tuples or strings::
[(suffix, dpi), suffix, ...]
that determine the file format and the DPI. For entries whose
DPI was omitted, sensible defaults are chosen.
plot_html_show_formats
Whether to show links to the files in HTML.
plot_rcparams
A dictionary containing any non-standard rcParams that should
be applied before each plot.
plot_apply_rcparams
By default, rcParams are applied when `context` option is not used in
a plot directive. This configuration option overrides this behaviour
and applies rcParams before each plot.
plot_working_directory
By default, the working directory will be changed to the directory of
the example, so the code can get at its data files, if any. Also its
path will be added to `sys.path` so it can import any helper modules
sitting beside it. This configuration option can be used to specify
a central directory (also added to `sys.path`) where data files and
helper modules for all code are located.
plot_template
Provide a customized template for preparing resturctured text.
"""
from __future__ import print_function
import sys, os, glob, shutil, imp, warnings, cStringIO, re, textwrap
import traceback
from docutils.parsers.rst import directives
from docutils import nodes
from docutils.parsers.rst.directives.images import Image
align = Image.align
import sphinx
sphinx_version = sphinx.__version__.split(".")
# The split is necessary for sphinx beta versions where the string is
# '6b1'
sphinx_version = tuple([int(re.split('[a-z]', x)[0])
for x in sphinx_version[:2]])
try:
# Sphinx depends on either Jinja or Jinja2
import jinja2
def format_template(template, **kw):
return jinja2.Template(template).render(**kw)
except ImportError:
import jinja
def format_template(template, **kw):
return jinja.from_string(template, **kw)
import matplotlib
import matplotlib.cbook as cbook
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib import _pylab_helpers
__version__ = 2
#------------------------------------------------------------------------------
# Relative pathnames
#------------------------------------------------------------------------------
# os.path.relpath is new in Python 2.6
try:
from os.path import relpath
except ImportError:
# Copied from Python 2.7
if 'posix' in sys.builtin_module_names:
def relpath(path, start=os.path.curdir):
"""Return a relative version of a path"""
from os.path import sep, curdir, join, abspath, commonprefix, \
pardir
if not path:
raise ValueError("no path specified")
start_list = abspath(start).split(sep)
path_list = abspath(path).split(sep)
# Work out how much of the filepath is shared by start and path.
i = len(commonprefix([start_list, path_list]))
rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
if not rel_list:
return curdir
return join(*rel_list)
elif 'nt' in sys.builtin_module_names:
def relpath(path, start=os.path.curdir):
"""Return a relative version of a path"""
from os.path import sep, curdir, join, abspath, commonprefix, \
pardir, splitunc
if not path:
raise ValueError("no path specified")
start_list = abspath(start).split(sep)
path_list = abspath(path).split(sep)
if start_list[0].lower() != path_list[0].lower():
unc_path, rest = splitunc(path)
unc_start, rest = splitunc(start)
if bool(unc_path) ^ bool(unc_start):
raise ValueError("Cannot mix UNC and non-UNC paths (%s and %s)"
% (path, start))
else:
raise ValueError("path is on drive %s, start on drive %s"
% (path_list[0], start_list[0]))
# Work out how much of the filepath is shared by start and path.
for i in range(min(len(start_list), len(path_list))):
if start_list[i].lower() != path_list[i].lower():
break
else:
i += 1
rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
if not rel_list:
return curdir
return join(*rel_list)
else:
raise RuntimeError("Unsupported platform (no relpath available!)")
#------------------------------------------------------------------------------
# Registration hook
#------------------------------------------------------------------------------
def plot_directive(name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
return run(arguments, content, options, state_machine, state, lineno)
plot_directive.__doc__ = __doc__
def _option_boolean(arg):
if not arg or not arg.strip():
# no argument given, assume used as a flag
return True
elif arg.strip().lower() in ('no', '0', 'false'):
return False
elif arg.strip().lower() in ('yes', '1', 'true'):
return True
else:
raise ValueError('"%s" unknown boolean' % arg)
def _option_format(arg):
return directives.choice(arg, ('python', 'doctest'))
def _option_align(arg):
return directives.choice(arg, ("top", "middle", "bottom", "left", "center",
"right"))
def mark_plot_labels(app, document):
"""
To make plots referenceable, we need to move the reference from
the "htmlonly" (or "latexonly") node to the actual figure node
itself.
"""
for name, explicit in document.nametypes.iteritems():
if not explicit:
continue
labelid = document.nameids[name]
if labelid is None:
continue
node = document.ids[labelid]
if node.tagname in ('html_only', 'latex_only'):
for n in node:
if n.tagname == 'figure':
sectname = name
for c in n:
if c.tagname == 'caption':
sectname = c.astext()
break
node['ids'].remove(labelid)
node['names'].remove(name)
n['ids'].append(labelid)
n['names'].append(name)
document.settings.env.labels[name] = \
document.settings.env.docname, labelid, sectname
break
def setup(app):
setup.app = app
setup.config = app.config
setup.confdir = app.confdir
options = {'alt': directives.unchanged,
'height': directives.length_or_unitless,
'width': directives.length_or_percentage_or_unitless,
'scale': directives.nonnegative_int,
'align': _option_align,
'class': directives.class_option,
'include-source': _option_boolean,
'format': _option_format,
'context': directives.flag,
'nofigs': directives.flag,
'encoding': directives.encoding
}
app.add_directive('plot', plot_directive, True, (0, 2, False), **options)
app.add_config_value('plot_pre_code', None, True)
app.add_config_value('plot_include_source', False, True)
app.add_config_value('plot_formats', ['png', 'hires.png', 'pdf'], True)
app.add_config_value('plot_basedir', None, True)
app.add_config_value('plot_html_show_formats', True, True)
app.add_config_value('plot_rcparams', {}, True)
app.add_config_value('plot_apply_rcparams', False, True)
app.add_config_value('plot_working_directory', None, True)
app.add_config_value('plot_template', None, True)
app.connect('doctree-read', mark_plot_labels)
#------------------------------------------------------------------------------
# Doctest handling
#------------------------------------------------------------------------------
def contains_doctest(text):
try:
# check if it's valid Python as-is
compile(text, '<string>', 'exec')
return False
except SyntaxError:
pass
r = re.compile(r'^\s*>>>', re.M)
m = r.search(text)
return bool(m)
def unescape_doctest(text):
"""
Extract code from a piece of text, which contains either Python code
or doctests.
"""
if not contains_doctest(text):
return text
code = ""
for line in text.split("\n"):
m = re.match(r'^\s*(>>>|\.\.\.) (.*)$', line)
if m:
code += m.group(2) + "\n"
elif line.strip():
code += "# " + line.strip() + "\n"
else:
code += "\n"
return code
def split_code_at_show(text):
"""
Split code at plt.show()
"""
parts = []
is_doctest = contains_doctest(text)
part = []
for line in text.split("\n"):
if (not is_doctest and line.strip() == 'plt.show()') or \
(is_doctest and line.strip() == '>>> plt.show()'):
part.append(line)
parts.append("\n".join(part))
part = []
else:
part.append(line)
if "\n".join(part).strip():
parts.append("\n".join(part))
return parts
#------------------------------------------------------------------------------
# Template
#------------------------------------------------------------------------------
TEMPLATE = """
{{ source_code }}
{{ only_html }}
{% if source_link or (html_show_formats and not multi_image) %}
(
{%- if source_link -%}
`Source code <{{ source_link }}>`__
{%- endif -%}
{%- if html_show_formats and not multi_image -%}
{%- for img in images -%}
{%- for fmt in img.formats -%}
{%- if source_link or not loop.first -%}, {% endif -%}
`{{ fmt }} <{{ dest_dir }}/{{ img.basename }}.{{ fmt }}>`__
{%- endfor -%}
{%- endfor -%}
{%- endif -%}
)
{% endif %}
{% for img in images %}
.. figure:: {{ build_dir }}/{{ img.basename }}.png
{%- for option in options %}
{{ option }}
{% endfor %}
{% if html_show_formats and multi_image -%}
(
{%- for fmt in img.formats -%}
{%- if not loop.first -%}, {% endif -%}
`{{ fmt }} <{{ dest_dir }}/{{ img.basename }}.{{ fmt }}>`__
{%- endfor -%}
)
{%- endif -%}
{{ caption }}
{% endfor %}
{{ only_latex }}
{% for img in images %}
.. image:: {{ build_dir }}/{{ img.basename }}.pdf
{% endfor %}
{{ only_texinfo }}
{% for img in images %}
.. image:: {{ build_dir }}/{{ img.basename }}.png
{%- for option in options %}
{{ option }}
{% endfor %}
{% endfor %}
"""
exception_template = """
.. htmlonly::
[`source code <%(linkdir)s/%(basename)s.py>`__]
Exception occurred rendering plot.
"""
# the context of the plot for all directives specified with the
# :context: option
plot_context = dict()
class ImageFile(object):
def __init__(self, basename, dirname):
self.basename = basename
self.dirname = dirname
self.formats = []
def filename(self, format):
return os.path.join(self.dirname, "%s.%s" % (self.basename, format))
def filenames(self):
return [self.filename(fmt) for fmt in self.formats]
def out_of_date(original, derived):
"""
Returns True if derivative is out-of-date wrt original,
both of which are full file paths.
"""
return (not os.path.exists(derived) or
(os.path.exists(original) and
os.stat(derived).st_mtime < os.stat(original).st_mtime))
class PlotError(RuntimeError):
pass
def run_code(code, code_path, ns=None, function_name=None):
"""
Import a Python module from a path, and run the function given by
name, if function_name is not None.
"""
# Change the working directory to the directory of the example, so
# it can get at its data files, if any. Add its path to sys.path
# so it can import any helper modules sitting beside it.
pwd = os.getcwd()
old_sys_path = list(sys.path)
if setup.config.plot_working_directory is not None:
try:
os.chdir(setup.config.plot_working_directory)
except OSError as err:
raise OSError(str(err) + '\n`plot_working_directory` option in'
'Sphinx configuration file must be a valid '
'directory path')
except TypeError as err:
raise TypeError(str(err) + '\n`plot_working_directory` option in '
'Sphinx configuration file must be a string or '
'None')
sys.path.insert(0, setup.config.plot_working_directory)
elif code_path is not None:
dirname = os.path.abspath(os.path.dirname(code_path))
os.chdir(dirname)
sys.path.insert(0, dirname)
# Redirect stdout
stdout = sys.stdout
sys.stdout = cStringIO.StringIO()
# Reset sys.argv
old_sys_argv = sys.argv
sys.argv = [code_path]
try:
try:
code = unescape_doctest(code)
if ns is None:
ns = {}
if not ns:
if setup.config.plot_pre_code is None:
exec "import numpy as np\nfrom matplotlib import pyplot as plt\n" in ns
else:
exec setup.config.plot_pre_code in ns
if "__main__" in code:
exec "__name__ = '__main__'" in ns
exec code in ns
if function_name is not None:
exec function_name + "()" in ns
except (Exception, SystemExit), err:
raise PlotError(traceback.format_exc())
finally:
os.chdir(pwd)
sys.argv = old_sys_argv
sys.path[:] = old_sys_path
sys.stdout = stdout
return ns
def clear_state(plot_rcparams):
plt.close('all')
matplotlib.rc_file_defaults()
matplotlib.rcParams.update(plot_rcparams)
def render_figures(code, code_path, output_dir, output_base, context,
function_name, config):
"""
Run a pyplot script and save the low and high res PNGs and a PDF
in outdir.
Save the images under *output_dir* with file names derived from
*output_base*
"""
# -- Parse format list
default_dpi = {'png': 80, 'hires.png': 200, 'pdf': 200}
formats = []
plot_formats = config.plot_formats
if isinstance(plot_formats, (str, unicode)):
plot_formats = eval(plot_formats)
for fmt in plot_formats:
if isinstance(fmt, str):
formats.append((fmt, default_dpi.get(fmt, 80)))
elif type(fmt) in (tuple, list) and len(fmt)==2:
formats.append((str(fmt[0]), int(fmt[1])))
else:
raise PlotError('invalid image format "%r" in plot_formats' % fmt)
# -- Try to determine if all images already exist
code_pieces = split_code_at_show(code)
# Look for single-figure output files first
# Look for single-figure output files first
all_exists = True
img = ImageFile(output_base, output_dir)
for format, dpi in formats:
if out_of_date(code_path, img.filename(format)):
all_exists = False
break
img.formats.append(format)
if all_exists:
return [(code, [img])]
# Then look for multi-figure output files
results = []
all_exists = True
for i, code_piece in enumerate(code_pieces):
images = []
for j in xrange(1000):
if len(code_pieces) > 1:
img = ImageFile('%s_%02d_%02d' % (output_base, i, j), output_dir)
else:
img = ImageFile('%s_%02d' % (output_base, j), output_dir)
for format, dpi in formats:
if out_of_date(code_path, img.filename(format)):
all_exists = False
break
img.formats.append(format)
# assume that if we have one, we have them all
if not all_exists:
all_exists = (j > 0)
break
images.append(img)
if not all_exists:
break
results.append((code_piece, images))
if all_exists:
return results
# We didn't find the files, so build them
results = []
if context:
ns = plot_context
else:
ns = {}
for i, code_piece in enumerate(code_pieces):
if not context or config.plot_apply_rcparams:
clear_state(config.plot_rcparams)
run_code(code_piece, code_path, ns, function_name)
images = []
fig_managers = _pylab_helpers.Gcf.get_all_fig_managers()
for j, figman in enumerate(fig_managers):
if len(fig_managers) == 1 and len(code_pieces) == 1:
img = ImageFile(output_base, output_dir)
elif len(code_pieces) == 1:
img = ImageFile("%s_%02d" % (output_base, j), output_dir)
else:
img = ImageFile("%s_%02d_%02d" % (output_base, i, j),
output_dir)
images.append(img)
for format, dpi in formats:
try:
figman.canvas.figure.savefig(img.filename(format), dpi=dpi)
except Exception,err:
raise PlotError(traceback.format_exc())
img.formats.append(format)
results.append((code_piece, images))
if not context or config.plot_apply_rcparams:
clear_state(config.plot_rcparams)
return results
def run(arguments, content, options, state_machine, state, lineno):
# The user may provide a filename *or* Python code content, but not both
if arguments and content:
raise RuntimeError("plot:: directive can't have both args and content")
document = state_machine.document
config = document.settings.env.config
nofigs = options.has_key('nofigs')
options.setdefault('include-source', config.plot_include_source)
context = options.has_key('context')
rst_file = document.attributes['source']
rst_dir = os.path.dirname(rst_file)
if len(arguments):
if not config.plot_basedir:
source_file_name = os.path.join(setup.app.builder.srcdir,
directives.uri(arguments[0]))
else:
source_file_name = os.path.join(setup.confdir, config.plot_basedir,
directives.uri(arguments[0]))
# If there is content, it will be passed as a caption.
caption = '\n'.join(content)
# If the optional function name is provided, use it
if len(arguments) == 2:
function_name = arguments[1]
else:
function_name = None
with open(source_file_name, 'r') as fd:
code = fd.read()
output_base = os.path.basename(source_file_name)
else:
source_file_name = rst_file
code = textwrap.dedent("\n".join(map(str, content)))
counter = document.attributes.get('_plot_counter', 0) + 1
document.attributes['_plot_counter'] = counter
base, ext = os.path.splitext(os.path.basename(source_file_name))
output_base = '%s-%d.py' % (base, counter)
function_name = None
caption = ''
base, source_ext = os.path.splitext(output_base)
if source_ext in ('.py', '.rst', '.txt'):
output_base = base
else:
source_ext = ''
# ensure that LaTeX includegraphics doesn't choke in foo.bar.pdf filenames
output_base = output_base.replace('.', '-')
# is it in doctest format?
is_doctest = contains_doctest(code)
if options.has_key('format'):
if options['format'] == 'python':
is_doctest = False
else:
is_doctest = True
# determine output directory name fragment
source_rel_name = relpath(source_file_name, setup.confdir)
source_rel_dir = os.path.dirname(source_rel_name)
while source_rel_dir.startswith(os.path.sep):
source_rel_dir = source_rel_dir[1:]
# build_dir: where to place output files (temporarily)
build_dir = os.path.join(os.path.dirname(setup.app.doctreedir),
'plot_directive',
source_rel_dir)
# get rid of .. in paths, also changes pathsep
# see note in Python docs for warning about symbolic links on Windows.
# need to compare source and dest paths at end
build_dir = os.path.normpath(build_dir)
if not os.path.exists(build_dir):
os.makedirs(build_dir)
# output_dir: final location in the builder's directory
dest_dir = os.path.abspath(os.path.join(setup.app.builder.outdir,
source_rel_dir))
if not os.path.exists(dest_dir):
os.makedirs(dest_dir) # no problem here for me, but just use built-ins
# how to link to files from the RST file
dest_dir_link = os.path.join(relpath(setup.confdir, rst_dir),
source_rel_dir).replace(os.path.sep, '/')
build_dir_link = relpath(build_dir, rst_dir).replace(os.path.sep, '/')
source_link = dest_dir_link + '/' + output_base + source_ext
# make figures
try:
results = render_figures(code, source_file_name, build_dir, output_base,
context, function_name, config)
errors = []
except PlotError, err:
reporter = state.memo.reporter
sm = reporter.system_message(
2, "Exception occurred in plotting %s\n from %s:\n%s" % (output_base,
source_file_name, err),
line=lineno)
results = [(code, [])]
errors = [sm]
# Properly indent the caption
caption = '\n'.join(' ' + line.strip()
for line in caption.split('\n'))
# generate output restructuredtext
total_lines = []
for j, (code_piece, images) in enumerate(results):
if options['include-source']:
if is_doctest:
lines = ['']
lines += [row.rstrip() for row in code_piece.split('\n')]
else:
lines = ['.. code-block:: python', '']
lines += [' %s' % row.rstrip()
for row in code_piece.split('\n')]
source_code = "\n".join(lines)
else:
source_code = ""
if nofigs:
images = []
opts = [':%s: %s' % (key, val) for key, val in options.items()
if key in ('alt', 'height', 'width', 'scale', 'align', 'class')]
only_html = ".. only:: html"
only_latex = ".. only:: latex"
only_texinfo = ".. only:: texinfo"
if j == 0:
src_link = source_link
else:
src_link = None
result = format_template(
config.plot_template or TEMPLATE,
dest_dir=dest_dir_link,
build_dir=build_dir_link,
source_link=src_link,
multi_image=len(images) > 1,
only_html=only_html,
only_latex=only_latex,
only_texinfo=only_texinfo,
options=opts,
images=images,
source_code=source_code,
html_show_formats=config.plot_html_show_formats,
caption=caption)
total_lines.extend(result.split("\n"))
total_lines.extend("\n")
if total_lines:
state_machine.insert_input(total_lines, source=source_file_name)
# copy image files to builder's output directory, if necessary
if not os.path.exists(dest_dir):
cbook.mkdirs(dest_dir)
for code_piece, images in results:
for img in images:
for fn in img.filenames():
destimg = os.path.join(dest_dir, os.path.basename(fn))
if fn != destimg:
shutil.copyfile(fn, destimg)
# copy script (if necessary)
target_name = os.path.join(dest_dir, output_base + source_ext)
with open(target_name, 'w') as f:
if source_file_name == rst_file:
code_escaped = unescape_doctest(code)
else:
code_escaped = code
f.write(code_escaped)
return errors
| Java |
'use strict';
exports.up = function (knex) {
return knex.schema.createTable('migration_test_trx_1', function (t) {
t.increments();
t.string('name');
});
};
exports.down = function (knex) {
return knex.schema.dropTable('migration_test_trx_1');
};
| Java |
#include <stdio.h>
#include <string.h>
int is_prime(char*);
int main() {
char input[11];
fgets(input, 11, stdin);
printf("%d", is_prime(input));
return 0;
}
int is_prime(char* input) {
int i, length, number = 0;
length = input[strlen(input) - 1] == '\n' ? strlen(input) - 1 : strlen(input);
for (i = 0; i < length; i++) {
if (input[i] < '0' || input[i] > '9') {
return -1;
}
}
for (i = 0; i < length; i++) {
number += input[i] - '0';
if (i != length - 1) {
number *= 10;
}
}
if (number == 0 || number == 1) {
return 0;
}
for (i = 2; i < number; i++) {
if (number % i == 0 && i != number) {
return 0;
}
}
return 1;
}
| Java |
/**
* @author mrdoob / http://mrdoob.com/
* @author bhouston / http://exocortex.com/
*/
( function ( THREE ) {
THREE.Raycaster = function ( origin, direction, near, far ) {
this.ray = new THREE.Ray( origin, direction );
// normalized ray.direction required for accurate distance calculations
if( this.ray.direction.lengthSq() > 0 ) {
this.ray.direction.normalize();
}
this.near = near || 0;
this.far = far || Infinity;
};
var sphere = new THREE.Sphere();
var localRay = new THREE.Ray();
var facePlane = new THREE.Plane();
var intersectPoint = new THREE.Vector3();
var matrixPosition = new THREE.Vector3();
var inverseMatrix = new THREE.Matrix4();
var descSort = function ( a, b ) {
return a.distance - b.distance;
};
var intersectObject = function ( object, raycaster, intersects ) {
if ( object instanceof THREE.Particle ) {
matrixPosition.getPositionFromMatrix( object.matrixWorld );
var distance = raycaster.ray.distanceToPoint( matrixPosition );
if ( distance > object.scale.x ) {
return intersects;
}
intersects.push( {
distance: distance,
point: object.position,
face: null,
object: object
} );
} else if ( object instanceof THREE.Mesh ) {
// Checking boundingSphere distance to ray
matrixPosition.getPositionFromMatrix( object.matrixWorld );
sphere.set(
matrixPosition,
object.geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis() );
if ( ! raycaster.ray.isIntersectionSphere( sphere ) ) {
return intersects;
}
// Checking faces
var geometry = object.geometry;
var vertices = geometry.vertices;
var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
var side = object.material.side;
var a, b, c, d;
var precision = raycaster.precision;
object.matrixRotationWorld.extractRotation( object.matrixWorld );
inverseMatrix.getInverse( object.matrixWorld );
localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
var face = geometry.faces[ f ];
var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
if ( material === undefined ) continue;
facePlane.setFromNormalAndCoplanarPoint( face.normal, vertices[face.a] );
var planeDistance = localRay.distanceToPlane( facePlane );
// bail if raycaster and plane are parallel
if ( Math.abs( planeDistance ) < precision ) continue;
// if negative distance, then plane is behind raycaster
if ( planeDistance < 0 ) continue;
// check if we hit the wrong side of a single sided face
side = material.side;
if( side !== THREE.DoubleSide ) {
var planeSign = localRay.direction.dot( facePlane.normal );
if( ! ( side === THREE.FrontSide ? planeSign < 0 : planeSign > 0 ) ) continue;
}
// this can be done using the planeDistance from localRay because localRay wasn't normalized, but ray was
if ( planeDistance < raycaster.near || planeDistance > raycaster.far ) continue;
intersectPoint = localRay.at( planeDistance, intersectPoint ); // passing in intersectPoint avoids a copy
if ( face instanceof THREE.Face3 ) {
a = vertices[ face.a ];
b = vertices[ face.b ];
c = vertices[ face.c ];
if ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, c ) ) continue;
} else if ( face instanceof THREE.Face4 ) {
a = vertices[ face.a ];
b = vertices[ face.b ];
c = vertices[ face.c ];
d = vertices[ face.d ];
if ( ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, d ) ) &&
( ! THREE.Triangle.containsPoint( intersectPoint, b, c, d ) ) ) continue;
} else {
// This is added because if we call out of this if/else group when none of the cases
// match it will add a point to the intersection list erroneously.
throw Error( "face type not supported" );
}
intersects.push( {
distance: planeDistance, // this works because the original ray was normalized, and the transformed localRay wasn't
point: raycaster.ray.at( planeDistance ),
face: face,
faceIndex: f,
object: object
} );
}
}
};
var intersectDescendants = function ( object, raycaster, intersects ) {
var descendants = object.getDescendants();
for ( var i = 0, l = descendants.length; i < l; i ++ ) {
intersectObject( descendants[ i ], raycaster, intersects );
}
};
//
THREE.Raycaster.prototype.precision = 0.0001;
THREE.Raycaster.prototype.set = function ( origin, direction ) {
this.ray.set( origin, direction );
// normalized ray.direction required for accurate distance calculations
if( this.ray.direction.length() > 0 ) {
this.ray.direction.normalize();
}
};
THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
var intersects = [];
if ( recursive === true ) {
intersectDescendants( object, this, intersects );
}
intersectObject( object, this, intersects );
intersects.sort( descSort );
return intersects;
};
THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
var intersects = [];
for ( var i = 0, l = objects.length; i < l; i ++ ) {
intersectObject( objects[ i ], this, intersects );
if ( recursive === true ) {
intersectDescendants( objects[ i ], this, intersects );
}
}
intersects.sort( descSort );
return intersects;
};
}( THREE ) );
| Java |
module Facter::Util::Virtual
##
# virt_what is a delegating helper method intended to make it easier to stub
# the system call without affecting other calls to
# Facter::Util::Resolution.exec
def self.virt_what(command = "virt-what")
Facter::Util::Resolution.exec command
end
##
# lspci is a delegating helper method intended to make it easier to stub the
# system call without affecting other calls to Facter::Util::Resolution.exec
def self.lspci(command = "lspci 2>/dev/null")
Facter::Util::Resolution.exec command
end
def self.openvz?
FileTest.directory?("/proc/vz") and not self.openvz_cloudlinux?
end
# So one can either have #6728 work on OpenVZ or Cloudlinux. Whoo.
def self.openvz_type
return false unless self.openvz?
return false unless FileTest.exists?( '/proc/self/status' )
envid = Facter::Util::Resolution.exec( 'grep "envID" /proc/self/status' )
if envid =~ /^envID:\s+0$/i
return 'openvzhn'
elsif envid =~ /^envID:\s+(\d+)$/i
return 'openvzve'
end
end
# Cloudlinux uses OpenVZ to a degree, but always has an empty /proc/vz/ and
# has /proc/lve/list present
def self.openvz_cloudlinux?
FileTest.file?("/proc/lve/list") or Dir.glob('/proc/vz/*').empty?
end
def self.zone?
return true if FileTest.directory?("/.SUNWnative")
z = Facter::Util::Resolution.exec("/sbin/zonename")
return false unless z
return z.chomp != 'global'
end
def self.vserver?
return false unless FileTest.exists?("/proc/self/status")
txt = File.read("/proc/self/status")
return true if txt =~ /^(s_context|VxID):[[:blank:]]*[0-9]/
return false
end
def self.vserver_type
if self.vserver?
if FileTest.exists?("/proc/virtual")
"vserver_host"
else
"vserver"
end
end
end
def self.xen?
["/proc/sys/xen", "/sys/bus/xen", "/proc/xen" ].detect do |f|
FileTest.exists?(f)
end
end
def self.kvm?
txt = if FileTest.exists?("/proc/cpuinfo")
File.read("/proc/cpuinfo")
elsif ["FreeBSD", "OpenBSD"].include? Facter.value(:kernel)
Facter::Util::Resolution.exec("/sbin/sysctl -n hw.model")
end
(txt =~ /QEMU Virtual CPU/) ? true : false
end
def self.kvm_type
# TODO Tell the difference between kvm and qemu
# Can't work out a way to do this at the moment that doesn't
# require a special binary
"kvm"
end
def self.jail?
path = case Facter.value(:kernel)
when "FreeBSD" then "/sbin"
when "GNU/kFreeBSD" then "/bin"
end
Facter::Util::Resolution.exec("#{path}/sysctl -n security.jail.jailed") == "1"
end
def self.hpvm?
Facter::Util::Resolution.exec("/usr/bin/getconf MACHINE_MODEL").chomp =~ /Virtual Machine/
end
def self.zlinux?
"zlinux"
end
end
| Java |
'use strict';
require('../../modules/es.weak-set');
require('../../modules/esnext.weak-set.from');
var WeakSet = require('../../internals/path').WeakSet;
var weakSetfrom = WeakSet.from;
module.exports = function from(source, mapFn, thisArg) {
return weakSetfrom.call(typeof this === 'function' ? this : WeakSet, source, mapFn, thisArg);
};
| Java |
/** @babel */
/** @jsx etch.dom **/
import etch from 'etch';
export default class WelcomeView {
constructor(props) {
this.props = props;
etch.initialize(this);
this.element.addEventListener('click', event => {
const link = event.target.closest('a');
if (link && link.dataset.event) {
this.props.reporterProxy.sendEvent(
`clicked-welcome-${link.dataset.event}-link`
);
}
});
}
didChangeShowOnStartup() {
atom.config.set('welcome.showOnStartup', this.checked);
}
update() {}
serialize() {
return {
deserializer: 'WelcomeView',
uri: this.props.uri
};
}
render() {
return (
<div className="welcome">
<div className="welcome-container">
<header className="welcome-header">
<a href="https://atom.io/">
<svg
className="welcome-logo"
width="330px"
height="68px"
viewBox="0 0 330 68"
version="1.1"
>
<g
stroke="none"
stroke-width="1"
fill="none"
fill-rule="evenodd"
>
<g transform="translate(2.000000, 1.000000)">
<g
transform="translate(96.000000, 8.000000)"
fill="currentColor"
>
<path d="M185.498,3.399 C185.498,2.417 186.34,1.573 187.324,1.573 L187.674,1.573 C188.447,1.573 189.01,1.995 189.5,2.628 L208.676,30.862 L227.852,2.628 C228.272,1.995 228.905,1.573 229.676,1.573 L230.028,1.573 C231.01,1.573 231.854,2.417 231.854,3.399 L231.854,49.403 C231.854,50.387 231.01,51.231 230.028,51.231 C229.044,51.231 228.202,50.387 228.202,49.403 L228.202,8.246 L210.151,34.515 C209.729,35.148 209.237,35.428 208.606,35.428 C207.973,35.428 207.481,35.148 207.061,34.515 L189.01,8.246 L189.01,49.475 C189.01,50.457 188.237,51.231 187.254,51.231 C186.27,51.231 185.498,50.458 185.498,49.475 L185.498,3.399 L185.498,3.399 Z" />
<path d="M113.086,26.507 L113.086,26.367 C113.086,12.952 122.99,0.941 137.881,0.941 C152.77,0.941 162.533,12.811 162.533,26.225 L162.533,26.367 C162.533,39.782 152.629,51.792 137.74,51.792 C122.85,51.792 113.086,39.923 113.086,26.507 M158.74,26.507 L158.74,26.367 C158.74,14.216 149.89,4.242 137.74,4.242 C125.588,4.242 116.879,14.075 116.879,26.225 L116.879,26.367 C116.879,38.518 125.729,48.491 137.881,48.491 C150.031,48.491 158.74,38.658 158.74,26.507" />
<path d="M76.705,5.155 L60.972,5.155 C60.06,5.155 59.287,4.384 59.287,3.469 C59.287,2.556 60.059,1.783 60.972,1.783 L96.092,1.783 C97.004,1.783 97.778,2.555 97.778,3.469 C97.778,4.383 97.005,5.155 96.092,5.155 L80.358,5.155 L80.358,49.405 C80.358,50.387 79.516,51.231 78.532,51.231 C77.55,51.231 76.706,50.387 76.706,49.405 L76.706,5.155 L76.705,5.155 Z" />
<path d="M0.291,48.562 L21.291,3.05 C21.783,1.995 22.485,1.292 23.75,1.292 L23.891,1.292 C25.155,1.292 25.858,1.995 26.348,3.05 L47.279,48.421 C47.49,48.843 47.56,49.194 47.56,49.546 C47.56,50.458 46.788,51.231 45.803,51.231 C44.961,51.231 44.329,50.599 43.978,49.826 L38.219,37.183 L9.21,37.183 L3.45,49.897 C3.099,50.739 2.538,51.231 1.694,51.231 C0.781,51.231 0.008,50.529 0.008,49.685 C0.009,49.404 0.08,48.983 0.291,48.562 L0.291,48.562 Z M36.673,33.882 L23.749,5.437 L10.755,33.882 L36.673,33.882 L36.673,33.882 Z" />
</g>
<g>
<path
d="M40.363,32.075 C40.874,34.44 39.371,36.77 37.006,37.282 C34.641,37.793 32.311,36.29 31.799,33.925 C31.289,31.56 32.791,29.23 35.156,28.718 C37.521,28.207 39.851,29.71 40.363,32.075"
fill="currentColor"
/>
<path
d="M48.578,28.615 C56.851,45.587 58.558,61.581 52.288,64.778 C45.822,68.076 33.326,56.521 24.375,38.969 C15.424,21.418 13.409,4.518 19.874,1.221 C22.689,-0.216 26.648,1.166 30.959,4.629"
stroke="currentColor"
stroke-width="3.08"
stroke-linecap="round"
/>
<path
d="M7.64,39.45 C2.806,36.94 -0.009,33.915 0.154,30.79 C0.531,23.542 16.787,18.497 36.462,19.52 C56.137,20.544 71.781,27.249 71.404,34.497 C71.241,37.622 68.127,40.338 63.06,42.333"
stroke="currentColor"
stroke-width="3.08"
stroke-linecap="round"
/>
<path
d="M28.828,59.354 C23.545,63.168 18.843,64.561 15.902,62.653 C9.814,58.702 13.572,42.102 24.296,25.575 C35.02,9.048 48.649,-1.149 54.736,2.803 C57.566,4.639 58.269,9.208 57.133,15.232"
stroke="currentColor"
stroke-width="3.08"
stroke-linecap="round"
/>
</g>
</g>
</g>
</svg>
<h1 className="welcome-title">
A hackable text editor for the 21<sup>st</sup> Century
</h1>
</a>
</header>
<section className="welcome-panel">
<p>For help, please visit</p>
<ul>
<li>
The{' '}
<a
href="https://www.atom.io/docs"
dataset={{ event: 'atom-docs' }}
>
Atom docs
</a>{' '}
for Guides and the API reference.
</li>
<li>
The Atom forum at{' '}
<a
href="https://github.com/atom/atom/discussions"
dataset={{ event: 'discussions' }}
>
Github Discussions
</a>
</li>
<li>
The{' '}
<a
href="https://github.com/atom"
dataset={{ event: 'atom-org' }}
>
Atom org
</a>
. This is where all GitHub-created Atom packages can be found.
</li>
</ul>
</section>
<section className="welcome-panel">
<label>
<input
className="input-checkbox"
type="checkbox"
checked={atom.config.get('welcome.showOnStartup')}
onchange={this.didChangeShowOnStartup}
/>
Show Welcome Guide when opening Atom
</label>
</section>
<footer className="welcome-footer">
<a href="https://atom.io/" dataset={{ event: 'footer-atom-io' }}>
atom.io
</a>{' '}
<span className="text-subtle">×</span>{' '}
<a
className="icon icon-octoface"
href="https://github.com/"
dataset={{ event: 'footer-octocat' }}
/>
</footer>
</div>
</div>
);
}
getURI() {
return this.props.uri;
}
getTitle() {
return 'Welcome';
}
isEqual(other) {
return other instanceof WelcomeView;
}
}
| Java |
---
title: Rule no-multi-spaces
layout: doc
---
<!-- Note: No pull requests accepted for this file. See README.md in the root directory for details. -->
# Disallow multiple spaces (no-multi-spaces)
(fixable) The `--fix` option on the [command line](../user-guide/command-line-interface#fix) automatically fixes problems reported by this rule.
Multiple spaces in a row that are not used for indentation are typically mistakes. For example:
```js
if(foo === "bar") {}
```
It's hard to tell, but there are two spaces between `foo` and `===`. Multiple spaces such as this are generally frowned upon in favor of single spaces:
```js
if(foo === "bar") {}
```
## Rule Details
This rule aims to disallow multiple whitespace around logical expressions, conditional expressions, declarations, array elements, object properties, sequences and function parameters.
Examples of **incorrect** code for this rule:
```js
/*eslint no-multi-spaces: "error"*/
var a = 1;
if(foo === "bar") {}
a << b
var arr = [1, 2];
a ? b: c
```
Examples of **correct** code for this rule:
```js
/*eslint no-multi-spaces: "error"*/
var a = 1;
if(foo === "bar") {}
a << b
var arr = [1, 2];
a ? b: c
```
## Options
To avoid contradictions if some other rules require multiple spaces, this rule has an option to ignore certain node types in the abstract syntax tree (AST) of JavaScript code.
### exceptions
The `exceptions` object expects property names to be AST node types as defined by [ESTree](https://github.com/estree/estree). The easiest way to determine the node types for `exceptions` is to use the [online demo](https://eslint.org/parser).
Only the `Property` node type is ignored by default, because for the [key-spacing](key-spacing) rule some alignment options require multiple spaces in properties of object literals.
Examples of **correct** code for the default `"exceptions": { "Property": true }` option:
```js
/*eslint no-multi-spaces: "error"*/
/*eslint key-spacing: ["error", { align: "value" }]*/
var obj = {
first: "first",
second: "second"
};
```
Examples of **incorrect** code for the `"exceptions": { "Property": false }` option:
```js
/*eslint no-multi-spaces: ["error", { exceptions: { "Property": false } }]*/
/*eslint key-spacing: ["error", { align: "value" }]*/
var obj = {
first: "first",
second: "second"
};
```
Examples of **correct** code for the `"exceptions": { "BinaryExpression": true }` option:
```js
/*eslint no-multi-spaces: ["error", { exceptions: { "BinaryExpression": true } }]*/
var a = 1 * 2;
```
Examples of **correct** code for the `"exceptions": { "VariableDeclarator": true }` option:
```js
/*eslint no-multi-spaces: ["error", { exceptions: { "VariableDeclarator": true } }]*/
var someVar = 'foo';
var someOtherVar = 'barBaz';
```
Examples of **correct** code for the `"exceptions": { "ImportDeclaration": true }` option:
```js
/*eslint no-multi-spaces: ["error", { exceptions: { "ImportDeclaration": true } }]*/
import mod from 'mod';
import someOtherMod from 'some-other-mod';
```
## When Not To Use It
If you don't want to check and disallow multiple spaces, then you should turn this rule off.
## Related Rules
* [key-spacing](key-spacing)
* [space-infix-ops](space-infix-ops)
* [space-in-brackets](space-in-brackets) (deprecated)
* [space-in-parens](space-in-parens)
* [space-after-keywords](space-after-keywords)
* [space-unary-ops](space-unary-ops)
* [space-return-throw-case](space-return-throw-case)
## Version
This rule was introduced in ESLint 0.9.0.
## Resources
* [Rule source](https://github.com/eslint/eslint/tree/master/lib/rules/no-multi-spaces.js)
* [Documentation source](https://github.com/eslint/eslint/tree/master/docs/rules/no-multi-spaces.md)
| Java |
/*
* Copyright (c) 2014-2015 Håkan Edling
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*
* http://github.com/piranhacms/piranha.vnext
*
*/
using System;
using System.IO;
namespace Piranha.IO
{
/// <summary>
/// Interface for creating an media provider.
/// </summary>
public interface IMedia
{
/// <summary>
/// Gets the binary data for the given media object.
/// </summary>
/// <param name="media">The media object</param>
/// <returns>The binary data</returns>
byte[] Get(Models.Media media);
/// <summary>
/// Saves the given binary data for the given media object.
/// </summary>
/// <param name="media">The media object</param>
/// <param name="bytes">The binary data</param>
void Put(Models.Media media, byte[] bytes);
/// <summary>
/// Saves the binary data available in the stream in the
/// given media object.
/// </summary>
/// <param name="media">The media object</param>
/// <param name="stream">The stream</param>
void Put(Models.Media media, Stream stream);
/// <summary>
/// Deletes the binary data for the given media object.
/// </summary>
/// <param name="media">The media object</param>
void Delete(Models.Media media);
}
}
| Java |
<?php
namespace PragmaRX\Tracker\Data\Repositories;
use PragmaRX\Tracker\Support\RefererParser;
class Referer extends Repository {
/**
* @var RefererParser
*/
private $refererParser;
/**
* @var
*/
private $currentUrl;
/**
* @var
*/
private $searchTermModel;
/**
* Create repository instance.
*
* @param RefererParser $refererParser
*/
public function __construct($model, $searchTermModel, $currentUrl, RefererParser $refererParser)
{
parent::__construct($model);
$this->refererParser = $refererParser;
$this->currentUrl = $currentUrl;
$this->searchTermModel = $searchTermModel;
}
/**
* @param $refererUrl
* @param $host
* @param $domain_id
* @return mixed
*/
public function store($refererUrl, $host, $domain_id)
{
$attributes = array(
'url' => $refererUrl,
'host' => $host,
'domain_id' => $domain_id,
'medium' => null,
'source' => null,
'search_terms_hash' => null
);
$parsed = $this->refererParser->parse($refererUrl, $this->currentUrl);
if ($parsed->isKnown())
{
$attributes['medium'] = $parsed->getMedium();
$attributes['source'] = $parsed->getSource();
$attributes['search_terms_hash'] = sha1($parsed->getSearchTerm());
}
$referer = $this->findOrCreate(
$attributes,
array('url', 'search_terms_hash')
);
$referer = $this->find($referer);
if ($parsed->isKnown())
{
$this->storeSearchTerms($referer, $parsed);
}
return $referer->id;
}
private function storeSearchTerms($referer, $parsed)
{
foreach (explode(' ', $parsed->getSearchTerm()) as $term)
{
$this->findOrCreate(
array(
'referer_id' => $referer->id,
'search_term' => $term
),
array('referer_id', 'search_term'),
$created,
$this->searchTermModel
);
}
}
}
| Java |
'use strict';
angular.module('sw.plugin.split', ['sw.plugins'])
.factory('split', function ($q) {
return {
execute: execute
};
function execute (url, swagger) {
var deferred = $q.defer();
if (swagger && swagger.swagger && !swagger.tags) {
var tags = {};
angular.forEach(swagger.paths, function (path, key) {
var t = key.replace(/^\/?([^\/]+).*$/g, '$1');
tags[t] = true;
angular.forEach(path, function (method) {
if (!method.tags || !method.tags.length) {
method.tags = [t];
}
});
});
swagger.tags = [];
Object.keys(tags).forEach(function (tag) {
swagger.tags.push({name: tag});
});
}
deferred.resolve(true);
return deferred.promise;
}
})
.run(function (plugins, split) {
plugins.add(plugins.BEFORE_PARSE, split);
});
| Java |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.Build.Engine.Incrementals
{
public sealed class ProcessorStepInfo
{
/// <summary>
/// The name of processor step.
/// </summary>
public string Name { get; set; }
/// <summary>
/// The context hash for incremental.
/// </summary>
public string IncrementalContextHash { get; set; }
/// <summary>
/// The file link for context info.
/// </summary>
public string ContextInfoFile { get; set; }
public override bool Equals(object obj)
{
var another = obj as ProcessorStepInfo;
if (another == null)
{
return false;
}
return Name == another.Name &&
IncrementalContextHash == another.IncrementalContextHash;
}
public override int GetHashCode()
{
return Name?.GetHashCode() ?? 0;
}
}
}
| Java |
/*-----------------------------------------------------------------------------------
/*
/* Main JS
/*
-----------------------------------------------------------------------------------*/
(function($) {
/*---------------------------------------------------- */
/* Preloader
------------------------------------------------------ */
$(window).load(function() {
// will first fade out the loading animation
$("#status").fadeOut("slow");
// will fade out the whole DIV that covers the website.
$("#preloader").delay(500).fadeOut("slow").remove();
$('.js #hero .hero-image img').addClass("animated fadeInUpBig");
$('.js #hero .buttons a.trial').addClass("animated shake");
})
/*---------------------------------------------------- */
/* Mobile Menu
------------------------------------------------------ */
var toggle_button = $("<a>", {
id: "toggle-btn",
html : "Menu",
title: "Menu",
href : "#" }
);
var nav_wrap = $('nav#nav-wrap')
var nav = $("ul#nav");
/* id JS is enabled, remove the two a.mobile-btns
and dynamically prepend a.toggle-btn to #nav-wrap */
nav_wrap.find('a.mobile-btn').remove();
nav_wrap.prepend(toggle_button);
toggle_button.on("click", function(e) {
e.preventDefault();
nav.slideToggle("fast");
});
if (toggle_button.is(':visible')) nav.addClass('mobile');
$(window).resize(function(){
if (toggle_button.is(':visible')) nav.addClass('mobile');
else nav.removeClass('mobile');
});
$('ul#nav li a').on("click", function(){
if (nav.hasClass('mobile')) nav.fadeOut('fast');
});
/*----------------------------------------------------*/
/* FitText Settings
------------------------------------------------------ */
setTimeout(function() {
$('h1.responsive-headline').fitText(1.2, { minFontSize: '25px', maxFontSize: '40px' });
}, 100);
/*----------------------------------------------------*/
/* Smooth Scrolling
------------------------------------------------------ */
$('.smoothscroll').on('click', function (e) {
e.preventDefault();
var target = this.hash,
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 800, 'swing', function () {
window.location.hash = target;
});
});
/*----------------------------------------------------*/
/* Highlight the current section in the navigation bar
------------------------------------------------------*/
var sections = $("section"),
navigation_links = $("#nav-wrap a");
sections.waypoint( {
handler: function(event, direction) {
var active_section;
active_section = $(this);
if (direction === "up") active_section = active_section.prev();
var active_link = $('#nav-wrap a[href="#' + active_section.attr("id") + '"]');
navigation_links.parent().removeClass("current");
active_link.parent().addClass("current");
},
offset: '35%'
});
/*----------------------------------------------------*/
/* FitVids
/*----------------------------------------------------*/
$(".fluid-video-wrapper").fitVids();
/*----------------------------------------------------*/
/* Waypoints Animations
------------------------------------------------------ */
$('.js .design').waypoint(function() {
$('.js .design .feature-media').addClass( 'animated pulse' );
}, { offset: 'bottom-in-view' });
$('.js .responsive').waypoint(function() {
$('.js .responsive .feature-media').addClass( 'animated pulse' );
}, { offset: 'bottom-in-view' });
$('.js .cross-browser').waypoint(function() {
$('.js .cross-browser .feature-media').addClass( 'animated pulse' );
}, { offset: 'bottom-in-view' });
$('.js .video').waypoint(function() {
$('.js .video .feature-media').addClass( 'animated pulse' );
}, { offset: 'bottom-in-view' });
$('.js #subscribe').waypoint(function() {
$('.js #subscribe input[type="email"]').addClass( 'animated fadeInLeftBig show' );
$('.js #subscribe input[type="submit"]').addClass( 'animated fadeInRightBig show' );
}, { offset: 'bottom-in-view' });
/*----------------------------------------------------*/
/* Flexslider
/*----------------------------------------------------*/
$('.flexslider').flexslider({
namespace: "flex-",
controlsContainer: ".flex-container",
animation: 'slide',
controlNav: true,
directionNav: false,
smoothHeight: true,
slideshowSpeed: 7000,
animationSpeed: 600,
randomize: false,
});
/*----------------------------------------------------*/
/* ImageLightbox
/*----------------------------------------------------*/
if($("html").hasClass('cssanimations')) {
var activityIndicatorOn = function()
{
$( '<div id="imagelightbox-loading"><div></div></div>' ).appendTo( 'body' );
},
activityIndicatorOff = function()
{
$( '#imagelightbox-loading' ).remove();
},
overlayOn = function()
{
$( '<div id="imagelightbox-overlay"></div>' ).appendTo( 'body' );
},
overlayOff = function()
{
$( '#imagelightbox-overlay' ).remove();
},
closeButtonOn = function( instance )
{
$( '<a href="#" id="imagelightbox-close" title="close"><i class="fa fa fa-times"></i></a>' ).appendTo( 'body' ).on( 'click touchend', function(){ $( this ).remove(); instance.quitImageLightbox(); return false; });
},
closeButtonOff = function()
{
$( '#imagelightbox-close' ).remove();
},
captionOn = function()
{
var description = $( 'a[href="' + $( '#imagelightbox' ).attr( 'src' ) + '"] img' ).attr( 'alt' );
if( description.length > 0 )
$( '<div id="imagelightbox-caption">' + description + '</div>' ).appendTo( 'body' );
},
captionOff = function()
{
$( '#imagelightbox-caption' ).remove();
};
var instanceA = $( 'a[data-imagelightbox="a"]' ).imageLightbox(
{
onStart: function() { overlayOn(); closeButtonOn( instanceA ); },
onEnd: function() { overlayOff(); captionOff(); closeButtonOff(); activityIndicatorOff(); },
onLoadStart: function() { captionOff(); activityIndicatorOn(); },
onLoadEnd: function() { captionOn(); activityIndicatorOff(); }
});
}
else {
/*----------------------------------------------------*/
/* prettyPhoto for old IE
/*----------------------------------------------------*/
$("#screenshots").find(".item-wrap a").attr("rel","prettyPhoto[pp_gal]");
$("a[rel^='prettyPhoto']").prettyPhoto( {
animation_speed: 'fast', /* fast/slow/normal */
slideshow: false, /* false OR interval time in ms */
autoplay_slideshow: false, /* true/false */
opacity: 0.80, /* Value between 0 and 1 */
show_title: true, /* true/false */
allow_resize: true, /* Resize the photos bigger than viewport. true/false */
default_width: 500,
default_height: 344,
counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
theme: 'pp_default', /* light_rounded / dark_rounded / light_square / dark_square / facebook */
hideflash: false, /* Hides all the flash object on a page, set to TRUE if flash appears over prettyPhoto */
wmode: 'opaque', /* Set the flash wmode attribute */
autoplay: true, /* Automatically start videos: True/False */
modal: false, /* If set to true, only the close button will close the window */
overlay_gallery: false, /* If set to true, a gallery will overlay the fullscreen image on mouse over */
keyboard_shortcuts: true, /* Set to false if you open forms inside prettyPhoto */
deeplinking: false,
social_tools: false
});
}
})(jQuery); | Java |
//******************************************************************************
//
// Copyright (c) Microsoft. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//******************************************************************************
#pragma once
#include "App.g.h"
namespace MinAppCppCx
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
ref class App sealed
{
protected:
virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ e) override;
internal:
App();
private:
void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ e);
void OnNavigationFailed(Platform::Object ^sender, Windows::UI::Xaml::Navigation::NavigationFailedEventArgs ^e);
};
}
| Java |
/**
* @license Highcharts Gantt JS v7.2.0 (2019-09-03)
*
* CurrentDateIndicator
*
* (c) 2010-2019 Lars A. V. Cabrera
*
* License: www.highcharts.com/license
*/
'use strict';
(function (factory) {
if (typeof module === 'object' && module.exports) {
factory['default'] = factory;
module.exports = factory;
} else if (typeof define === 'function' && define.amd) {
define('highcharts/modules/current-date-indicator', ['highcharts'], function (Highcharts) {
factory(Highcharts);
factory.Highcharts = Highcharts;
return factory;
});
} else {
factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined);
}
}(function (Highcharts) {
var _modules = Highcharts ? Highcharts._modules : {};
function _registerModule(obj, path, args, fn) {
if (!obj.hasOwnProperty(path)) {
obj[path] = fn.apply(null, args);
}
}
_registerModule(_modules, 'parts-gantt/CurrentDateIndicator.js', [_modules['parts/Globals.js']], function (H) {
/* *
*
* (c) 2016-2019 Highsoft AS
*
* Author: Lars A. V. Cabrera
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var addEvent = H.addEvent, Axis = H.Axis, PlotLineOrBand = H.PlotLineOrBand, merge = H.merge, wrap = H.wrap;
var defaultConfig = {
/**
* Show an indicator on the axis for the current date and time. Can be a
* boolean or a configuration object similar to
* [xAxis.plotLines](#xAxis.plotLines).
*
* @sample gantt/current-date-indicator/demo
* Current date indicator enabled
* @sample gantt/current-date-indicator/object-config
* Current date indicator with custom options
*
* @type {boolean|*}
* @default true
* @extends xAxis.plotLines
* @excluding value
* @product gantt
* @apioption xAxis.currentDateIndicator
*/
currentDateIndicator: true,
color: '#ccd6eb',
width: 2,
label: {
/**
* Format of the label. This options is passed as the fist argument to
* [dateFormat](/class-reference/Highcharts#dateFormat) function.
*
* @type {string}
* @default '%a, %b %d %Y, %H:%M'
* @product gantt
* @apioption xAxis.currentDateIndicator.label.format
*/
format: '%a, %b %d %Y, %H:%M',
formatter: function (value, format) {
return H.dateFormat(format, value);
},
rotation: 0,
style: {
fontSize: '10px'
}
}
};
/* eslint-disable no-invalid-this */
addEvent(Axis, 'afterSetOptions', function () {
var options = this.options, cdiOptions = options.currentDateIndicator;
if (cdiOptions) {
cdiOptions = typeof cdiOptions === 'object' ?
merge(defaultConfig, cdiOptions) : merge(defaultConfig);
cdiOptions.value = new Date();
if (!options.plotLines) {
options.plotLines = [];
}
options.plotLines.push(cdiOptions);
}
});
addEvent(PlotLineOrBand, 'render', function () {
// If the label already exists, update its text
if (this.label) {
this.label.attr({
text: this.getLabelText(this.options.label)
});
}
});
wrap(PlotLineOrBand.prototype, 'getLabelText', function (defaultMethod, defaultLabelOptions) {
var options = this.options;
if (options.currentDateIndicator && options.label &&
typeof options.label.formatter === 'function') {
options.value = new Date();
return options.label.formatter
.call(this, options.value, options.label.format);
}
return defaultMethod.call(this, defaultLabelOptions);
});
});
_registerModule(_modules, 'masters/modules/current-date-indicator.src.js', [], function () {
});
})); | Java |
export DJANGO_SETTINGS_MODULE=froide.settings
export DJANGO_CONFIGURATION=Test
export PYTHONWARNINGS=ignore
test:
flake8 --ignore=E501,E123,E124,E126,E127,E128,E402,E731 --exclude=south_migrations froide
coverage run --branch --source=froide manage.py test froide
coverage report --omit="*/south_migrations/*,*/migrations/*"
| Java |
/******************************************************************************
*
* Module Name: dswscope - Scope stack manipulation
*
*****************************************************************************/
/******************************************************************************
*
* 1. Copyright Notice
*
* Some or all of this work - Copyright (c) 1999 - 2012, Intel Corp.
* All rights reserved.
*
* 2. License
*
* 2.1. This is your license from Intel Corp. under its intellectual property
* rights. You may have additional license terms from the party that provided
* you this software, covering your right to use that party's intellectual
* property rights.
*
* 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a
* copy of the source code appearing in this file ("Covered Code") an
* irrevocable, perpetual, worldwide license under Intel's copyrights in the
* base code distributed originally by Intel ("Original Intel Code") to copy,
* make derivatives, distribute, use and display any portion of the Covered
* Code in any form, with the right to sublicense such rights; and
*
* 2.3. Intel grants Licensee a non-exclusive and non-transferable patent
* license (with the right to sublicense), under only those claims of Intel
* patents that are infringed by the Original Intel Code, to make, use, sell,
* offer to sell, and import the Covered Code and derivative works thereof
* solely to the minimum extent necessary to exercise the above copyright
* license, and in no event shall the patent license extend to any additions
* to or modifications of the Original Intel Code. No other license or right
* is granted directly or by implication, estoppel or otherwise;
*
* The above copyright and patent license is granted only if the following
* conditions are met:
*
* 3. Conditions
*
* 3.1. Redistribution of Source with Rights to Further Distribute Source.
* Redistribution of source code of any substantial portion of the Covered
* Code or modification with rights to further distribute source must include
* the above Copyright Notice, the above License, this list of Conditions,
* and the following Disclaimer and Export Compliance provision. In addition,
* Licensee must cause all Covered Code to which Licensee contributes to
* contain a file documenting the changes Licensee made to create that Covered
* Code and the date of any change. Licensee must include in that file the
* documentation of any changes made by any predecessor Licensee. Licensee
* must include a prominent statement that the modification is derived,
* directly or indirectly, from Original Intel Code.
*
* 3.2. Redistribution of Source with no Rights to Further Distribute Source.
* Redistribution of source code of any substantial portion of the Covered
* Code or modification without rights to further distribute source must
* include the following Disclaimer and Export Compliance provision in the
* documentation and/or other materials provided with distribution. In
* addition, Licensee may not authorize further sublicense of source of any
* portion of the Covered Code, and must include terms to the effect that the
* license from Licensee to its licensee is limited to the intellectual
* property embodied in the software Licensee provides to its licensee, and
* not to intellectual property embodied in modifications its licensee may
* make.
*
* 3.3. Redistribution of Executable. Redistribution in executable form of any
* substantial portion of the Covered Code or modification must reproduce the
* above Copyright Notice, and the following Disclaimer and Export Compliance
* provision in the documentation and/or other materials provided with the
* distribution.
*
* 3.4. Intel retains all right, title, and interest in and to the Original
* Intel Code.
*
* 3.5. Neither the name Intel nor any other trademark owned or controlled by
* Intel shall be used in advertising or otherwise to promote the sale, use or
* other dealings in products derived from or relating to the Covered Code
* without prior written authorization from Intel.
*
* 4. Disclaimer and Export Compliance
*
* 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED
* HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE
* IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE,
* INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY
* UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY
* IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A
* PARTICULAR PURPOSE.
*
* 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES
* OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR
* COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT,
* SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY
* CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL
* HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS
* SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY
* LIMITED REMEDY.
*
* 4.3. Licensee shall not export, either directly or indirectly, any of this
* software or system incorporating such software without first obtaining any
* required license or other approval from the U. S. Department of Commerce or
* any other agency or department of the United States Government. In the
* event Licensee exports any such software from the United States or
* re-exports any such software from a foreign destination, Licensee shall
* ensure that the distribution and export/re-export of the software is in
* compliance with all laws, regulations, orders, or other restrictions of the
* U.S. Export Administration Regulations. Licensee agrees that neither it nor
* any of its subsidiaries will export/re-export any technical data, process,
* software, or service, directly or indirectly, to any country for which the
* United States government or any agency thereof requires an export license,
* other governmental approval, or letter of assurance, without first obtaining
* such license, approval or letter.
*
*****************************************************************************/
#define __DSWSCOPE_C__
#include "acpi.h"
#include "accommon.h"
#include "acdispat.h"
#define _COMPONENT ACPI_DISPATCHER
ACPI_MODULE_NAME ("dswscope")
/****************************************************************************
*
* FUNCTION: AcpiDsScopeStackClear
*
* PARAMETERS: WalkState - Current state
*
* RETURN: None
*
* DESCRIPTION: Pop (and free) everything on the scope stack except the
* root scope object (which remains at the stack top.)
*
***************************************************************************/
void
AcpiDsScopeStackClear (
ACPI_WALK_STATE *WalkState)
{
ACPI_GENERIC_STATE *ScopeInfo;
ACPI_FUNCTION_NAME (DsScopeStackClear);
while (WalkState->ScopeInfo)
{
/* Pop a scope off the stack */
ScopeInfo = WalkState->ScopeInfo;
WalkState->ScopeInfo = ScopeInfo->Scope.Next;
ACPI_DEBUG_PRINT ((ACPI_DB_EXEC,
"Popped object type (%s)\n",
AcpiUtGetTypeName (ScopeInfo->Common.Value)));
AcpiUtDeleteGenericState (ScopeInfo);
}
}
/****************************************************************************
*
* FUNCTION: AcpiDsScopeStackPush
*
* PARAMETERS: Node - Name to be made current
* Type - Type of frame being pushed
* WalkState - Current state
*
* RETURN: Status
*
* DESCRIPTION: Push the current scope on the scope stack, and make the
* passed Node current.
*
***************************************************************************/
ACPI_STATUS
AcpiDsScopeStackPush (
ACPI_NAMESPACE_NODE *Node,
ACPI_OBJECT_TYPE Type,
ACPI_WALK_STATE *WalkState)
{
ACPI_GENERIC_STATE *ScopeInfo;
ACPI_GENERIC_STATE *OldScopeInfo;
ACPI_FUNCTION_TRACE (DsScopeStackPush);
if (!Node)
{
/* Invalid scope */
ACPI_ERROR ((AE_INFO, "Null scope parameter"));
return_ACPI_STATUS (AE_BAD_PARAMETER);
}
/* Make sure object type is valid */
if (!AcpiUtValidObjectType (Type))
{
ACPI_WARNING ((AE_INFO,
"Invalid object type: 0x%X", Type));
}
/* Allocate a new scope object */
ScopeInfo = AcpiUtCreateGenericState ();
if (!ScopeInfo)
{
return_ACPI_STATUS (AE_NO_MEMORY);
}
/* Init new scope object */
ScopeInfo->Common.DescriptorType = ACPI_DESC_TYPE_STATE_WSCOPE;
ScopeInfo->Scope.Node = Node;
ScopeInfo->Common.Value = (UINT16) Type;
WalkState->ScopeDepth++;
ACPI_DEBUG_PRINT ((ACPI_DB_EXEC,
"[%.2d] Pushed scope ", (UINT32) WalkState->ScopeDepth));
OldScopeInfo = WalkState->ScopeInfo;
if (OldScopeInfo)
{
ACPI_DEBUG_PRINT_RAW ((ACPI_DB_EXEC,
"[%4.4s] (%s)",
AcpiUtGetNodeName (OldScopeInfo->Scope.Node),
AcpiUtGetTypeName (OldScopeInfo->Common.Value)));
}
else
{
ACPI_DEBUG_PRINT_RAW ((ACPI_DB_EXEC,
"[\\___] (%s)", "ROOT"));
}
ACPI_DEBUG_PRINT_RAW ((ACPI_DB_EXEC,
", New scope -> [%4.4s] (%s)\n",
AcpiUtGetNodeName (ScopeInfo->Scope.Node),
AcpiUtGetTypeName (ScopeInfo->Common.Value)));
/* Push new scope object onto stack */
AcpiUtPushGenericState (&WalkState->ScopeInfo, ScopeInfo);
return_ACPI_STATUS (AE_OK);
}
/****************************************************************************
*
* FUNCTION: AcpiDsScopeStackPop
*
* PARAMETERS: WalkState - Current state
*
* RETURN: Status
*
* DESCRIPTION: Pop the scope stack once.
*
***************************************************************************/
ACPI_STATUS
AcpiDsScopeStackPop (
ACPI_WALK_STATE *WalkState)
{
ACPI_GENERIC_STATE *ScopeInfo;
ACPI_GENERIC_STATE *NewScopeInfo;
ACPI_FUNCTION_TRACE (DsScopeStackPop);
/*
* Pop scope info object off the stack.
*/
ScopeInfo = AcpiUtPopGenericState (&WalkState->ScopeInfo);
if (!ScopeInfo)
{
return_ACPI_STATUS (AE_STACK_UNDERFLOW);
}
WalkState->ScopeDepth--;
ACPI_DEBUG_PRINT ((ACPI_DB_EXEC,
"[%.2d] Popped scope [%4.4s] (%s), New scope -> ",
(UINT32) WalkState->ScopeDepth,
AcpiUtGetNodeName (ScopeInfo->Scope.Node),
AcpiUtGetTypeName (ScopeInfo->Common.Value)));
NewScopeInfo = WalkState->ScopeInfo;
if (NewScopeInfo)
{
ACPI_DEBUG_PRINT_RAW ((ACPI_DB_EXEC,
"[%4.4s] (%s)\n",
AcpiUtGetNodeName (NewScopeInfo->Scope.Node),
AcpiUtGetTypeName (NewScopeInfo->Common.Value)));
}
else
{
ACPI_DEBUG_PRINT_RAW ((ACPI_DB_EXEC,
"[\\___] (ROOT)\n"));
}
AcpiUtDeleteGenericState (ScopeInfo);
return_ACPI_STATUS (AE_OK);
}
| Java |
<?php
namespace Illuminate\Support;
use stdClass;
use Countable;
use Exception;
use ArrayAccess;
use Traversable;
use ArrayIterator;
use CachingIterator;
use JsonSerializable;
use IteratorAggregate;
use Illuminate\Support\Debug\Dumper;
use Illuminate\Support\Traits\Macroable;
use Illuminate\Contracts\Support\Jsonable;
use Illuminate\Contracts\Support\Arrayable;
class Collection implements ArrayAccess, Arrayable, Countable, IteratorAggregate, Jsonable, JsonSerializable
{
use Macroable;
/**
* The items contained in the collection.
*
* @var array
*/
protected $items = [];
/**
* The methods that can be proxied.
*
* @var array
*/
protected static $proxies = [
'average', 'avg', 'contains', 'each', 'every', 'filter', 'first', 'flatMap',
'keyBy', 'map', 'partition', 'reject', 'sortBy', 'sortByDesc', 'sum',
];
/**
* Create a new collection.
*
* @param mixed $items
* @return void
*/
public function __construct($items = [])
{
$this->items = $this->getArrayableItems($items);
}
/**
* Create a new collection instance if the value isn't one already.
*
* @param mixed $items
* @return static
*/
public static function make($items = [])
{
return new static($items);
}
/**
* Wrap the given value in a collection if applicable.
*
* @param mixed $value
* @return static
*/
public static function wrap($value)
{
return $value instanceof self
? new static($value)
: new static(Arr::wrap($value));
}
/**
* Get the underlying items from the given collection if applicable.
*
* @param array|static $value
* @return array
*/
public static function unwrap($value)
{
return $value instanceof self ? $value->all() : $value;
}
/**
* Create a new collection by invoking the callback a given amount of times.
*
* @param int $number
* @param callable $callback
* @return static
*/
public static function times($number, callable $callback = null)
{
if ($number < 1) {
return new static;
}
if (is_null($callback)) {
return new static(range(1, $number));
}
return (new static(range(1, $number)))->map($callback);
}
/**
* Get all of the items in the collection.
*
* @return array
*/
public function all()
{
return $this->items;
}
/**
* Get the average value of a given key.
*
* @param callable|string|null $callback
* @return mixed
*/
public function avg($callback = null)
{
if ($count = $this->count()) {
return $this->sum($callback) / $count;
}
}
/**
* Alias for the "avg" method.
*
* @param callable|string|null $callback
* @return mixed
*/
public function average($callback = null)
{
return $this->avg($callback);
}
/**
* Get the median of a given key.
*
* @param null $key
* @return mixed
*/
public function median($key = null)
{
$count = $this->count();
if ($count == 0) {
return;
}
$values = (isset($key) ? $this->pluck($key) : $this)
->sort()->values();
$middle = (int) ($count / 2);
if ($count % 2) {
return $values->get($middle);
}
return (new static([
$values->get($middle - 1), $values->get($middle),
]))->average();
}
/**
* Get the mode of a given key.
*
* @param mixed $key
* @return array|null
*/
public function mode($key = null)
{
$count = $this->count();
if ($count == 0) {
return;
}
$collection = isset($key) ? $this->pluck($key) : $this;
$counts = new self;
$collection->each(function ($value) use ($counts) {
$counts[$value] = isset($counts[$value]) ? $counts[$value] + 1 : 1;
});
$sorted = $counts->sort();
$highestValue = $sorted->last();
return $sorted->filter(function ($value) use ($highestValue) {
return $value == $highestValue;
})->sort()->keys()->all();
}
/**
* Collapse the collection of items into a single array.
*
* @return static
*/
public function collapse()
{
return new static(Arr::collapse($this->items));
}
/**
* Determine if an item exists in the collection.
*
* @param mixed $key
* @param mixed $operator
* @param mixed $value
* @return bool
*/
public function contains($key, $operator = null, $value = null)
{
if (func_num_args() == 1) {
if ($this->useAsCallable($key)) {
$placeholder = new stdClass;
return $this->first($key, $placeholder) !== $placeholder;
}
return in_array($key, $this->items);
}
return $this->contains($this->operatorForWhere(...func_get_args()));
}
/**
* Determine if an item exists in the collection using strict comparison.
*
* @param mixed $key
* @param mixed $value
* @return bool
*/
public function containsStrict($key, $value = null)
{
if (func_num_args() == 2) {
return $this->contains(function ($item) use ($key, $value) {
return data_get($item, $key) === $value;
});
}
if ($this->useAsCallable($key)) {
return ! is_null($this->first($key));
}
return in_array($key, $this->items, true);
}
/**
* Cross join with the given lists, returning all possible permutations.
*
* @param mixed ...$lists
* @return static
*/
public function crossJoin(...$lists)
{
return new static(Arr::crossJoin(
$this->items, ...array_map([$this, 'getArrayableItems'], $lists)
));
}
/**
* Dump the collection and end the script.
*
* @return void
*/
public function dd(...$args)
{
http_response_code(500);
call_user_func_array([$this, 'dump'], $args);
die(1);
}
/**
* Dump the collection.
*
* @return $this
*/
public function dump()
{
(new static(func_get_args()))
->push($this)
->each(function ($item) {
(new Dumper)->dump($item);
});
return $this;
}
/**
* Get the items in the collection that are not present in the given items.
*
* @param mixed $items
* @return static
*/
public function diff($items)
{
return new static(array_diff($this->items, $this->getArrayableItems($items)));
}
/**
* Get the items in the collection whose keys and values are not present in the given items.
*
* @param mixed $items
* @return static
*/
public function diffAssoc($items)
{
return new static(array_diff_assoc($this->items, $this->getArrayableItems($items)));
}
/**
* Get the items in the collection whose keys are not present in the given items.
*
* @param mixed $items
* @return static
*/
public function diffKeys($items)
{
return new static(array_diff_key($this->items, $this->getArrayableItems($items)));
}
/**
* Execute a callback over each item.
*
* @param callable $callback
* @return $this
*/
public function each(callable $callback)
{
foreach ($this->items as $key => $item) {
if ($callback($item, $key) === false) {
break;
}
}
return $this;
}
/**
* Execute a callback over each nested chunk of items.
*
* @param callable $callback
* @return static
*/
public function eachSpread(callable $callback)
{
return $this->each(function ($chunk, $key) use ($callback) {
$chunk[] = $key;
return $callback(...$chunk);
});
}
/**
* Determine if all items in the collection pass the given test.
*
* @param string|callable $key
* @param mixed $operator
* @param mixed $value
* @return bool
*/
public function every($key, $operator = null, $value = null)
{
if (func_num_args() == 1) {
$callback = $this->valueRetriever($key);
foreach ($this->items as $k => $v) {
if (! $callback($v, $k)) {
return false;
}
}
return true;
}
return $this->every($this->operatorForWhere(...func_get_args()));
}
/**
* Get all items except for those with the specified keys.
*
* @param \Illuminate\Support\Collection|mixed $keys
* @return static
*/
public function except($keys)
{
if ($keys instanceof self) {
$keys = $keys->all();
} elseif (! is_array($keys)) {
$keys = func_get_args();
}
return new static(Arr::except($this->items, $keys));
}
/**
* Run a filter over each of the items.
*
* @param callable|null $callback
* @return static
*/
public function filter(callable $callback = null)
{
if ($callback) {
return new static(Arr::where($this->items, $callback));
}
return new static(array_filter($this->items));
}
/**
* Apply the callback if the value is truthy.
*
* @param bool $value
* @param callable $callback
* @param callable $default
* @return mixed
*/
public function when($value, callable $callback, callable $default = null)
{
if ($value) {
return $callback($this, $value);
} elseif ($default) {
return $default($this, $value);
}
return $this;
}
/**
* Apply the callback if the value is falsy.
*
* @param bool $value
* @param callable $callback
* @param callable $default
* @return mixed
*/
public function unless($value, callable $callback, callable $default = null)
{
return $this->when(! $value, $callback, $default);
}
/**
* Filter items by the given key value pair.
*
* @param string $key
* @param mixed $operator
* @param mixed $value
* @return static
*/
public function where($key, $operator, $value = null)
{
return $this->filter($this->operatorForWhere(...func_get_args()));
}
/**
* Get an operator checker callback.
*
* @param string $key
* @param string $operator
* @param mixed $value
* @return \Closure
*/
protected function operatorForWhere($key, $operator, $value = null)
{
if (func_num_args() == 2) {
$value = $operator;
$operator = '=';
}
return function ($item) use ($key, $operator, $value) {
$retrieved = data_get($item, $key);
$strings = array_filter([$retrieved, $value], function ($value) {
return is_string($value) || (is_object($value) && method_exists($value, '__toString'));
});
if (count($strings) < 2 && count(array_filter([$retrieved, $value], 'is_object')) == 1) {
return in_array($operator, ['!=', '<>', '!==']);
}
switch ($operator) {
default:
case '=':
case '==': return $retrieved == $value;
case '!=':
case '<>': return $retrieved != $value;
case '<': return $retrieved < $value;
case '>': return $retrieved > $value;
case '<=': return $retrieved <= $value;
case '>=': return $retrieved >= $value;
case '===': return $retrieved === $value;
case '!==': return $retrieved !== $value;
}
};
}
/**
* Filter items by the given key value pair using strict comparison.
*
* @param string $key
* @param mixed $value
* @return static
*/
public function whereStrict($key, $value)
{
return $this->where($key, '===', $value);
}
/**
* Filter items by the given key value pair.
*
* @param string $key
* @param mixed $values
* @param bool $strict
* @return static
*/
public function whereIn($key, $values, $strict = false)
{
$values = $this->getArrayableItems($values);
return $this->filter(function ($item) use ($key, $values, $strict) {
return in_array(data_get($item, $key), $values, $strict);
});
}
/**
* Filter items by the given key value pair using strict comparison.
*
* @param string $key
* @param mixed $values
* @return static
*/
public function whereInStrict($key, $values)
{
return $this->whereIn($key, $values, true);
}
/**
* Filter items by the given key value pair.
*
* @param string $key
* @param mixed $values
* @param bool $strict
* @return static
*/
public function whereNotIn($key, $values, $strict = false)
{
$values = $this->getArrayableItems($values);
return $this->reject(function ($item) use ($key, $values, $strict) {
return in_array(data_get($item, $key), $values, $strict);
});
}
/**
* Filter items by the given key value pair using strict comparison.
*
* @param string $key
* @param mixed $values
* @return static
*/
public function whereNotInStrict($key, $values)
{
return $this->whereNotIn($key, $values, true);
}
/**
* Get the first item from the collection.
*
* @param callable|null $callback
* @param mixed $default
* @return mixed
*/
public function first(callable $callback = null, $default = null)
{
return Arr::first($this->items, $callback, $default);
}
/**
* Get the first item by the given key value pair.
*
* @param string $key
* @param mixed $operator
* @param mixed $value
* @return static
*/
public function firstWhere($key, $operator, $value = null)
{
return $this->first($this->operatorForWhere(...func_get_args()));
}
/**
* Get a flattened array of the items in the collection.
*
* @param int $depth
* @return static
*/
public function flatten($depth = INF)
{
return new static(Arr::flatten($this->items, $depth));
}
/**
* Flip the items in the collection.
*
* @return static
*/
public function flip()
{
return new static(array_flip($this->items));
}
/**
* Remove an item from the collection by key.
*
* @param string|array $keys
* @return $this
*/
public function forget($keys)
{
foreach ((array) $keys as $key) {
$this->offsetUnset($key);
}
return $this;
}
/**
* Get an item from the collection by key.
*
* @param mixed $key
* @param mixed $default
* @return mixed
*/
public function get($key, $default = null)
{
if ($this->offsetExists($key)) {
return $this->items[$key];
}
return value($default);
}
/**
* Group an associative array by a field or using a callback.
*
* @param callable|string $groupBy
* @param bool $preserveKeys
* @return static
*/
public function groupBy($groupBy, $preserveKeys = false)
{
if (is_array($groupBy)) {
$nextGroups = $groupBy;
$groupBy = array_shift($nextGroups);
}
$groupBy = $this->valueRetriever($groupBy);
$results = [];
foreach ($this->items as $key => $value) {
$groupKeys = $groupBy($value, $key);
if (! is_array($groupKeys)) {
$groupKeys = [$groupKeys];
}
foreach ($groupKeys as $groupKey) {
$groupKey = is_bool($groupKey) ? (int) $groupKey : $groupKey;
if (! array_key_exists($groupKey, $results)) {
$results[$groupKey] = new static;
}
$results[$groupKey]->offsetSet($preserveKeys ? $key : null, $value);
}
}
$result = new static($results);
if (! empty($nextGroups)) {
return $result->map->groupBy($nextGroups, $preserveKeys);
}
return $result;
}
/**
* Key an associative array by a field or using a callback.
*
* @param callable|string $keyBy
* @return static
*/
public function keyBy($keyBy)
{
$keyBy = $this->valueRetriever($keyBy);
$results = [];
foreach ($this->items as $key => $item) {
$resolvedKey = $keyBy($item, $key);
if (is_object($resolvedKey)) {
$resolvedKey = (string) $resolvedKey;
}
$results[$resolvedKey] = $item;
}
return new static($results);
}
/**
* Determine if an item exists in the collection by key.
*
* @param mixed $key
* @return bool
*/
public function has($key)
{
$keys = is_array($key) ? $key : func_get_args();
foreach ($keys as $value) {
if (! $this->offsetExists($value)) {
return false;
}
}
return true;
}
/**
* Concatenate values of a given key as a string.
*
* @param string $value
* @param string $glue
* @return string
*/
public function implode($value, $glue = null)
{
$first = $this->first();
if (is_array($first) || is_object($first)) {
return implode($glue, $this->pluck($value)->all());
}
return implode($value, $this->items);
}
/**
* Intersect the collection with the given items.
*
* @param mixed $items
* @return static
*/
public function intersect($items)
{
return new static(array_intersect($this->items, $this->getArrayableItems($items)));
}
/**
* Intersect the collection with the given items by key.
*
* @param mixed $items
* @return static
*/
public function intersectByKeys($items)
{
return new static(array_intersect_key(
$this->items, $this->getArrayableItems($items)
));
}
/**
* Determine if the collection is empty or not.
*
* @return bool
*/
public function isEmpty()
{
return empty($this->items);
}
/**
* Determine if the collection is not empty.
*
* @return bool
*/
public function isNotEmpty()
{
return ! $this->isEmpty();
}
/**
* Determine if the given value is callable, but not a string.
*
* @param mixed $value
* @return bool
*/
protected function useAsCallable($value)
{
return ! is_string($value) && is_callable($value);
}
/**
* Get the keys of the collection items.
*
* @return static
*/
public function keys()
{
return new static(array_keys($this->items));
}
/**
* Get the last item from the collection.
*
* @param callable|null $callback
* @param mixed $default
* @return mixed
*/
public function last(callable $callback = null, $default = null)
{
return Arr::last($this->items, $callback, $default);
}
/**
* Get the values of a given key.
*
* @param string|array $value
* @param string|null $key
* @return static
*/
public function pluck($value, $key = null)
{
return new static(Arr::pluck($this->items, $value, $key));
}
/**
* Run a map over each of the items.
*
* @param callable $callback
* @return static
*/
public function map(callable $callback)
{
$keys = array_keys($this->items);
$items = array_map($callback, $this->items, $keys);
return new static(array_combine($keys, $items));
}
/**
* Run a map over each nested chunk of items.
*
* @param callable $callback
* @return static
*/
public function mapSpread(callable $callback)
{
return $this->map(function ($chunk, $key) use ($callback) {
$chunk[] = $key;
return $callback(...$chunk);
});
}
/**
* Run a dictionary map over the items.
*
* The callback should return an associative array with a single key/value pair.
*
* @param callable $callback
* @return static
*/
public function mapToDictionary(callable $callback)
{
$dictionary = $this->map($callback)->reduce(function ($groups, $pair) {
$groups[key($pair)][] = reset($pair);
return $groups;
}, []);
return new static($dictionary);
}
/**
* Run a grouping map over the items.
*
* The callback should return an associative array with a single key/value pair.
*
* @param callable $callback
* @return static
*/
public function mapToGroups(callable $callback)
{
$groups = $this->mapToDictionary($callback);
return $groups->map([$this, 'make']);
}
/**
* Run an associative map over each of the items.
*
* The callback should return an associative array with a single key/value pair.
*
* @param callable $callback
* @return static
*/
public function mapWithKeys(callable $callback)
{
$result = [];
foreach ($this->items as $key => $value) {
$assoc = $callback($value, $key);
foreach ($assoc as $mapKey => $mapValue) {
$result[$mapKey] = $mapValue;
}
}
return new static($result);
}
/**
* Map a collection and flatten the result by a single level.
*
* @param callable $callback
* @return static
*/
public function flatMap(callable $callback)
{
return $this->map($callback)->collapse();
}
/**
* Map the values into a new class.
*
* @param string $class
* @return static
*/
public function mapInto($class)
{
return $this->map(function ($value, $key) use ($class) {
return new $class($value, $key);
});
}
/**
* Get the max value of a given key.
*
* @param callable|string|null $callback
* @return mixed
*/
public function max($callback = null)
{
$callback = $this->valueRetriever($callback);
return $this->filter(function ($value) {
return ! is_null($value);
})->reduce(function ($result, $item) use ($callback) {
$value = $callback($item);
return is_null($result) || $value > $result ? $value : $result;
});
}
/**
* Merge the collection with the given items.
*
* @param mixed $items
* @return static
*/
public function merge($items)
{
return new static(array_merge($this->items, $this->getArrayableItems($items)));
}
/**
* Create a collection by using this collection for keys and another for its values.
*
* @param mixed $values
* @return static
*/
public function combine($values)
{
return new static(array_combine($this->all(), $this->getArrayableItems($values)));
}
/**
* Union the collection with the given items.
*
* @param mixed $items
* @return static
*/
public function union($items)
{
return new static($this->items + $this->getArrayableItems($items));
}
/**
* Get the min value of a given key.
*
* @param callable|string|null $callback
* @return mixed
*/
public function min($callback = null)
{
$callback = $this->valueRetriever($callback);
return $this->filter(function ($value) {
return ! is_null($value);
})->reduce(function ($result, $item) use ($callback) {
$value = $callback($item);
return is_null($result) || $value < $result ? $value : $result;
});
}
/**
* Create a new collection consisting of every n-th element.
*
* @param int $step
* @param int $offset
* @return static
*/
public function nth($step, $offset = 0)
{
$new = [];
$position = 0;
foreach ($this->items as $item) {
if ($position % $step === $offset) {
$new[] = $item;
}
$position++;
}
return new static($new);
}
/**
* Get the items with the specified keys.
*
* @param mixed $keys
* @return static
*/
public function only($keys)
{
if (is_null($keys)) {
return new static($this->items);
}
if ($keys instanceof self) {
$keys = $keys->all();
}
$keys = is_array($keys) ? $keys : func_get_args();
return new static(Arr::only($this->items, $keys));
}
/**
* "Paginate" the collection by slicing it into a smaller collection.
*
* @param int $page
* @param int $perPage
* @return static
*/
public function forPage($page, $perPage)
{
$offset = max(0, ($page - 1) * $perPage);
return $this->slice($offset, $perPage);
}
/**
* Partition the collection into two arrays using the given callback or key.
*
* @param callable|string $callback
* @return static
*/
public function partition($callback)
{
$partitions = [new static, new static];
$callback = $this->valueRetriever($callback);
foreach ($this->items as $key => $item) {
$partitions[(int) ! $callback($item, $key)][$key] = $item;
}
return new static($partitions);
}
/**
* Pass the collection to the given callback and return the result.
*
* @param callable $callback
* @return mixed
*/
public function pipe(callable $callback)
{
return $callback($this);
}
/**
* Get and remove the last item from the collection.
*
* @return mixed
*/
public function pop()
{
return array_pop($this->items);
}
/**
* Push an item onto the beginning of the collection.
*
* @param mixed $value
* @param mixed $key
* @return $this
*/
public function prepend($value, $key = null)
{
$this->items = Arr::prepend($this->items, $value, $key);
return $this;
}
/**
* Push an item onto the end of the collection.
*
* @param mixed $value
* @return $this
*/
public function push($value)
{
$this->offsetSet(null, $value);
return $this;
}
/**
* Push all of the given items onto the collection.
*
* @param \Traversable $source
* @return $this
*/
public function concat($source)
{
$result = new static($this);
foreach ($source as $item) {
$result->push($item);
}
return $result;
}
/**
* Get and remove an item from the collection.
*
* @param mixed $key
* @param mixed $default
* @return mixed
*/
public function pull($key, $default = null)
{
return Arr::pull($this->items, $key, $default);
}
/**
* Put an item in the collection by key.
*
* @param mixed $key
* @param mixed $value
* @return $this
*/
public function put($key, $value)
{
$this->offsetSet($key, $value);
return $this;
}
/**
* Get one or a specified number of items randomly from the collection.
*
* @param int|null $number
* @return mixed
*
* @throws \InvalidArgumentException
*/
public function random($number = null)
{
if (is_null($number)) {
return Arr::random($this->items);
}
return new static(Arr::random($this->items, $number));
}
/**
* Reduce the collection to a single value.
*
* @param callable $callback
* @param mixed $initial
* @return mixed
*/
public function reduce(callable $callback, $initial = null)
{
return array_reduce($this->items, $callback, $initial);
}
/**
* Create a collection of all elements that do not pass a given truth test.
*
* @param callable|mixed $callback
* @return static
*/
public function reject($callback)
{
if ($this->useAsCallable($callback)) {
return $this->filter(function ($value, $key) use ($callback) {
return ! $callback($value, $key);
});
}
return $this->filter(function ($item) use ($callback) {
return $item != $callback;
});
}
/**
* Reverse items order.
*
* @return static
*/
public function reverse()
{
return new static(array_reverse($this->items, true));
}
/**
* Search the collection for a given value and return the corresponding key if successful.
*
* @param mixed $value
* @param bool $strict
* @return mixed
*/
public function search($value, $strict = false)
{
if (! $this->useAsCallable($value)) {
return array_search($value, $this->items, $strict);
}
foreach ($this->items as $key => $item) {
if (call_user_func($value, $item, $key)) {
return $key;
}
}
return false;
}
/**
* Get and remove the first item from the collection.
*
* @return mixed
*/
public function shift()
{
return array_shift($this->items);
}
/**
* Shuffle the items in the collection.
*
* @param int $seed
* @return static
*/
public function shuffle($seed = null)
{
$items = $this->items;
if (is_null($seed)) {
shuffle($items);
} else {
srand($seed);
usort($items, function () {
return rand(-1, 1);
});
}
return new static($items);
}
/**
* Slice the underlying collection array.
*
* @param int $offset
* @param int $length
* @return static
*/
public function slice($offset, $length = null)
{
return new static(array_slice($this->items, $offset, $length, true));
}
/**
* Split a collection into a certain number of groups.
*
* @param int $numberOfGroups
* @return static
*/
public function split($numberOfGroups)
{
if ($this->isEmpty()) {
return new static;
}
$groupSize = ceil($this->count() / $numberOfGroups);
return $this->chunk($groupSize);
}
/**
* Chunk the underlying collection array.
*
* @param int $size
* @return static
*/
public function chunk($size)
{
if ($size <= 0) {
return new static;
}
$chunks = [];
foreach (array_chunk($this->items, $size, true) as $chunk) {
$chunks[] = new static($chunk);
}
return new static($chunks);
}
/**
* Sort through each item with a callback.
*
* @param callable|null $callback
* @return static
*/
public function sort(callable $callback = null)
{
$items = $this->items;
$callback
? uasort($items, $callback)
: asort($items);
return new static($items);
}
/**
* Sort the collection using the given callback.
*
* @param callable|string $callback
* @param int $options
* @param bool $descending
* @return static
*/
public function sortBy($callback, $options = SORT_REGULAR, $descending = false)
{
$results = [];
$callback = $this->valueRetriever($callback);
// First we will loop through the items and get the comparator from a callback
// function which we were given. Then, we will sort the returned values and
// and grab the corresponding values for the sorted keys from this array.
foreach ($this->items as $key => $value) {
$results[$key] = $callback($value, $key);
}
$descending ? arsort($results, $options)
: asort($results, $options);
// Once we have sorted all of the keys in the array, we will loop through them
// and grab the corresponding model so we can set the underlying items list
// to the sorted version. Then we'll just return the collection instance.
foreach (array_keys($results) as $key) {
$results[$key] = $this->items[$key];
}
return new static($results);
}
/**
* Sort the collection in descending order using the given callback.
*
* @param callable|string $callback
* @param int $options
* @return static
*/
public function sortByDesc($callback, $options = SORT_REGULAR)
{
return $this->sortBy($callback, $options, true);
}
/**
* Splice a portion of the underlying collection array.
*
* @param int $offset
* @param int|null $length
* @param mixed $replacement
* @return static
*/
public function splice($offset, $length = null, $replacement = [])
{
if (func_num_args() == 1) {
return new static(array_splice($this->items, $offset));
}
return new static(array_splice($this->items, $offset, $length, $replacement));
}
/**
* Get the sum of the given values.
*
* @param callable|string|null $callback
* @return mixed
*/
public function sum($callback = null)
{
if (is_null($callback)) {
return array_sum($this->items);
}
$callback = $this->valueRetriever($callback);
return $this->reduce(function ($result, $item) use ($callback) {
return $result + $callback($item);
}, 0);
}
/**
* Take the first or last {$limit} items.
*
* @param int $limit
* @return static
*/
public function take($limit)
{
if ($limit < 0) {
return $this->slice($limit, abs($limit));
}
return $this->slice(0, $limit);
}
/**
* Pass the collection to the given callback and then return it.
*
* @param callable $callback
* @return $this
*/
public function tap(callable $callback)
{
$callback(new static($this->items));
return $this;
}
/**
* Transform each item in the collection using a callback.
*
* @param callable $callback
* @return $this
*/
public function transform(callable $callback)
{
$this->items = $this->map($callback)->all();
return $this;
}
/**
* Return only unique items from the collection array.
*
* @param string|callable|null $key
* @param bool $strict
* @return static
*/
public function unique($key = null, $strict = false)
{
if (is_null($key)) {
return new static(array_unique($this->items, SORT_REGULAR));
}
$callback = $this->valueRetriever($key);
$exists = [];
return $this->reject(function ($item, $key) use ($callback, $strict, &$exists) {
if (in_array($id = $callback($item, $key), $exists, $strict)) {
return true;
}
$exists[] = $id;
});
}
/**
* Return only unique items from the collection array using strict comparison.
*
* @param string|callable|null $key
* @return static
*/
public function uniqueStrict($key = null)
{
return $this->unique($key, true);
}
/**
* Reset the keys on the underlying array.
*
* @return static
*/
public function values()
{
return new static(array_values($this->items));
}
/**
* Get a value retrieving callback.
*
* @param string $value
* @return callable
*/
protected function valueRetriever($value)
{
if ($this->useAsCallable($value)) {
return $value;
}
return function ($item) use ($value) {
return data_get($item, $value);
};
}
/**
* Zip the collection together with one or more arrays.
*
* e.g. new Collection([1, 2, 3])->zip([4, 5, 6]);
* => [[1, 4], [2, 5], [3, 6]]
*
* @param mixed ...$items
* @return static
*/
public function zip($items)
{
$arrayableItems = array_map(function ($items) {
return $this->getArrayableItems($items);
}, func_get_args());
$params = array_merge([function () {
return new static(func_get_args());
}, $this->items], $arrayableItems);
return new static(call_user_func_array('array_map', $params));
}
/**
* Pad collection to the specified length with a value.
*
* @param int $size
* @param mixed $value
* @return static
*/
public function pad($size, $value)
{
return new static(array_pad($this->items, $size, $value));
}
/**
* Get the collection of items as a plain array.
*
* @return array
*/
public function toArray()
{
return array_map(function ($value) {
return $value instanceof Arrayable ? $value->toArray() : $value;
}, $this->items);
}
/**
* Convert the object into something JSON serializable.
*
* @return array
*/
public function jsonSerialize()
{
return array_map(function ($value) {
if ($value instanceof JsonSerializable) {
return $value->jsonSerialize();
} elseif ($value instanceof Jsonable) {
return json_decode($value->toJson(), true);
} elseif ($value instanceof Arrayable) {
return $value->toArray();
}
return $value;
}, $this->items);
}
/**
* Get the collection of items as JSON.
*
* @param int $options
* @return string
*/
public function toJson($options = 0)
{
return json_encode($this->jsonSerialize(), $options);
}
/**
* Get an iterator for the items.
*
* @return \ArrayIterator
*/
public function getIterator()
{
return new ArrayIterator($this->items);
}
/**
* Get a CachingIterator instance.
*
* @param int $flags
* @return \CachingIterator
*/
public function getCachingIterator($flags = CachingIterator::CALL_TOSTRING)
{
return new CachingIterator($this->getIterator(), $flags);
}
/**
* Count the number of items in the collection.
*
* @return int
*/
public function count()
{
return count($this->items);
}
/**
* Get a base Support collection instance from this collection.
*
* @return \Illuminate\Support\Collection
*/
public function toBase()
{
return new self($this);
}
/**
* Determine if an item exists at an offset.
*
* @param mixed $key
* @return bool
*/
public function offsetExists($key)
{
return array_key_exists($key, $this->items);
}
/**
* Get an item at a given offset.
*
* @param mixed $key
* @return mixed
*/
public function offsetGet($key)
{
return $this->items[$key];
}
/**
* Set the item at a given offset.
*
* @param mixed $key
* @param mixed $value
* @return void
*/
public function offsetSet($key, $value)
{
if (is_null($key)) {
$this->items[] = $value;
} else {
$this->items[$key] = $value;
}
}
/**
* Unset the item at a given offset.
*
* @param string $key
* @return void
*/
public function offsetUnset($key)
{
unset($this->items[$key]);
}
/**
* Convert the collection to its string representation.
*
* @return string
*/
public function __toString()
{
return $this->toJson();
}
/**
* Results array of items from Collection or Arrayable.
*
* @param mixed $items
* @return array
*/
protected function getArrayableItems($items)
{
if (is_array($items)) {
return $items;
} elseif ($items instanceof self) {
return $items->all();
} elseif ($items instanceof Arrayable) {
return $items->toArray();
} elseif ($items instanceof Jsonable) {
return json_decode($items->toJson(), true);
} elseif ($items instanceof JsonSerializable) {
return $items->jsonSerialize();
} elseif ($items instanceof Traversable) {
return iterator_to_array($items);
}
return (array) $items;
}
/**
* Add a method to the list of proxied methods.
*
* @param string $method
* @return void
*/
public static function proxy($method)
{
static::$proxies[] = $method;
}
/**
* Dynamically access collection proxies.
*
* @param string $key
* @return mixed
*
* @throws \Exception
*/
public function __get($key)
{
if (! in_array($key, static::$proxies)) {
throw new Exception("Property [{$key}] does not exist on this collection instance.");
}
return new HigherOrderCollectionProxy($this, $key);
}
}
| Java |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XX XX
XX BasicBlock XX
XX XX
XX XX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
*/
/*****************************************************************************/
#ifndef _BLOCK_H_
#define _BLOCK_H_
/*****************************************************************************/
#include "vartype.h" // For "var_types.h"
#include "_typeinfo.h"
/*****************************************************************************/
// Defines VARSET_TP
#include "varset.h"
#include "blockset.h"
#include "jitstd.h"
#include "bitvec.h"
#include "simplerhash.h"
/*****************************************************************************/
typedef BitVec EXPSET_TP;
#if LARGE_EXPSET
#define EXPSET_SZ 64
#else
#define EXPSET_SZ 32
#endif
typedef BitVec ASSERT_TP;
typedef BitVec_ValArg_T ASSERT_VALARG_TP;
typedef BitVec_ValRet_T ASSERT_VALRET_TP;
/*****************************************************************************
*
* Each basic block ends with a jump which is described as a value
* of the following enumeration.
*/
DECLARE_TYPED_ENUM(BBjumpKinds, BYTE)
{
BBJ_EHFINALLYRET, // block ends with 'endfinally' (for finally or fault)
BBJ_EHFILTERRET, // block ends with 'endfilter'
BBJ_EHCATCHRET, // block ends with a leave out of a catch (only #if FEATURE_EH_FUNCLETS)
BBJ_THROW, // block ends with 'throw'
BBJ_RETURN, // block ends with 'ret'
BBJ_NONE, // block flows into the next one (no jump)
BBJ_ALWAYS, // block always jumps to the target
BBJ_LEAVE, // block always jumps to the target, maybe out of guarded
// region. Used temporarily until importing
BBJ_CALLFINALLY, // block always calls the target finally
BBJ_COND, // block conditionally jumps to the target
BBJ_SWITCH, // block ends with a switch statement
BBJ_COUNT
}
END_DECLARE_TYPED_ENUM(BBjumpKinds, BYTE)
struct GenTree;
struct GenTreeStmt;
struct BasicBlock;
class Compiler;
class typeInfo;
struct BasicBlockList;
struct flowList;
struct EHblkDsc;
#if FEATURE_STACK_FP_X87
struct FlatFPStateX87;
#endif
/*****************************************************************************
*
* The following describes a switch block.
*
* Things to know:
* 1. If bbsHasDefault is true, the default case is the last one in the array of basic block addresses
* namely bbsDstTab[bbsCount - 1].
* 2. bbsCount must be at least 1, for the default case. bbsCount cannot be zero. It appears that the ECMA spec
* allows for a degenerate switch with zero cases. Normally, the optimizer will optimize degenerate
* switches with just a default case to a BBJ_ALWAYS branch, and a switch with just two cases to a BBJ_COND.
* However, in debuggable code, we might not do that, so bbsCount might be 1.
*/
struct BBswtDesc
{
unsigned bbsCount; // count of cases (includes 'default' if bbsHasDefault)
BasicBlock** bbsDstTab; // case label table address
bool bbsHasDefault;
BBswtDesc() : bbsHasDefault(true)
{
}
void removeDefault()
{
assert(bbsHasDefault);
assert(bbsCount > 0);
bbsHasDefault = false;
bbsCount--;
}
BasicBlock* getDefault()
{
assert(bbsHasDefault);
assert(bbsCount > 0);
return bbsDstTab[bbsCount - 1];
}
};
struct StackEntry
{
GenTree* val;
typeInfo seTypeInfo;
};
/*****************************************************************************/
enum ThisInitState
{
TIS_Bottom, // We don't know anything about the 'this' pointer.
TIS_Uninit, // The 'this' pointer for this constructor is known to be uninitialized.
TIS_Init, // The 'this' pointer for this constructor is known to be initialized.
TIS_Top, // This results from merging the state of two blocks one with TIS_Unint and the other with TIS_Init.
// We use this in fault blocks to prevent us from accessing the 'this' pointer, but otherwise
// allowing the fault block to generate code.
};
struct EntryState
{
ThisInitState thisInitialized : 8; // used to track whether the this ptr is initialized (we could use
// fewer bits here)
unsigned esStackDepth : 24; // size of esStack
StackEntry* esStack; // ptr to stack
};
// Enumeration of the kinds of memory whose state changes the compiler tracks
enum MemoryKind
{
ByrefExposed = 0, // Includes anything byrefs can read/write (everything in GcHeap, address-taken locals,
// unmanaged heap, callers' locals, etc.)
GcHeap, // Includes actual GC heap, and also static fields
MemoryKindCount, // Number of MemoryKinds
};
#ifdef DEBUG
const char* const memoryKindNames[] = {"ByrefExposed", "GcHeap"};
#endif // DEBUG
// Bitmask describing a set of memory kinds (usable in bitfields)
typedef unsigned int MemoryKindSet;
// Bitmask for a MemoryKindSet containing just the specified MemoryKind
inline MemoryKindSet memoryKindSet(MemoryKind memoryKind)
{
return (1U << memoryKind);
}
// Bitmask for a MemoryKindSet containing the specified MemoryKinds
template <typename... MemoryKinds>
inline MemoryKindSet memoryKindSet(MemoryKind memoryKind, MemoryKinds... memoryKinds)
{
return memoryKindSet(memoryKind) | memoryKindSet(memoryKinds...);
}
// Bitmask containing all the MemoryKinds
const MemoryKindSet fullMemoryKindSet = (1 << MemoryKindCount) - 1;
// Bitmask containing no MemoryKinds
const MemoryKindSet emptyMemoryKindSet = 0;
// Standard iterator class for iterating through MemoryKinds
class MemoryKindIterator
{
int value;
public:
explicit inline MemoryKindIterator(int val) : value(val)
{
}
inline MemoryKindIterator& operator++()
{
++value;
return *this;
}
inline MemoryKindIterator operator++(int)
{
return MemoryKindIterator(value++);
}
inline MemoryKind operator*()
{
return static_cast<MemoryKind>(value);
}
friend bool operator==(const MemoryKindIterator& left, const MemoryKindIterator& right)
{
return left.value == right.value;
}
friend bool operator!=(const MemoryKindIterator& left, const MemoryKindIterator& right)
{
return left.value != right.value;
}
};
// Empty struct that allows enumerating memory kinds via `for(MemoryKind kind : allMemoryKinds())`
struct allMemoryKinds
{
inline allMemoryKinds()
{
}
inline MemoryKindIterator begin()
{
return MemoryKindIterator(0);
}
inline MemoryKindIterator end()
{
return MemoryKindIterator(MemoryKindCount);
}
};
// This encapsulates the "exception handling" successors of a block. That is,
// if a basic block BB1 occurs in a try block, we consider the first basic block
// BB2 of the corresponding handler to be an "EH successor" of BB1. Because we
// make the conservative assumption that control flow can jump from a try block
// to its handler at any time, the immediate (regular control flow)
// predecessor(s) of the the first block of a try block are also considered to
// have the first block of the handler as an EH successor. This makes variables that
// are "live-in" to the handler become "live-out" for these try-predecessor block,
// so that they become live-in to the try -- which we require.
class EHSuccessorIter
{
// The current compilation.
Compiler* m_comp;
// The block whose EH successors we are iterating over.
BasicBlock* m_block;
// The current "regular" successor of "m_block" that we're considering.
BasicBlock* m_curRegSucc;
// The current try block. If non-null, then the current successor "m_curRegSucc"
// is the first block of the handler of this block. While this try block has
// enclosing try's that also start with "m_curRegSucc", the corresponding handlers will be
// further EH successors.
EHblkDsc* m_curTry;
// The number of "regular" (i.e., non-exceptional) successors that remain to
// be considered. If BB1 has successor BB2, and BB2 is the first block of a
// try block, then we consider the catch block of BB2's try to be an EH
// successor of BB1. This captures the iteration over the successors of BB1
// for this purpose. (In reverse order; we're done when this field is 0).
int m_remainingRegSuccs;
// Requires that "m_curTry" is NULL. Determines whether there is, as
// discussed just above, a regular successor that's the first block of a
// try; if so, sets "m_curTry" to that try block. (As noted above, selecting
// the try containing the current regular successor as the "current try" may cause
// multiple first-blocks of catches to be yielded as EH successors: trys enclosing
// the current try are also included if they also start with the current EH successor.)
void FindNextRegSuccTry();
public:
// Returns the standard "end" iterator.
EHSuccessorIter()
: m_comp(nullptr), m_block(nullptr), m_curRegSucc(nullptr), m_curTry(nullptr), m_remainingRegSuccs(0)
{
}
// Initializes the iterator to represent the EH successors of "block".
EHSuccessorIter(Compiler* comp, BasicBlock* block);
// Go on to the next EH successor.
void operator++(void);
// Requires that "this" is not equal to the standard "end" iterator. Returns the
// current EH successor.
BasicBlock* operator*();
// Returns "true" iff "*this" is equal to "ehsi" -- ignoring the "m_comp"
// and "m_block" fields.
bool operator==(const EHSuccessorIter& ehsi)
{
// Ignore the compiler; we'll assume that's the same.
return m_curTry == ehsi.m_curTry && m_remainingRegSuccs == ehsi.m_remainingRegSuccs;
}
bool operator!=(const EHSuccessorIter& ehsi)
{
return !((*this) == ehsi);
}
};
// Yields both normal and EH successors (in that order) in one iteration.
class AllSuccessorIter
{
// Normal succ state.
Compiler* m_comp;
BasicBlock* m_blk;
unsigned m_normSucc;
unsigned m_numNormSuccs;
EHSuccessorIter m_ehIter;
// True iff m_blk is a BBJ_CALLFINALLY block, and the current try block of m_ehIter,
// the first block of whose handler would be next yielded, is the jump target of m_blk.
inline bool CurTryIsBlkCallFinallyTarget();
public:
inline AllSuccessorIter()
{
}
// Initializes "this" to iterate over all successors of "block."
inline AllSuccessorIter(Compiler* comp, BasicBlock* block);
// Used for constructing an appropriate "end" iter. Should be called with
// the number of normal successors of the block being iterated.
AllSuccessorIter(unsigned numSuccs) : m_normSucc(numSuccs), m_numNormSuccs(numSuccs), m_ehIter()
{
}
// Go on to the next successor.
inline void operator++(void);
// Requires that "this" is not equal to the standard "end" iterator. Returns the
// current successor.
inline BasicBlock* operator*();
// Returns "true" iff "*this" is equal to "asi" -- ignoring the "m_comp"
// and "m_block" fields.
bool operator==(const AllSuccessorIter& asi)
{
return m_normSucc == asi.m_normSucc && m_ehIter == asi.m_ehIter;
}
bool operator!=(const AllSuccessorIter& asi)
{
return !((*this) == asi);
}
};
//------------------------------------------------------------------------
// BasicBlock: describes a basic block in the flowgraph.
//
// Note that this type derives from LIR::Range in order to make the LIR
// utilities that are polymorphic over basic block and scratch ranges
// faster and simpler.
//
struct BasicBlock : private LIR::Range
{
friend class LIR;
BasicBlock* bbNext; // next BB in ascending PC offset order
BasicBlock* bbPrev;
void setNext(BasicBlock* next)
{
bbNext = next;
if (next)
{
next->bbPrev = this;
}
}
unsigned __int64 bbFlags; // see BBF_xxxx below
unsigned bbNum; // the block's number
unsigned bbPostOrderNum; // the block's post order number in the graph.
unsigned bbRefs; // number of blocks that can reach here, either by fall-through or a branch. If this falls to zero,
// the block is unreachable.
#define BBF_VISITED 0x00000001 // BB visited during optimizations
#define BBF_MARKED 0x00000002 // BB marked during optimizations
#define BBF_CHANGED 0x00000004 // input/output of this block has changed
#define BBF_REMOVED 0x00000008 // BB has been removed from bb-list
#define BBF_DONT_REMOVE 0x00000010 // BB should not be removed during flow graph optimizations
#define BBF_IMPORTED 0x00000020 // BB byte-code has been imported
#define BBF_INTERNAL 0x00000040 // BB has been added by the compiler
#define BBF_FAILED_VERIFICATION 0x00000080 // BB has verification exception
#define BBF_TRY_BEG 0x00000100 // BB starts a 'try' block
#define BBF_FUNCLET_BEG 0x00000200 // BB is the beginning of a funclet
#define BBF_HAS_NULLCHECK 0x00000400 // BB contains a null check
#define BBF_NEEDS_GCPOLL 0x00000800 // This BB is the source of a back edge and needs a GC Poll
#define BBF_RUN_RARELY 0x00001000 // BB is rarely run (catch clauses, blocks with throws etc)
#define BBF_LOOP_HEAD 0x00002000 // BB is the head of a loop
#define BBF_LOOP_CALL0 0x00004000 // BB starts a loop that sometimes won't call
#define BBF_LOOP_CALL1 0x00008000 // BB starts a loop that will always call
#define BBF_HAS_LABEL 0x00010000 // BB needs a label
#define BBF_JMP_TARGET 0x00020000 // BB is a target of an implicit/explicit jump
#define BBF_HAS_JMP 0x00040000 // BB executes a JMP instruction (instead of return)
#define BBF_GC_SAFE_POINT 0x00080000 // BB has a GC safe point (a call). More abstractly, BB does not
// require a (further) poll -- this may be because this BB has a
// call, or, in some cases, because the BB occurs in a loop, and
// we've determined that all paths in the loop body leading to BB
// include a call.
#define BBF_HAS_VTABREF 0x00100000 // BB contains reference of vtable
#define BBF_HAS_IDX_LEN 0x00200000 // BB contains simple index or length expressions on an array local var.
#define BBF_HAS_NEWARRAY 0x00400000 // BB contains 'new' of an array
#define BBF_HAS_NEWOBJ 0x00800000 // BB contains 'new' of an object type.
#if FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_)
#define BBF_FINALLY_TARGET 0x01000000 // BB is the target of a finally return: where a finally will return during
// non-exceptional flow. Because the ARM calling sequence for calling a
// finally explicitly sets the return address to the finally target and jumps
// to the finally, instead of using a call instruction, ARM needs this to
// generate correct code at the finally target, to allow for proper stack
// unwind from within a non-exceptional call to a finally.
#endif // FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_)
#define BBF_BACKWARD_JUMP 0x02000000 // BB is surrounded by a backward jump/switch arc
#define BBF_RETLESS_CALL 0x04000000 // BBJ_CALLFINALLY that will never return (and therefore, won't need a paired
// BBJ_ALWAYS); see isBBCallAlwaysPair().
#define BBF_LOOP_PREHEADER 0x08000000 // BB is a loop preheader block
#define BBF_COLD 0x10000000 // BB is cold
#define BBF_PROF_WEIGHT 0x20000000 // BB weight is computed from profile data
#ifdef LEGACY_BACKEND
#define BBF_FORWARD_SWITCH 0x40000000 // Aux flag used in FP codegen to know if a jmptable entry has been forwarded
#else // !LEGACY_BACKEND
#define BBF_IS_LIR 0x40000000 // Set if the basic block contains LIR (as opposed to HIR)
#endif // LEGACY_BACKEND
#define BBF_KEEP_BBJ_ALWAYS 0x80000000 // A special BBJ_ALWAYS block, used by EH code generation. Keep the jump kind
// as BBJ_ALWAYS. Used for the paired BBJ_ALWAYS block following the
// BBJ_CALLFINALLY block, as well as, on x86, the final step block out of a
// finally.
#define BBF_CLONED_FINALLY_BEGIN 0x100000000 // First block of a cloned finally region
#define BBF_CLONED_FINALLY_END 0x200000000 // Last block of a cloned finally region
// Flags that relate blocks to loop structure.
#define BBF_LOOP_FLAGS (BBF_LOOP_PREHEADER | BBF_LOOP_HEAD | BBF_LOOP_CALL0 | BBF_LOOP_CALL1)
bool isRunRarely() const
{
return ((bbFlags & BBF_RUN_RARELY) != 0);
}
bool isLoopHead() const
{
return ((bbFlags & BBF_LOOP_HEAD) != 0);
}
// Flags to update when two blocks are compacted
#define BBF_COMPACT_UPD \
(BBF_CHANGED | BBF_GC_SAFE_POINT | BBF_HAS_JMP | BBF_NEEDS_GCPOLL | BBF_HAS_IDX_LEN | BBF_BACKWARD_JUMP | \
BBF_HAS_NEWARRAY | BBF_HAS_NEWOBJ)
// Flags a block should not have had before it is split.
#ifdef LEGACY_BACKEND
#define BBF_SPLIT_NONEXIST \
(BBF_CHANGED | BBF_LOOP_HEAD | BBF_LOOP_CALL0 | BBF_LOOP_CALL1 | BBF_RETLESS_CALL | BBF_LOOP_PREHEADER | \
BBF_COLD | BBF_FORWARD_SWITCH)
#else // !LEGACY_BACKEND
#define BBF_SPLIT_NONEXIST \
(BBF_CHANGED | BBF_LOOP_HEAD | BBF_LOOP_CALL0 | BBF_LOOP_CALL1 | BBF_RETLESS_CALL | BBF_LOOP_PREHEADER | BBF_COLD)
#endif // LEGACY_BACKEND
// Flags lost by the top block when a block is split.
// Note, this is a conservative guess.
// For example, the top block might or might not have BBF_GC_SAFE_POINT,
// but we assume it does not have BBF_GC_SAFE_POINT any more.
#define BBF_SPLIT_LOST (BBF_GC_SAFE_POINT | BBF_HAS_JMP | BBF_KEEP_BBJ_ALWAYS | BBF_CLONED_FINALLY_END)
// Flags gained by the bottom block when a block is split.
// Note, this is a conservative guess.
// For example, the bottom block might or might not have BBF_HAS_NEWARRAY,
// but we assume it has BBF_HAS_NEWARRAY.
// TODO: Should BBF_RUN_RARELY be added to BBF_SPLIT_GAINED ?
#define BBF_SPLIT_GAINED \
(BBF_DONT_REMOVE | BBF_HAS_LABEL | BBF_HAS_JMP | BBF_BACKWARD_JUMP | BBF_HAS_IDX_LEN | BBF_HAS_NEWARRAY | \
BBF_PROF_WEIGHT | BBF_HAS_NEWOBJ | BBF_KEEP_BBJ_ALWAYS | BBF_CLONED_FINALLY_END)
#ifndef __GNUC__ // GCC doesn't like C_ASSERT at global scope
static_assert_no_msg((BBF_SPLIT_NONEXIST & BBF_SPLIT_LOST) == 0);
static_assert_no_msg((BBF_SPLIT_NONEXIST & BBF_SPLIT_GAINED) == 0);
#endif
#ifdef DEBUG
void dspFlags(); // Print the flags
unsigned dspCheapPreds(); // Print the predecessors (bbCheapPreds)
unsigned dspPreds(); // Print the predecessors (bbPreds)
unsigned dspSuccs(Compiler* compiler); // Print the successors. The 'compiler' argument determines whether EH
// regions are printed: see NumSucc() for details.
void dspJumpKind(); // Print the block jump kind (e.g., BBJ_NONE, BBJ_COND, etc.).
void dspBlockHeader(Compiler* compiler,
bool showKind = true,
bool showFlags = false,
bool showPreds = true); // Print a simple basic block header for various output, including a
// list of predecessors and successors.
#endif // DEBUG
typedef unsigned weight_t; // Type used to hold block and edge weights
// Note that for CLR v2.0 and earlier our
// block weights were stored using unsigned shorts
#define BB_UNITY_WEIGHT 100 // how much a normal execute once block weights
#define BB_LOOP_WEIGHT 8 // how much more loops are weighted
#define BB_ZERO_WEIGHT 0
#define BB_MAX_WEIGHT ULONG_MAX // we're using an 'unsigned' for the weight
#define BB_VERY_HOT_WEIGHT 256 // how many average hits a BB has (per BBT scenario run) for this block
// to be considered as very hot
weight_t bbWeight; // The dynamic execution weight of this block
// getBBWeight -- get the normalized weight of this block
unsigned getBBWeight(Compiler* comp);
// setBBWeight -- if the block weight is not derived from a profile, then set the weight to the input
// weight, but make sure to not overflow BB_MAX_WEIGHT
void setBBWeight(unsigned weight)
{
if (!(this->bbFlags & BBF_PROF_WEIGHT))
{
this->bbWeight = min(weight, BB_MAX_WEIGHT);
}
}
// modifyBBWeight -- same as setBBWeight, but also make sure that if the block is rarely run, it stays that
// way, and if it's not rarely run then its weight never drops below 1.
void modifyBBWeight(unsigned weight)
{
if (this->bbWeight != BB_ZERO_WEIGHT)
{
setBBWeight(max(weight, 1));
}
}
// setBBProfileWeight -- Set the profile-derived weight for a basic block
void setBBProfileWeight(unsigned weight)
{
this->bbFlags |= BBF_PROF_WEIGHT;
// Check if the multiplication by BB_UNITY_WEIGHT will overflow.
this->bbWeight = (weight <= BB_MAX_WEIGHT / BB_UNITY_WEIGHT) ? weight * BB_UNITY_WEIGHT : BB_MAX_WEIGHT;
}
// this block will inherit the same weight and relevant bbFlags as bSrc
void inheritWeight(BasicBlock* bSrc)
{
this->bbWeight = bSrc->bbWeight;
if (bSrc->bbFlags & BBF_PROF_WEIGHT)
{
this->bbFlags |= BBF_PROF_WEIGHT;
}
else
{
this->bbFlags &= ~BBF_PROF_WEIGHT;
}
if (this->bbWeight == 0)
{
this->bbFlags |= BBF_RUN_RARELY;
}
else
{
this->bbFlags &= ~BBF_RUN_RARELY;
}
}
// Similar to inheritWeight(), but we're splitting a block (such as creating blocks for qmark removal).
// So, specify a percentage (0 to 99; if it's 100, just use inheritWeight()) of the weight that we're
// going to inherit. Since the number isn't exact, clear the BBF_PROF_WEIGHT flag.
void inheritWeightPercentage(BasicBlock* bSrc, unsigned percentage)
{
assert(0 <= percentage && percentage < 100);
// Check for overflow
if (bSrc->bbWeight * 100 <= bSrc->bbWeight)
{
this->bbWeight = bSrc->bbWeight;
}
else
{
this->bbWeight = bSrc->bbWeight * percentage / 100;
}
this->bbFlags &= ~BBF_PROF_WEIGHT;
if (this->bbWeight == 0)
{
this->bbFlags |= BBF_RUN_RARELY;
}
else
{
this->bbFlags &= ~BBF_RUN_RARELY;
}
}
// makeBlockHot()
// This is used to override any profiling data
// and force a block to be in the hot region.
// We only call this method for handler entry point
// and only when HANDLER_ENTRY_MUST_BE_IN_HOT_SECTION is 1.
// Doing this helps fgReorderBlocks() by telling
// it to try to move these blocks into the hot region.
// Note that we do this strictly as an optimization,
// not for correctness. fgDetermineFirstColdBlock()
// will find all handler entry points and ensure that
// for now we don't place them in the cold section.
//
void makeBlockHot()
{
if (this->bbWeight == BB_ZERO_WEIGHT)
{
this->bbFlags &= ~BBF_RUN_RARELY; // Clear any RarelyRun flag
this->bbFlags &= ~BBF_PROF_WEIGHT; // Clear any profile-derived flag
this->bbWeight = 1;
}
}
bool isMaxBBWeight()
{
return (bbWeight == BB_MAX_WEIGHT);
}
// Returns "true" if the block is empty. Empty here means there are no statement
// trees *except* PHI definitions.
bool isEmpty();
// Returns "true" iff "this" is the first block of a BBJ_CALLFINALLY/BBJ_ALWAYS pair --
// a block corresponding to an exit from the try of a try/finally. In the flow graph,
// this becomes a block that calls the finally, and a second, immediately
// following empty block (in the bbNext chain) to which the finally will return, and which
// branches unconditionally to the next block to be executed outside the try/finally.
// Note that code is often generated differently than this description. For example, on ARM,
// the target of the BBJ_ALWAYS is loaded in LR (the return register), and a direct jump is
// made to the 'finally'. The effect is that the 'finally' returns directly to the target of
// the BBJ_ALWAYS. A "retless" BBJ_CALLFINALLY is one that has no corresponding BBJ_ALWAYS.
// This can happen if the finally is known to not return (e.g., it contains a 'throw'). In
// that case, the BBJ_CALLFINALLY flags has BBF_RETLESS_CALL set. Note that ARM never has
// "retless" BBJ_CALLFINALLY blocks due to a requirement to use the BBJ_ALWAYS for
// generating code.
bool isBBCallAlwaysPair()
{
#if FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_)
if (this->bbJumpKind == BBJ_CALLFINALLY)
#else
if ((this->bbJumpKind == BBJ_CALLFINALLY) && !(this->bbFlags & BBF_RETLESS_CALL))
#endif
{
#if FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_)
// On ARM, there are no retless BBJ_CALLFINALLY.
assert(!(this->bbFlags & BBF_RETLESS_CALL));
#endif
// Some asserts that the next block is a BBJ_ALWAYS of the proper form.
assert(this->bbNext != nullptr);
assert(this->bbNext->bbJumpKind == BBJ_ALWAYS);
assert(this->bbNext->bbFlags & BBF_KEEP_BBJ_ALWAYS);
assert(this->bbNext->isEmpty());
return true;
}
else
{
return false;
}
}
BBjumpKinds bbJumpKind; // jump (if any) at the end of this block
/* The following union describes the jump target(s) of this block */
union {
unsigned bbJumpOffs; // PC offset (temporary only)
BasicBlock* bbJumpDest; // basic block
BBswtDesc* bbJumpSwt; // switch descriptor
};
// NumSucc() gives the number of successors, and GetSucc() allows one to iterate over them.
//
// The behavior of both for blocks that end in BBJ_EHFINALLYRET (a return from a finally or fault block)
// depends on whether "comp" is non-null. If it is null, then the block is considered to have no
// successor. If it is non-null, we figure out the actual successors. Some cases will want one behavior,
// other cases the other. For example, IL verification requires that these blocks end in an empty operand
// stack, and since the dataflow analysis of IL verification is concerned only with the contents of the
// operand stack, we can consider the finally block to have no successors. But a more general dataflow
// analysis that is tracking the contents of local variables might want to consider *all* successors,
// and would pass the current Compiler object.
//
// Similarly, BBJ_EHFILTERRET blocks are assumed to have no successors if "comp" is null; if non-null,
// NumSucc/GetSucc yields the first block of the try blocks handler.
//
// Also, the behavior for switches changes depending on the value of "comp". If it is null, then all
// switch successors are returned. If it is non-null, then only unique switch successors are returned;
// the duplicate successors are omitted.
//
// Note that for BBJ_COND, which has two successors (fall through and condition true branch target),
// only the unique targets are returned. Thus, if both targets are the same, NumSucc() will only return 1
// instead of 2.
//
// Returns the number of successors of "this".
unsigned NumSucc(Compiler* comp = nullptr);
// Returns the "i"th successor. Requires (0 <= i < NumSucc()).
BasicBlock* GetSucc(unsigned i, Compiler* comp = nullptr);
BasicBlock* GetUniquePred(Compiler* comp);
BasicBlock* GetUniqueSucc();
unsigned countOfInEdges() const
{
return bbRefs;
}
__declspec(property(get = getBBTreeList, put = setBBTreeList)) GenTree* bbTreeList; // the body of the block.
GenTree* getBBTreeList() const
{
return m_firstNode;
}
void setBBTreeList(GenTree* tree)
{
m_firstNode = tree;
}
EntryState* bbEntryState; // verifier tracked state of all entries in stack.
#define NO_BASE_TMP UINT_MAX // base# to use when we have none
unsigned bbStkTempsIn; // base# for input stack temps
unsigned bbStkTempsOut; // base# for output stack temps
#define MAX_XCPTN_INDEX (USHRT_MAX - 1)
// It would be nice to make bbTryIndex and bbHndIndex private, but there is still code that uses them directly,
// especially Compiler::fgNewBBinRegion() and friends.
// index, into the compHndBBtab table, of innermost 'try' clause containing the BB (used for raising exceptions).
// Stored as index + 1; 0 means "no try index".
unsigned short bbTryIndex;
// index, into the compHndBBtab table, of innermost handler (filter, catch, fault/finally) containing the BB.
// Stored as index + 1; 0 means "no handler index".
unsigned short bbHndIndex;
// Given two EH indices that are either bbTryIndex or bbHndIndex (or related), determine if index1 might be more
// deeply nested than index2. Both index1 and index2 are in the range [0..compHndBBtabCount], where 0 means
// "main function" and otherwise the value is an index into compHndBBtab[]. Note that "sibling" EH regions will
// have a numeric index relationship that doesn't indicate nesting, whereas a more deeply nested region must have
// a lower index than the region it is nested within. Note that if you compare a single block's bbTryIndex and
// bbHndIndex, there is guaranteed to be a nesting relationship, since that block can't be simultaneously in two
// sibling EH regions. In that case, "maybe" is actually "definitely".
static bool ehIndexMaybeMoreNested(unsigned index1, unsigned index2)
{
if (index1 == 0)
{
// index1 is in the main method. It can't be more deeply nested than index2.
return false;
}
else if (index2 == 0)
{
// index1 represents an EH region, whereas index2 is the main method. Thus, index1 is more deeply nested.
assert(index1 > 0);
return true;
}
else
{
// If index1 has a smaller index, it might be more deeply nested than index2.
assert(index1 > 0);
assert(index2 > 0);
return index1 < index2;
}
}
// catch type: class token of handler, or one of BBCT_*. Only set on first block of catch handler.
unsigned bbCatchTyp;
bool hasTryIndex() const
{
return bbTryIndex != 0;
}
bool hasHndIndex() const
{
return bbHndIndex != 0;
}
unsigned getTryIndex() const
{
assert(bbTryIndex != 0);
return bbTryIndex - 1;
}
unsigned getHndIndex() const
{
assert(bbHndIndex != 0);
return bbHndIndex - 1;
}
void setTryIndex(unsigned val)
{
bbTryIndex = (unsigned short)(val + 1);
assert(bbTryIndex != 0);
}
void setHndIndex(unsigned val)
{
bbHndIndex = (unsigned short)(val + 1);
assert(bbHndIndex != 0);
}
void clearTryIndex()
{
bbTryIndex = 0;
}
void clearHndIndex()
{
bbHndIndex = 0;
}
void copyEHRegion(const BasicBlock* from)
{
bbTryIndex = from->bbTryIndex;
bbHndIndex = from->bbHndIndex;
}
static bool sameTryRegion(const BasicBlock* blk1, const BasicBlock* blk2)
{
return blk1->bbTryIndex == blk2->bbTryIndex;
}
static bool sameHndRegion(const BasicBlock* blk1, const BasicBlock* blk2)
{
return blk1->bbHndIndex == blk2->bbHndIndex;
}
static bool sameEHRegion(const BasicBlock* blk1, const BasicBlock* blk2)
{
return sameTryRegion(blk1, blk2) && sameHndRegion(blk1, blk2);
}
// Some non-zero value that will not collide with real tokens for bbCatchTyp
#define BBCT_NONE 0x00000000
#define BBCT_FAULT 0xFFFFFFFC
#define BBCT_FINALLY 0xFFFFFFFD
#define BBCT_FILTER 0xFFFFFFFE
#define BBCT_FILTER_HANDLER 0xFFFFFFFF
#define handlerGetsXcptnObj(hndTyp) ((hndTyp) != BBCT_NONE && (hndTyp) != BBCT_FAULT && (hndTyp) != BBCT_FINALLY)
// TODO-Cleanup: Get rid of bbStkDepth and use bbStackDepthOnEntry() instead
union {
unsigned short bbStkDepth; // stack depth on entry
unsigned short bbFPinVars; // number of inner enregistered FP vars
};
// Basic block predecessor lists. Early in compilation, some phases might need to compute "cheap" predecessor
// lists. These are stored in bbCheapPreds, computed by fgComputeCheapPreds(). If bbCheapPreds is valid,
// 'fgCheapPredsValid' will be 'true'. Later, the "full" predecessor lists are created by fgComputePreds(), stored
// in 'bbPreds', and then maintained throughout compilation. 'fgComputePredsDone' will be 'true' after the
// full predecessor lists are created. See the comment at fgComputeCheapPreds() to see how those differ from
// the "full" variant.
union {
BasicBlockList* bbCheapPreds; // ptr to list of cheap predecessors (used before normal preds are computed)
flowList* bbPreds; // ptr to list of predecessors
};
BlockSet bbReach; // Set of all blocks that can reach this one
BasicBlock* bbIDom; // Represent the closest dominator to this block (called the Immediate
// Dominator) used to compute the dominance tree.
unsigned bbDfsNum; // The index of this block in DFS reverse post order
// relative to the flow graph.
#if ASSERTION_PROP
// A set of blocks which dominate this one *except* the normal entry block. This is lazily initialized
// and used only by Assertion Prop, intersected with fgEnterBlks!
BlockSet bbDoms;
#endif
IL_OFFSET bbCodeOffs; // IL offset of the beginning of the block
IL_OFFSET bbCodeOffsEnd; // IL offset past the end of the block. Thus, the [bbCodeOffs..bbCodeOffsEnd)
// range is not inclusive of the end offset. The count of IL bytes in the block
// is bbCodeOffsEnd - bbCodeOffs, assuming neither are BAD_IL_OFFSET.
#ifdef DEBUG
void dspBlockILRange(); // Display the block's IL range as [XXX...YYY), where XXX and YYY might be "???" for
// BAD_IL_OFFSET.
#endif // DEBUG
VARSET_TP bbVarUse; // variables used by block (before an assignment)
VARSET_TP bbVarDef; // variables assigned by block (before a use)
VARSET_TP bbLiveIn; // variables live on entry
VARSET_TP bbLiveOut; // variables live on exit
// Use, def, live in/out information for the implicit memory variable.
MemoryKindSet bbMemoryUse : MemoryKindCount; // must be set for any MemoryKinds this block references
MemoryKindSet bbMemoryDef : MemoryKindCount; // must be set for any MemoryKinds this block mutates
MemoryKindSet bbMemoryLiveIn : MemoryKindCount;
MemoryKindSet bbMemoryLiveOut : MemoryKindCount;
MemoryKindSet bbMemoryHavoc : MemoryKindCount; // If true, at some point the block does an operation
// that leaves memory in an unknown state. (E.g.,
// unanalyzed call, store through unknown pointer...)
// We want to make phi functions for the special implicit var memory. But since this is not a real
// lclVar, and thus has no local #, we can't use a GenTreePhiArg. Instead, we use this struct.
struct MemoryPhiArg
{
unsigned m_ssaNum; // SSA# for incoming value.
MemoryPhiArg* m_nextArg; // Next arg in the list, else NULL.
unsigned GetSsaNum()
{
return m_ssaNum;
}
MemoryPhiArg(unsigned ssaNum, MemoryPhiArg* nextArg = nullptr) : m_ssaNum(ssaNum), m_nextArg(nextArg)
{
}
void* operator new(size_t sz, class Compiler* comp);
};
static MemoryPhiArg* EmptyMemoryPhiDef; // Special value (0x1, FWIW) to represent a to-be-filled in Phi arg list
// for Heap.
MemoryPhiArg* bbMemorySsaPhiFunc[MemoryKindCount]; // If the "in" Heap SSA var is not a phi definition, this value
// is NULL.
// Otherwise, it is either the special value EmptyMemoryPhiDefn, to indicate
// that Heap needs a phi definition on entry, or else it is the linked list
// of the phi arguments.
unsigned bbMemorySsaNumIn[MemoryKindCount]; // The SSA # of memory on entry to the block.
unsigned bbMemorySsaNumOut[MemoryKindCount]; // The SSA # of memory on exit from the block.
VARSET_TP bbScope; // variables in scope over the block
void InitVarSets(class Compiler* comp);
/* The following are the standard bit sets for dataflow analysis.
* We perform CSE and range-checks at the same time
* and assertion propagation separately,
* thus we can union them since the two operations are completely disjunct.
*/
union {
EXPSET_TP bbCseGen; // CSEs computed by block
#if ASSERTION_PROP
ASSERT_TP bbAssertionGen; // value assignments computed by block
#endif
};
union {
#if ASSERTION_PROP
ASSERT_TP bbAssertionKill; // value assignments killed by block
#endif
};
union {
EXPSET_TP bbCseIn; // CSEs available on entry
#if ASSERTION_PROP
ASSERT_TP bbAssertionIn; // value assignments available on entry
#endif
};
union {
EXPSET_TP bbCseOut; // CSEs available on exit
#if ASSERTION_PROP
ASSERT_TP bbAssertionOut; // value assignments available on exit
#endif
};
void* bbEmitCookie;
#if FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_)
void* bbUnwindNopEmitCookie;
#endif // FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_)
#ifdef VERIFIER
stackDesc bbStackIn; // stack descriptor for input
stackDesc bbStackOut; // stack descriptor for output
verTypeVal* bbTypesIn; // list of variable types on input
verTypeVal* bbTypesOut; // list of variable types on output
#endif // VERIFIER
#if FEATURE_STACK_FP_X87
FlatFPStateX87* bbFPStateX87; // State of FP stack on entry to the basic block
#endif // FEATURE_STACK_FP_X87
/* The following fields used for loop detection */
typedef unsigned char loopNumber;
static const unsigned NOT_IN_LOOP = UCHAR_MAX;
#ifdef DEBUG
// This is the label a loop gets as part of the second, reachability-based
// loop discovery mechanism. This is apparently only used for debugging.
// We hope we'll eventually just have one loop-discovery mechanism, and this will go away.
loopNumber bbLoopNum; // set to 'n' for a loop #n header
#endif // DEBUG
loopNumber bbNatLoopNum; // Index, in optLoopTable, of most-nested loop that contains this block,
// or else NOT_IN_LOOP if this block is not in a loop.
#define MAX_LOOP_NUM 16 // we're using a 'short' for the mask
#define LOOP_MASK_TP unsigned // must be big enough for a mask
//-------------------------------------------------------------------------
#if MEASURE_BLOCK_SIZE
static size_t s_Size;
static size_t s_Count;
#endif // MEASURE_BLOCK_SIZE
bool bbFallsThrough();
// Our slop fraction is 1/128 of the block weight rounded off
static weight_t GetSlopFraction(weight_t weightBlk)
{
return ((weightBlk + 64) / 128);
}
// Given an the edge b1 -> b2, calculate the slop fraction by
// using the higher of the two block weights
static weight_t GetSlopFraction(BasicBlock* b1, BasicBlock* b2)
{
return GetSlopFraction(max(b1->bbWeight, b2->bbWeight));
}
#ifdef DEBUG
unsigned bbTgtStkDepth; // Native stack depth on entry (for throw-blocks)
static unsigned s_nMaxTrees; // The max # of tree nodes in any BB
unsigned bbStmtNum; // The statement number of the first stmt in this block
// This is used in integrity checks. We semi-randomly pick a traversal stamp, label all blocks
// in the BB list with that stamp (in this field); then we can tell if (e.g.) predecessors are
// still in the BB list by whether they have the same stamp (with high probability).
unsigned bbTraversalStamp;
#endif // DEBUG
ThisInitState bbThisOnEntry();
unsigned bbStackDepthOnEntry();
void bbSetStack(void* stackBuffer);
StackEntry* bbStackOnEntry();
void bbSetRunRarely();
// "bbNum" is one-based (for unknown reasons); it is sometimes useful to have the corresponding
// zero-based number for use as an array index.
unsigned bbInd()
{
assert(bbNum > 0);
return bbNum - 1;
}
GenTreeStmt* firstStmt() const;
GenTreeStmt* lastStmt() const;
GenTreeStmt* lastTopLevelStmt();
GenTree* firstNode();
GenTree* lastNode();
bool containsStatement(GenTree* statement);
bool endsWithJmpMethod(Compiler* comp);
bool endsWithTailCall(Compiler* comp,
bool fastTailCallsOnly,
bool tailCallsConvertibleToLoopOnly,
GenTree** tailCall);
bool endsWithTailCallOrJmp(Compiler* comp, bool fastTailCallsOnly = false);
bool endsWithTailCallConvertibleToLoop(Compiler* comp, GenTree** tailCall);
// Returns the first statement in the statement list of "this" that is
// not an SSA definition (a lcl = phi(...) assignment).
GenTreeStmt* FirstNonPhiDef();
GenTree* FirstNonPhiDefOrCatchArgAsg();
BasicBlock()
:
#if ASSERTION_PROP
BLOCKSET_INIT_NOCOPY(bbDoms, BlockSetOps::UninitVal())
,
#endif // ASSERTION_PROP
VARSET_INIT_NOCOPY(bbLiveIn, VarSetOps::UninitVal())
, VARSET_INIT_NOCOPY(bbLiveOut, VarSetOps::UninitVal())
{
}
private:
EHSuccessorIter StartEHSuccs(Compiler* comp)
{
return EHSuccessorIter(comp, this);
}
EHSuccessorIter EndEHSuccs()
{
return EHSuccessorIter();
}
friend struct EHSuccs;
AllSuccessorIter StartAllSuccs(Compiler* comp)
{
return AllSuccessorIter(comp, this);
}
AllSuccessorIter EndAllSuccs(Compiler* comp)
{
return AllSuccessorIter(NumSucc(comp));
}
friend struct AllSuccs;
public:
// Iteratable collection of the EH successors of a block.
class EHSuccs
{
Compiler* m_comp;
BasicBlock* m_block;
public:
EHSuccs(Compiler* comp, BasicBlock* block) : m_comp(comp), m_block(block)
{
}
EHSuccessorIter begin()
{
return m_block->StartEHSuccs(m_comp);
}
EHSuccessorIter end()
{
return EHSuccessorIter();
}
};
EHSuccs GetEHSuccs(Compiler* comp)
{
return EHSuccs(comp, this);
}
class AllSuccs
{
Compiler* m_comp;
BasicBlock* m_block;
public:
AllSuccs(Compiler* comp, BasicBlock* block) : m_comp(comp), m_block(block)
{
}
AllSuccessorIter begin()
{
return m_block->StartAllSuccs(m_comp);
}
AllSuccessorIter end()
{
return AllSuccessorIter(m_block->NumSucc(m_comp));
}
};
AllSuccs GetAllSuccs(Compiler* comp)
{
return AllSuccs(comp, this);
}
// Try to clone block state and statements from `from` block to `to` block (which must be new/empty),
// optionally replacing uses of local `varNum` with IntCns `varVal`. Return true if all statements
// in the block are cloned successfully, false (with partially-populated `to` block) if one fails.
static bool CloneBlockState(
Compiler* compiler, BasicBlock* to, const BasicBlock* from, unsigned varNum = (unsigned)-1, int varVal = 0);
void MakeLIR(GenTree* firstNode, GenTree* lastNode);
bool IsLIR();
};
template <>
struct PtrKeyFuncs<BasicBlock> : public KeyFuncsDefEquals<const BasicBlock*>
{
public:
// Make sure hashing is deterministic and not on "ptr."
static unsigned GetHashCode(const BasicBlock* ptr);
};
// A set of blocks.
typedef SimplerHashTable<BasicBlock*, PtrKeyFuncs<BasicBlock>, bool, JitSimplerHashBehavior> BlkSet;
// A map of block -> set of blocks, can be used as sparse block trees.
typedef SimplerHashTable<BasicBlock*, PtrKeyFuncs<BasicBlock>, BlkSet*, JitSimplerHashBehavior> BlkToBlkSetMap;
// Map from Block to Block. Used for a variety of purposes.
typedef SimplerHashTable<BasicBlock*, PtrKeyFuncs<BasicBlock>, BasicBlock*, JitSimplerHashBehavior> BlockToBlockMap;
// In compiler terminology the control flow between two BasicBlocks
// is typically referred to as an "edge". Most well known are the
// backward branches for loops, which are often called "back-edges".
//
// "struct flowList" is the type that represents our control flow edges.
// This type is a linked list of zero or more "edges".
// (The list of zero edges is represented by NULL.)
// Every BasicBlock has a field called bbPreds of this type. This field
// represents the list of "edges" that flow into this BasicBlock.
// The flowList type only stores the BasicBlock* of the source for the
// control flow edge. The destination block for the control flow edge
// is implied to be the block which contained the bbPreds field.
//
// For a switch branch target there may be multiple "edges" that have
// the same source block (and destination block). We need to count the
// number of these edges so that during optimization we will know when
// we have zero of them. Rather than have extra flowList entries we
// increment the flDupCount field.
//
// When we have Profile weight for the BasicBlocks we can usually compute
// the number of times each edge was executed by examining the adjacent
// BasicBlock weights. As we are doing for BasicBlocks, we call the number
// of times that a control flow edge was executed the "edge weight".
// In order to compute the edge weights we need to use a bounded range
// for every edge weight. These two fields, 'flEdgeWeightMin' and 'flEdgeWeightMax'
// are used to hold a bounded range. Most often these will converge such
// that both values are the same and that value is the exact edge weight.
// Sometimes we are left with a rage of possible values between [Min..Max]
// which represents an inexact edge weight.
//
// The bbPreds list is initially created by Compiler::fgComputePreds()
// and is incrementally kept up to date.
//
// The edge weight are computed by Compiler::fgComputeEdgeWeights()
// the edge weights are used to straighten conditional branches
// by Compiler::fgReorderBlocks()
//
// We have a simpler struct, BasicBlockList, which is simply a singly-linked
// list of blocks. This is used for various purposes, but one is as a "cheap"
// predecessor list, computed by fgComputeCheapPreds(), and stored as a list
// on BasicBlock pointed to by bbCheapPreds.
struct BasicBlockList
{
BasicBlockList* next; // The next BasicBlock in the list, nullptr for end of list.
BasicBlock* block; // The BasicBlock of interest.
BasicBlockList() : next(nullptr), block(nullptr)
{
}
BasicBlockList(BasicBlock* blk, BasicBlockList* rest) : next(rest), block(blk)
{
}
};
struct flowList
{
flowList* flNext; // The next BasicBlock in the list, nullptr for end of list.
BasicBlock* flBlock; // The BasicBlock of interest.
BasicBlock::weight_t flEdgeWeightMin;
BasicBlock::weight_t flEdgeWeightMax;
unsigned flDupCount; // The count of duplicate "edges" (use only for switch stmts)
// These two methods are used to set new values for flEdgeWeightMin and flEdgeWeightMax
// they are used only during the computation of the edge weights
// They return false if the newWeight is not between the current [min..max]
// when slop is non-zero we allow for the case where our weights might be off by 'slop'
//
bool setEdgeWeightMinChecked(BasicBlock::weight_t newWeight, BasicBlock::weight_t slop, bool* wbUsedSlop);
bool setEdgeWeightMaxChecked(BasicBlock::weight_t newWeight, BasicBlock::weight_t slop, bool* wbUsedSlop);
flowList() : flNext(nullptr), flBlock(nullptr), flEdgeWeightMin(0), flEdgeWeightMax(0), flDupCount(0)
{
}
flowList(BasicBlock* blk, flowList* rest)
: flNext(rest), flBlock(blk), flEdgeWeightMin(0), flEdgeWeightMax(0), flDupCount(0)
{
}
};
// This enum represents a pre/post-visit action state to emulate a depth-first
// spanning tree traversal of a tree or graph.
enum DfsStackState
{
DSS_Invalid, // The initialized, invalid error state
DSS_Pre, // The DFS pre-order (first visit) traversal state
DSS_Post // The DFS post-order (last visit) traversal state
};
// These structs represents an entry in a stack used to emulate a non-recursive
// depth-first spanning tree traversal of a graph. The entry contains either a
// block pointer or a block number depending on which is more useful.
struct DfsBlockEntry
{
DfsStackState dfsStackState; // The pre/post traversal action for this entry
BasicBlock* dfsBlock; // The corresponding block for the action
DfsBlockEntry() : dfsStackState(DSS_Invalid), dfsBlock(nullptr)
{
}
DfsBlockEntry(DfsStackState state, BasicBlock* basicBlock) : dfsStackState(state), dfsBlock(basicBlock)
{
}
};
struct DfsNumEntry
{
DfsStackState dfsStackState; // The pre/post traversal action for this entry
unsigned dfsNum; // The corresponding block number for the action
DfsNumEntry() : dfsStackState(DSS_Invalid), dfsNum(0)
{
}
DfsNumEntry(DfsStackState state, unsigned bbNum) : dfsStackState(state), dfsNum(bbNum)
{
}
};
/*****************************************************************************/
extern BasicBlock* __cdecl verAllocBasicBlock();
#ifdef DEBUG
extern void __cdecl verDispBasicBlocks();
#endif
/*****************************************************************************
*
* The following call-backs supplied by the client; it's used by the code
* emitter to convert a basic block to its corresponding emitter cookie.
*/
void* emitCodeGetCookie(BasicBlock* block);
AllSuccessorIter::AllSuccessorIter(Compiler* comp, BasicBlock* block)
: m_comp(comp), m_blk(block), m_normSucc(0), m_numNormSuccs(block->NumSucc(comp)), m_ehIter(comp, block)
{
if (CurTryIsBlkCallFinallyTarget())
{
++m_ehIter;
}
}
bool AllSuccessorIter::CurTryIsBlkCallFinallyTarget()
{
return (m_blk->bbJumpKind == BBJ_CALLFINALLY) && (m_ehIter != EHSuccessorIter()) &&
(m_blk->bbJumpDest == (*m_ehIter));
}
void AllSuccessorIter::operator++(void)
{
if (m_normSucc < m_numNormSuccs)
{
m_normSucc++;
}
else
{
++m_ehIter;
// If the original block whose successors we're iterating over
// is a BBJ_CALLFINALLY, that finally clause's first block
// will be yielded as a normal successor. Don't also yield as
// an exceptional successor.
if (CurTryIsBlkCallFinallyTarget())
{
++m_ehIter;
}
}
}
// Requires that "this" is not equal to the standard "end" iterator. Returns the
// current successor.
BasicBlock* AllSuccessorIter::operator*()
{
if (m_normSucc < m_numNormSuccs)
{
return m_blk->GetSucc(m_normSucc, m_comp);
}
else
{
return *m_ehIter;
}
}
/*****************************************************************************/
#endif // _BLOCK_H_
/*****************************************************************************/
| Java |
// FBO.h
#pragma once
#if defined(_WIN32)
#include <windows.h>
#endif
#ifdef __APPLE__
#include <OpenGL/glu.h>
#else
#include <GL/glu.h>
#endif
struct FBO {
GLuint id, tex, depth;
GLuint w, h;
};
void allocateFBO(FBO&, int w, int h);
void deallocateFBO(FBO&);
void bindFBO(const FBO&, float fboScale=1.0f);
void unbindFBO();
| Java |
export interface StripeCardTokenParams {
/**
* Card number
*/
number: string;
/**
* Expiry month
*/
expMonth: number;
/**
* Expiry year
*/
expYear: number;
/**
* CVC / CVV
*/
cvc?: string;
/**
* Cardholder name
*/
name?: string;
/**
* Address line 1
*/
address_line1?: string;
/**
* Address line 2
*/
address_line2?: string;
/**
* City
*/
address_city?: string;
/**
* State / Province
*/
address_state?: string;
/**
* Country
*/
address_country?: string;
/**
* Postal code / ZIP Code
*/
postal_code?: string;
/**
* 3-letter ISO code for currency
*/
currency?: string;
}
/**
* @beta
* @name Stripe
* @description
* A plugin that allows you to use Stripe's Native SDKs for Android and iOS.
*
* @usage
* ```
* import { Stripe } from 'ionic-native';
*
* Stripe.setPublishableKey('my_publishable_key');
*
* let card = {
* number: '4242424242424242',
* expMonth: 12,
* expYear: 2020,
* cvc: 220
* };
*
* Stripe.createToken(card)
* .then(token => console.log(token))
* .catch(error => console.error(error));
*
* ```
*
* @interfaces
* StripeCardTokenParams
*/
export declare class Stripe {
/**
* Set publishable key
* @param publishableKey {string} Publishable key
* @return {Promise<void>}
*/
static setPublishableKey(publishableKey: string): Promise<void>;
/**
* Create Credit Card Token
* @param params {StripeCardTokenParams} Credit card information
* @return {Promise<string>} returns a promise that resolves with the token, or reject with an error
*/
static createCardToken(params: StripeCardTokenParams): Promise<string>;
}
| Java |
require 'helper'
class TestRepeaterWeek < TestCase
def setup
@now = Time.local(2006, 8, 16, 14, 0, 0, 0)
end
def test_next_future
weeks = Chronic::RepeaterWeek.new(:week)
weeks.start = @now
next_week = weeks.next(:future)
assert_equal Time.local(2006, 8, 20), next_week.begin
assert_equal Time.local(2006, 8, 27), next_week.end
next_next_week = weeks.next(:future)
assert_equal Time.local(2006, 8, 27), next_next_week.begin
assert_equal Time.local(2006, 9, 3), next_next_week.end
end
def test_next_past
weeks = Chronic::RepeaterWeek.new(:week)
weeks.start = @now
last_week = weeks.next(:past)
assert_equal Time.local(2006, 8, 6), last_week.begin
assert_equal Time.local(2006, 8, 13), last_week.end
last_last_week = weeks.next(:past)
assert_equal Time.local(2006, 7, 30), last_last_week.begin
assert_equal Time.local(2006, 8, 6), last_last_week.end
end
def test_this_future
weeks = Chronic::RepeaterWeek.new(:week)
weeks.start = @now
this_week = weeks.this(:future)
assert_equal Time.local(2006, 8, 16, 15), this_week.begin
assert_equal Time.local(2006, 8, 20), this_week.end
end
def test_this_past
weeks = Chronic::RepeaterWeek.new(:week)
weeks.start = @now
this_week = weeks.this(:past)
assert_equal Time.local(2006, 8, 13, 0), this_week.begin
assert_equal Time.local(2006, 8, 16, 14), this_week.end
end
def test_offset
span = Chronic::Span.new(@now, @now + 1)
offset_span = Chronic::RepeaterWeek.new(:week).offset(span, 3, :future)
assert_equal Time.local(2006, 9, 6, 14), offset_span.begin
assert_equal Time.local(2006, 9, 6, 14, 0, 1), offset_span.end
end
def test_next_future_starting_on_monday
weeks = Chronic::RepeaterWeek.new(:week, :week_start => :monday)
weeks.start = @now
next_week = weeks.next(:future)
assert_equal Time.local(2006, 8, 21), next_week.begin
assert_equal Time.local(2006, 8, 28), next_week.end
next_next_week = weeks.next(:future)
assert_equal Time.local(2006, 8, 28), next_next_week.begin
assert_equal Time.local(2006, 9, 4), next_next_week.end
end
def test_next_past_starting_on_monday
weeks = Chronic::RepeaterWeek.new(:week, :week_start => :monday)
weeks.start = @now
last_week = weeks.next(:past)
assert_equal Time.local(2006, 8, 7), last_week.begin
assert_equal Time.local(2006, 8, 14), last_week.end
last_last_week = weeks.next(:past)
assert_equal Time.local(2006, 7, 31), last_last_week.begin
assert_equal Time.local(2006, 8, 7), last_last_week.end
end
def test_this_future_starting_on_monday
weeks = Chronic::RepeaterWeek.new(:week, :week_start => :monday)
weeks.start = @now
this_week = weeks.this(:future)
assert_equal Time.local(2006, 8, 16, 15), this_week.begin
assert_equal Time.local(2006, 8, 21), this_week.end
end
def test_this_past_starting_on_monday
weeks = Chronic::RepeaterWeek.new(:week, :week_start => :monday)
weeks.start = @now
this_week = weeks.this(:past)
assert_equal Time.local(2006, 8, 14, 0), this_week.begin
assert_equal Time.local(2006, 8, 16, 14), this_week.end
end
def test_offset_starting_on_monday
weeks = Chronic::RepeaterWeek.new(:week, :week_start => :monday)
span = Chronic::Span.new(@now, @now + 1)
offset_span = weeks.offset(span, 3, :future)
assert_equal Time.local(2006, 9, 6, 14), offset_span.begin
assert_equal Time.local(2006, 9, 6, 14, 0, 1), offset_span.end
end
end
| Java |
<?php
/**
* Copyright (c) 2013 Robin Appelman <[email protected]>
* This file is licensed under the Affero General Public License version 3 or
* later.
* See the COPYING-README file.
*/
namespace OC\User;
use OC\Hooks\PublicEmitter;
use OCP\IUserManager;
/**
* Class Manager
*
* Hooks available in scope \OC\User:
* - preSetPassword(\OC\User\User $user, string $password, string $recoverPassword)
* - postSetPassword(\OC\User\User $user, string $password, string $recoverPassword)
* - preDelete(\OC\User\User $user)
* - postDelete(\OC\User\User $user)
* - preCreateUser(string $uid, string $password)
* - postCreateUser(\OC\User\User $user, string $password)
*
* @package OC\User
*/
class Manager extends PublicEmitter implements IUserManager {
/**
* @var \OC_User_Interface[] $backends
*/
private $backends = array();
/**
* @var \OC\User\User[] $cachedUsers
*/
private $cachedUsers = array();
/**
* @var \OC\AllConfig $config
*/
private $config;
/**
* @param \OC\AllConfig $config
*/
public function __construct($config = null) {
$this->config = $config;
$cachedUsers = $this->cachedUsers;
$this->listen('\OC\User', 'postDelete', function ($user) use (&$cachedUsers) {
$i = array_search($user, $cachedUsers);
if ($i !== false) {
unset($cachedUsers[$i]);
}
});
$this->listen('\OC\User', 'postLogin', function ($user) {
$user->updateLastLoginTimestamp();
});
$this->listen('\OC\User', 'postRememberedLogin', function ($user) {
$user->updateLastLoginTimestamp();
});
}
/**
* register a user backend
*
* @param \OC_User_Interface $backend
*/
public function registerBackend($backend) {
$this->backends[] = $backend;
}
/**
* remove a user backend
*
* @param \OC_User_Interface $backend
*/
public function removeBackend($backend) {
$this->cachedUsers = array();
if (($i = array_search($backend, $this->backends)) !== false) {
unset($this->backends[$i]);
}
}
/**
* remove all user backends
*/
public function clearBackends() {
$this->cachedUsers = array();
$this->backends = array();
}
/**
* get a user by user id
*
* @param string $uid
* @return \OC\User\User
*/
public function get($uid) {
if (isset($this->cachedUsers[$uid])) { //check the cache first to prevent having to loop over the backends
return $this->cachedUsers[$uid];
}
foreach ($this->backends as $backend) {
if ($backend->userExists($uid)) {
return $this->getUserObject($uid, $backend);
}
}
return null;
}
/**
* get or construct the user object
*
* @param string $uid
* @param \OC_User_Interface $backend
* @return \OC\User\User
*/
protected function getUserObject($uid, $backend) {
if (isset($this->cachedUsers[$uid])) {
return $this->cachedUsers[$uid];
}
$this->cachedUsers[$uid] = new User($uid, $backend, $this, $this->config);
return $this->cachedUsers[$uid];
}
/**
* check if a user exists
*
* @param string $uid
* @return bool
*/
public function userExists($uid) {
$user = $this->get($uid);
return ($user !== null);
}
/**
* remove deleted user from cache
*
* @param string $uid
* @return bool
*/
public function delete($uid) {
if (isset($this->cachedUsers[$uid])) {
unset($this->cachedUsers[$uid]);
return true;
}
return false;
}
/**
* Check if the password is valid for the user
*
* @param string $loginname
* @param string $password
* @return mixed the User object on success, false otherwise
*/
public function checkPassword($loginname, $password) {
foreach ($this->backends as $backend) {
if ($backend->implementsActions(\OC_USER_BACKEND_CHECK_PASSWORD)) {
$uid = $backend->checkPassword($loginname, $password);
if ($uid !== false) {
return $this->getUserObject($uid, $backend);
}
}
}
$remoteAddr = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
$forwardedFor = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : '';
\OC::$server->getLogger()->warning('Login failed: \''. $loginname .'\' (Remote IP: \''. $remoteAddr .'\', X-Forwarded-For: \''. $forwardedFor .'\')', array('app' => 'core'));
return false;
}
/**
* search by user id
*
* @param string $pattern
* @param int $limit
* @param int $offset
* @return \OC\User\User[]
*/
public function search($pattern, $limit = null, $offset = null) {
$users = array();
foreach ($this->backends as $backend) {
$backendUsers = $backend->getUsers($pattern, $limit, $offset);
if (is_array($backendUsers)) {
foreach ($backendUsers as $uid) {
$users[$uid] = $this->getUserObject($uid, $backend);
}
}
}
uasort($users, function ($a, $b) {
/**
* @var \OC\User\User $a
* @var \OC\User\User $b
*/
return strcmp($a->getUID(), $b->getUID());
});
return $users;
}
/**
* search by displayName
*
* @param string $pattern
* @param int $limit
* @param int $offset
* @return \OC\User\User[]
*/
public function searchDisplayName($pattern, $limit = null, $offset = null) {
$users = array();
foreach ($this->backends as $backend) {
$backendUsers = $backend->getDisplayNames($pattern, $limit, $offset);
if (is_array($backendUsers)) {
foreach ($backendUsers as $uid => $displayName) {
$users[] = $this->getUserObject($uid, $backend);
}
}
}
usort($users, function ($a, $b) {
/**
* @var \OC\User\User $a
* @var \OC\User\User $b
*/
return strcmp($a->getDisplayName(), $b->getDisplayName());
});
return $users;
}
/**
* @param string $uid
* @param string $password
* @throws \Exception
* @return bool|\OC\User\User the created user of false
*/
public function createUser($uid, $password) {
$l = \OC_L10N::get('lib');
// Check the name for bad characters
// Allowed are: "a-z", "A-Z", "0-9" and "_.@-"
if (preg_match('/[^a-zA-Z0-9 _\.@\-]/', $uid)) {
throw new \Exception($l->t('Only the following characters are allowed in a username:'
. ' "a-z", "A-Z", "0-9", and "_.@-"'));
}
// No empty username
if (trim($uid) == '') {
throw new \Exception($l->t('A valid username must be provided'));
}
// No empty password
if (trim($password) == '') {
throw new \Exception($l->t('A valid password must be provided'));
}
// Check if user already exists
if ($this->userExists($uid)) {
throw new \Exception($l->t('The username is already being used'));
}
$this->emit('\OC\User', 'preCreateUser', array($uid, $password));
foreach ($this->backends as $backend) {
if ($backend->implementsActions(\OC_USER_BACKEND_CREATE_USER)) {
$backend->createUser($uid, $password);
$user = $this->getUserObject($uid, $backend);
$this->emit('\OC\User', 'postCreateUser', array($user, $password));
return $user;
}
}
return false;
}
/**
* returns how many users per backend exist (if supported by backend)
*
* @return array an array of backend class as key and count number as value
*/
public function countUsers() {
$userCountStatistics = array();
foreach ($this->backends as $backend) {
if ($backend->implementsActions(\OC_USER_BACKEND_COUNT_USERS)) {
$backendusers = $backend->countUsers();
if($backendusers !== false) {
if(isset($userCountStatistics[get_class($backend)])) {
$userCountStatistics[get_class($backend)] += $backendusers;
} else {
$userCountStatistics[get_class($backend)] = $backendusers;
}
}
}
}
return $userCountStatistics;
}
}
| Java |
var dep = require('./dep');
dep(''); | Java |
package org.multibit.hd.ui.views.wizards.appearance_settings;
import com.google.common.base.Optional;
import org.multibit.hd.ui.views.wizards.AbstractWizard;
import org.multibit.hd.ui.views.wizards.AbstractWizardPanelView;
import java.util.Map;
/**
* <p>Wizard to provide the following to UI for "appearance" wizard:</p>
* <ol>
* <li>Enter details</li>
* </ol>
*
* @since 0.0.1
*
*/
public class AppearanceSettingsWizard extends AbstractWizard<AppearanceSettingsWizardModel> {
public AppearanceSettingsWizard(AppearanceSettingsWizardModel model) {
super(model, false, Optional.absent());
}
@Override
protected void populateWizardViewMap(Map<String, AbstractWizardPanelView> wizardViewMap) {
// Use the wizard parameter to retrieve the appropriate mode
wizardViewMap.put(
AppearanceSettingsState.APPEARANCE_ENTER_DETAILS.name(),
new AppearanceSettingsPanelView(this, AppearanceSettingsState.APPEARANCE_ENTER_DETAILS.name())
);
}
}
| Java |
// TODO: This doesn't pass on android 64bit CI...
// Figure out why!
#![cfg(not(target_os = "android"))]
use mio::{Events, Poll, PollOpt, Ready, Token};
use mio::net::UdpSocket;
use bytes::{Buf, MutBuf, RingBuf, SliceBuf};
use std::str;
use std::net::IpAddr;
use localhost;
const LISTENER: Token = Token(0);
const SENDER: Token = Token(1);
pub struct UdpHandler {
tx: UdpSocket,
rx: UdpSocket,
msg: &'static str,
buf: SliceBuf<'static>,
rx_buf: RingBuf,
localhost: IpAddr,
shutdown: bool,
}
impl UdpHandler {
fn new(tx: UdpSocket, rx: UdpSocket, msg: &'static str) -> UdpHandler {
let sock = UdpSocket::bind(&"127.0.0.1:12345".parse().unwrap()).unwrap();
UdpHandler {
tx: tx,
rx: rx,
msg: msg,
buf: SliceBuf::wrap(msg.as_bytes()),
rx_buf: RingBuf::new(1024),
localhost: sock.local_addr().unwrap().ip(),
shutdown: false,
}
}
fn handle_read(&mut self, _: &mut Poll, token: Token, _: Ready) {
match token {
LISTENER => {
debug!("We are receiving a datagram now...");
match unsafe { self.rx.recv_from(self.rx_buf.mut_bytes()) } {
Ok((cnt, addr)) => {
unsafe { MutBuf::advance(&mut self.rx_buf, cnt); }
assert_eq!(addr.ip(), self.localhost);
}
res => panic!("unexpected result: {:?}", res),
}
assert!(str::from_utf8(self.rx_buf.bytes()).unwrap() == self.msg);
self.shutdown = true;
},
_ => ()
}
}
fn handle_write(&mut self, _: &mut Poll, token: Token, _: Ready) {
match token {
SENDER => {
let addr = self.rx.local_addr().unwrap();
let cnt = self.tx.send_to(self.buf.bytes(), &addr).unwrap();
self.buf.advance(cnt);
},
_ => ()
}
}
}
#[test]
pub fn test_multicast() {
drop(::env_logger::init());
debug!("Starting TEST_UDP_CONNECTIONLESS");
let mut poll = Poll::new().unwrap();
let addr = localhost();
let any = "0.0.0.0:0".parse().unwrap();
let tx = UdpSocket::bind(&any).unwrap();
let rx = UdpSocket::bind(&addr).unwrap();
info!("Joining group 227.1.1.100");
let any = "0.0.0.0".parse().unwrap();
rx.join_multicast_v4(&"227.1.1.100".parse().unwrap(), &any).unwrap();
info!("Joining group 227.1.1.101");
rx.join_multicast_v4(&"227.1.1.101".parse().unwrap(), &any).unwrap();
info!("Registering SENDER");
poll.register(&tx, SENDER, Ready::writable(), PollOpt::edge()).unwrap();
info!("Registering LISTENER");
poll.register(&rx, LISTENER, Ready::readable(), PollOpt::edge()).unwrap();
let mut events = Events::with_capacity(1024);
let mut handler = UdpHandler::new(tx, rx, "hello world");
info!("Starting event loop to test with...");
while !handler.shutdown {
poll.poll(&mut events, None).unwrap();
for event in &events {
if event.readiness().is_readable() {
handler.handle_read(&mut poll, event.token(), event.readiness());
}
if event.readiness().is_writable() {
handler.handle_write(&mut poll, event.token(), event.readiness());
}
}
}
}
| Java |
/*
The MIT License
Copyright (c) 2012 by Jorrit Tyberghein
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef __modelrepository_h
#define __modelrepository_h
#include "editor/imodelrepository.h"
class AresEdit3DView;
class AppAresEditWX;
class DynfactCollectionValue;
class FactoriesValue;
class ObjectsValue;
class TemplatesValue;
class ClassesValue;
class ActionsValue;
class WizardsValue;
/**
* The model repository.
*/
class ModelRepository : public scfImplementation1<ModelRepository, iModelRepository>
{
private:
AppAresEditWX* app;
csRef<DynfactCollectionValue> dynfactCollectionValue;
csRef<FactoriesValue> factoriesValue;
csRef<ObjectsValue> objectsValue;
csRef<TemplatesValue> templatesValue;
csRef<ClassesValue> classesValue;
csRef<ActionsValue> actionsValue;
csRef<WizardsValue> templateWizardsValue;
csRef<WizardsValue> questWizardsValue;
/// Debug drawing enabled.
public:
ModelRepository (AresEdit3DView* view3d, AppAresEditWX* app);
virtual ~ModelRepository ();
ObjectsValue* GetObjectsValueInt () { return objectsValue; }
TemplatesValue* GetTemplatesValueInt () { return templatesValue; }
// Refresh the models after load or save.
virtual void Refresh ();
virtual Ares::Value* GetDynfactCollectionValue () const;
virtual Ares::Value* GetFactoriesValue () const;
virtual Ares::Value* GetObjectsValue () const;
virtual Ares::Value* GetTemplatesValue () const;
virtual csRef<Ares::Value> GetWritableAssetsValue () const;
virtual csRef<Ares::Value> GetAssetsValue () const;
virtual csRef<Ares::Value> GetResourcesValue () const;
virtual csRef<Ares::Value> GetQuestsValue () const;
virtual Ares::Value* GetClassesValue () const;
virtual Ares::Value* GetActionsValue () const;
virtual Ares::Value* GetTemplateWizardsValue () const;
virtual Ares::Value* GetQuestWizardsValue () const;
virtual csRef<Ares::Value> GetObjectsWithEntityValue () const;
virtual csRef<Ares::Value> GetPropertyClassesValue (const char* pcname) const;
virtual void RefreshObjectsValue ();
virtual iDynamicObject* GetDynamicObjectFromObjects (Ares::Value* value);
virtual iObject* GetResourceFromResources (Ares::Value* value);
virtual iAsset* GetAssetFromAssets (Ares::Value* value);
virtual size_t GetDynamicObjectIndexFromObjects (iDynamicObject* dynobj);
virtual size_t GetTemplateIndexFromTemplates (iCelEntityTemplate* tpl);
};
#endif // __modelrepository_h
| Java |
---
layout: center
permalink: /404.html
---
# 404
Sorry, we can't seem to find this page's pixylls.
<div class="mt3">
<a href="{{ site.baseurl }}/" class="button button-blue button-big">Home</a>
<a href="{{ site.baseurl }}/about/" class="button button-blue button-big">About</a>
</div>
| Java |
package scorex.network.peer
import java.net.InetSocketAddress
//todo: add optional nonce
case class PeerInfo(lastSeen: Long, nonce: Option[Long] = None, nodeName: Option[String] = None)
trait PeerDatabase {
def addOrUpdateKnownPeer(peer: InetSocketAddress, peerInfo: PeerInfo): Unit
def knownPeers(forSelf: Boolean): Map[InetSocketAddress, PeerInfo]
def blacklistPeer(peer: InetSocketAddress): Unit
def blacklistedPeers(): Seq[String]
def isBlacklisted(address: InetSocketAddress): Boolean
}
| Java |
/*
* Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.toxml;
import com.google.common.base.Preconditions;
import org.opendaylight.controller.netconf.confignetconfconnector.util.Util;
import org.w3c.dom.Document;
import java.util.List;
import java.util.Map;
public class SimpleUnionAttributeWritingStrategy extends SimpleAttributeWritingStrategy {
/**
* @param document
* @param key
*/
public SimpleUnionAttributeWritingStrategy(Document document, String key) {
super(document, key);
}
protected Object preprocess(Object value) {
Util.checkType(value, Map.class);
Preconditions.checkArgument(((Map)value).size() == 1, "Unexpected number of values in %s, expected 1", value);
Object listOfStrings = ((Map) value).values().iterator().next();
Util.checkType(listOfStrings, List.class);
StringBuilder b = new StringBuilder();
for (Object character: (List)listOfStrings) {
Util.checkType(character, String.class);
b.append(character);
}
return b.toString();
}
}
| Java |
/*******************************************************************************
* Copyright (c) 2006, 2009 David A Carlson
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* David A Carlson (XMLmodeling.com) - initial API and implementation
*******************************************************************************/
package org.openhealthtools.mdht.emf.w3c.xhtml.internal.impl;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.openhealthtools.mdht.emf.w3c.xhtml.Code;
import org.openhealthtools.mdht.emf.w3c.xhtml.MifClassType;
import org.openhealthtools.mdht.emf.w3c.xhtml.StyleSheet;
import org.openhealthtools.mdht.emf.w3c.xhtml.XhtmlPackage;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Code</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link org.openhealthtools.mdht.emf.w3c.xhtml.internal.impl.CodeImpl#getClass_ <em>Class</em>}</li>
* <li>{@link org.openhealthtools.mdht.emf.w3c.xhtml.internal.impl.CodeImpl#getLang <em>Lang</em>}</li>
* <li>{@link org.openhealthtools.mdht.emf.w3c.xhtml.internal.impl.CodeImpl#getStyle <em>Style</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class CodeImpl extends InlineImpl implements Code {
/**
* The default value of the '{@link #getClass_() <em>Class</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getClass_()
* @generated
* @ordered
*/
protected static final MifClassType CLASS_EDEFAULT = MifClassType.INSERTED;
/**
* The cached value of the '{@link #getClass_() <em>Class</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getClass_()
* @generated
* @ordered
*/
protected MifClassType class_ = CLASS_EDEFAULT;
/**
* This is true if the Class attribute has been set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
protected boolean classESet;
/**
* The default value of the '{@link #getLang() <em>Lang</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getLang()
* @generated
* @ordered
*/
protected static final String LANG_EDEFAULT = null;
/**
* The cached value of the '{@link #getLang() <em>Lang</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getLang()
* @generated
* @ordered
*/
protected String lang = LANG_EDEFAULT;
/**
* The default value of the '{@link #getStyle() <em>Style</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getStyle()
* @generated
* @ordered
*/
protected static final StyleSheet STYLE_EDEFAULT = StyleSheet.REQUIREMENT;
/**
* The cached value of the '{@link #getStyle() <em>Style</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getStyle()
* @generated
* @ordered
*/
protected StyleSheet style = STYLE_EDEFAULT;
/**
* This is true if the Style attribute has been set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
protected boolean styleESet;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected CodeImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return XhtmlPackage.Literals.CODE;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MifClassType getClass_() {
return class_;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setClass(MifClassType newClass) {
MifClassType oldClass = class_;
class_ = newClass == null
? CLASS_EDEFAULT
: newClass;
boolean oldClassESet = classESet;
classESet = true;
if (eNotificationRequired()) {
eNotify(new ENotificationImpl(
this, Notification.SET, XhtmlPackage.CODE__CLASS, oldClass, class_, !oldClassESet));
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void unsetClass() {
MifClassType oldClass = class_;
boolean oldClassESet = classESet;
class_ = CLASS_EDEFAULT;
classESet = false;
if (eNotificationRequired()) {
eNotify(new ENotificationImpl(
this, Notification.UNSET, XhtmlPackage.CODE__CLASS, oldClass, CLASS_EDEFAULT, oldClassESet));
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean isSetClass() {
return classESet;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getLang() {
return lang;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setLang(String newLang) {
String oldLang = lang;
lang = newLang;
if (eNotificationRequired()) {
eNotify(new ENotificationImpl(this, Notification.SET, XhtmlPackage.CODE__LANG, oldLang, lang));
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public StyleSheet getStyle() {
return style;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setStyle(StyleSheet newStyle) {
StyleSheet oldStyle = style;
style = newStyle == null
? STYLE_EDEFAULT
: newStyle;
boolean oldStyleESet = styleESet;
styleESet = true;
if (eNotificationRequired()) {
eNotify(new ENotificationImpl(
this, Notification.SET, XhtmlPackage.CODE__STYLE, oldStyle, style, !oldStyleESet));
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void unsetStyle() {
StyleSheet oldStyle = style;
boolean oldStyleESet = styleESet;
style = STYLE_EDEFAULT;
styleESet = false;
if (eNotificationRequired()) {
eNotify(new ENotificationImpl(
this, Notification.UNSET, XhtmlPackage.CODE__STYLE, oldStyle, STYLE_EDEFAULT, oldStyleESet));
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean isSetStyle() {
return styleESet;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case XhtmlPackage.CODE__CLASS:
return getClass_();
case XhtmlPackage.CODE__LANG:
return getLang();
case XhtmlPackage.CODE__STYLE:
return getStyle();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case XhtmlPackage.CODE__CLASS:
setClass((MifClassType) newValue);
return;
case XhtmlPackage.CODE__LANG:
setLang((String) newValue);
return;
case XhtmlPackage.CODE__STYLE:
setStyle((StyleSheet) newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case XhtmlPackage.CODE__CLASS:
unsetClass();
return;
case XhtmlPackage.CODE__LANG:
setLang(LANG_EDEFAULT);
return;
case XhtmlPackage.CODE__STYLE:
unsetStyle();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case XhtmlPackage.CODE__CLASS:
return isSetClass();
case XhtmlPackage.CODE__LANG:
return LANG_EDEFAULT == null
? lang != null
: !LANG_EDEFAULT.equals(lang);
case XhtmlPackage.CODE__STYLE:
return isSetStyle();
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) {
return super.toString();
}
StringBuffer result = new StringBuffer(super.toString());
result.append(" (class: ");
if (classESet) {
result.append(class_);
} else {
result.append("<unset>");
}
result.append(", lang: ");
result.append(lang);
result.append(", style: ");
if (styleESet) {
result.append(style);
} else {
result.append("<unset>");
}
result.append(')');
return result.toString();
}
} // CodeImpl
| Java |
/*******************************************************************************
* Copyright (c) 2002, 2010 QNX Software Systems and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* QNX Software Systems - initial API and implementation
* Wind River Systems, Inc.
* Mikhail Zabaluev (Nokia) - bug 82744
* Corey Ashford (IBM) - bug 272370, bug 272372
*******************************************************************************/
/* _XOPEN_SOURCE is needed to bring in the header for ptsname */
#define _XOPEN_SOURCE
#include <sys/types.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <stdbool.h>
/**
* This is taken from R. W. Stevens book.
* Alain Magloire.
*/
void
set_noecho(int fd)
{
struct termios stermios;
if (tcgetattr(fd, &stermios) < 0) {
return ;
}
/* turn off echo */
stermios.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL);
/* Turn off the NL to CR/NL mapping ou output. */
/*stermios.c_oflag &= ~(ONLCR);*/
stermios.c_iflag |= (IGNCR);
tcsetattr(fd, TCSANOW, &stermios);
}
int
ptys_open(int fdm, const char *pts_name, bool acquire) {
int fds;
/* following should allocate controlling terminal */
fds = open(pts_name, O_RDWR);
if (fds < 0) {
close(fdm);
return -5;
}
#if defined(TIOCSCTTY)
if (acquire) {
/* TIOCSCTTY is the BSD way to acquire a controlling terminal. */
if (ioctl(fds, TIOCSCTTY, (char *) 0) < 0) {
// ignore error: this is expected in console-mode
}
}
#endif
return fds;
}
| Java |
/*******************************************************************************
* Copyright (c) 2005-2010 VecTrace (Zingo Andersen) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* John Peberdy implementation
*******************************************************************************/
package com.vectrace.MercurialEclipse.commands;
import java.io.File;
import java.util.List;
import org.eclipse.core.runtime.Assert;
/**
* A command to invoke hg definitely outside of an hg root.
*/
public class RootlessHgCommand extends AbstractShellCommand {
public RootlessHgCommand(String command, String uiName) {
this(command, uiName, null);
}
public RootlessHgCommand(String command, String uiName, File workingDir) {
super(uiName, null, workingDir, false);
Assert.isNotNull(command);
this.command = command;
}
// operations
/**
* @see com.vectrace.MercurialEclipse.commands.AbstractShellCommand#customizeCommands(java.util.List)
*/
@Override
protected void customizeCommands(List<String> cmd) {
cmd.add(1, "-y");
}
/**
* @see com.vectrace.MercurialEclipse.commands.AbstractShellCommand#getExecutable()
*/
@Override
protected String getExecutable() {
return HgClients.getExecutable();
}
}
| Java |
#include "parser.h"
#include "test.h"
int main(int argc, char *argv[])
{
BOOL ret;
char *fname, *test;
int fd;
struct stat st;
io_struct ps;
if (argc < 3) {
printf("usage: vluke <structure> <file>\n");
exit(1);
}
test = argv[1];
fname = argv[2];
fd = open(fname,O_RDONLY);
if (fd == -1) {
perror(fname);
exit(1);
}
fstat(fd, &st);
io_init(&ps, 0, MARSHALL);
ps.is_dynamic=True;
io_read(&ps, fd, st.st_size, 0);
ps.data_offset = 0;
ps.buffer_size = ps.grow_size;
ps.io = UNMARSHALL;
ps.autoalign = OPTION_autoalign;
ret = run_test(test, &ps, PARSE_SCALARS|PARSE_BUFFERS);
printf("\nret=%s\n", ret?"OK":"Bad");
printf("Trailer is %d bytes\n\n", ps.grow_size - ps.data_offset);
if (ps.grow_size - ps.data_offset > 0) {
dump_data(0, ps.data_p + ps.data_offset, ps.grow_size - ps.data_offset);
}
return !ret;
}
| Java |
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2011-2012 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <[email protected]>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
package org.opennms.smoketest;
import org.junit.Before;
import org.junit.Test;
public class ChartsPageTest extends OpenNMSSeleniumTestCase {
@Before
public void setUp() throws Exception {
super.setUp();
clickAndWait("link=Charts");
}
@Test
public void testChartsPage() throws Exception {
waitForText("Charts");
waitForElement("css=img[alt=sample-bar-chart]");
waitForElement("css=img[alt=sample-bar-chart2]");
waitForElement("css=img[alt=sample-bar-chart3]");
}
}
| Java |
#ifndef TABLEDICT_H
#define TABLEDICT_H
#include <fcitx-utils/utf8.h>
#include <fcitx-config/fcitx-config.h>
#include <fcitx-config/hotkey.h>
#include <fcitx-utils/memory.h>
#define MAX_CODE_LENGTH 30
#define PHRASE_MAX_LENGTH 10
#define FH_MAX_LENGTH 10
#define TABLE_AUTO_SAVE_AFTER 1024
#define AUTO_PHRASE_COUNT 10000
#define SINGLE_HZ_COUNT 66000
#define RECORDTYPE_NORMAL 0x0
#define RECORDTYPE_PINYIN 0x1
#define RECORDTYPE_CONSTRUCT 0x2
#define RECORDTYPE_PROMPT 0x3
struct _FcitxTableState;
typedef enum _ADJUSTORDER {
AD_NO = 0,
AD_FAST = 1,
AD_FREQ = 2
} ADJUSTORDER;
typedef struct _FH {
char strFH[FH_MAX_LENGTH * 2 + 1];
} FH;
typedef struct _RULE_RULE {
unsigned char iFlag; // 1 --> 正序 0 --> 逆序
unsigned char iWhich; //第几个字
unsigned char iIndex; //第几个编码
} RULE_RULE;
typedef struct _RULE {
unsigned char iWords; //多少个字
unsigned char iFlag; //1 --> 大于等于iWords 0 --> 等于iWords
RULE_RULE *rule;
} RULE;
typedef struct _RECORD {
char *strCode;
char *strHZ;
struct _RECORD *next;
struct _RECORD *prev;
unsigned int iHit;
unsigned int iIndex;
int8_t type;
} RECORD;
typedef struct _AUTOPHRASE {
char *strHZ;
char *strCode;
char iSelected;
struct _AUTOPHRASE *next; //构造一个队列
} AUTOPHRASE;
/* 根据键码生成一个简单的索引,指向该键码起始的第一个记录 */
typedef struct _RECORD_INDEX {
RECORD *record;
char cCode;
} RECORD_INDEX;
typedef struct _SINGLE_HZ {
char strHZ[UTF8_MAX_LENGTH + 1];
} SINGLE_HZ;
typedef struct _TableMetaData {
FcitxGenericConfig config;
char *uniqueName;
char *strName;
char *strIconName;
char *strPath;
ADJUSTORDER tableOrder;
int iPriority;
boolean bUsePY;
char cPinyin; //输入该键后,表示进入临时拼音状态
int iTableAutoSendToClient; //自动上屏
int iTableAutoSendToClientWhenNone; //空码自动上屏
boolean bSendRawPreedit;
char *strEndCode; //中止键,按下该键相当于输入该键后再按一个空格
boolean bUseMatchingKey; //是否模糊匹配
char cMatchingKey;
boolean bTableExactMatch; //是否只显示精确匹配的候选字/词
boolean bAutoPhrase; //是否自动造词
boolean bAutoPhrasePhrase; //词组是否参与造词
int iAutoPhraseLength; //自动造词长度
int iSaveAutoPhraseAfter; //选择N次后保存自动词组,0-不保存,1-立即保存
boolean bPromptTableCode; //输入完毕后是否提示编码
char *strSymbol;
char *strSymbolFile;
char *strChoose; //设置选择键
char *langCode;
char *kbdlayout;
boolean customPrompt;
boolean bUseAlternativePageKey;
boolean bFirstCandidateAsPreedit;
boolean bCommitAndPassByInvalidKey;
boolean bIgnorePunc;
FcitxHotkey hkAlternativePrevPage[2];
FcitxHotkey hkAlternativeNextPage[2];
boolean bEnabled;
struct _FcitxTableState* owner;
struct _TableDict* tableDict;
} TableMetaData;
typedef struct _TableDict {
char* strInputCode;
RECORD_INDEX* recordIndex;
unsigned char iCodeLength;
unsigned char iPYCodeLength;
char* strIgnoreChars;
unsigned char bRule;
RULE* rule;
unsigned int iRecordCount;
RECORD* tableSingleHZ[SINGLE_HZ_COUNT];
RECORD* tableSingleHZCons[SINGLE_HZ_COUNT];
unsigned int iTableIndex;
boolean bHasPinyin;
RECORD* currentRecord;
RECORD* recordHead;
int iFH;
FH* fh;
char* strNewPhraseCode;
AUTOPHRASE* autoPhrase;
AUTOPHRASE* insertPoint;
int iAutoPhrase;
int iTableChanged;
int iHZLastInputCount;
SINGLE_HZ hzLastInput[PHRASE_MAX_LENGTH]; //Records last HZ input
RECORD* promptCode[256];
FcitxMemoryPool* pool;
} TableDict;
boolean LoadTableDict(TableMetaData* tableMetaData);
void SaveTableDict(TableMetaData* tableMetaData);
void FreeTableDict(TableMetaData* tableMetaData);
void TableInsertPhrase(TableDict* tableDict, const char *strCode, const char *strHZ);
RECORD *TableFindPhrase(const TableDict* tableDict, const char *strHZ);
boolean TableCreatePhraseCode(TableDict* tableDict, char* strHZ);
void TableCreateAutoPhrase(TableMetaData* tableMetaData, char iCount);
RECORD *TableHasPhrase(const TableDict* tableDict, const char *strCode, const char *strHZ);
void TableDelPhraseByHZ(TableDict* tableDict, const char *strHZ);
void TableDelPhrase(TableDict* tableDict, RECORD * record);
void TableUpdateHitFrequency(TableMetaData* tableMetaData, RECORD * record);
int TableCompareCode(const TableMetaData* tableMetaData, const char *strUser, const char *strDict);
int TableFindFirstMatchCode(TableMetaData* tableMetaData, const char* strCodeInput);
void TableResetFlags(TableDict* tableDict);
boolean IsInputKey(const TableDict* tableDict, int iKey);
boolean IsEndKey(const TableMetaData* tableMetaData, char cChar);
boolean IsIgnoreChar(const TableDict* tableDict, char cChar);
unsigned int CalHZIndex(char *strHZ);
boolean HasMatchingKey(const TableMetaData* tableMetaData, const char* strCodeInput);
CONFIG_BINDING_DECLARE(TableMetaData);
#endif
// kate: indent-mode cstyle; space-indent on; indent-width 0;
| Java |
<?php
/**
* @package gantry
* @subpackage core
* @version 3.2.12 October 30, 2011
* @author RocketTheme http://www.rockettheme.com
* @copyright Copyright (C) 2007 - 2011 RocketTheme, LLC
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only
*
* Gantry uses the Joomla Framework (http://www.joomla.org), a GNU/GPLv2 content management system
*
*/
defined('GANTRY_VERSION') or die();
/**
* Base class for all Gantry custom features.
*
* @package gantry
* @subpackage core
*/
class GantryLayout {
var $render_params = array();
function render($params = array()){
global $gantry;
ob_start();
return ob_get_clean();
}
function _getParams($params = array()){
$ret = new stdClass();
$ret_array = array_merge($this->render_params, $params);
foreach($ret_array as $param_name => $param_value){
$ret->$param_name = $param_value;
}
return $ret;
}
} | Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.