text
stringlengths 2
1.04M
| meta
dict |
---|---|
import React from 'react';
import PropTypes from 'prop-types';
import {stack as d3Stack, stackOffsetWiggle} from 'd3-shape';
import {range, transpose} from 'd3-array';
import {FlexibleWidthXYPlot, AreaSeries} from 'index';
import './streamgraph-example.scss';
const NUMBER_OF_LAYERS = 20;
const SAMPLES_PER_LAYER = 200;
const BUMPS_PER_LAYER = 10;
const bump = (aggregatingData, samplesPerLayer) => {
const x = 1 / (0.1 + Math.random());
const y = 2 * Math.random() - 0.5;
const z = 10 / (0.1 + Math.random());
return aggregatingData.map((v, i) => {
const w = (i / samplesPerLayer - y) * z;
return v + (x * Math.exp(-w * w));
});
};
// Inspired by Bostock's version of Lee Byron’s test data generator.
function bumps(samplesPerLayer, bumpsPerLayer) {
const dataOutline = (new Array(samplesPerLayer)).fill(0);
return range(bumpsPerLayer).reduce(res => bump(res, samplesPerLayer), dataOutline);
}
function generateData() {
const stack = d3Stack().keys(range(NUMBER_OF_LAYERS)).offset(stackOffsetWiggle);
const transposed = transpose(range(NUMBER_OF_LAYERS).map(() => bumps(SAMPLES_PER_LAYER, BUMPS_PER_LAYER)));
return stack(transposed).map(series => series.map((row, x) => ({x, y0: row[0], y: row[1]})));
}
class StreamgraphExample extends React.Component {
state = {
data: generateData(),
hoveredIndex: false
}
render() {
const {forFrontPage} = this.props;
const {data, hoveredIndex} = this.state;
return (
<div className="streamgraph-example">
{!forFrontPage && (<button
className="showcase-button"
onClick={() => this.setState({data: generateData()})}>
{'Click me!'}
</button>)}
<div className="streamgraph">
<FlexibleWidthXYPlot
animation
onMouseLeave={() => this.setState({hoveredIndex: false})}
height={300}>
{data.map((series, index) => (
<AreaSeries
key={index}
curve="curveNatural"
className={`${index === hoveredIndex ? 'highlighted-stream' : ''}`}
onSeriesMouseOver={() => this.setState({hoveredIndex: index})}
data={series} />
))}
</FlexibleWidthXYPlot>
</div>
</div>
);
}
}
StreamgraphExample.propTypes = {
forFrontPage: PropTypes.bool
};
export default StreamgraphExample;
| {
"content_hash": "df91a31df627251cc8077b2aba3f36b1",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 109,
"avg_line_length": 31.285714285714285,
"alnum_prop": 0.6135325861353259,
"repo_name": "Apercu/react-vis",
"id": "48bf4f9bc59288ef5421441ce7c9eeeacae92cde",
"size": "3540",
"binary": false,
"copies": "1",
"ref": "refs/heads/test-ocular",
"path": "showcase/examples/streamgraph/streamgraph-example.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "14068"
},
{
"name": "HTML",
"bytes": "281"
},
{
"name": "JavaScript",
"bytes": "703207"
},
{
"name": "Shell",
"bytes": "347"
}
],
"symlink_target": ""
} |
/*
* eXist Open Source Native XML Database
* Copyright (C) 2001-06 Wolfgang M. Meier
* [email protected]
* http://exist.sourceforge.net
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* $Id: Except.java 3457 2006-05-07 14:46:21Z wolfgang_m $
*/
package org.exist.xquery;
import java.util.Set;
import java.util.TreeSet;
import org.exist.xquery.util.ExpressionDumper;
import org.exist.xquery.value.Item;
import org.exist.xquery.value.Sequence;
import org.exist.xquery.value.SequenceIterator;
import org.exist.xquery.value.Type;
import org.exist.xquery.value.ValueSequence;
/**
* @author Wolfgang Meier ([email protected])
*/
public class Except extends CombiningExpression {
public Except(XQueryContext context, PathExpr left, PathExpr right) {
super(context, left, right);
}
/* (non-Javadoc)
* @see org.exist.xquery.CombiningExpression#eval(org.exist.dom.DocumentSet, org.exist.xquery.value.Sequence, org.exist.xquery.value.Item)
*/
public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathException {
if (context.getProfiler().isEnabled()) {
context.getProfiler().start(this);
context.getProfiler().message(this, Profiler.DEPENDENCIES, "DEPENDENCIES", Dependency.getDependenciesName(this.getDependencies()));
if (contextSequence != null)
context.getProfiler().message(this, Profiler.START_SEQUENCES, "CONTEXT SEQUENCE", contextSequence);
if (contextItem != null)
context.getProfiler().message(this, Profiler.START_SEQUENCES, "CONTEXT ITEM", contextItem.toSequence());
}
Sequence lval = left.eval(contextSequence, contextItem);
Sequence rval = right.eval(contextSequence, contextItem);
lval.removeDuplicates();
rval.removeDuplicates();
Sequence result;
if (lval.isEmpty()) {
result = Sequence.EMPTY_SEQUENCE;
} else if (rval.isEmpty()) {
if(!Type.subTypeOf(lval.getItemType(), Type.NODE))
throw new XPathException(getASTNode(), "Error XPTY0004 : except operand is not a node sequence");
result = lval;
} else {
if(!(Type.subTypeOf(lval.getItemType(), Type.NODE) && Type.subTypeOf(rval.getItemType(), Type.NODE)))
throw new XPathException(getASTNode(), "Error XPTY0004 : except operand is not a node sequence");
if (lval.isPersistentSet() && rval.isPersistentSet())
result = lval.toNodeSet().except(rval.toNodeSet());
else {
result = new ValueSequence();
Set set = new TreeSet();
for (SequenceIterator i = rval.unorderedIterator(); i.hasNext(); )
set.add(i.nextItem());
for (SequenceIterator i = lval.unorderedIterator(); i.hasNext(); ) {
Item next = i.nextItem();
if (!set.contains(next))
result.add(next);
}
result.removeDuplicates();
}
}
if (context.getProfiler().isEnabled())
context.getProfiler().end(this, "", result);
return result;
}
/* (non-Javadoc)
* @see org.exist.xquery.Expression#dump(org.exist.xquery.util.ExpressionDumper)
*/
public void dump(ExpressionDumper dumper) {
left.dump(dumper);
dumper.display(" except ");
right.dump(dumper);
}
public String toString() {
StringBuffer result = new StringBuffer();
result.append(left.toString());
result.append(" except ");
result.append(right.toString());
return result.toString();
}
}
| {
"content_hash": "442ce45861e63d449bccf5af92f3bab1",
"timestamp": "",
"source": "github",
"line_count": 113,
"max_line_length": 143,
"avg_line_length": 40.88495575221239,
"alnum_prop": 0.6134199134199134,
"repo_name": "NCIP/cadsr-cgmdr-nci-uk",
"id": "4b77777600fa0918a9176fbac6730fbb3bbed882",
"size": "4793",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/org/exist/xquery/Except.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C#",
"bytes": "291811"
},
{
"name": "CSS",
"bytes": "46374"
},
{
"name": "Emacs Lisp",
"bytes": "1302"
},
{
"name": "Java",
"bytes": "12447025"
},
{
"name": "JavaScript",
"bytes": "659235"
},
{
"name": "Perl",
"bytes": "14339"
},
{
"name": "Python",
"bytes": "8079"
},
{
"name": "Shell",
"bytes": "47723"
},
{
"name": "XQuery",
"bytes": "592174"
},
{
"name": "XSLT",
"bytes": "441742"
}
],
"symlink_target": ""
} |
#ifndef SOUND_FIREWIRE_AMDTP_H_INCLUDED
#define SOUND_FIREWIRE_AMDTP_H_INCLUDED
#include <linux/err.h>
#include <linux/interrupt.h>
#include <linux/mutex.h>
#include <sound/asound.h>
#include "packets-buffer.h"
/**
* enum cip_out_flags - describes details of the streaming protocol
* @CIP_NONBLOCKING: In non-blocking mode, each packet contains
* sample_rate/8000 samples, with rounding up or down to adjust
* for clock skew and left-over fractional samples. This should
* be used if supported by the device.
* @CIP_BLOCKING: In blocking mode, each packet contains either zero or
* SYT_INTERVAL samples, with these two types alternating so that
* the overall sample rate comes out right.
* @CIP_HI_DUALWIRE: At rates above 96 kHz, pretend that the stream runs
* at half the actual sample rate with twice the number of channels;
* two samples of a channel are stored consecutively in the packet.
* Requires blocking mode and SYT_INTERVAL-aligned PCM buffer size.
*/
enum cip_out_flags {
CIP_NONBLOCKING = 0x00,
CIP_BLOCKING = 0x01,
CIP_HI_DUALWIRE = 0x02,
};
/**
* enum cip_sfc - a stream's sample rate
*/
enum cip_sfc {
CIP_SFC_32000 = 0,
CIP_SFC_44100 = 1,
CIP_SFC_48000 = 2,
CIP_SFC_88200 = 3,
CIP_SFC_96000 = 4,
CIP_SFC_176400 = 5,
CIP_SFC_192000 = 6,
CIP_SFC_COUNT
};
#define AMDTP_OUT_PCM_FORMAT_BITS (SNDRV_PCM_FMTBIT_S16 | \
SNDRV_PCM_FMTBIT_S32)
struct fw_unit;
struct fw_iso_context;
struct snd_pcm_substream;
struct amdtp_out_stream {
struct fw_unit *unit;
enum cip_out_flags flags;
struct fw_iso_context *context;
struct mutex mutex;
enum cip_sfc sfc;
bool dual_wire;
unsigned int data_block_quadlets;
unsigned int pcm_channels;
unsigned int midi_ports;
void (*transfer_samples)(struct amdtp_out_stream *s,
struct snd_pcm_substream *pcm,
__be32 *buffer, unsigned int frames);
unsigned int syt_interval;
unsigned int transfer_delay;
unsigned int source_node_id_field;
struct iso_packets_buffer buffer;
struct snd_pcm_substream *pcm;
struct tasklet_struct period_tasklet;
int packet_index;
unsigned int data_block_counter;
unsigned int data_block_state;
unsigned int last_syt_offset;
unsigned int syt_offset_state;
unsigned int pcm_buffer_pointer;
unsigned int pcm_period_pointer;
bool pointer_flush;
};
int amdtp_out_stream_init(struct amdtp_out_stream *s, struct fw_unit *unit,
enum cip_out_flags flags);
void amdtp_out_stream_destroy(struct amdtp_out_stream *s);
void amdtp_out_stream_set_parameters(struct amdtp_out_stream *s,
unsigned int rate,
unsigned int pcm_channels,
unsigned int midi_ports);
unsigned int amdtp_out_stream_get_max_payload(struct amdtp_out_stream *s);
int amdtp_out_stream_start(struct amdtp_out_stream *s, int channel, int speed);
void amdtp_out_stream_update(struct amdtp_out_stream *s);
void amdtp_out_stream_stop(struct amdtp_out_stream *s);
void amdtp_out_stream_set_pcm_format(struct amdtp_out_stream *s,
snd_pcm_format_t format);
void amdtp_out_stream_pcm_prepare(struct amdtp_out_stream *s);
unsigned long amdtp_out_stream_pcm_pointer(struct amdtp_out_stream *s);
void amdtp_out_stream_pcm_abort(struct amdtp_out_stream *s);
extern const unsigned int amdtp_syt_intervals[CIP_SFC_COUNT];
static inline bool amdtp_out_stream_running(struct amdtp_out_stream *s)
{
return !IS_ERR(s->context);
}
/**
* amdtp_out_streaming_error - check for streaming error
* @s: the AMDTP output stream
*
* If this function returns true, the stream's packet queue has stopped due to
* an asynchronous error.
*/
static inline bool amdtp_out_streaming_error(struct amdtp_out_stream *s)
{
return s->packet_index < 0;
}
/**
* amdtp_out_stream_pcm_trigger - start/stop playback from a PCM device
* @s: the AMDTP output stream
* @pcm: the PCM device to be started, or %NULL to stop the current device
*
* Call this function on a running isochronous stream to enable the actual
* transmission of PCM data. This function should be called from the PCM
* device's .trigger callback.
*/
static inline void amdtp_out_stream_pcm_trigger(struct amdtp_out_stream *s,
struct snd_pcm_substream *pcm)
{
ACCESS_ONCE(s->pcm) = pcm;
}
static inline bool cip_sfc_is_base_44100(enum cip_sfc sfc)
{
return sfc & 1;
}
#endif
| {
"content_hash": "ab96248016d2a965e1ffe56db377cb1a",
"timestamp": "",
"source": "github",
"line_count": 146,
"max_line_length": 79,
"avg_line_length": 29.328767123287673,
"alnum_prop": 0.7307333021952359,
"repo_name": "lokeshjindal15/pd-gem5",
"id": "2746ecd291af057bf778379cecd7530e353d5fc2",
"size": "4282",
"binary": false,
"copies": "367",
"ref": "refs/heads/master",
"path": "kernel_dvfs/linux-linaro-tracking-gem5/sound/firewire/amdtp.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "10138943"
},
{
"name": "Awk",
"bytes": "19269"
},
{
"name": "C",
"bytes": "469972635"
},
{
"name": "C++",
"bytes": "18163034"
},
{
"name": "CMake",
"bytes": "2202"
},
{
"name": "Clojure",
"bytes": "333"
},
{
"name": "Emacs Lisp",
"bytes": "1969"
},
{
"name": "Groff",
"bytes": "63956"
},
{
"name": "HTML",
"bytes": "136898"
},
{
"name": "Hack",
"bytes": "2489"
},
{
"name": "Java",
"bytes": "3096"
},
{
"name": "Jupyter Notebook",
"bytes": "1231954"
},
{
"name": "Lex",
"bytes": "59257"
},
{
"name": "M4",
"bytes": "52982"
},
{
"name": "Makefile",
"bytes": "1453704"
},
{
"name": "Objective-C",
"bytes": "1315749"
},
{
"name": "Perl",
"bytes": "716374"
},
{
"name": "Perl6",
"bytes": "3727"
},
{
"name": "Protocol Buffer",
"bytes": "3246"
},
{
"name": "Python",
"bytes": "4102365"
},
{
"name": "Scilab",
"bytes": "21433"
},
{
"name": "Shell",
"bytes": "512873"
},
{
"name": "SourcePawn",
"bytes": "4687"
},
{
"name": "UnrealScript",
"bytes": "10556"
},
{
"name": "Visual Basic",
"bytes": "2884"
},
{
"name": "XS",
"bytes": "1239"
},
{
"name": "Yacc",
"bytes": "121715"
}
],
"symlink_target": ""
} |
from bet_sizing import BetTiers
import handscore
import constants as C
class Fear(object):
"""Mix-in object for managing fear in the Brain"""
def update_fear(self, bet):
if not self.data.table_cards:
# TODO: should include re-raises eventually
preflop_fear = OpponentPreflopFear(self.data, bet)
self.data.preflop_fear = max(self.data.preflop_fear,
preflop_fear.hand_filter())
else:
hand_fear = OpponentHandRangeFear(self.data, bet)
self.data.hand_fear = max(self.data.hand_fear,
hand_fear.minimum_handscore())
class OpponentFear(object):
def __init__(self, data_obj, to_call):
pot = data_obj.pot
bb = data_obj.big_blind
is_preflop = not data_obj.table_cards
self.data = data_obj
self.bet = to_call
# TODO: opponent stack?
tiers = BetTiers(pot, bb, is_preflop)
self.tier = tiers.tier(to_call)
class OpponentPreflopFear(OpponentFear):
"""Class that tracks opponent's preflop actions to estimate their
starting hand strength"""
RAISE_FEARS = {
"CHECK": -1,
"MIN_RAISE": 40,
"RAISE": 45,
"BIG_RAISE": 50,
"OVERBET": 60,
}
def hand_filter(self):
return self.RAISE_FEARS.get(self.tier.name, -1)
class OpponentHandRangeFear(OpponentFear):
"""Class that looks at opponent's bets to estimate their minimum hand"""
RAISE_FEARS = {
"CHECK": (0, None),
"MIN_RAISE": (0, C.QUEEN),
"RAISE": (1, None),
"BIG_RAISE": (1, C.QUEEN),
"OVERBET": (2, None),
}
def minimum_handscore(self):
table_best = self.find_table_score(self.data.table_cards)
type_increase, kicker = self.RAISE_FEARS[self.tier.name]
table_best.type += type_increase
fear_kicker = tuple([kicker] * 5)
table_best.kicker = max(table_best.kicker, fear_kicker)
return table_best
def find_table_score(self, cards):
builder = handscore.HandBuilder(cards)
score = builder.score_hand()
score.type = max(score.type, 0)
return score
| {
"content_hash": "d5fea9edfcb7e31c9145662e1cd227dc",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 76,
"avg_line_length": 32.20289855072464,
"alnum_prop": 0.5868586858685868,
"repo_name": "gnmerritt/poker",
"id": "b8ca345833b0ed6f533d1fa516b256e297866777",
"size": "2222",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pokeher/fear.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "668"
},
{
"name": "Python",
"bytes": "174467"
},
{
"name": "Shell",
"bytes": "113"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "c27943437424dc14efe4d3eedcde7bc9",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "5e32d22d08c8040f27d0b85fba1025ca6df46931",
"size": "175",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Malvales/Malvaceae/Abutilon/Abutilon stellatum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
/**
* This class defines the structure of the 'instmembership' table.
*
*
*
* This map class is used by Propel to do runtime db structure discovery.
* For example, the createSelectSql() method checks the type of a given column used in an
* ORDER BY clause to know whether it needs to apply SQL to make the ORDER BY case-insensitive
* (i.e. if it's a text column type).
*
* @package propel.generator.fbapp.map
*/
class InstmembershipTableMap extends TableMap
{
/**
* The (dot-path) name of this class
*/
const CLASS_NAME = 'fbapp.map.InstmembershipTableMap';
/**
* Initialize the table attributes, columns and validators
* Relations are not initialized by this method since they are lazy loaded
*
* @return void
* @throws PropelException
*/
public function initialize()
{
// attributes
$this->setName('instmembership');
$this->setPhpName('Instmembership');
$this->setClassname('Instmembership');
$this->setPackage('fbapp');
$this->setUseIdGenerator(false);
// columns
$this->addPrimaryKey('ID', 'Id', 'INTEGER', true, null, null);
$this->addPrimaryKey('Country', 'Country', 'VARCHAR', true, 30, null);
$this->addColumn('C_Code', 'CCode', 'VARCHAR', false, 50, null);
$this->addColumn('Status', 'Status', 'VARCHAR', false, 50, null);
$this->addColumn('Year', 'Year', 'TIMESTAMP', false, null, null);
$this->addColumn('TS', 'Ts', 'TIMESTAMP', false, null, null);
// validators
} // initialize()
/**
* Build the RelationMap objects for this table relationships
*/
public function buildRelations()
{
} // buildRelations()
} // InstmembershipTableMap
| {
"content_hash": "f99a9adc1ea6a7b2920c3680e60c7560",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 94,
"avg_line_length": 31.12280701754386,
"alnum_prop": 0.6285231116121759,
"repo_name": "royrusso/fishbase",
"id": "946706d56b08068ab5f9f19a7dff194ceff7e349",
"size": "1774",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "classes/fbapp/map/InstmembershipTableMap.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "54469"
},
{
"name": "JavaScript",
"bytes": "257574"
},
{
"name": "PHP",
"bytes": "43155398"
}
],
"symlink_target": ""
} |
<p class="lead">
<strong>Terranet/Options</strong>
</p> | {
"content_hash": "f5b7b2e9c314fe65a8faa3ca6388c060",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 37,
"avg_line_length": 19.666666666666668,
"alnum_prop": 0.6440677966101694,
"repo_name": "adminarchitect/options",
"id": "6a99380476c3b319681007d344de039fd35c6e0d",
"size": "59",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/_index.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "14631"
}
],
"symlink_target": ""
} |
package mtrbac.CloudSvcPEP;
import com.sun.xacml.PDP;
import com.sun.xacml.ctx.RequestCtx;
import com.sun.xacml.ctx.ResponseCtx;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.*;
import java.net.*;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import mtrbac.CloudSvcPEP.BasicTest;
import mtrbac.CloudSvcPEP.Test;
import mtrbac.CloudSvcPEP.TestPolicyFinderModule;
import mtrbac.CloudSvcPEP.TestUtil;
import mtrbac.CloudSvcPEP.BasicTestThread;
/**
* A simple implementation of a single conformance test case.
*
* @author Seth Proctor
*/
public class BasicTest implements Test
{
ServerSocket CloudSvcSocket;
Socket connection = null;
OutputStream os;
InputStream is;
//String message;
// the PDP and module that manage this test's policies
private PDP pdp;
private TestPolicyFinderModule module;
// the policies and references used by this test
private Set policies;
private Map policyRefs;
private Map policySetRefs;
// meta-data associated with this test
private String name;
private boolean errorExpected;
private boolean experimental;
/**
* Constructor that accepts all values associatd with a test.
*
* @param pdp the pdp that manages this test's evaluations
* @param module the module that manages this test's policies
* @param policies the files containing the policies used by this test,
* or null if we only use the default policy for this test
* @param policyRefs the policy references used by this test
* @param policySetRefs the policy set references used by this test
* @param name the name of this test
* @param errorExpected true if en error is expected from a normal run
* @param experimental true if this is an experimental test
*/
public BasicTest(PDP pdp, TestPolicyFinderModule module, Set policies,
Map policyRefs, Map policySetRefs, String name,
boolean errorExpected, boolean experimental) {
this.pdp = pdp;
this.module = module;
this.policies = policies;
this.policyRefs = policyRefs;
this.policySetRefs = policySetRefs;
this.name = name;
this.errorExpected = errorExpected;
this.experimental = experimental;
}
/**
* Creates an instance of a test from its XML representation.
*
* @param root the root of the XML-encoded data for this test
* @param pdp the <code>PDP</code> used by this test
* @param module the module used for this test's policies
*/
public static BasicTest getInstance(Node root, PDP pdp,
TestPolicyFinderModule module) {
NamedNodeMap map = root.getAttributes();
// the name is required...
String name = map.getNamedItem("name").getNodeValue();
// ...but the other two aren't
boolean errorExpected = isAttrTrue(map, "errorExpected");
boolean experimental = isAttrTrue(map, "experimental");
// see if there's any content
Set policies = null;
Map policyRefs = null;
Map policySetRefs = null;
if (root.hasChildNodes()) {
NodeList children = root.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
String childName = child.getNodeName();
if (childName.equals("policy")) {
if (policies == null)
policies = new HashSet();
policies.add(child.getFirstChild().getNodeValue());
} else if (childName.equals("policyReference")) {
if (policyRefs == null)
policyRefs = new HashMap();
policyRefs.put(child.getAttributes().getNamedItem("ref").
getNodeValue(),
child.getFirstChild().getNodeValue());
} else if (childName.equals("policySetReference")) {
if (policySetRefs == null)
policySetRefs = new HashMap();
policySetRefs.put(child.getAttributes().
getNamedItem("ref").getNodeValue(),
child.getFirstChild().getNodeValue());
}
}
}
return new BasicTest(pdp, module, policies, policyRefs, policySetRefs,
name, errorExpected, experimental);
}
/**
* Private helper that reads a attribute to see if it's set, and if so
* if its value is "true".
*/
private static boolean isAttrTrue(NamedNodeMap map, String attrName) {
Node attrNode = map.getNamedItem(attrName);
if (attrNode == null)
return false;
return attrNode.getNodeValue().equals("true");
}
public String getName() {
return name;
}
public boolean isErrorExpected() {
return errorExpected;
}
public boolean isExperimental() {
return experimental;
}
public int run(String testPrefix) {
System.out.print("test " + name + ": ");
//System.out.println("FilePrefix = " + testPrefix + name);
int errorCount = 0;
boolean failurePointReached = false;
// FIXME: we should get more specific with the exceptions, so we can
// make sure that an error happened _for the right reason_
// long t0 = 0, t1 = 0;
try {
// load the request for this test
RequestCtx request =
RequestCtx.getInstance(new FileInputStream(testPrefix + name + "Request.xml"));
// load the reponse that we expected to get
ResponseCtx expectedResponse =
ResponseCtx.getInstance(new FileInputStream(testPrefix + name + "Response.xml"));
try{
//1. creating a server socket
CloudSvcSocket = new ServerSocket(9999, 10);
//2. Wait for connection
System.out.println("Cloud Service> Waiting for connection ...");
while(true){
new BasicTestThread(CloudSvcSocket.accept(), request, expectedResponse, testPrefix).start();
System.out.println("Cloud Service> connection accepted ...");
}
/*
connection = PDPSvrSocket.accept();
System.out.println("Connection received from " + connection.getInetAddress().getHostName());
//3. get Input and Output streams
os = connection.getOutputStream();
os.flush();
is = connection.getInputStream();
//FileOutputStream fos = new FileOutputStream(testDir + "MT-RBACPEPRequest.xml");
//BufferedOutputStream bos = new BufferedOutputStream(fos);
//byte[] buffer = new byte[1024*1024];
//sendMessage("Connection successful");
//4. The two parts communicate via the input and output streams
// int bytesRead = is.read(buffer, 0, buffer.length);
// System.out.println("client>Request File Length = " + bytesRead
// + " Bytes");
// bos.write(buffer, 0, bytesRead);
// bos.close();
// System.out.println("server>" + "PEPRequest.xml stored.");
ByteArrayInputStream bais = new ByteArrayInputStream(readBytes(is));
RequestCtx request = RequestCtx.getInstance(bais);
System.out.println("client>" + request.toString());
//evaluate the request
System.out.println("======== Beginning Evaluation ==========");
// actually do the evaluation
ResponseCtx response = pdp.evaluate(request);
System.out.println("======== Ending Evaluation ==========");
response.encode(os);
//os.flush();
connection.shutdownOutput(); //send EOS
System.out.println("server>" + response.toString());
// FileOutputStream fos = new FileOutputStream(testPrefix + name + "PDPResponse.xml");
// response.encode(fos);
// fos.close();
//response = ResponseCtx.getInstance(new FileInputStream(testPrefix
//+ name + "PDPResponse.xml"));
// if we're supposed to fail, we should have done so by now
if (errorExpected) {
System.out.println("failed");
errorCount++;
} else {
failurePointReached = true;
// load the reponse that we expectd to get
ResponseCtx expectedResponse =
ResponseCtx.
getInstance(new FileInputStream(testPrefix + name +
"Response.xml"));
// see if the actual result matches the expected result
boolean equiv = TestUtil.areEquivalent(response,
expectedResponse);
if (equiv) {
System.out.println("passed");
} else {
System.out.println("failed:");
response.encode(System.out);
errorCount++;
}
}
}
catch(IOException ioException){
ioException.printStackTrace();
*/
}
finally{
//4: Closing connection
try{
CloudSvcSocket.close();
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
} catch (Exception e) {
// any errors happen as exceptions, and may be successes if we're
// supposed to fail and we haven't reached the failure point yet
if (! failurePointReached) {
if (errorExpected) {
System.out.println("passed");
} else {
System.out.println("EXCEPTION: " + e.getMessage());
errorCount++;
}
} else {
System.out.println("UNEXPECTED EXCEPTION: " + e.getMessage());
errorCount++;
}
}
// errorCount = (int)(t1-t0);
// return the number of errors that occured
return errorCount;
}
public static byte[] readBytes(InputStream inputStream) throws IOException {
// this dynamically extends to take the bytes you read
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
// this is storage overwritten on each iteration with bytes
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
// we need to know how may bytes were read to write them to the byteBuffer
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
// and then we can return your byte array.
return byteBuffer.toByteArray();
}
}
| {
"content_hash": "5f3f4f95d0ac2abc1b723aae2d07b6d2",
"timestamp": "",
"source": "github",
"line_count": 337,
"max_line_length": 101,
"avg_line_length": 34.54302670623145,
"alnum_prop": 0.5682501503307276,
"repo_name": "townbull/mtaaas",
"id": "c12efbd118dee2100e61e0c881b49e1bee7b16d9",
"size": "13451",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CloudSvcPEP/mtrbac/CloudSvcPEP/BasicTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1440895"
},
{
"name": "Shell",
"bytes": "8283"
}
],
"symlink_target": ""
} |
<!doctype html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta id="viewport" name="viewport" content="width=500" />
<!--RSS FEEDS-->
<link rel="alternate" href="http://deebuls.github.io/feeds/all.atom.xml" type="application/atom+xml" title="Simpleton Full Atom Feed"/>
<title>Naive Bayes Implementation using Pandas // Simpleton</title>
<link rel="stylesheet" href="http://deebuls.github.io/theme/css/normalize.css" type="text/css" />
<link rel="stylesheet" href="http://deebuls.github.io/theme/css/base.css" type="text/css" />
<link rel="stylesheet" href="http://deebuls.github.io/theme/css/code.css" type="text/css" />
<link rel="stylesheet" href="http://deebuls.github.io/theme/css/article.css" type="text/css" />
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]},
TeX: { equationNumbers: { autoNumber: "all" } }
});
</script>
<script type="text/javascript" src="//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
</head>
<body>
<!--Top image-->
<div class="container">
<div class="topimage">
<img src="/theme/images/logo.png">
</div>
</div>
<!--Links and site title-->
<div class="topbar">
<span><a href="http://deebuls.github.io/">Simpleton</a></span>
<ul>
<li><a href="http://deebuls.github.io/blog.html">Blog</a></li>
<li><a href="http://deebuls.github.io/pages/about.html">About</a></li>
</ul>
</div>
<!--Content, footer, and scripts-->
<div class="container">
<div class="page-title">
<h1>Naive Bayes Implementation using Pandas</h1>
<p>Fr 13 Januar 2017 — under
<a class="post-category" href="http://deebuls.github.io/tag/bayes.html">Bayes</a>,
<a class="post-category" href="http://deebuls.github.io/tag/python.html">Python</a>,
<a class="post-category" href="http://deebuls.github.io/tag/machine-learning.html">Machine Learning</a>,
<a class="post-category" href="http://deebuls.github.io/tag/pandas.html">Pandas</a>
</p>
</div>
<style type="text/css">/*!
*
* IPython notebook
*
*/
/* CSS font colors for translated ANSI colors. */
.ansibold {
font-weight: bold;
}
/* use dark versions for foreground, to improve visibility */
.ansiblack {
color: black;
}
.ansired {
color: darkred;
}
.ansigreen {
color: darkgreen;
}
.ansiyellow {
color: #c4a000;
}
.ansiblue {
color: darkblue;
}
.ansipurple {
color: darkviolet;
}
.ansicyan {
color: steelblue;
}
.ansigray {
color: gray;
}
/* and light for background, for the same reason */
.ansibgblack {
background-color: black;
}
.ansibgred {
background-color: red;
}
.ansibggreen {
background-color: green;
}
.ansibgyellow {
background-color: yellow;
}
.ansibgblue {
background-color: blue;
}
.ansibgpurple {
background-color: magenta;
}
.ansibgcyan {
background-color: cyan;
}
.ansibggray {
background-color: gray;
}
div.cell {
/* Old browsers */
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-box-align: stretch;
display: -moz-box;
-moz-box-orient: vertical;
-moz-box-align: stretch;
display: box;
box-orient: vertical;
box-align: stretch;
/* Modern browsers */
display: flex;
flex-direction: column;
align-items: stretch;
border-radius: 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
border-width: 1px;
border-style: solid;
border-color: transparent;
width: 100%;
padding: 5px;
/* This acts as a spacer between cells, that is outside the border */
margin: 0px;
outline: none;
border-left-width: 1px;
padding-left: 5px;
background: linear-gradient(to right, transparent -40px, transparent 1px, transparent 1px, transparent 100%);
}
div.cell.jupyter-soft-selected {
border-left-color: #90CAF9;
border-left-color: #E3F2FD;
border-left-width: 1px;
padding-left: 5px;
border-right-color: #E3F2FD;
border-right-width: 1px;
background: #E3F2FD;
}
@media print {
div.cell.jupyter-soft-selected {
border-color: transparent;
}
}
div.cell.selected {
border-color: #ababab;
border-left-width: 0px;
padding-left: 6px;
background: linear-gradient(to right, #42A5F5 -40px, #42A5F5 5px, transparent 5px, transparent 100%);
}
@media print {
div.cell.selected {
border-color: transparent;
}
}
div.cell.selected.jupyter-soft-selected {
border-left-width: 0;
padding-left: 6px;
background: linear-gradient(to right, #42A5F5 -40px, #42A5F5 7px, #E3F2FD 7px, #E3F2FD 100%);
}
.edit_mode div.cell.selected {
border-color: #66BB6A;
border-left-width: 0px;
padding-left: 6px;
background: linear-gradient(to right, #66BB6A -40px, #66BB6A 5px, transparent 5px, transparent 100%);
}
@media print {
.edit_mode div.cell.selected {
border-color: transparent;
}
}
.prompt {
/* This needs to be wide enough for 3 digit prompt numbers: In[100]: */
min-width: 14ex;
/* This padding is tuned to match the padding on the CodeMirror editor. */
padding: 0.4em;
margin: 0px;
font-family: monospace;
text-align: right;
/* This has to match that of the the CodeMirror class line-height below */
line-height: 1.21429em;
/* Don't highlight prompt number selection */
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
/* Use default cursor */
cursor: default;
}
@media (max-width: 540px) {
.prompt {
text-align: left;
}
}
div.inner_cell {
/* Old browsers */
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-box-align: stretch;
display: -moz-box;
-moz-box-orient: vertical;
-moz-box-align: stretch;
display: box;
box-orient: vertical;
box-align: stretch;
/* Modern browsers */
display: flex;
flex-direction: column;
align-items: stretch;
/* Old browsers */
-webkit-box-flex: 1;
-moz-box-flex: 1;
box-flex: 1;
/* Modern browsers */
flex: 1;
}
@-moz-document url-prefix() {
div.inner_cell {
overflow-x: hidden;
}
}
/* input_area and input_prompt must match in top border and margin for alignment */
div.input_area {
border: 1px solid #cfcfcf;
border-radius: 2px;
background: #f7f7f7;
line-height: 1.21429em;
}
/* This is needed so that empty prompt areas can collapse to zero height when there
is no content in the output_subarea and the prompt. The main purpose of this is
to make sure that empty JavaScript output_subareas have no height. */
div.prompt:empty {
padding-top: 0;
padding-bottom: 0;
}
div.unrecognized_cell {
padding: 5px 5px 5px 0px;
/* Old browsers */
display: -webkit-box;
-webkit-box-orient: horizontal;
-webkit-box-align: stretch;
display: -moz-box;
-moz-box-orient: horizontal;
-moz-box-align: stretch;
display: box;
box-orient: horizontal;
box-align: stretch;
/* Modern browsers */
display: flex;
flex-direction: row;
align-items: stretch;
}
div.unrecognized_cell .inner_cell {
border-radius: 2px;
padding: 5px;
font-weight: bold;
color: red;
border: 1px solid #cfcfcf;
background: #eaeaea;
}
div.unrecognized_cell .inner_cell a {
color: inherit;
text-decoration: none;
}
div.unrecognized_cell .inner_cell a:hover {
color: inherit;
text-decoration: none;
}
@media (max-width: 540px) {
div.unrecognized_cell > div.prompt {
display: none;
}
}
div.code_cell {
/* avoid page breaking on code cells when printing */
}
@media print {
div.code_cell {
page-break-inside: avoid;
}
}
/* any special styling for code cells that are currently running goes here */
div.input {
page-break-inside: avoid;
/* Old browsers */
display: -webkit-box;
-webkit-box-orient: horizontal;
-webkit-box-align: stretch;
display: -moz-box;
-moz-box-orient: horizontal;
-moz-box-align: stretch;
display: box;
box-orient: horizontal;
box-align: stretch;
/* Modern browsers */
display: flex;
flex-direction: row;
align-items: stretch;
}
@media (max-width: 540px) {
div.input {
/* Old browsers */
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-box-align: stretch;
display: -moz-box;
-moz-box-orient: vertical;
-moz-box-align: stretch;
display: box;
box-orient: vertical;
box-align: stretch;
/* Modern browsers */
display: flex;
flex-direction: column;
align-items: stretch;
}
}
/* input_area and input_prompt must match in top border and margin for alignment */
div.input_prompt {
color: #303F9F;
border-top: 1px solid transparent;
}
div.input_area > div.highlight {
margin: 0.4em;
border: none;
padding: 0px;
background-color: transparent;
}
div.input_area > div.highlight > pre {
margin: 0px;
border: none;
padding: 0px;
background-color: transparent;
}
/* The following gets added to the <head> if it is detected that the user has a
* monospace font with inconsistent normal/bold/italic height. See
* notebookmain.js. Such fonts will have keywords vertically offset with
* respect to the rest of the text. The user should select a better font.
* See: https://github.com/ipython/ipython/issues/1503
*
* .CodeMirror span {
* vertical-align: bottom;
* }
*/
.CodeMirror {
line-height: 1.21429em;
/* Changed from 1em to our global default */
font-size: 14px;
height: auto;
/* Changed to auto to autogrow */
background: none;
/* Changed from white to allow our bg to show through */
}
.CodeMirror-scroll {
/* The CodeMirror docs are a bit fuzzy on if overflow-y should be hidden or visible.*/
/* We have found that if it is visible, vertical scrollbars appear with font size changes.*/
overflow-y: hidden;
overflow-x: auto;
}
.CodeMirror-lines {
/* In CM2, this used to be 0.4em, but in CM3 it went to 4px. We need the em value because */
/* we have set a different line-height and want this to scale with that. */
padding: 0.4em;
}
.CodeMirror-linenumber {
padding: 0 8px 0 4px;
}
.CodeMirror-gutters {
border-bottom-left-radius: 2px;
border-top-left-radius: 2px;
}
.CodeMirror pre {
/* In CM3 this went to 4px from 0 in CM2. We need the 0 value because of how we size */
/* .CodeMirror-lines */
padding: 0;
border: 0;
border-radius: 0;
}
/*
Original style from softwaremaniacs.org (c) Ivan Sagalaev <[email protected]>
Adapted from GitHub theme
*/
.highlight-base {
color: #000;
}
.highlight-variable {
color: #000;
}
.highlight-variable-2 {
color: #1a1a1a;
}
.highlight-variable-3 {
color: #333333;
}
.highlight-string {
color: #BA2121;
}
.highlight-comment {
color: #408080;
font-style: italic;
}
.highlight-number {
color: #080;
}
.highlight-atom {
color: #88F;
}
.highlight-keyword {
color: #008000;
font-weight: bold;
}
.highlight-builtin {
color: #008000;
}
.highlight-error {
color: #f00;
}
.highlight-operator {
color: #AA22FF;
font-weight: bold;
}
.highlight-meta {
color: #AA22FF;
}
/* previously not defined, copying from default codemirror */
.highlight-def {
color: #00f;
}
.highlight-string-2 {
color: #f50;
}
.highlight-qualifier {
color: #555;
}
.highlight-bracket {
color: #997;
}
.highlight-tag {
color: #170;
}
.highlight-attribute {
color: #00c;
}
.highlight-header {
color: blue;
}
.highlight-quote {
color: #090;
}
.highlight-link {
color: #00c;
}
/* apply the same style to codemirror */
.cm-s-ipython span.cm-keyword {
color: #008000;
font-weight: bold;
}
.cm-s-ipython span.cm-atom {
color: #88F;
}
.cm-s-ipython span.cm-number {
color: #080;
}
.cm-s-ipython span.cm-def {
color: #00f;
}
.cm-s-ipython span.cm-variable {
color: #000;
}
.cm-s-ipython span.cm-operator {
color: #AA22FF;
font-weight: bold;
}
.cm-s-ipython span.cm-variable-2 {
color: #1a1a1a;
}
.cm-s-ipython span.cm-variable-3 {
color: #333333;
}
.cm-s-ipython span.cm-comment {
color: #408080;
font-style: italic;
}
.cm-s-ipython span.cm-string {
color: #BA2121;
}
.cm-s-ipython span.cm-string-2 {
color: #f50;
}
.cm-s-ipython span.cm-meta {
color: #AA22FF;
}
.cm-s-ipython span.cm-qualifier {
color: #555;
}
.cm-s-ipython span.cm-builtin {
color: #008000;
}
.cm-s-ipython span.cm-bracket {
color: #997;
}
.cm-s-ipython span.cm-tag {
color: #170;
}
.cm-s-ipython span.cm-attribute {
color: #00c;
}
.cm-s-ipython span.cm-header {
color: blue;
}
.cm-s-ipython span.cm-quote {
color: #090;
}
.cm-s-ipython span.cm-link {
color: #00c;
}
.cm-s-ipython span.cm-error {
color: #f00;
}
.cm-s-ipython span.cm-tab {
background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAMCAYAAAAkuj5RAAAAAXNSR0IArs4c6QAAAGFJREFUSMft1LsRQFAQheHPowAKoACx3IgEKtaEHujDjORSgWTH/ZOdnZOcM/sgk/kFFWY0qV8foQwS4MKBCS3qR6ixBJvElOobYAtivseIE120FaowJPN75GMu8j/LfMwNjh4HUpwg4LUAAAAASUVORK5CYII=);
background-position: right;
background-repeat: no-repeat;
}
div.output_wrapper {
/* this position must be relative to enable descendents to be absolute within it */
position: relative;
/* Old browsers */
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-box-align: stretch;
display: -moz-box;
-moz-box-orient: vertical;
-moz-box-align: stretch;
display: box;
box-orient: vertical;
box-align: stretch;
/* Modern browsers */
display: flex;
flex-direction: column;
align-items: stretch;
z-index: 1;
}
/* class for the output area when it should be height-limited */
div.output_scroll {
/* ideally, this would be max-height, but FF barfs all over that */
height: 24em;
/* FF needs this *and the wrapper* to specify full width, or it will shrinkwrap */
width: 100%;
overflow: auto;
border-radius: 2px;
-webkit-box-shadow: inset 0 2px 8px rgba(0, 0, 0, 0.8);
box-shadow: inset 0 2px 8px rgba(0, 0, 0, 0.8);
display: block;
}
/* output div while it is collapsed */
div.output_collapsed {
margin: 0px;
padding: 0px;
/* Old browsers */
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-box-align: stretch;
display: -moz-box;
-moz-box-orient: vertical;
-moz-box-align: stretch;
display: box;
box-orient: vertical;
box-align: stretch;
/* Modern browsers */
display: flex;
flex-direction: column;
align-items: stretch;
}
div.out_prompt_overlay {
height: 100%;
padding: 0px 0.4em;
position: absolute;
border-radius: 2px;
}
div.out_prompt_overlay:hover {
/* use inner shadow to get border that is computed the same on WebKit/FF */
-webkit-box-shadow: inset 0 0 1px #000;
box-shadow: inset 0 0 1px #000;
background: rgba(240, 240, 240, 0.5);
}
div.output_prompt {
color: #D84315;
}
/* This class is the outer container of all output sections. */
div.output_area {
padding: 0px;
page-break-inside: avoid;
/* Old browsers */
display: -webkit-box;
-webkit-box-orient: horizontal;
-webkit-box-align: stretch;
display: -moz-box;
-moz-box-orient: horizontal;
-moz-box-align: stretch;
display: box;
box-orient: horizontal;
box-align: stretch;
/* Modern browsers */
display: flex;
flex-direction: row;
align-items: stretch;
}
div.output_area .MathJax_Display {
text-align: left !important;
}
div.output_area
div.output_area
div.output_area img,
div.output_area svg {
max-width: 100%;
height: auto;
}
div.output_area img.unconfined,
div.output_area svg.unconfined {
max-width: none;
}
/* This is needed to protect the pre formating from global settings such
as that of bootstrap */
.output {
/* Old browsers */
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-box-align: stretch;
display: -moz-box;
-moz-box-orient: vertical;
-moz-box-align: stretch;
display: box;
box-orient: vertical;
box-align: stretch;
/* Modern browsers */
display: flex;
flex-direction: column;
align-items: stretch;
}
@media (max-width: 540px) {
div.output_area {
/* Old browsers */
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-box-align: stretch;
display: -moz-box;
-moz-box-orient: vertical;
-moz-box-align: stretch;
display: box;
box-orient: vertical;
box-align: stretch;
/* Modern browsers */
display: flex;
flex-direction: column;
align-items: stretch;
}
}
div.output_area pre {
margin: 0;
padding: 0;
border: 0;
vertical-align: baseline;
color: black;
background-color: transparent;
border-radius: 0;
}
/* This class is for the output subarea inside the output_area and after
the prompt div. */
div.output_subarea {
overflow-x: auto;
padding: 0.4em;
/* Old browsers */
-webkit-box-flex: 1;
-moz-box-flex: 1;
box-flex: 1;
/* Modern browsers */
flex: 1;
max-width: calc(100% - 14ex);
}
div.output_scroll div.output_subarea {
overflow-x: visible;
}
/* The rest of the output_* classes are for special styling of the different
output types */
/* all text output has this class: */
div.output_text {
text-align: left;
color: #000;
/* This has to match that of the the CodeMirror class line-height below */
line-height: 1.21429em;
}
/* stdout/stderr are 'text' as well as 'stream', but execute_result/error are *not* streams */
div.output_stderr {
background: #fdd;
/* very light red background for stderr */
}
div.output_latex {
text-align: left;
}
/* Empty output_javascript divs should have no height */
div.output_javascript:empty {
padding: 0;
}
.js-error {
color: darkred;
}
/* raw_input styles */
div.raw_input_container {
line-height: 1.21429em;
padding-top: 5px;
}
pre.raw_input_prompt {
/* nothing needed here. */
}
input.raw_input {
font-family: monospace;
font-size: inherit;
color: inherit;
width: auto;
/* make sure input baseline aligns with prompt */
vertical-align: baseline;
/* padding + margin = 0.5em between prompt and cursor */
padding: 0em 0.25em;
margin: 0em 0.25em;
}
input.raw_input:focus {
box-shadow: none;
}
p.p-space {
margin-bottom: 10px;
}
div.output_unrecognized {
padding: 5px;
font-weight: bold;
color: red;
}
div.output_unrecognized a {
color: inherit;
text-decoration: none;
}
div.output_unrecognized a:hover {
color: inherit;
text-decoration: none;
}
.rendered_html {
color: #000;
/* any extras will just be numbers: */
}
.rendered_html :link {
text-decoration: underline;
}
.rendered_html :visited {
text-decoration: underline;
}
.rendered_html h1:first-child {
margin-top: 0.538em;
}
.rendered_html h2:first-child {
margin-top: 0.636em;
}
.rendered_html h3:first-child {
margin-top: 0.777em;
}
.rendered_html h4:first-child {
margin-top: 1em;
}
.rendered_html h5:first-child {
margin-top: 1em;
}
.rendered_html h6:first-child {
margin-top: 1em;
}
.rendered_html * + ul {
margin-top: 1em;
}
.rendered_html * + ol {
margin-top: 1em;
}
.rendered_html pre,
.rendered_html tr,
.rendered_html th,
.rendered_html td,
.rendered_html * + table {
margin-top: 1em;
}
.rendered_html * + p {
margin-top: 1em;
}
.rendered_html * + img {
margin-top: 1em;
}
.rendered_html img,
.rendered_html img.unconfined,
div.text_cell {
/* Old browsers */
display: -webkit-box;
-webkit-box-orient: horizontal;
-webkit-box-align: stretch;
display: -moz-box;
-moz-box-orient: horizontal;
-moz-box-align: stretch;
display: box;
box-orient: horizontal;
box-align: stretch;
/* Modern browsers */
display: flex;
flex-direction: row;
align-items: stretch;
}
@media (max-width: 540px) {
div.text_cell > div.prompt {
display: none;
}
}
div.text_cell_render {
/*font-family: "Helvetica Neue", Arial, Helvetica, Geneva, sans-serif;*/
outline: none;
resize: none;
width: inherit;
border-style: none;
padding: 0.5em 0.5em 0.5em 0.4em;
color: #000;
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
}
a.anchor-link:link {
text-decoration: none;
padding: 0px 20px;
visibility: hidden;
}
h1:hover .anchor-link,
h2:hover .anchor-link,
h3:hover .anchor-link,
h4:hover .anchor-link,
h5:hover .anchor-link,
h6:hover .anchor-link {
visibility: visible;
}
.text_cell.rendered .input_area {
display: none;
}
.text_cell.rendered
.text_cell.unrendered .text_cell_render {
display: none;
}
.cm-header-1,
.cm-header-2,
.cm-header-3,
.cm-header-4,
.cm-header-5,
.cm-header-6 {
font-weight: bold;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}
.cm-header-1 {
font-size: 185.7%;
}
.cm-header-2 {
font-size: 157.1%;
}
.cm-header-3 {
font-size: 128.6%;
}
.cm-header-4 {
font-size: 110%;
}
.cm-header-5 {
font-size: 100%;
font-style: italic;
}
.cm-header-6 {
font-size: 100%;
font-style: italic;
}
</style>
<style type="text/css">.highlight .hll { background-color: #ffffcc }
.highlight { background: #f8f8f8; }
.highlight .c { color: #408080; font-style: italic } /* Comment */
.highlight .err { border: 1px solid #FF0000 } /* Error */
.highlight .k { color: #008000; font-weight: bold } /* Keyword */
.highlight .o { color: #666666 } /* Operator */
.highlight .cm { color: #408080; font-style: italic } /* Comment.Multiline */
.highlight .cp { color: #BC7A00 } /* Comment.Preproc */
.highlight .c1 { color: #408080; font-style: italic } /* Comment.Single */
.highlight .cs { color: #408080; font-style: italic } /* Comment.Special */
.highlight .gd { color: #A00000 } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gr { color: #FF0000 } /* Generic.Error */
.highlight .gh { color: #000080; font-weight: bold } /* Generic.Heading */
.highlight .gi { color: #00A000 } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #000080; font-weight: bold } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #800080; font-weight: bold } /* Generic.Subheading */
.highlight .gt { color: #0044DD } /* Generic.Traceback */
.highlight .kc { color: #008000; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008000 } /* Keyword.Pseudo */
.highlight .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #B00040 } /* Keyword.Type */
.highlight .m { color: #666666 } /* Literal.Number */
.highlight .s { color: #BA2121 } /* Literal.String */
.highlight .na { color: #7D9029 } /* Name.Attribute */
.highlight .nb { color: #008000 } /* Name.Builtin */
.highlight .nc { color: #0000FF; font-weight: bold } /* Name.Class */
.highlight .no { color: #880000 } /* Name.Constant */
.highlight .nd { color: #AA22FF } /* Name.Decorator */
.highlight .ni { color: #999999; font-weight: bold } /* Name.Entity */
.highlight .ne { color: #D2413A; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0000FF } /* Name.Function */
.highlight .nl { color: #A0A000 } /* Name.Label */
.highlight .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */
.highlight .nt { color: #008000; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #19177C } /* Name.Variable */
.highlight .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #666666 } /* Literal.Number.Bin */
.highlight .mf { color: #666666 } /* Literal.Number.Float */
.highlight .mh { color: #666666 } /* Literal.Number.Hex */
.highlight .mi { color: #666666 } /* Literal.Number.Integer */
.highlight .mo { color: #666666 } /* Literal.Number.Oct */
.highlight .sb { color: #BA2121 } /* Literal.String.Backtick */
.highlight .sc { color: #BA2121 } /* Literal.String.Char */
.highlight .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */
.highlight .s2 { color: #BA2121 } /* Literal.String.Double */
.highlight .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */
.highlight .sh { color: #BA2121 } /* Literal.String.Heredoc */
.highlight .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */
.highlight .sx { color: #008000 } /* Literal.String.Other */
.highlight .sr { color: #BB6688 } /* Literal.String.Regex */
.highlight .s1 { color: #BA2121 } /* Literal.String.Single */
.highlight .ss { color: #19177C } /* Literal.String.Symbol */
.highlight .bp { color: #008000 } /* Name.Builtin.Pseudo */
.highlight .vc { color: #19177C } /* Name.Variable.Class */
.highlight .vg { color: #19177C } /* Name.Variable.Global */
.highlight .vi { color: #19177C } /* Name.Variable.Instance */
.highlight .il { color: #666666 } /* Literal.Number.Integer.Long */</style>
<style type="text/css">
/* Temporary definitions which will become obsolete with Notebook release 5.0 */
.ansi-black-fg { color: #3E424D; }
.ansi-black-bg { background-color: #3E424D; }
.ansi-black-intense-fg { color: #282C36; }
.ansi-black-intense-bg { background-color: #282C36; }
.ansi-red-fg { color: #E75C58; }
.ansi-red-bg { background-color: #E75C58; }
.ansi-red-intense-fg { color: #B22B31; }
.ansi-red-intense-bg { background-color: #B22B31; }
.ansi-green-fg { color: #00A250; }
.ansi-green-bg { background-color: #00A250; }
.ansi-green-intense-fg { color: #007427; }
.ansi-green-intense-bg { background-color: #007427; }
.ansi-yellow-fg { color: #DDB62B; }
.ansi-yellow-bg { background-color: #DDB62B; }
.ansi-yellow-intense-fg { color: #B27D12; }
.ansi-yellow-intense-bg { background-color: #B27D12; }
.ansi-blue-fg { color: #208FFB; }
.ansi-blue-bg { background-color: #208FFB; }
.ansi-blue-intense-fg { color: #0065CA; }
.ansi-blue-intense-bg { background-color: #0065CA; }
.ansi-magenta-fg { color: #D160C4; }
.ansi-magenta-bg { background-color: #D160C4; }
.ansi-magenta-intense-fg { color: #A03196; }
.ansi-magenta-intense-bg { background-color: #A03196; }
.ansi-cyan-fg { color: #60C6C8; }
.ansi-cyan-bg { background-color: #60C6C8; }
.ansi-cyan-intense-fg { color: #258F8F; }
.ansi-cyan-intense-bg { background-color: #258F8F; }
.ansi-white-fg { color: #C5C1B4; }
.ansi-white-bg { background-color: #C5C1B4; }
.ansi-white-intense-fg { color: #A1A6B2; }
.ansi-white-intense-bg { background-color: #A1A6B2; }
.ansi-bold { font-weight: bold; }
</style>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h1 id="Naive-Bayes">Naive Bayes<a class="anchor-link" href="#Naive-Bayes">¶</a></h1><p><a href="https://en.wikipedia.org/wiki/Naive_Bayes_classifier">Naive Bayes</a> is one of the simplest classification machine learning algorithm. As the name suggests its based on the Bayes theorem.</p>
<p>Doing my thesis using Probabilistic Programming I always had read about many models and how it compared with Naive Bayes classifier. Even though of the simplicity Naive bayes is a pretty solid and basic classifier every machine learning student should know. But I never had an opportunity to fully understand this simple tool mainly because I used it like a blackbox using many implementations available, the most famous being from <a href="http://scikit-learn.org/stable/modules/naive_bayes.html">scikit learn</a>.</p>
<p>I got inspired by <a href="https://sebastianraschka.com/faq/docs/implementing-from-scratch.html">Sebastian Raschka</a> about implementing machine learning algorithms from scarch. I completely agree to the argument that it just improves your learning. So here I start with the simple implementation of the Naive Bayes and later using the Probabilistic Programming prespective.</p>
<h2 id="Bayes-Theorem">Bayes Theorem<a class="anchor-link" href="#Bayes-Theorem">¶</a></h2>$$ P(A|B) = \frac{P(B|A) P(A) }{P(B)}$$<p>The above formula can be reinterpreted in the machine learning terms of features and class label. Classification is a problem of assigning classes based on the features provided.</p>
$$ P(class | features ) = \frac{P(features | class) P(class)}{P(features)}$$<p>For example we need to classify a person's sex based on the height and weight. So here the class={male,female} and features={height,weight}, and the formula can he re-written as :</p>
$$ P(sex | height, weight ) = \frac{P(height, weight | sex) P(sex)}{P(height,weight)}$$<p>Based on these information lets go ahead and implement the algorithm on a discretized problem using the vectorization properties of the problem. To understand what is vectorization of problem please read <a href="http://www.labri.fr/perso/nrougier/from-python-to-numpy/">From Python to Numpy</a>.</p>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h1 id="Dataset">Dataset<a class="anchor-link" href="#Dataset">¶</a></h1><p>Lets see and example problem .
This is the data set that we will be using is shown bellow .</p>
<p>In the above dataset if we give the hypothesis =</p>
<h2 id='{"Age":'<=30',-"Income":"medium",-"Student":'yes'-,-"Creadit_Rating":'fair'}'>{"Age":'<=30', "Income":"medium", "Student":'yes' , "Creadit_Rating":'fair'}<a class="anchor-link" href='#{"Age":'<=30',-"Income":"medium",-"Student":'yes'-,-"Creadit_Rating":'fair'}'>¶</a></h2><p>then what is the probability that he will buy or will not buy a computer.</p>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [2]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span class="c"># Dataset</span>
<span class="kn">import</span> <span class="nn">pandas</span> <span class="k">as</span> <span class="nn">pd</span>
<span class="n">data</span> <span class="o">=</span> <span class="n">pd</span><span class="o">.</span><span class="n">read_csv</span> <span class="p">(</span><span class="s">'./naive_bayes_dataset.csv'</span><span class="p">)</span>
<span class="nb">print</span> <span class="p">(</span><span class="n">data</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area"><div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre> Age Income Student Credit_Rating Buys_Computer
0 <=30 high no fair no
1 <=30 high no excellent no
2 31-40 high no fair yes
3 >40 medium no fair yes
4 >40 low yes fair yes
5 >40 low yes excellent no
6 31-40 low yes excellent yes
7 <=30 medium no fair no
8 <=30 low yes fair yes
9 >40 medium yes fair yes
10 <=30 medium yes excellent yes
11 31-40 medium no excellent yes
12 31-40 high yes fair yes
13 >40 medium no excellent no
</pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h1 id="Formulation">Formulation<a class="anchor-link" href="#Formulation">¶</a></h1>$$ P(Buys computer | Age, Income, Student, Credit rating) = \frac{P(Age, Income, Student, Credit rating | Buys computer) P(Buys computer) } {P(Age, Income, Student, Credit rating)}$$<p>The Naive part of the Naive Bayes algorithm is the following assumptiong that the features are mutually independent(which is rarely true). But it allows us to do this simplfyied mathematics .</p>
$$ P(Age, Income, Student, Credit rating | Buys computer) = P(Age | Buys computer) * P(Income | Buys computer) * P(Student | Buys computer) * P(Credit rating | Buys computer)$$
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h1 id="Calculating-the-prior">Calculating the prior<a class="anchor-link" href="#Calculating-the-prior">¶</a></h1><p>prior = P(Buys computer)</p>
<p>P(Buys computer ) = How many times (yes/no) appears / Total observations</p>
<p>P(Buys computer = Yes)
P(Buys computer = No)</p>
<p>We use the groupby function from pandas</p>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [69]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span class="n">prior</span> <span class="o">=</span> <span class="n">data</span><span class="o">.</span><span class="n">groupby</span><span class="p">(</span><span class="s">'Buys_Computer'</span><span class="p">)</span><span class="o">.</span><span class="n">size</span><span class="p">()</span><span class="o">.</span><span class="n">div</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">data</span><span class="p">))</span> <span class="c">#count()['Age']/len(data)</span>
<span class="nb">print</span> <span class="n">prior</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area"><div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>Buys_Computer
no 0.357143
yes 0.642857
dtype: float64
</pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h1 id="Calculating-likelihood">Calculating likelihood<a class="anchor-link" href="#Calculating-likelihood">¶</a></h1><p>Likelihood is generated for each of the features of the dataset.
Basicallay likelihood is probability of finding each feature given class label.</p>
$$ P(Age | Buys computer) $$$$ P(Income | Buys computer) $$$$ P(Student | Buys computer) $$$$ P(Credit rating | Buys computer) $$
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [81]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span class="n">likelihood</span> <span class="o">=</span> <span class="p">{}</span>
<span class="n">likelihood</span><span class="p">[</span><span class="s">'Credit_Rating'</span><span class="p">]</span> <span class="o">=</span> <span class="n">data</span><span class="o">.</span><span class="n">groupby</span><span class="p">([</span><span class="s">'Buys_Computer'</span><span class="p">,</span> <span class="s">'Credit_Rating'</span><span class="p">])</span><span class="o">.</span><span class="n">size</span><span class="p">()</span><span class="o">.</span><span class="n">div</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">data</span><span class="p">))</span><span class="o">.</span><span class="n">div</span><span class="p">(</span><span class="n">prior</span><span class="p">)</span>
<span class="n">likelihood</span><span class="p">[</span><span class="s">'Age'</span><span class="p">]</span> <span class="o">=</span> <span class="n">data</span><span class="o">.</span><span class="n">groupby</span><span class="p">([</span><span class="s">'Buys_Computer'</span><span class="p">,</span> <span class="s">'Age'</span><span class="p">])</span><span class="o">.</span><span class="n">size</span><span class="p">()</span><span class="o">.</span><span class="n">div</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">data</span><span class="p">))</span><span class="o">.</span><span class="n">div</span><span class="p">(</span><span class="n">prior</span><span class="p">)</span>
<span class="n">likelihood</span><span class="p">[</span><span class="s">'Income'</span><span class="p">]</span> <span class="o">=</span> <span class="n">data</span><span class="o">.</span><span class="n">groupby</span><span class="p">([</span><span class="s">'Buys_Computer'</span><span class="p">,</span> <span class="s">'Income'</span><span class="p">])</span><span class="o">.</span><span class="n">size</span><span class="p">()</span><span class="o">.</span><span class="n">div</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">data</span><span class="p">))</span><span class="o">.</span><span class="n">div</span><span class="p">(</span><span class="n">prior</span><span class="p">)</span>
<span class="n">likelihood</span><span class="p">[</span><span class="s">'Student'</span><span class="p">]</span> <span class="o">=</span> <span class="n">data</span><span class="o">.</span><span class="n">groupby</span><span class="p">([</span><span class="s">'Buys_Computer'</span><span class="p">,</span> <span class="s">'Student'</span><span class="p">])</span><span class="o">.</span><span class="n">size</span><span class="p">()</span><span class="o">.</span><span class="n">div</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">data</span><span class="p">))</span><span class="o">.</span><span class="n">div</span><span class="p">(</span><span class="n">prior</span><span class="p">)</span>
<span class="nb">print</span> <span class="p">(</span><span class="n">likelihood</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area"><div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>{'Credit_Rating': Buys_Computer Credit_Rating
no excellent 0.600000
fair 0.400000
yes excellent 0.333333
fair 0.666667
dtype: float64, 'Age': Buys_Computer Age
no <=30 0.600000
>40 0.400000
yes 31-40 0.444444
<=30 0.222222
>40 0.333333
dtype: float64, 'Student': Buys_Computer Student
no no 0.800000
yes 0.200000
yes no 0.333333
yes 0.666667
dtype: float64, 'Income': Buys_Computer Income
no high 0.400000
low 0.200000
medium 0.400000
yes high 0.222222
low 0.333333
medium 0.444444
dtype: float64}
</pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h1 id="Calculating-posterior">Calculating posterior<a class="anchor-link" href="#Calculating-posterior">¶</a></h1><p>We need to if a person wil buy computer based on the following new information</p>
<p>{"Age":'<=30', "Income":"medium", "Student":'yes' , "Credit_Rating":'fair'}</p>
<p>Substituing the values in the likehood data and in the bayes formula, we get</p>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [77]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span class="c"># Probability that the person will buy</span>
<span class="n">p_yes</span> <span class="o">=</span> <span class="n">likelihood</span><span class="p">[</span><span class="s">'Age'</span><span class="p">][</span><span class="s">'yes'</span><span class="p">][</span><span class="s">'<=30'</span><span class="p">]</span> <span class="o">*</span> <span class="n">likelihood</span><span class="p">[</span><span class="s">'Income'</span><span class="p">][</span><span class="s">'yes'</span><span class="p">][</span><span class="s">'medium'</span><span class="p">]</span> <span class="o">*</span> \
<span class="n">likelihood</span><span class="p">[</span><span class="s">'Student'</span><span class="p">][</span><span class="s">'yes'</span><span class="p">][</span><span class="s">'yes'</span><span class="p">]</span> <span class="o">*</span> <span class="n">likelihood</span><span class="p">[</span><span class="s">'Credit_Rating'</span><span class="p">][</span><span class="s">'yes'</span><span class="p">][</span><span class="s">'fair'</span><span class="p">]</span> \
<span class="o">*</span> <span class="n">prior</span><span class="p">[</span><span class="s">'yes'</span><span class="p">]</span>
<span class="c"># Probability that the person will NOT buy</span>
<span class="n">p_no</span> <span class="o">=</span> <span class="n">likelihood</span><span class="p">[</span><span class="s">'Age'</span><span class="p">][</span><span class="s">'no'</span><span class="p">][</span><span class="s">'<=30'</span><span class="p">]</span> <span class="o">*</span> <span class="n">likelihood</span><span class="p">[</span><span class="s">'Income'</span><span class="p">][</span><span class="s">'no'</span><span class="p">][</span><span class="s">'medium'</span><span class="p">]</span> <span class="o">*</span> \
<span class="n">likelihood</span><span class="p">[</span><span class="s">'Student'</span><span class="p">][</span><span class="s">'no'</span><span class="p">][</span><span class="s">'yes'</span><span class="p">]</span> <span class="o">*</span> <span class="n">likelihood</span><span class="p">[</span><span class="s">'Credit_Rating'</span><span class="p">][</span><span class="s">'no'</span><span class="p">][</span><span class="s">'fair'</span><span class="p">]</span> \
<span class="o">*</span> <span class="n">prior</span><span class="p">[</span><span class="s">'no'</span><span class="p">]</span>
<span class="nb">print</span> <span class="p">(</span><span class="s">'Yes : '</span><span class="p">,</span> <span class="n">p_yes</span><span class="p">)</span>
<span class="nb">print</span> <span class="p">(</span><span class="s">'No : '</span><span class="p">,</span> <span class="n">p_no</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area"><div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>('Yes : ', 0.028218694885361544)
('No : ', 0.0068571428571428551)
</pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>As we can see there is a higher probability that the person will <strong>buy</strong> the computer.</p>
<p>Note : We dont need to calculate the denominator of bayes as in the end we need to do comparison between the different probabilities so dividing by same number dsnt change the comparison.</p>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<h1 id="Using-Sklearn">Using Sklearn<a class="anchor-link" href="#Using-Sklearn">¶</a></h1><p>We try to solve the same problem using <a href="http://scikit-learn.org/stable/modules/naive_bayes.html">Naive Bayes</a> calssifier implemented in the sklearn library</p>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [30]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span class="kn">from</span> <span class="nn">sklearn.preprocessing</span> <span class="k">import</span> <span class="n">LabelEncoder</span>
<span class="n">encoded_data</span> <span class="o">=</span> <span class="n">data</span><span class="o">.</span><span class="n">apply</span><span class="p">(</span><span class="n">LabelEncoder</span><span class="p">()</span><span class="o">.</span><span class="n">fit_transform</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing code_cell rendered">
<div class="input">
<div class="prompt input_prompt">In [29]:</div>
<div class="inner_cell">
<div class="input_area">
<div class=" highlight hl-ipython3"><pre><span class="kn">from</span> <span class="nn">sklearn.naive_bayes</span> <span class="k">import</span> <span class="n">MultinomialNB</span>
<span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="n">clf</span> <span class="o">=</span> <span class="n">MultinomialNB</span><span class="p">()</span>
<span class="n">clf</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">encoded_data</span><span class="o">.</span><span class="n">drop</span><span class="p">([</span><span class="s">'Buys_Computer'</span><span class="p">],</span> <span class="n">axis</span><span class="o">=</span><span class="mi">1</span><span class="p">),</span> <span class="n">encoded_data</span><span class="p">[</span><span class="s">'Buys_Computer'</span><span class="p">])</span>
<span class="c"># {"Age":'<=30', "Income":"medium", "Student":'yes' , "Credit_Rating":'fair'}</span>
<span class="c"># The data is encoded as [1,2,1,1]</span>
<span class="n">X</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">1</span><span class="p">])</span>
<span class="nb">print</span> <span class="p">(</span><span class="n">clf</span><span class="o">.</span><span class="n">_joint_log_likelihood</span><span class="p">(</span><span class="n">X</span><span class="o">.</span><span class="n">reshape</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span><span class="o">-</span><span class="mi">1</span><span class="p">)))</span>
<span class="nb">print</span> <span class="p">(</span><span class="s">"Prediction of : "</span><span class="p">,</span> <span class="n">clf</span><span class="o">.</span><span class="n">predict</span><span class="p">(</span><span class="n">X</span><span class="o">.</span><span class="n">reshape</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span><span class="o">-</span><span class="mi">1</span><span class="p">)))</span>
</pre></div>
</div>
</div>
</div>
<div class="output_wrapper">
<div class="output">
<div class="output_area"><div class="prompt"></div>
<div class="output_subarea output_stream output_stdout output_text">
<pre>[[-8.29709436 -7.15971488]]
('Prediction of : ', array([1]))
</pre>
</div>
</div>
</div>
</div>
</div>
<div class="cell border-box-sizing text_cell rendered">
<div class="prompt input_prompt">
</div>
<div class="inner_cell">
<div class="text_cell_render border-box-sizing rendered_html">
<p>Thus even with Sklearn the answer is <strong>YES</strong> . In sklearn the log_likelihood is being used rather than the likelihood.</p>
<p>The beauty of the Naive Bayes for the discretized features set is that it just involves <strong>counting and multiplication </strong> to get the answer. The algorithm can be extended to continous feature variables. For continuous feature variables we need to decide which probability distributions to use and their likelihoods.</p>
<h3 id="Thus-we-have-implemented-the-Naive-Bayes-algorithm-using--Pandas-library-vectorization--properties.">Thus we have implemented the Naive Bayes algorithm using <strong> Pandas library vectorization </strong> properties.<a class="anchor-link" href="#Thus-we-have-implemented-the-Naive-Bayes-algorithm-using--Pandas-library-vectorization--properties.">¶</a></h3><h4 id="In-the-next-blog-we-will-solve-the-naive-bayes-problem-using--Probabilistic-Programming--techniques.">In the next blog we will solve the naive bayes problem using <strong> Probabilistic Programming </strong> techniques.<a class="anchor-link" href="#In-the-next-blog-we-will-solve-the-naive-bayes-problem-using--Probabilistic-Programming--techniques.">¶</a></h4>
</div>
</div>
</div>
<script type="text/javascript">if (!document.getElementById('mathjaxscript_pelican_#%@#$@#')) {
var mathjaxscript = document.createElement('script');
mathjaxscript.id = 'mathjaxscript_pelican_#%@#$@#';
mathjaxscript.type = 'text/javascript';
mathjaxscript.src = '//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML';
mathjaxscript[(window.opera ? "innerHTML" : "text")] =
"MathJax.Hub.Config({" +
" config: ['MMLorHTML.js']," +
" TeX: { extensions: ['AMSmath.js','AMSsymbols.js','noErrors.js','noUndefined.js'], equationNumbers: { autoNumber: 'AMS' } }," +
" jax: ['input/TeX','input/MathML','output/HTML-CSS']," +
" extensions: ['tex2jax.js','mml2jax.js','MathMenu.js','MathZoom.js']," +
" displayAlign: 'center'," +
" displayIndent: '0em'," +
" showMathMenu: true," +
" tex2jax: { " +
" inlineMath: [ ['$','$'] ], " +
" displayMath: [ ['$$','$$'] ]," +
" processEscapes: true," +
" preview: 'TeX'," +
" }, " +
" 'HTML-CSS': { " +
" styles: { '.MathJax_Display, .MathJax .mo, .MathJax .mi, .MathJax .mn': {color: 'black ! important'} }" +
" } " +
"}); ";
(document.body || document.getElementsByTagName('head')[0]).appendChild(mathjaxscript);
}
</script>
<div class="container bottom">
<hr>
<p>
All content copyright 2014-2016 Deebul Nair unless otherwise noted.
Licensed under <a href="http://creativecommons.org/licenses/by-nc-sa/3.0/">Creative Commons</a>.
</p>
<p>
Find me on <a href="https://twitter.com/deebuls">Twitter</a>, <a
href="https://github.com/deebuls">GitHub</a>, <a, or shoot me an <a
href="mailto:[email protected]">email</a>.
</p>
</div> </div>
</body>
</html> | {
"content_hash": "06ea9347be8d9da47301c8258b3426ea",
"timestamp": "",
"source": "github",
"line_count": 1353,
"max_line_length": 756,
"avg_line_length": 37.39393939393939,
"alnum_prop": 0.6556706328813693,
"repo_name": "deebuls/deebuls.github.io",
"id": "5f39109ec9d1e238d585d9e7feda9e7f08cfd0d7",
"size": "50611",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Naive-Bayes-Pandas.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "11156"
},
{
"name": "HTML",
"bytes": "427153"
}
],
"symlink_target": ""
} |
int
main(){
#pragma omp parallel num_threads(4)
{
printf("Hello world from thread %d!\n", omp_get_thread_num());
}
return 0;
}
| {
"content_hash": "16f4cbd496eb659f0005a3178b3fdf68",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 66,
"avg_line_length": 15.777777777777779,
"alnum_prop": 0.5985915492957746,
"repo_name": "yeephycho/codePieces",
"id": "38122b0f80f72da601bb01154a09157f5c0166d4",
"size": "179",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "OMP_ENV/openmp_test.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "179"
},
{
"name": "C++",
"bytes": "5650"
},
{
"name": "Makefile",
"bytes": "321"
},
{
"name": "Python",
"bytes": "2580"
}
],
"symlink_target": ""
} |
<?php
include 'header.php';
?>
<div class="container ">
<div class="innerpage">
<div class="cart">
<div class="client-prod">
<div class="col-md-12 col-sm-12 col-xs-12 col-xxs-12 text-center"> <div class="pinktext cart-heading">Thank You for shopping at PretMode.com.</div>
<p class="mb20">We will send you the tracking number as soon as we ship the product/s.
</p>
</div>
<div class=" col-md-8 col-md-offset-2 col-sm-10 col-sm-offset-1 cart-left-cotent clearfix orderdtlbox orderdetails">
<div class="heading-wrapper row ">
<div class="col-md-12 col-sm-12 col-xs-12 col-xxs-12 text-center orderdtl">
<div class="number-id"><span class="order-no">Order ID:</span><span class="order-id"> 130627715</span></div>
<div class="placed-on">Placed on: <b>13-07-2016</b> | Status: <b>pending</b> | Total Amount <b><span class="rupee"></span> 1649 </b></div>
</div>
</div>
<div class="product-heading row text-uppercase hidden-xs"> <span class="col-md-6 col-sm-8">Products</span> <span class="col-md-6 col-sm-4 text-right">total Amount</span> </div>
<article class="row">
<section class="media cart-content">
<div class="media-left cart-img-container"> <a href="#"> <img class="media-object" src="./images/product/423_2.jpg" alt="..."> </a> </div>
<div class="media-body item-desc">
<div class="row cart-inner-main">
<div class="col-md-8 col-sm-9 col-xs-12 col-xxs-12 item-desc">
<div class="heading">
<div class="item-head-main"> <a href="product/call-me-chanel-dress" class="item-heading">Chanel</a> <a href="product/call-me-chanel-dress" class="item-brief text-capitalize">Call me Chanel dress</a> </div>
</div>
<div class="row">
<div class="col-sm-6 ">
<div class="productwrap">
<h4>Colour & size</h4>
<div class="prodsummary">
<ul class="product_color">
<li style="background-color:#ffffff; "></li>
</ul>
<span class="sizescart">S</span> </div>
</div>
</div>
<div class="col-sm-6 ">
<div class="productwrap">
<h4>Product code</h4>
<div class="">397 - 6</div>
</div></div>
</div>
</div>
<div class="col-md-4 col-sm-3 col-xs-12 col-xxs-12 item-price off-edit-hide">
<span class="price"><span class="rupee"></span>18000</span> </div>
</div>
</div>
</section>
<section class="media cart-content">
<div class="media-left cart-img-container"> <a href="#"> <img class="media-object" src="./images/product/423_2.jpg" alt="..."> </a> </div>
<div class="media-body item-desc">
<div class="row cart-inner-main">
<div class="col-md-8 col-sm-9 col-xs-12 col-xxs-12 item-desc">
<div class="heading">
<div class="item-head-main"> <a href="product/call-me-chanel-dress" class="item-heading">Chanel</a> <a href="product/call-me-chanel-dress" class="item-brief text-capitalize">Call me Chanel dress</a> </div>
</div>
<div class="row">
<div class="col-sm-6 ">
<div class="productwrap">
<h4>Colour & size</h4>
<div class="prodsummary">
<ul class="product_color">
<li style="background-color:#ffffff; "></li>
</ul>
<span class="sizescart">S</span> </div>
</div>
</div>
<div class="col-sm-6 ">
<div class="productwrap">
<h4>Product code</h4>
<div class="">397 - 6</div>
</div></div>
</div>
</div>
<div class="col-md-4 col-sm-3 col-xs-12 col-xxs-12 item-price off-edit-hide">
<span class="price"><span class="rupee"></span>18000</span> </div>
</div>
</div>
</section>
</article>
</div>
</div>
</div>
<!--end-->
</div>
</div>
<?php
include 'footer.php';
?>
| {
"content_hash": "cc48886ed181de846dd095ee612a0c0b",
"timestamp": "",
"source": "github",
"line_count": 97,
"max_line_length": 227,
"avg_line_length": 47.43298969072165,
"alnum_prop": 0.4857639643555749,
"repo_name": "ParthXe/Myntra",
"id": "244c315bf33e8f5c96a1865812ffa4b1f4fb6cd0",
"size": "4601",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "html/cart-complete.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "669"
},
{
"name": "CSS",
"bytes": "1147222"
},
{
"name": "HTML",
"bytes": "3815099"
},
{
"name": "JavaScript",
"bytes": "6454925"
},
{
"name": "PHP",
"bytes": "3258245"
}
],
"symlink_target": ""
} |
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
namespace FancyScrollView.Example05
{
class Example05 : MonoBehaviour
{
[SerializeField] ScrollView scrollView = default;
[SerializeField] Button prevCellButton = default;
[SerializeField] Button nextCellButton = default;
[SerializeField] Text selectedItemInfo = default;
void Start()
{
prevCellButton.onClick.AddListener(scrollView.SelectPrevCell);
nextCellButton.onClick.AddListener(scrollView.SelectNextCell);
scrollView.OnSelectionChanged(OnSelectionChanged);
var items = Enumerable.Range(0, 20)
.Select(i => new ItemData($"Cell {i}"))
.ToList();
scrollView.UpdateData(items);
scrollView.UpdateSelection(10);
scrollView.JumpTo(10);
}
void OnSelectionChanged(int index)
{
selectedItemInfo.text = $"Selected item info: index {index}";
}
}
}
| {
"content_hash": "d5dc33a27986b15d3892be9ad0753670",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 74,
"avg_line_length": 28.63888888888889,
"alnum_prop": 0.6217264791464597,
"repo_name": "setchi/FancyScrollView",
"id": "fa94b30795085df2d52c7f034538d9001d6c7fc0",
"size": "1217",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Assets/FancyScrollView/Examples/Sources/05_Voronoi/Example05.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "149643"
},
{
"name": "HLSL",
"bytes": "3514"
},
{
"name": "ShaderLab",
"bytes": "6179"
}
],
"symlink_target": ""
} |
template <typename T>
class Heap {
public:
using CompareFunction = std::function<bool(const T &a, const T &b)>;
// Construct a max-heap with a custom comparator
// @param cmp The comparator to use (default: std::less)
// Returns "true" when `a` is `less` than `b`
Heap(const CompareFunction &cmp = [](const T &a,
const T &b) { return std::less<T>()(a, b); })
: cmp_(cmp) {
}
// Construct a max-heap from an existing vector
Heap(const std::vector<T> &vector,
const CompareFunction &cmp = [](const T &a,
const T &b) { return std::less<T>()(a, b); })
: cmp_(cmp), vector_(vector) {
std::make_heap(vector_, cmp_);
}
Heap(const Heap<T> &o_heap) : cmp_(o_heap.cmp_), vector_(o_heap.vector_) {
}
// Remove the drop element of the heap without any copies
void drop() {
std::pop_heap(vector_.begin(), vector_.end(), cmp_);
vector_.pop_back();
}
// Return a copy of the top (max) element of the heap, and delete it from the heap
T pop() {
std::pop_heap(vector_.begin(), vector_.end(), cmp_);
const T result = vector_.back();
vector_.pop_back();
return result;
}
// Return a reference to the top (max) element of the heap
const T &top() const {
return vector_.front();
}
// Add an element to the heap
// @param item The thing to be pushed to the heap
void push(const T &item) {
vector_.push_back(item);
std::push_heap(vector_.begin(), vector_.end(), cmp_);
}
// Remove all elements from the heap
void clear() {
vector_.clear();
}
// @returns The number of elements in the heap
size_t size() const {
return vector_.size();
}
// @returns True if the heap is empty
bool empty() const {
return vector_.empty();
}
// Returns a sorted vector made from the elements of the heap
std::vector<T> to_sorted_vector() const {
Heap heap2 = *this;
std::vector<T> result;
while (!heap2.empty()) {
result.push_back(heap2.top());
heap2.drop();
}
return result;
}
private:
CompareFunction cmp_;
std::vector<T> vector_;
};
| {
"content_hash": "d7e0b2621fbbd4950f2fb83bb8d70cdd",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 84,
"avg_line_length": 27.175,
"alnum_prop": 0.5837166513339467,
"repo_name": "jpanikulam/experiments",
"id": "4ada2a39724dbb9459ecf4df6c17d4f988ac18f5",
"size": "2325",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "util/heap.hh",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "36550"
},
{
"name": "C++",
"bytes": "1261845"
},
{
"name": "CMake",
"bytes": "9017"
},
{
"name": "Cuda",
"bytes": "7609"
},
{
"name": "GLSL",
"bytes": "13391"
},
{
"name": "Python",
"bytes": "73701"
},
{
"name": "Shell",
"bytes": "806"
}
],
"symlink_target": ""
} |
package org.bouncycastle.cert;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
import java.util.Date;
import java.util.List;
import java.util.Set;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1Encoding;
import org.bouncycastle.asn1.ASN1OutputStream;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.Certificate;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.asn1.x509.Extensions;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.asn1.x509.TBSCertificate;
import org.bouncycastle.operator.ContentVerifier;
import org.bouncycastle.operator.ContentVerifierProvider;
/**
* Holding class for an X.509 Certificate structure.
*/
public class X509CertificateHolder
{
private Certificate x509Certificate;
private Extensions extensions;
private static Certificate parseBytes(byte[] certEncoding)
throws IOException
{
try
{
return Certificate.getInstance(ASN1Primitive.fromByteArray(certEncoding));
}
catch (ClassCastException e)
{
throw new CertIOException("malformed data: " + e.getMessage(), e);
}
catch (IllegalArgumentException e)
{
throw new CertIOException("malformed data: " + e.getMessage(), e);
}
}
/**
* Create a X509CertificateHolder from the passed in bytes.
*
* @param certEncoding BER/DER encoding of the certificate.
* @throws IOException in the event of corrupted data, or an incorrect structure.
*/
public X509CertificateHolder(byte[] certEncoding)
throws IOException
{
this(parseBytes(certEncoding));
}
/**
* Create a X509CertificateHolder from the passed in ASN.1 structure.
*
* @param x509Certificate an ASN.1 Certificate structure.
*/
public X509CertificateHolder(Certificate x509Certificate)
{
this.x509Certificate = x509Certificate;
this.extensions = x509Certificate.getTBSCertificate().getExtensions();
}
public int getVersionNumber()
{
return x509Certificate.getVersionNumber();
}
/**
* @deprecated use getVersionNumber
*/
public int getVersion()
{
return x509Certificate.getVersionNumber();
}
/**
* Return whether or not the holder's certificate contains extensions.
*
* @return true if extension are present, false otherwise.
*/
public boolean hasExtensions()
{
return extensions != null;
}
/**
* Look up the extension associated with the passed in OID.
*
* @param oid the OID of the extension of interest.
*
* @return the extension if present, null otherwise.
*/
public Extension getExtension(ASN1ObjectIdentifier oid)
{
if (extensions != null)
{
return extensions.getExtension(oid);
}
return null;
}
/**
* Return the extensions block associated with this certificate if there is one.
*
* @return the extensions block, null otherwise.
*/
public Extensions getExtensions()
{
return extensions;
}
/**
* Returns a list of ASN1ObjectIdentifier objects representing the OIDs of the
* extensions contained in this holder's certificate.
*
* @return a list of extension OIDs.
*/
public List getExtensionOIDs()
{
return CertUtils.getExtensionOIDs(extensions);
}
/**
* Returns a set of ASN1ObjectIdentifier objects representing the OIDs of the
* critical extensions contained in this holder's certificate.
*
* @return a set of critical extension OIDs.
*/
public Set getCriticalExtensionOIDs()
{
return CertUtils.getCriticalExtensionOIDs(extensions);
}
/**
* Returns a set of ASN1ObjectIdentifier objects representing the OIDs of the
* non-critical extensions contained in this holder's certificate.
*
* @return a set of non-critical extension OIDs.
*/
public Set getNonCriticalExtensionOIDs()
{
return CertUtils.getNonCriticalExtensionOIDs(extensions);
}
/**
* Return the serial number of this attribute certificate.
*
* @return the serial number.
*/
public BigInteger getSerialNumber()
{
return x509Certificate.getSerialNumber().getValue();
}
/**
* Return the issuer of this certificate.
*
* @return the certificate issuer.
*/
public X500Name getIssuer()
{
return X500Name.getInstance(x509Certificate.getIssuer());
}
/**
* Return the subject this certificate is for.
*
* @return the subject for the certificate.
*/
public X500Name getSubject()
{
return X500Name.getInstance(x509Certificate.getSubject());
}
/**
* Return the date before which this certificate is not valid.
*
* @return the start time for the certificate's validity period.
*/
public Date getNotBefore()
{
return x509Certificate.getStartDate().getDate();
}
/**
* Return the date after which this certificate is not valid.
*
* @return the final time for the certificate's validity period.
*/
public Date getNotAfter()
{
return x509Certificate.getEndDate().getDate();
}
/**
* Return the SubjectPublicKeyInfo describing the public key this certificate is carrying.
*
* @return the public key ASN.1 structure contained in the certificate.
*/
public SubjectPublicKeyInfo getSubjectPublicKeyInfo()
{
return x509Certificate.getSubjectPublicKeyInfo();
}
/**
* Return the underlying ASN.1 structure for the certificate in this holder.
*
* @return a X509CertificateStructure object.
*/
public Certificate toASN1Structure()
{
return x509Certificate;
}
/**
* Return the details of the signature algorithm used to create this attribute certificate.
*
* @return the AlgorithmIdentifier describing the signature algorithm used to create this attribute certificate.
*/
public AlgorithmIdentifier getSignatureAlgorithm()
{
return x509Certificate.getSignatureAlgorithm();
}
/**
* Return the bytes making up the signature associated with this attribute certificate.
*
* @return the attribute certificate signature bytes.
*/
public byte[] getSignature()
{
return x509Certificate.getSignature().getBytes();
}
/**
* Return whether or not this certificate is valid on a particular date.
*
* @param date the date of interest.
* @return true if the certificate is valid, false otherwise.
*/
public boolean isValidOn(Date date)
{
return !CertUtils.dateBefore(date, x509Certificate.getStartDate().getDate()) && !CertUtils.dateAfter(date, x509Certificate.getEndDate().getDate());
}
/**
* Validate the signature on the certificate in this holder.
*
* @param verifierProvider a ContentVerifierProvider that can generate a verifier for the signature.
* @return true if the signature is valid, false otherwise.
* @throws CertException if the signature cannot be processed or is inappropriate.
*/
public boolean isSignatureValid(ContentVerifierProvider verifierProvider)
throws CertException
{
TBSCertificate tbsCert = x509Certificate.getTBSCertificate();
if (!CertUtils.isAlgIdEqual(tbsCert.getSignature(), x509Certificate.getSignatureAlgorithm()))
{
throw new CertException("signature invalid - algorithm identifier mismatch");
}
ContentVerifier verifier;
try
{
verifier = verifierProvider.get((tbsCert.getSignature()));
OutputStream sOut = verifier.getOutputStream();
ASN1OutputStream dOut = ASN1OutputStream.create(sOut, ASN1Encoding.DER);
dOut.writeObject(tbsCert);
sOut.close();
}
catch (Exception e)
{
throw new CertException("unable to process signature: " + e.getMessage(), e);
}
return verifier.verify(x509Certificate.getSignature().getBytes());
}
public boolean equals(
Object o)
{
if (o == this)
{
return true;
}
if (!(o instanceof X509CertificateHolder))
{
return false;
}
X509CertificateHolder other = (X509CertificateHolder)o;
return this.x509Certificate.equals(other.x509Certificate);
}
public int hashCode()
{
return this.x509Certificate.hashCode();
}
/**
* Return the ASN.1 encoding of this holder's certificate.
*
* @return a DER encoded byte array.
* @throws IOException if an encoding cannot be generated.
*/
public byte[] getEncoded()
throws IOException
{
return x509Certificate.getEncoded();
}
}
| {
"content_hash": "4ec4492f5249111f5be2a92123a5e2b9",
"timestamp": "",
"source": "github",
"line_count": 328,
"max_line_length": 155,
"avg_line_length": 28.195121951219512,
"alnum_prop": 0.6552768166089965,
"repo_name": "bcgit/bc-java",
"id": "00fcf65bdb12010459d5ca4677145f9a0d247890",
"size": "9248",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pkix/src/main/j2me/org/bouncycastle/cert/X509CertificateHolder.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "12956"
},
{
"name": "HTML",
"bytes": "66943"
},
{
"name": "Java",
"bytes": "31612485"
},
{
"name": "Shell",
"bytes": "97225"
}
],
"symlink_target": ""
} |
import colorama
import refactoring # Note: refactoring.py need to be in the current working directory
colorama.init()
paths = ["C:/Users/petst55/Work/Inviwo/Inviwo-dev", "C:/Users/petst55/Work/Inviwo/Inviwo-research"]
excludespatterns = ["*/ext/*", "*moc_*", "*cmake*", "*/proteindocking/*",
"*/proteindocking2/*", "*/genetree/*", "*/vrnbase/*"]
files = refactoring.find_files(paths, ['*.h', '*.cpp'], excludes=excludespatterns)
def replace(pattern, replacement):
print("Matches:")
matches = refactoring.find_matches(files, pattern)
print("\n")
print("Replacing:")
refactoring.replace_matches(matches, pattern, replacement)
serializerReplacements = {
"IvwSerializeConstants::XML_VERSION": "SerializeConstants::XmlVersion",
"IvwSerializeConstants::INVIWO_TREEDATA": "SerializeConstants::InviwoTreedata",
"IvwSerializeConstants::INVIWO_VERSION": "SerializeConstants::InviwoVersion",
"IvwSerializeConstants::NETWORK_VERSION": "SerializeConstants::NetworkVersion",
"IvwSerializeConstants::VERSION": "SerializeConstants::Version",
"IvwSerializeConstants::EDIT_COMMENT": "SerializeConstants::EditComment",
"IvwSerializeConstants::ID_ATTRIBUTE": "SerializeConstants::IDAttribute",
"IvwSerializeConstants::REF_ATTRIBUTE": "SerializeConstants::RefAttribute",
"IvwSerializeConstants::VERSION_ATTRIBUTE": "SerializeConstants::VersionAttribute",
"IvwSerializeConstants::CONTENT_ATTRIBUTE": "SerializeConstants::ContentAttribute",
"IvwSerializeConstants::TYPE_ATTRIBUTE": "SerializeConstants::TypeAttribute",
"IvwSerializeConstants::KEY_ATTRIBUTE": "SerializeConstants::KeyAttribute",
"IvwSerializeConstants::VECTOR_ATTRIBUTES": "SerializeConstants::VectorAttributes",
"IvwSerializeConstants::PROPERTY_ATTRIBUTE_1": "SerializeConstants::PropertyAttribute1",
"IvwSerializeConstants::PROPERTY_ATTRIBUTE_2": "SerializeConstants::PropertyAttribute2",
"IvwSerializeConstants::PROCESSOR_ATTRIBUTE_1": "SerializeConstants::ProcessorAttribute1",
"IvwSerializeConstants::PROCESSOR_ATTRIBUTE_2": "SerializeConstants::ProcessorAttribute2",
"IvwSerializeConstants": "SerializeConstants",
"IvwSerializeBase": "SerializeBase",
"IvwDeserializer": "Deserializer",
"IvwSerializable": "Serializable",
"IvwSerializer": "Serializer",
"inviwo/core/io/serialization/ivwdeserializer.h": "inviwo/core/io/serialization/deserializer.h",
"inviwo/core/io/serialization/ivwserializable.h": "inviwo/core/io/serialization/serializable.h",
"inviwo/core/io/serialization/ivwserialization.h": "inviwo/core/io/serialization/serialization.h",
"inviwo/core/io/serialization/ivwserializebase.h": "inviwo/core/io/serialization/serializebase.h",
"inviwo/core/io/serialization/ivwserializeconstants.h": "inviwo/core/io/serialization/serializeconstants.h",
"inviwo/core/io/serialization/ivwserializer.h": "inviwo/core/io/serialization/serializer.h"
}
for k, v in serializerReplacements.items():
replace(r"\b" + k + r"\b", v)
| {
"content_hash": "0a4645c0ed4283dccf60333caa34ca50",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 112,
"avg_line_length": 55.21818181818182,
"alnum_prop": 0.7543628580836351,
"repo_name": "inviwo/inviwo",
"id": "aa9134cfe1017ac8602b81daaad2773e61954895",
"size": "3037",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tools/refactoring/serializerename.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C",
"bytes": "146426"
},
{
"name": "C++",
"bytes": "15986580"
},
{
"name": "CMake",
"bytes": "444333"
},
{
"name": "CSS",
"bytes": "8925"
},
{
"name": "Dockerfile",
"bytes": "1760"
},
{
"name": "GLSL",
"bytes": "615425"
},
{
"name": "Groovy",
"bytes": "12826"
},
{
"name": "HTML",
"bytes": "148248"
},
{
"name": "JavaScript",
"bytes": "286267"
},
{
"name": "Mathematica",
"bytes": "304992"
},
{
"name": "Python",
"bytes": "1965605"
},
{
"name": "QMake",
"bytes": "172"
},
{
"name": "Shell",
"bytes": "992"
}
],
"symlink_target": ""
} |
package samples
import (
"context"
"github.com/google/gapid/gapis/atom"
"github.com/google/gapid/gapis/gfxapi/gles"
)
// DrawTexturedSquare returns the atom list needed to create a context then
// draw a textured square.
func DrawTexturedSquare(ctx context.Context) (atoms *atom.List, draw atom.ID, swap atom.ID) {
squareVertices := []float32{
-0.5, -0.5, 0.5,
-0.5, +0.5, 0.5,
+0.5, +0.5, 0.5,
+0.5, -0.5, 0.5,
}
squareIndices := []uint16{
0, 1, 2, 0, 2, 3,
}
textureVSSource := `
precision mediump float;
attribute vec3 position;
varying vec2 texcoord;
void main() {
gl_Position = vec4(position, 1.0);
texcoord = position.xy + vec2(0.5, 0.5);
}`
textureFSSource := `
precision mediump float;
uniform sampler2D tex;
varying vec2 texcoord;
void main() {
gl_FragColor = texture(tex, texcoord);
}`
b := newBuilder(ctx)
vs, fs, prog, pos := b.newShaderID(), b.newShaderID(), b.newProgramID(), gles.AttributeLocation(0)
_, eglSurface, eglDisplay := b.newEglContext(128, 128, false)
texLoc := gles.UniformLocation(0)
textureNames := []gles.TextureId{1}
textureNamesPtr := b.data(ctx, textureNames)
texData := make([]uint8, 3*64*64)
for y := 0; y < 64; y++ {
for x := 0; x < 64; x++ {
texData[y*64*3+x*3] = uint8(x * 4)
texData[y*64*3+x*3+1] = uint8(y * 4)
texData[y*64*3+x*3+2] = 255
}
}
textureData := b.data(ctx, texData)
squareIndicesPtr := b.data(ctx, squareIndices)
squareVerticesPtr := b.data(ctx, squareVertices)
b.program(ctx, vs, fs, prog, textureVSSource, textureFSSource)
draw = b.Add(
gles.NewGlEnable(gles.GLenum_GL_DEPTH_TEST), // Required for depth-writing
gles.NewGlClearColor(0.0, 1.0, 0.0, 1.0),
gles.NewGlClear(gles.GLbitfield_GL_COLOR_BUFFER_BIT|gles.GLbitfield_GL_DEPTH_BUFFER_BIT),
atom.WithExtras(
gles.NewGlLinkProgram(prog),
&gles.ProgramInfo{
LinkStatus: gles.GLboolean_GL_TRUE,
ActiveUniforms: gles.UniformIndexːActiveUniformᵐ{
0: {
Type: gles.GLenum_GL_SAMPLER_2D,
Name: "tex",
ArraySize: 1,
Location: texLoc,
},
},
}),
gles.NewGlUseProgram(prog),
gles.NewGlGenTextures(1, textureNamesPtr.Ptr()).AddWrite(textureNamesPtr.Data()),
gles.NewGlGetUniformLocation(prog, "tex", texLoc),
gles.NewGlActiveTexture(gles.GLenum_GL_TEXTURE0),
gles.NewGlBindTexture(gles.GLenum_GL_TEXTURE_2D, textureNames[0]),
gles.NewGlTexParameteri(gles.GLenum_GL_TEXTURE_2D, gles.GLenum_GL_TEXTURE_MIN_FILTER, gles.GLint(gles.GLenum_GL_NEAREST)),
gles.NewGlTexParameteri(gles.GLenum_GL_TEXTURE_2D, gles.GLenum_GL_TEXTURE_MAG_FILTER, gles.GLint(gles.GLenum_GL_NEAREST)),
gles.NewGlUniform1i(texLoc, 0),
gles.NewGlTexImage2D(
gles.GLenum_GL_TEXTURE_2D,
0,
gles.GLint(gles.GLenum_GL_RGB),
64,
64,
0,
gles.GLenum_GL_RGB,
gles.GLenum_GL_UNSIGNED_BYTE,
textureData.Ptr(),
).AddRead(textureData.Data()),
gles.NewGlGetAttribLocation(prog, "position", gles.GLint(pos)),
gles.NewGlEnableVertexAttribArray(pos),
gles.NewGlVertexAttribPointer(pos, 3, gles.GLenum_GL_FLOAT, gles.GLboolean(0), 0, squareVerticesPtr.Ptr()),
gles.NewGlDrawElements(gles.GLenum_GL_TRIANGLES, 6, gles.GLenum_GL_UNSIGNED_SHORT, squareIndicesPtr.Ptr()).
AddRead(squareIndicesPtr.Data()).
AddRead(squareVerticesPtr.Data()),
)
swap = b.Add(
gles.NewEglSwapBuffers(eglDisplay, eglSurface, gles.EGLBoolean(1)),
)
return &b.List, draw, swap
}
| {
"content_hash": "5eebc15d214e6294e5090abee46e4d64",
"timestamp": "",
"source": "github",
"line_count": 111,
"max_line_length": 124,
"avg_line_length": 30.864864864864863,
"alnum_prop": 0.6894337419731466,
"repo_name": "ianthehat/gapid",
"id": "e18a25bd35fec682289a967978e0d4235f3d200f",
"size": "4023",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/integration/replay/gles/samples/draw_textured_square.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "763"
},
{
"name": "C",
"bytes": "223243"
},
{
"name": "C++",
"bytes": "1081024"
},
{
"name": "CMake",
"bytes": "390556"
},
{
"name": "GLSL",
"bytes": "22280"
},
{
"name": "Go",
"bytes": "4280527"
},
{
"name": "HTML",
"bytes": "99377"
},
{
"name": "Java",
"bytes": "1106214"
},
{
"name": "JavaScript",
"bytes": "13177"
},
{
"name": "Objective-C++",
"bytes": "11819"
},
{
"name": "Protocol Buffer",
"bytes": "104558"
},
{
"name": "Shell",
"bytes": "4910"
}
],
"symlink_target": ""
} |
package ip
import (
"bytes"
"encoding/binary"
"fmt"
"math/big"
"net"
"sort"
)
const (
ipv4BitLen = 8 * net.IPv4len
ipv6BitLen = 8 * net.IPv6len
)
// CountIPsInCIDR takes a RFC4632/RFC4291-formatted IPv4/IPv6 CIDR and
// determines how many IP addresses reside within that CIDR.
// Returns 0 if the input CIDR cannot be parsed.
func CountIPsInCIDR(cidr string) int {
_, ipnet, err := net.ParseCIDR(cidr)
if err != nil {
return 0
}
subnet, size := ipnet.Mask.Size()
if subnet == size {
return 1
}
return 1<<uint(size-subnet) - 1
}
var (
// v4Mappedv6Prefix is the RFC2765 IPv4-mapped address prefix.
v4Mappedv6Prefix = []byte{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xff, 0xff}
ipv4LeadingZeroes = []byte{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}
defaultIPv4 = []byte{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xff, 0xff, 0x0, 0x0, 0x0, 0x0}
defaultIPv6 = []byte{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}
upperIPv4 = []byte{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xff, 0xff, 255, 255, 255, 255}
upperIPv6 = []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}
)
// NetsByMask is used to sort a list of IP networks by the size of their masks.
// Implements sort.Interface.
type NetsByMask []*net.IPNet
func (s NetsByMask) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s NetsByMask) Less(i, j int) bool {
iPrefixSize, _ := s[i].Mask.Size()
jPrefixSize, _ := s[j].Mask.Size()
if iPrefixSize == jPrefixSize {
if bytes.Compare(s[i].IP, s[j].IP) < 0 {
return true
}
return false
}
return iPrefixSize < jPrefixSize
}
func (s NetsByMask) Len() int {
return len(s)
}
// Assert that NetsByMask implements sort.Interface.
var _ sort.Interface = NetsByMask{}
var _ sort.Interface = NetsByRange{}
// NetsByRange is used to sort a list of ranges, first by their last IPs, then by
// their first IPs
// Implements sort.Interface.
type NetsByRange []*netWithRange
func (s NetsByRange) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s NetsByRange) Less(i, j int) bool {
// First compare by last IP.
lastComparison := bytes.Compare(*s[i].Last, *s[j].Last)
if lastComparison < 0 {
return true
} else if lastComparison > 0 {
return false
}
// Then compare by first IP.
firstComparison := bytes.Compare(*s[i].First, *s[i].First)
if firstComparison < 0 {
return true
} else if firstComparison > 0 {
return false
}
// First and last IPs are the same, so thus are equal, and s[i]
// is not less than s[j].
return false
}
func (s NetsByRange) Len() int {
return len(s)
}
// RemoveCIDRs removes the specified CIDRs from another set of CIDRs. If a CIDR
// to remove is not contained within the CIDR, the CIDR to remove is ignored. A
// slice of CIDRs is returned which contains the set of CIDRs provided minus
// the set of CIDRs which were removed. Both input slices may be modified by
// calling this function.
func RemoveCIDRs(allowCIDRs, removeCIDRs []*net.IPNet) ([]*net.IPNet, error) {
// Ensure that we iterate through the provided CIDRs in order of largest
// subnet first.
sort.Sort(NetsByMask(removeCIDRs))
PreLoop:
// Remove CIDRs which are contained within CIDRs that we want to remove;
// such CIDRs are redundant.
for j, removeCIDR := range removeCIDRs {
for i, removeCIDR2 := range removeCIDRs {
if i == j {
continue
}
if removeCIDR.Contains(removeCIDR2.IP) {
removeCIDRs = append(removeCIDRs[:i], removeCIDRs[i+1:]...)
// Re-trigger loop since we have modified the slice we are iterating over.
goto PreLoop
}
}
}
for _, remove := range removeCIDRs {
Loop:
for i, allowCIDR := range allowCIDRs {
// Don't allow comparison of different address spaces.
if allowCIDR.IP.To4() != nil && remove.IP.To4() == nil ||
allowCIDR.IP.To4() == nil && remove.IP.To4() != nil {
return nil, fmt.Errorf("cannot mix IP addresses of different IP protocol versions")
}
// Only remove CIDR if it is contained in the subnet we are allowing.
if allowCIDR.Contains(remove.IP.Mask(remove.Mask)) {
nets, err := removeCIDR(allowCIDR, remove)
if err != nil {
return nil, err
}
// Remove CIDR that we have just processed and append new CIDRs
// that we computed from removing the CIDR to remove.
allowCIDRs = append(allowCIDRs[:i], allowCIDRs[i+1:]...)
allowCIDRs = append(allowCIDRs, nets...)
goto Loop
} else if remove.Contains(allowCIDR.IP.Mask(allowCIDR.Mask)) {
// If a CIDR that we want to remove contains a CIDR in the list
// that is allowed, then we can just remove the CIDR to allow.
allowCIDRs = append(allowCIDRs[:i], allowCIDRs[i+1:]...)
goto Loop
}
}
}
return allowCIDRs, nil
}
func getNetworkPrefix(ipNet *net.IPNet) *net.IP {
var mask net.IP
if ipNet.IP.To4() == nil {
mask = make(net.IP, net.IPv6len)
for i := 0; i < len(ipNet.Mask); i++ {
mask[net.IPv6len-i-1] = ipNet.IP[net.IPv6len-i-1] & ^ipNet.Mask[i]
}
} else {
mask = make(net.IP, net.IPv4len)
for i := 0; i < net.IPv4len; i++ {
mask[net.IPv4len-i-1] = ipNet.IP[net.IPv6len-i-1] & ^ipNet.Mask[i]
}
}
return &mask
}
func removeCIDR(allowCIDR, removeCIDR *net.IPNet) ([]*net.IPNet, error) {
var allows []*net.IPNet
var allowIsIpv4, removeIsIpv4 bool
var allowBitLen int
if allowCIDR.IP.To4() != nil {
allowIsIpv4 = true
allowBitLen = ipv4BitLen
} else {
allowBitLen = ipv6BitLen
}
if removeCIDR.IP.To4() != nil {
removeIsIpv4 = true
}
if removeIsIpv4 != allowIsIpv4 {
return nil, fmt.Errorf("cannot mix IP addresses of different IP protocol versions")
}
// Get size of each CIDR mask.
allowSize, _ := allowCIDR.Mask.Size()
removeSize, _ := removeCIDR.Mask.Size()
if allowSize >= removeSize {
return nil, fmt.Errorf("allow CIDR prefix must be a superset of " +
"remove CIDR prefix")
}
allowFirstIPMasked := allowCIDR.IP.Mask(allowCIDR.Mask)
removeFirstIPMasked := removeCIDR.IP.Mask(removeCIDR.Mask)
// Convert to IPv4 in IPv6 addresses if needed.
if allowIsIpv4 {
allowFirstIPMasked = append(v4Mappedv6Prefix, allowFirstIPMasked...)
}
if removeIsIpv4 {
removeFirstIPMasked = append(v4Mappedv6Prefix, removeFirstIPMasked...)
}
allowFirstIP := &allowFirstIPMasked
removeFirstIP := &removeFirstIPMasked
// Create CIDR prefixes with mask size of Y+1, Y+2 ... X where Y is the mask
// length of the CIDR prefix B from which we are excluding a CIDR prefix A
// with mask length X.
for i := (allowBitLen - allowSize - 1); i >= (allowBitLen - removeSize); i-- {
// The mask for each CIDR prefix is simply the ith bit flipped, and then
// zero'ing out all subsequent bits (the host identifier part of the
// prefix).
newMaskSize := allowBitLen - i
newIP := (*net.IP)(flipNthBit((*[]byte)(removeFirstIP), uint(i)))
for k := range *allowFirstIP {
(*newIP)[k] = (*allowFirstIP)[k] | (*newIP)[k]
}
newMask := net.CIDRMask(newMaskSize, allowBitLen)
newIPMasked := newIP.Mask(newMask)
newIPNet := net.IPNet{IP: newIPMasked, Mask: newMask}
allows = append(allows, &newIPNet)
}
return allows, nil
}
func getByteIndexOfBit(bit uint) uint {
return net.IPv6len - (bit / 8) - 1
}
func getNthBit(ip *net.IP, bitNum uint) uint8 {
byteNum := getByteIndexOfBit(bitNum)
bits := (*ip)[byteNum]
b := uint8(bits)
return b >> (bitNum % 8) & 1
}
func flipNthBit(ip *[]byte, bitNum uint) *[]byte {
ipCopy := make([]byte, len(*ip))
copy(ipCopy, *ip)
byteNum := getByteIndexOfBit(bitNum)
ipCopy[byteNum] = ipCopy[byteNum] ^ 1<<(bitNum%8)
return &ipCopy
}
func ipNetToRange(ipNet net.IPNet) netWithRange {
firstIP := make(net.IP, len(ipNet.IP))
lastIP := make(net.IP, len(ipNet.IP))
copy(firstIP, ipNet.IP)
copy(lastIP, ipNet.IP)
firstIP = firstIP.Mask(ipNet.Mask)
lastIP = lastIP.Mask(ipNet.Mask)
if firstIP.To4() != nil {
firstIP = append(v4Mappedv6Prefix, firstIP...)
lastIP = append(v4Mappedv6Prefix, lastIP...)
}
lastIPMask := make(net.IPMask, len(ipNet.Mask))
copy(lastIPMask, ipNet.Mask)
for i := range lastIPMask {
lastIPMask[len(lastIPMask)-i-1] = ^lastIPMask[len(lastIPMask)-i-1]
lastIP[net.IPv6len-i-1] = lastIP[net.IPv6len-i-1] | lastIPMask[len(lastIPMask)-i-1]
}
return netWithRange{First: &firstIP, Last: &lastIP, Network: &ipNet}
}
func getPreviousIP(ip net.IP) net.IP {
// Cannot go lower than zero!
if ip.Equal(net.IP(defaultIPv4)) || ip.Equal(net.IP(defaultIPv6)) {
return ip
}
previousIP := make(net.IP, len(ip))
copy(previousIP, ip)
var overflow bool
var lowerByteBound int
if ip.To4() != nil {
lowerByteBound = net.IPv6len - net.IPv4len
} else {
lowerByteBound = 0
}
for i := len(ip) - 1; i >= lowerByteBound; i-- {
if overflow || i == len(ip)-1 {
previousIP[i]--
}
// Track if we have overflowed and thus need to continue subtracting.
if ip[i] == 0 && previousIP[i] == 255 {
overflow = true
} else {
overflow = false
}
}
return previousIP
}
// GetNextIP returns the next IP from the given IP address. If the given IP is
// the last IP of a v4 or v6 range, the same IP is returned.
func GetNextIP(ip net.IP) net.IP {
if ip.Equal(upperIPv4) || ip.Equal(upperIPv6) {
return ip
}
nextIP := make(net.IP, len(ip))
switch len(ip) {
case net.IPv4len:
ipU32 := binary.BigEndian.Uint32(ip)
ipU32++
binary.BigEndian.PutUint32(nextIP, ipU32)
return nextIP
case net.IPv6len:
ipU64 := binary.BigEndian.Uint64(ip[net.IPv6len/2:])
ipU64++
binary.BigEndian.PutUint64(nextIP[net.IPv6len/2:], ipU64)
if ipU64 == 0 {
ipU64 = binary.BigEndian.Uint64(ip[:net.IPv6len/2])
ipU64++
binary.BigEndian.PutUint64(nextIP[:net.IPv6len/2], ipU64)
} else {
copy(nextIP[:net.IPv6len/2], ip[:net.IPv6len/2])
}
return nextIP
default:
return ip
}
}
func createSpanningCIDR(r netWithRange) net.IPNet {
// Don't want to modify the values of the provided range, so make copies.
lowest := *r.First
highest := *r.Last
var isIPv4 bool
var spanningMaskSize, bitLen, byteLen int
if lowest.To4() != nil {
isIPv4 = true
bitLen = ipv4BitLen
byteLen = net.IPv4len
} else {
bitLen = ipv6BitLen
byteLen = net.IPv6len
}
if isIPv4 {
spanningMaskSize = ipv4BitLen
} else {
spanningMaskSize = ipv6BitLen
}
// Convert to big Int so we can easily do bitshifting on the IP addresses,
// since golang only provides up to 64-bit unsigned integers.
lowestBig := big.NewInt(0).SetBytes(lowest)
highestBig := big.NewInt(0).SetBytes(highest)
// Starting from largest mask / smallest range possible, apply a mask one bit
// larger in each iteration to the upper bound in the range until we have
// masked enough to pass the lower bound in the range. This
// gives us the size of the prefix for the spanning CIDR to return as
// well as the IP for the CIDR prefix of the spanning CIDR.
for spanningMaskSize > 0 && lowestBig.Cmp(highestBig) < 0 {
spanningMaskSize--
mask := big.NewInt(1)
mask = mask.Lsh(mask, uint(bitLen-spanningMaskSize))
mask = mask.Mul(mask, big.NewInt(-1))
highestBig = highestBig.And(highestBig, mask)
}
// If ipv4, need to append 0s because math.Big gets rid of preceding zeroes.
if isIPv4 {
highest = append(ipv4LeadingZeroes, highestBig.Bytes()...)
} else {
highest = highestBig.Bytes()
}
// Int does not store leading zeroes.
if len(highest) == 0 {
highest = make([]byte, byteLen)
}
newNet := net.IPNet{IP: highest, Mask: net.CIDRMask(spanningMaskSize, bitLen)}
return newNet
}
type netWithRange struct {
First *net.IP
Last *net.IP
Network *net.IPNet
}
func mergeAdjacentCIDRs(ranges []*netWithRange) []*netWithRange {
// Sort the ranges. This sorts first by the last IP, then first IP, then by
// the IP network in the list itself
sort.Sort(NetsByRange(ranges))
// Merge adjacent CIDRs if possible.
for i := len(ranges) - 1; i > 0; i-- {
first1 := getPreviousIP(*ranges[i].First)
// Since the networks are sorted, we know that if a network in the list
// is adjacent to another one in the list, it will be the network next
// to it in the list. If the previous IP of the current network we are
// processing overlaps with the last IP of the previous network in the
// list, then we can merge the two ranges together.
if bytes.Compare(first1, *ranges[i-1].Last) <= 0 {
// Pick the minimum of the first two IPs to represent the start
// of the new range.
var minFirstIP *net.IP
if bytes.Compare(*ranges[i-1].First, *ranges[i].First) < 0 {
minFirstIP = ranges[i-1].First
} else {
minFirstIP = ranges[i].First
}
// Always take the last IP of the ith IP.
newRangeLast := make(net.IP, len(*ranges[i].Last))
copy(newRangeLast, *ranges[i].Last)
newRangeFirst := make(net.IP, len(*minFirstIP))
copy(newRangeFirst, *minFirstIP)
// Can't set the network field because since we are combining a
// range of IPs, and we don't yet know what CIDR prefix(es) represent
// the new range.
ranges[i-1] = &netWithRange{First: &newRangeFirst, Last: &newRangeLast, Network: nil}
// Since we have combined ranges[i] with the preceding item in the
// ranges list, we can delete ranges[i] from the slice.
ranges = append(ranges[:i], ranges[i+1:]...)
}
}
return ranges
}
// coalesceRanges converts ranges into an equivalent list of net.IPNets.
// All IPs in ranges should be of the same address family (IPv4 or IPv6).
func coalesceRanges(ranges []*netWithRange) []*net.IPNet {
coalescedCIDRs := []*net.IPNet{}
// Create CIDRs from ranges that were combined if needed.
for _, netRange := range ranges {
// If the Network field of netWithRange wasn't modified, then we can
// add it to the list which we will return, as it cannot be joined with
// any other CIDR in the list.
if netRange.Network != nil {
coalescedCIDRs = append(coalescedCIDRs, netRange.Network)
} else {
// We have joined two ranges together, so we need to find the new CIDRs
// that represent this range.
rangeCIDRs := rangeToCIDRs(*netRange.First, *netRange.Last)
coalescedCIDRs = append(coalescedCIDRs, rangeCIDRs...)
}
}
return coalescedCIDRs
}
// CoalesceCIDRs transforms the provided list of CIDRs into the most-minimal
// equivalent set of IPv4 and IPv6 CIDRs.
// It removes CIDRs that are subnets of other CIDRs in the list, and groups
// together CIDRs that have the same mask size into a CIDR of the same mask
// size provided that they share the same number of most significant
// mask-size bits.
//
// Note: this algorithm was ported from the Python library netaddr.
// https://github.com/drkjam/netaddr .
func CoalesceCIDRs(cidrs []*net.IPNet) ([]*net.IPNet, []*net.IPNet) {
ranges4 := []*netWithRange{}
ranges6 := []*netWithRange{}
for _, network := range cidrs {
newNetToRange := ipNetToRange(*network)
if network.IP.To4() != nil {
ranges4 = append(ranges4, &newNetToRange)
} else {
ranges6 = append(ranges6, &newNetToRange)
}
}
return coalesceRanges(mergeAdjacentCIDRs(ranges4)), coalesceRanges(mergeAdjacentCIDRs(ranges6))
}
// rangeToCIDRs converts the range of IPs covered by firstIP and lastIP to
// a list of CIDRs that contains all of the IPs covered by the range.
func rangeToCIDRs(firstIP, lastIP net.IP) []*net.IPNet {
// First, create a CIDR that spans both IPs.
spanningCIDR := createSpanningCIDR(netWithRange{&firstIP, &lastIP, nil})
spanningRange := ipNetToRange(spanningCIDR)
firstIPSpanning := spanningRange.First
lastIPSpanning := spanningRange.Last
cidrList := []*net.IPNet{}
// If the first IP of the spanning CIDR passes the lower bound (firstIP),
// we need to split the spanning CIDR and only take the IPs that are
// greater than the value which we split on, as we do not want the lesser
// values since they are less than the lower-bound (firstIP).
if bytes.Compare(*firstIPSpanning, firstIP) < 0 {
// Split on the previous IP of the first IP so that the right list of IPs
// of the partition includes the firstIP.
prevFirstRangeIP := getPreviousIP(firstIP)
var bitLen int
if prevFirstRangeIP.To4() != nil {
bitLen = ipv4BitLen
} else {
bitLen = ipv6BitLen
}
_, _, right := partitionCIDR(spanningCIDR, net.IPNet{IP: prevFirstRangeIP, Mask: net.CIDRMask(bitLen, bitLen)})
// Append all CIDRs but the first, as this CIDR includes the upper
// bound of the spanning CIDR, which we still need to partition on.
cidrList = append(cidrList, right...)
spanningCIDR = *right[0]
cidrList = cidrList[1:]
}
// Conversely, if the last IP of the spanning CIDR passes the upper bound
// (lastIP), we need to split the spanning CIDR and only take the IPs that
// are greater than the value which we split on, as we do not want the greater
// values since they are greater than the upper-bound (lastIP).
if bytes.Compare(*lastIPSpanning, lastIP) > 0 {
// Split on the next IP of the last IP so that the left list of IPs
// of the partition include the lastIP.
nextFirstRangeIP := GetNextIP(lastIP)
var bitLen int
if nextFirstRangeIP.To4() != nil {
bitLen = ipv4BitLen
} else {
bitLen = ipv6BitLen
}
left, _, _ := partitionCIDR(spanningCIDR, net.IPNet{IP: nextFirstRangeIP, Mask: net.CIDRMask(bitLen, bitLen)})
cidrList = append(cidrList, left...)
} else {
// Otherwise, there is no need to partition; just use add the spanning
// CIDR to the list of networks.
cidrList = append(cidrList, &spanningCIDR)
}
return cidrList
}
// partitionCIDR returns a list of IP Networks partitioned upon excludeCIDR.
// The first list contains the networks to the left of the excludeCIDR in the
// partition, the second is a list containing the excludeCIDR itself if it is
// contained within the targetCIDR (nil otherwise), and the
// third is a list containing the networks to the right of the excludeCIDR in
// the partition.
func partitionCIDR(targetCIDR net.IPNet, excludeCIDR net.IPNet) ([]*net.IPNet, []*net.IPNet, []*net.IPNet) {
var targetIsIPv4 bool
if targetCIDR.IP.To4() != nil {
targetIsIPv4 = true
}
targetIPRange := ipNetToRange(targetCIDR)
excludeIPRange := ipNetToRange(excludeCIDR)
targetFirstIP := *targetIPRange.First
targetLastIP := *targetIPRange.Last
excludeFirstIP := *excludeIPRange.First
excludeLastIP := *excludeIPRange.Last
targetMaskSize, _ := targetCIDR.Mask.Size()
excludeMaskSize, _ := excludeCIDR.Mask.Size()
if bytes.Compare(excludeLastIP, targetFirstIP) < 0 {
return nil, nil, []*net.IPNet{&targetCIDR}
} else if bytes.Compare(targetLastIP, excludeFirstIP) < 0 {
return []*net.IPNet{&targetCIDR}, nil, nil
}
if targetMaskSize >= excludeMaskSize {
return nil, []*net.IPNet{&targetCIDR}, nil
}
left := []*net.IPNet{}
right := []*net.IPNet{}
newPrefixLen := targetMaskSize + 1
targetFirstCopy := make(net.IP, len(targetFirstIP))
copy(targetFirstCopy, targetFirstIP)
iLowerOld := make(net.IP, len(targetFirstCopy))
copy(iLowerOld, targetFirstCopy)
// Since golang only supports up to unsigned 64-bit integers, and we need
// to perform addition on addresses, use math/big library, which allows
// for manipulation of large integers.
// Used to track the current lower and upper bounds of the ranges to compare
// to excludeCIDR.
iLower := big.NewInt(0)
iUpper := big.NewInt(0)
iLower = iLower.SetBytes(targetFirstCopy)
var bitLen int
if targetIsIPv4 {
bitLen = ipv4BitLen
} else {
bitLen = ipv6BitLen
}
shiftAmount := (uint)(bitLen - newPrefixLen)
targetIPInt := big.NewInt(0)
targetIPInt.SetBytes(targetFirstIP.To16())
exp := big.NewInt(0)
// Use left shift for exponentiation
exp = exp.Lsh(big.NewInt(1), shiftAmount)
iUpper = iUpper.Add(targetIPInt, exp)
matched := big.NewInt(0)
for excludeMaskSize >= newPrefixLen {
// Append leading zeros to IPv4 addresses, as math.Big.Int does not
// append them when the IP address is copied from a byte array to
// math.Big.Int. Leading zeroes are required for parsing IPv4 addresses
// for use with net.IP / net.IPNet.
var iUpperBytes, iLowerBytes []byte
if targetIsIPv4 {
iUpperBytes = append(ipv4LeadingZeroes, iUpper.Bytes()...)
iLowerBytes = append(ipv4LeadingZeroes, iLower.Bytes()...)
} else {
iUpperBytesLen := len(iUpper.Bytes())
// Make sure that the number of bytes in the array matches what net
// package expects, as big package doesn't append leading zeroes.
if iUpperBytesLen != net.IPv6len {
numZeroesToAppend := net.IPv6len - iUpperBytesLen
zeroBytes := make([]byte, numZeroesToAppend)
iUpperBytes = append(zeroBytes, iUpper.Bytes()...)
} else {
iUpperBytes = iUpper.Bytes()
}
iLowerBytesLen := len(iLower.Bytes())
if iLowerBytesLen != net.IPv6len {
numZeroesToAppend := net.IPv6len - iLowerBytesLen
zeroBytes := make([]byte, numZeroesToAppend)
iLowerBytes = append(zeroBytes, iLower.Bytes()...)
} else {
iLowerBytes = iLower.Bytes()
}
}
// If the IP we are excluding over is of a higher value than the current
// CIDR prefix we are generating, add the CIDR prefix to the set of IPs
// to the left of the exclude CIDR
if bytes.Compare(excludeFirstIP, iUpperBytes) >= 0 {
left = append(left, &net.IPNet{IP: iLowerBytes, Mask: net.CIDRMask(newPrefixLen, bitLen)})
matched = matched.Set(iUpper)
} else {
// Same as above, but opposite.
right = append(right, &net.IPNet{IP: iUpperBytes, Mask: net.CIDRMask(newPrefixLen, bitLen)})
matched = matched.Set(iLower)
}
newPrefixLen++
if newPrefixLen > bitLen {
break
}
iLower = iLower.Set(matched)
iUpper = iUpper.Add(matched, big.NewInt(0).Lsh(big.NewInt(1), uint(bitLen-newPrefixLen)))
}
excludeList := []*net.IPNet{&excludeCIDR}
return left, excludeList, right
}
// KeepUniqueIPs transforms the provided multiset of IPs into a single set,
// lexicographically sorted via a byte-wise comparison of the IP slices (i.e.
// IPv4 addresses show up before IPv6).
// The slice is manipulated in-place destructively.
//
// 1- Sort the slice by comparing the IPs as bytes
// 2- For every unseen unique IP in the sorted slice, move it to the end of
// the return slice.
// Note that the slice is always large enough and, because it is sorted, we
// will not overwrite a valid element with another. To overwrite an element i
// with j, i must have come before j AND we decided it was a duplicate of the
// element at i-1.
func KeepUniqueIPs(ips []net.IP) []net.IP {
sort.Slice(ips, func(i, j int) bool {
return bytes.Compare(ips[i], ips[j]) == -1
})
returnIPs := ips[:0] // len==0 but cap==cap(ips)
for readIdx, ip := range ips {
if len(returnIPs) == 0 ||
bytes.Compare(returnIPs[len(returnIPs)-1], ips[readIdx]) != 0 {
returnIPs = append(returnIPs, ip)
}
}
return returnIPs
}
| {
"content_hash": "08db3fdf2e84b4a8d94c6f5f13c70ed2",
"timestamp": "",
"source": "github",
"line_count": 730,
"max_line_length": 123,
"avg_line_length": 31.221917808219178,
"alnum_prop": 0.6944980694980695,
"repo_name": "scanf/cilium",
"id": "ccd7a4f0efc5dbe585aa7135bcad31f593140cf4",
"size": "23387",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pkg/ip/ip.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "660212"
},
{
"name": "C++",
"bytes": "6177"
},
{
"name": "Dockerfile",
"bytes": "4492"
},
{
"name": "Go",
"bytes": "4476462"
},
{
"name": "Makefile",
"bytes": "25535"
},
{
"name": "Perl 6",
"bytes": "4948"
},
{
"name": "Python",
"bytes": "10259"
},
{
"name": "Ruby",
"bytes": "11622"
},
{
"name": "Shell",
"bytes": "225848"
},
{
"name": "TeX",
"bytes": "416"
},
{
"name": "sed",
"bytes": "4191"
}
],
"symlink_target": ""
} |
package net.minidev.ovh.api.dedicatedcloud.host;
/**
* All states a Dedicated Cloud Host can be in
*/
public enum OvhStateEnum {
adding("adding"),
delivered("delivered"),
error("error"),
removing("removing"),
unknown("unknown");
final String value;
OvhStateEnum(String s) {
this.value = s;
}
public String toString() {
return this.value;
}
}
| {
"content_hash": "4d3d6ea6eaf1666c500fa269a7c61d92",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 48,
"avg_line_length": 16.454545454545453,
"alnum_prop": 0.6850828729281768,
"repo_name": "UrielCh/ovh-java-sdk",
"id": "635a49b14ad3e1672644d04fdffbb737a983e92c",
"size": "362",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ovh-java-sdk-dedicatedCloud/src/main/java/net/minidev/ovh/api/dedicatedcloud/host/OvhStateEnum.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "5788982"
}
],
"symlink_target": ""
} |
@interface ShufflingView ()
@property(nonatomic, assign) int startIndex;
@property(nonatomic, assign) int endIndex;
@property(nonatomic, strong) UIView *view;
@property(nonatomic, strong) UIImageView *imageView;
@property(nonatomic, strong) UIImageView *imageViewOne;
@property(nonatomic, assign) CGRect selfrect;
@property(nonatomic, strong) NSTimer *timer;
@property(nonatomic,assign) CGFloat magnification;
@end
@implementation ShufflingView
- (void)setImageNameArray:(NSArray *)imageNameArray {
_imageNameArray = imageNameArray;
if (self.amplification) {
self.magnification = self.amplification;
}else{
self.magnification = 1.2;
}
[self setView];
}
- (void)setView {
UIView *view = [[UIView alloc] initWithFrame:self.frame];
[self addSubview:view];
view.userInteractionEnabled = YES;
self.view = view;
self.view.clipsToBounds = YES;
self.startIndex = 1;
// 第一个 imageView;
UIImageView *imageView = [[UIImageView alloc]
initWithImage:[UIImage imageNamed:self.imageNameArray[0]]];
self.imageView = imageView;
imageView.frame = self.view.frame;
[self.view addSubview:imageView];
NSString *imageName = self.imageNameArray[1];
// 第二个 imageView
UIImageView *imageviewOne =
[[UIImageView alloc] initWithImage:[UIImage imageNamed:imageName]];
imageviewOne.alpha = 0.0;
imageviewOne.bounds = CGRectMake(0, 0, self.view.frame.size.width * self.magnification,
self.view.frame.size.height * self.magnification);
imageviewOne.center = self.view.center;
self.imageViewOne = imageviewOne;
[self.view addSubview:imageviewOne];
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:self.animateDelay
target:self
selector:@selector(shuffling)
userInfo:nil
repeats:YES];
self.timer = timer;
UIButton *button = [[UIButton alloc] initWithFrame:self.view.frame];
[button addTarget:self
action:@selector(ClickImage:)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
}
return self;
}
- (void)ClickImage:(UITapGestureRecognizer *)recognizer {
// NSLog(@"点击了图片.现在的图片 tag
// 是%@",self.imageNameArray[self.endstartIndex]);
if (self.delegate) {
[self.delegate ClickImageView:self imageNameArrayIndex:self.endIndex];
}
}
- (void)shuffling {
self.startIndex++;
if (self.startIndex > self.imageNameArray.count - 1) {
self.startIndex = 0;
}
self.endIndex = self.startIndex - 1;
if (self.endIndex < 0) {
self.endIndex = (int)self.imageNameArray.count - 1;
}
self.imageView.alpha = 1.0;
if ([self.delegate respondsToSelector:@selector(shufflingView:
presentImageNameArrayindex:)]) {
[self.delegate shufflingView:self presentImageNameArrayindex:self.endIndex];
}
NSString *imageName = self.imageNameArray[self.startIndex];
NSString *imageName1 = self.imageNameArray[self.endIndex];
[UIView animateWithDuration:1.0
animations:^{
self.imageView.alpha = 0.0;
self.imageView.center = self.view.center;
self.imageView.bounds =
CGRectMake(0, 0, self.view.frame.size.width * self.magnification,
self.view.frame.size.height * self.magnification);
self.imageViewOne.alpha = 1.0;
self.imageViewOne.bounds = self.view.frame;
}
completion:^(BOOL finished) {
self.imageViewOne.image = [UIImage imageNamed:imageName];
self.imageView.image = [UIImage imageNamed:imageName1];
self.imageViewOne.bounds =
CGRectMake(0, 0, self.view.frame.size.width * self.magnification,
self.view.frame.size.height * self.magnification);
self.imageViewOne.alpha = 0.0;
self.imageView.frame = self.view.bounds;
self.imageView.alpha = 1.0;
}];
}
//重写 set 方法.在赋值的时候.做跳转的动画
- (void)setPresentIndex:(int)presentIndex {
if (self.endIndex == presentIndex) {
NSLog(@"相同.直接跳出去");
return;
}
_presentIndex = presentIndex;
//关闭定时器
[self.timer invalidate];
self.timer = nil;
NSLog(@"当前%d,目标%d", self.endIndex, presentIndex);
self.imageViewOne.alpha = 0.0;
self.imageView.image =
[UIImage imageNamed:self.imageNameArray[self.endIndex]];
self.imageViewOne.image =
[UIImage imageNamed:self.imageNameArray[presentIndex]];
self.startIndex = presentIndex;
[UIView animateWithDuration:0.5
animations:^{
self.imageView.alpha = 0.0;
self.imageView.center = self.view.center;
self.imageView.bounds =
CGRectMake(0, 0, self.view.frame.size.width * self.magnification,
self.view.frame.size.height * self.magnification);
self.imageViewOne.alpha = 1.0;
self.imageViewOne.bounds = self.view.frame;
}
completion:^(BOOL finished) {
self.timer =
[NSTimer scheduledTimerWithTimeInterval:self.animateDelay
target:self
selector:@selector(shuffling)
userInfo:nil
repeats:YES];
}];
// 当前图片下标
}
@end
| {
"content_hash": "39756bbf87606bd0833e0a2e9230d1b4",
"timestamp": "",
"source": "github",
"line_count": 206,
"max_line_length": 89,
"avg_line_length": 27.07766990291262,
"alnum_prop": 0.6281821441376838,
"repo_name": "xixisplit/net",
"id": "4199da625a095f0383c01bef38e265ad71b2eabd",
"size": "5848",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "图片轮播器/图片轮播器/ShufflingView.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "130609"
}
],
"symlink_target": ""
} |
import subprocess
import sys
from uqbar.graphs import Grapher
import supriya
class Player:
### INITIALIZER ###
def __init__(self, renderable, **kwargs):
self.renderable = renderable
self.render_kwargs = kwargs
### SPECIAL METHODS ###
def __call__(self):
output_path = self.render()
self.open_output_path(output_path)
return output_path
### PUBLIC METHODS ###
def open_output_path(self, output_path):
viewer = "open -a 'QuickTime Player'"
if sys.platform.lower().startswith("linux"):
viewer = "xdg-open"
subprocess.run(f"{viewer} {output_path}", shell=True, check=True)
def render(self):
return self.renderable.__render__(**self.render_kwargs)
def graph(graphable, format_="pdf", layout="dot", verbose=False):
return Grapher(
graphable,
format_=format_,
layout=layout,
output_directory=supriya.output_path,
verbose=verbose,
)()
def play(renderable, **kwargs):
return Player(renderable, **kwargs)()
def render(renderable, output_file_path=None, render_directory_path=None, **kwargs):
return renderable.__render__(
output_file_path=output_file_path,
render_directory_path=render_directory_path,
**kwargs,
)
__all__ = ["Player", "graph", "play", "render"]
| {
"content_hash": "4ce0c28983265e49a338e4d40b8464a8",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 84,
"avg_line_length": 23.56896551724138,
"alnum_prop": 0.6166788588149232,
"repo_name": "Pulgama/supriya",
"id": "1336cfc902b5d2c1e27884dd7d9120311595712f",
"size": "1367",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "supriya/io.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "6712"
},
{
"name": "CSS",
"bytes": "446"
},
{
"name": "HTML",
"bytes": "1083"
},
{
"name": "JavaScript",
"bytes": "6163"
},
{
"name": "Makefile",
"bytes": "6775"
},
{
"name": "Python",
"bytes": "2790612"
},
{
"name": "Shell",
"bytes": "569"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "2dacda5134587db484add1e43571bd43",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "9931ce7e142f98182a88b09d550f19de5199fb8c",
"size": "210",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Liliopsida/Liliales/Liliaceae/Gagea/Gagea bohemica/ Syn. Gagea szovitsii/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeCamp.Models
{
public class Track
{
public string Color { get; set; }
public string Description { get; set; }
public string Name { get; set; }
public int TrackId { get; set; }
}
}
| {
"content_hash": "397a148ab44d0a21d88797fcdf0ae391",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 43,
"avg_line_length": 19.647058823529413,
"alnum_prop": 0.688622754491018,
"repo_name": "jamesmontemagno/code-camp-app",
"id": "c9de6246d54d323cbfd60f2eff8f4cd2c242b7e3",
"size": "336",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CodeCamp/Models/Track.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "76612"
}
],
"symlink_target": ""
} |
package negroni
import (
"fmt"
"log"
"net/http"
"os"
"runtime"
"runtime/debug"
)
// Recovery is a Negroni middleware that recovers from any panics and writes a 500 if there was one.
type Recovery struct {
Logger *log.Logger
PrintStack bool
ErrorHandlerFunc func(interface{})
StackAll bool
StackSize int
}
// NewRecovery returns a new instance of Recovery
func NewRecovery() *Recovery {
return &Recovery{
Logger: log.New(os.Stdout, "[negroni] ", 0),
PrintStack: true,
StackAll: false,
StackSize: 1024 * 8,
}
}
func (rec *Recovery) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
defer func() {
if err := recover(); err != nil {
if rw.Header().Get("Content-Type") == "" {
rw.Header().Set("Content-Type", "text/plain; charset=utf-8")
}
rw.WriteHeader(http.StatusInternalServerError)
stack := make([]byte, rec.StackSize)
stack = stack[:runtime.Stack(stack, rec.StackAll)]
f := "PANIC: %s\n%s"
rec.Logger.Printf(f, err, stack)
if rec.PrintStack {
fmt.Fprintf(rw, f, err, stack)
}
if rec.ErrorHandlerFunc != nil {
func() {
defer func() {
if err := recover(); err != nil {
rec.Logger.Printf("provided ErrorHandlerFunc panic'd: %s, trace:\n%s", err, debug.Stack())
rec.Logger.Printf("%s\n", debug.Stack())
}
}()
rec.ErrorHandlerFunc(err)
}()
}
}
}()
next(rw, r)
}
| {
"content_hash": "241def67c5b21f403d0ad1ac07488f02",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 100,
"avg_line_length": 22.307692307692307,
"alnum_prop": 0.6193103448275862,
"repo_name": "akanto/traefik",
"id": "1fb19981d3bc3e3decb8f8d9a3feb90972f50d52",
"size": "1450",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "vendor/github.com/codegangsta/negroni/recovery.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1551"
},
{
"name": "Go",
"bytes": "600394"
},
{
"name": "HTML",
"bytes": "7391"
},
{
"name": "JavaScript",
"bytes": "23029"
},
{
"name": "Makefile",
"bytes": "2919"
},
{
"name": "Shell",
"bytes": "17291"
}
],
"symlink_target": ""
} |
namespace Lucene
{
/// This attribute can be used to pass different flags down the tokenizer chain, eg from one TokenFilter
/// to another one.
class LPPAPI FlagsAttribute : public Attribute
{
public:
FlagsAttribute();
virtual ~FlagsAttribute();
LUCENE_CLASS(FlagsAttribute);
protected:
int32_t flags;
public:
virtual String toString();
/// Get the bitset for any bits that have been set. This is completely distinct from {@link
/// TypeAttribute#type()}, although they do share similar purposes. The flags can be used to encode
/// information about the token for use by other {@link TokenFilter}s.
virtual int32_t getFlags();
/// @see #getFlags()
virtual void setFlags(int32_t flags);
virtual void clear();
virtual bool equals(LuceneObjectPtr other);
virtual int32_t hashCode();
virtual void copyTo(AttributePtr target);
virtual LuceneObjectPtr clone(LuceneObjectPtr other = LuceneObjectPtr());
};
}
#endif
| {
"content_hash": "fee069cd30cd399c24a57ab7542a64d2",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 109,
"avg_line_length": 31.52777777777778,
"alnum_prop": 0.6158590308370044,
"repo_name": "ustramooner/LucenePlusPlus",
"id": "be7478e32fab5233fd93b22f4b148c3bab78883d",
"size": "1549",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "include/FlagsAttribute.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "2124374"
},
{
"name": "C++",
"bytes": "6187446"
},
{
"name": "Python",
"bytes": "159441"
}
],
"symlink_target": ""
} |
'use strict';
/**
* @private
* @description Module dependencies.
*/
var http = require('http');
var querystring = require('querystring');
var escapeJSON = require('escape-json-node');
var trim = require('deep-trim-node');
/**
* @private
* @constant {String}
* @description Module version.
*/
var VERSION = require('../package.json').version;
/**
* @public
* @constructor
* @description Initialize instance of Forismatic with default request options.
* @property {Object} defaultRequestOptions - Default request options.
* @property {String} defaultRequestOptions.hostname - Default request hostname.
* @property {Number} defaultRequestOptions.port - Default request port.
* @property {String} defaultRequestOptions.basePath - Default request base path.
*/
function Forismatic() {
this.defaultRequestOptions = {
hostname: 'api.forismatic.com',
port: 80,
basePath: '/api/1.0/'
};
}
/**
* @public
* @function getQuote
* @description Request random quote.
* @param {Object} [options] - Optional request parameters.
* @param {String} [options.lang] - Response language ('en' or 'ru').
* @param {Number|String} [options.key] - Influence the choice of quotation, the maximum length is 6 characters.
* @param {Boolean} [options.generateKey] - Determine whether numeric key is auto-generated.
* @param {getQuote~callback} callback - Callback when response comes in.
*/
Forismatic.prototype.getQuote = function (options, callback) {
if ((typeof options === 'function') || (options instanceof Function)) {
callback = options;
} else if ((typeof callback !== 'function') || !(callback instanceof Function)) {
throw new Error('getQuote(): callback is undefined or contains non-function value');
}
var requestParameters = {
method: 'getQuote',
format: 'json',
lang: options.lang || 'en'
};
if (options.generateKey === true) {
requestParameters.key = generateKey();
} else {
if(options.key) {
requestParameters.key = options.key;
}
}
var request = http.get({
hostname: this.defaultRequestOptions.hostname,
port: this.defaultRequestOptions.port,
path: this.defaultRequestOptions.basePath + '?' + querystring.stringify(requestParameters),
headers: {
'Accept': 'application/json',
'Accept-Charset': 'utf-8',
'Accept-Encoding': '*',
'Accept-Language': options.lang ? options.lang : 'en',
'Accept-Datetime': new Date().toUTCString(),
'Cache-Control': 'no-cache',
'Connection': 'close',
'Date': new Date().toUTCString(),
'Host': this.defaultRequestOptions.hostname,
'Max-Forwards': 1,
'Pragma': 'no-cache',
'TE': 'trailers, deflate',
'User-Agent': 'forismatic-node/' + VERSION
},
agent: false,
keepAlive: false
}, function (response) {
var rawResponse = '';
response.on('data', function (data) {
rawResponse += data;
});
response.on('end', function () {
var parsedResponse;
try {
parsedResponse = JSON.parse(escapeJSON(rawResponse));
} catch (error) {
return callback(error);
}
callback(null, trim(parsedResponse));
});
response.on('error', function (error) {
callback(error);
});
});
request.on('error', function (error) {
callback(error);
});
};
/**
* @callback getQuote~callback
* @description Use as callback in getQuote function.
* @param {Object} error - Generic error object.
* @param {Object} quote - Quote object.
*/
/**
* @private
* @function generateKey
* @description Generate numeric key with maximum length of 6 digits.
* @returns {Number} - Generated numeric key.
*/
function generateKey() {
return Math.floor(Math.random() * (999999 - 1 + 1)) + 1;
}
/**
* @public
* @description Expose instance of Forismatic.
* @returns {Object} - Instance of Forismatic.
*/
module.exports = function () {
return new Forismatic();
};
| {
"content_hash": "2b52915ff8cb47a53ad44d6f5e288c8d",
"timestamp": "",
"source": "github",
"line_count": 143,
"max_line_length": 112,
"avg_line_length": 29.573426573426573,
"alnum_prop": 0.6100733033814141,
"repo_name": "AnatoliyGatt/forismatic-node",
"id": "49161cf08aa20ba466b4eb7ab308cb38010fb262",
"size": "4436",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/forismatic.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "10870"
}
],
"symlink_target": ""
} |
var cordova = require('../src/cordova/cordova'),
console = require('console'),
path = require('path'),
shell = require('shelljs'),
fs = require('fs'),
Q = require('q'),
util = require('../src/cordova/util'),
hooker = require('../src/cordova/hooker'),
tempDir,
http = require('http'),
firefoxos_parser = require('../src/cordova/metadata/firefoxos_parser'),
android_parser = require('../src/cordova/metadata/android_parser'),
ios_parser = require('../src/cordova/metadata/ios_parser'),
blackberry_parser = require('../src/cordova/metadata/blackberry10_parser'),
wp8_parser = require('../src/cordova/metadata/wp8_parser');
var cwd = process.cwd();
describe('serve command', function() {
var payloads = {},
consoleSpy;
beforeEach(function() {
// Make a temp directory
tempDir = path.join(__dirname, '..', 'temp-' + Date.now());
shell.rm('-rf', tempDir);
shell.mkdir('-p', tempDir);
consoleSpy = spyOn(console, 'log');
});
afterEach(function() {
process.chdir(cwd);
process.env.PWD = cwd;
shell.rm('-rf', tempDir);
})
it('should not run outside of a Cordova-based project', function() {
process.chdir(tempDir);
expect(function() {
cordova.serve().then(function(server) {
expect(server).toBe(null);
server.close();
});
}).toThrow("Current working directory is not a Cordova-based project.");
});
describe('`serve`', function() {
var done = false, failed = false;
beforeEach(function() {
done = false;
failed = false;
});
afterEach(function() {
payloads = {};
});
function cit(cond) {
if (cond) {
return it;
}
return xit;
}
function itifapps(apps) {
return cit(apps.every(function (bin) {return shell.which(bin);}));
}
function test_serve(platform, ref, expectedContents, opts) {
var timeout = opts && 'timeout' in opts && opts.timeout || 1000;
return function() {
var server;
runs(function() {
cordova.raw.create(tempDir).then(function () {
process.chdir(tempDir);
process.env.PWD = tempDir;
var plats = [];
Object.getOwnPropertyNames(payloads).forEach(function(plat) {
var d = Q.defer();
plats.push(d.promise);
cordova.raw.platform('add', plat, {spawnoutput:'ignore'}).then(function () {
var dir = path.join(tempDir, 'merges', plat);
shell.mkdir('-p', dir);
// Write testing HTML files into the directory.
fs.writeFileSync(path.join(dir, 'test.html'), payloads[plat]);
d.resolve();
}).catch(function (e) {
expect(e).toBeUndefined();
failed = true;
});
});
Q.allSettled(plats).then(function () {
opts && 'setup' in opts && opts.setup();
cordova.serve(opts && 'port' in opts && opts.port).then(function (srv) {
server = srv;
});
}).catch(function (e) {
expect(e).toBeUndefined();
failed = true;
});
}).catch(function (e) {
expect(e).toBeUndefined();
failed = true;
});
});
waitsFor(function() {
return server || failed;
}, 'the server should start', timeout);
var done, errorCB;
runs(function() {
if (failed) {
return;
}
expect(server).toBeDefined();
errorCB = jasmine.createSpy();
http.get({
host: 'localhost',
port: opts && 'port' in opts ? opts.port : 8000,
path: '/' + platform + '/www' + ref,
connection: 'Close'
}).on('response', function(res) {
var response = '';
res.on('data', function(data) {
response += data;
});
res.on('end', function() {
expect(response).toEqual(expectedContents)
if (response === expectedContents) {
expect(res.statusCode).toEqual(200);
}
done = true;
});
}).on('error', errorCB);
});
waitsFor(function() {
return done || failed;
}, 'the HTTP request should complete', timeout);
runs(function() {
if (!failed) {
expect(done).toBeTruthy();
expect(errorCB).not.toHaveBeenCalled();
}
opts && 'cleanup' in opts && opts.cleanup();
server && server.close();
});
};
};
it('should serve from top-level www if the file exists there', function() {
var payload = 'This is test file.';
payloads.firefoxos = 'This is the firefoxos test file.'
test_serve('firefoxos', '/basictest.html', payload, {
setup: function (){
fs.writeFileSync(path.join(util.projectWww(tempDir), 'basictest.html'), payload);
}
})();
});
it('should honour a custom port setting', function() {
var payload = 'This is test file.';
payloads.firefoxos = 'This is the firefoxos test file.'
test_serve('firefoxos', '/basictest.html', payload, {
port: 9001,
setup: function (){
fs.writeFileSync(path.join(util.projectWww(tempDir), 'basictest.html'), payload);
}
})();
});
itifapps([
'android',
'ant',
])('should fall back to assets/www on Android', function() {
payloads.android = 'This is the Android test file.';
test_serve('android', '/test.html', payloads.android, {timeout: 20000})();
});
itifapps([
'blackberry-nativepackager',
'blackberry-deploy',
'blackberry-signer',
'blackberry-debugtokenrequest',
])('should fall back to www on BlackBerry10', function() {
payloads.blackberry10 = 'This is the BlackBerry10 test file.';
test_serve('blackberry10', '/test.html', payloads.blackberry10, {timeout: 10000})();
});
itifapps([
'xcodebuild',
])('should fall back to www on iOS', function() {
payloads.ios = 'This is the iOS test file.';
test_serve('ios', '/test.html', payloads.ios, {timeout: 10000})();
});
it('should fall back to www on firefoxos', function() {
payloads.firefoxos = 'This is the firefoxos test file.';
test_serve('firefoxos', '/test.html', payloads.firefoxos)();
});
});
});
| {
"content_hash": "f5c5e2a7cc102461cf8a90ebdf283022",
"timestamp": "",
"source": "github",
"line_count": 203,
"max_line_length": 104,
"avg_line_length": 39.073891625615765,
"alnum_prop": 0.4466717095310136,
"repo_name": "blackberry-webworks/cordova-lib",
"id": "e74c99d147890c84d1d9e4eee8ea2112ac70b203",
"size": "8747",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cordova-lib/spec-cordova/serve.spec.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "1846"
},
{
"name": "C#",
"bytes": "27860"
},
{
"name": "C++",
"bytes": "191338"
},
{
"name": "CSS",
"bytes": "11157"
},
{
"name": "Java",
"bytes": "123293"
},
{
"name": "JavaScript",
"bytes": "383024"
},
{
"name": "Matlab",
"bytes": "4"
},
{
"name": "Objective-C",
"bytes": "154614"
},
{
"name": "Shell",
"bytes": "26870"
}
],
"symlink_target": ""
} |
from django import forms
from django.forms.utils import ErrorList
from crits.campaigns.campaign import Campaign
from crits.core.forms import add_bucketlist_to_form, add_ticket_to_form
from crits.core.handlers import get_item_names, get_source_names
from crits.core.user_tools import get_user_organization
from crits.core import form_consts
from crits.vocabulary.relationships import RelationshipTypes
relationship_choices = [(c, c) for c in RelationshipTypes.values(sort=True)]
class AddExploitForm(forms.Form):
"""
Django form for adding an Exploit to CRITs.
"""
error_css_class = 'error'
required_css_class = 'required'
name = forms.CharField(label=form_consts.Exploit.NAME, required=True)
cve = forms.CharField(label=form_consts.Exploit.CVE, required=False)
description = forms.CharField(label=form_consts.Exploit.DESCRIPTION,
required=False)
campaign = forms.ChoiceField(widget=forms.Select,
label=form_consts.Exploit.CAMPAIGN,
required=False)
confidence = forms.ChoiceField(label=form_consts.Exploit.CAMPAIGN_CONFIDENCE,
required=False)
source = forms.ChoiceField(widget=forms.Select(attrs={'class': 'bulknoinitial'}),
label=form_consts.Exploit.SOURCE,
required=True)
source_method = forms.CharField(label=form_consts.Exploit.SOURCE_METHOD,
required=False)
source_reference = forms.CharField(widget=forms.TextInput(attrs={'size': '90'}),
label=form_consts.Exploit.SOURCE_REFERENCE,
required=False)
related_id = forms.CharField(widget=forms.HiddenInput(), required=False)
related_type = forms.CharField(widget=forms.HiddenInput(), required=False)
relationship_type = forms.ChoiceField(required=False,
label='Relationship Type',
widget=forms.Select(attrs={'id':'relationship_type'}))
def __init__(self, username, *args, **kwargs):
super(AddExploitForm, self).__init__(*args, **kwargs)
self.fields['campaign'].choices = [('', '')] + [
(c.name, c.name) for c in get_item_names(Campaign, True)]
self.fields['confidence'].choices = [
('', ''),
('low', 'low'),
('medium', 'medium'),
('high', 'high')]
self.fields['source'].choices = [
(c.name, c.name) for c in get_source_names(True, True, username)]
self.fields['source'].initial = get_user_organization(username)
self.fields['relationship_type'].choices = relationship_choices
self.fields['relationship_type'].initial = RelationshipTypes.RELATED_TO
add_bucketlist_to_form(self)
add_ticket_to_form(self)
def clean(self):
cleaned_data = super(AddExploitForm, self).clean()
campaign = cleaned_data.get('campaign')
if campaign:
confidence = cleaned_data.get('confidence')
if not confidence or confidence == '':
self._errors.setdefault('confidence', ErrorList())
self._errors['confidence'].append(u'This field is required if campaign is specified.')
return cleaned_data
| {
"content_hash": "f3293e7955a49782476c8c9434e9065b",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 102,
"avg_line_length": 46.2972972972973,
"alnum_prop": 0.6088733216579101,
"repo_name": "ckane/crits",
"id": "80ec35547cff3fb96acd3c279a4a254801ec8a3a",
"size": "3426",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "crits/exploits/forms.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "8694"
},
{
"name": "CSS",
"bytes": "390510"
},
{
"name": "HTML",
"bytes": "478069"
},
{
"name": "JavaScript",
"bytes": "3555668"
},
{
"name": "Python",
"bytes": "2002476"
},
{
"name": "Shell",
"bytes": "20173"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
De nuttige planten van Nederlandsch Indië, Edn 2, I 1: 78 (1927)
#### Original name
Pleurotus anas Overeem
### Remarks
null | {
"content_hash": "27d222bf0303a4a7fae9a60a49446059",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 64,
"avg_line_length": 14.384615384615385,
"alnum_prop": 0.7165775401069518,
"repo_name": "mdoering/backbone",
"id": "3fab53063d82e34887fd8fffe10c4a617e06f1fe",
"size": "234",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Pleurotaceae/Pleurotus/Pleurotus anas/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
#include <srs_app_http_api.hpp>
#ifdef SRS_AUTO_HTTP_API
#include <sstream>
#include <stdlib.h>
#include <signal.h>
using namespace std;
#include <srs_kernel_log.hpp>
#include <srs_kernel_error.hpp>
#include <srs_app_st.hpp>
#include <srs_core_autofree.hpp>
#include <srs_protocol_json.hpp>
#include <srs_kernel_utility.hpp>
#include <srs_app_utility.hpp>
#include <srs_app_statistic.hpp>
#include <srs_rtmp_stack.hpp>
#include <srs_app_dvr.hpp>
#include <srs_app_config.hpp>
#include <srs_app_source.hpp>
#include <srs_app_http_conn.hpp>
#include <srs_kernel_consts.hpp>
#include <srs_app_server.hpp>
#include <srs_protocol_amf0.hpp>
int srs_api_response_jsonp(ISrsHttpResponseWriter* w, string callback, string data)
{
int ret = ERROR_SUCCESS;
SrsHttpHeader* h = w->header();
h->set_content_length(data.length() + callback.length() + 2);
h->set_content_type("text/javascript");
if (!callback.empty() && (ret = w->write((char*)callback.data(), (int)callback.length())) != ERROR_SUCCESS) {
return ret;
}
static char* c0 = (char*)"(";
if ((ret = w->write(c0, 1)) != ERROR_SUCCESS) {
return ret;
}
if ((ret = w->write((char*)data.data(), (int)data.length())) != ERROR_SUCCESS) {
return ret;
}
static char* c1 = (char*)")";
if ((ret = w->write(c1, 1)) != ERROR_SUCCESS) {
return ret;
}
return ret;
}
int srs_api_response_jsonp_code(ISrsHttpResponseWriter* w, string callback, int code)
{
SrsJsonObject* obj = SrsJsonAny::object();
SrsAutoFree(SrsJsonObject, obj);
obj->set("code", SrsJsonAny::integer(code));
return srs_api_response_jsonp(w, callback, obj->dumps());
}
int srs_api_response_json(ISrsHttpResponseWriter* w, string data)
{
SrsHttpHeader* h = w->header();
h->set_content_length(data.length());
h->set_content_type("application/json");
return w->write((char*)data.data(), (int)data.length());
}
int srs_api_response_json_code(ISrsHttpResponseWriter* w, int code)
{
SrsJsonObject* obj = SrsJsonAny::object();
SrsAutoFree(SrsJsonObject, obj);
obj->set("code", SrsJsonAny::integer(code));
return srs_api_response_json(w, obj->dumps());
}
int srs_api_response(ISrsHttpResponseWriter* w, ISrsHttpMessage* r, std::string json)
{
// no jsonp, directly response.
if (!r->is_jsonp()) {
return srs_api_response_json(w, json);
}
// jsonp, get function name from query("callback")
string callback = r->query_get("callback");
return srs_api_response_jsonp(w, callback, json);
}
int srs_api_response_code(ISrsHttpResponseWriter* w, ISrsHttpMessage* r, int code)
{
// no jsonp, directly response.
if (!r->is_jsonp()) {
return srs_api_response_json_code(w, code);
}
// jsonp, get function name from query("callback")
string callback = r->query_get("callback");
return srs_api_response_jsonp_code(w, callback, code);
}
SrsGoApiRoot::SrsGoApiRoot()
{
}
SrsGoApiRoot::~SrsGoApiRoot()
{
}
int SrsGoApiRoot::serve_http(ISrsHttpResponseWriter* w, ISrsHttpMessage* r)
{
SrsStatistic* stat = SrsStatistic::instance();
SrsJsonObject* obj = SrsJsonAny::object();
SrsAutoFree(SrsJsonObject, obj);
obj->set("code", SrsJsonAny::integer(ERROR_SUCCESS));
obj->set("server", SrsJsonAny::integer(stat->server_id()));
SrsJsonObject* urls = SrsJsonAny::object();
obj->set("urls", urls);
urls->set("api", SrsJsonAny::str("the api root"));
return srs_api_response(w, r, obj->dumps());
}
SrsGoApiApi::SrsGoApiApi()
{
}
SrsGoApiApi::~SrsGoApiApi()
{
}
int SrsGoApiApi::serve_http(ISrsHttpResponseWriter* w, ISrsHttpMessage* r)
{
SrsStatistic* stat = SrsStatistic::instance();
SrsJsonObject* obj = SrsJsonAny::object();
SrsAutoFree(SrsJsonObject, obj);
obj->set("code", SrsJsonAny::integer(ERROR_SUCCESS));
obj->set("server", SrsJsonAny::integer(stat->server_id()));
SrsJsonObject* urls = SrsJsonAny::object();
obj->set("urls", urls);
urls->set("v1", SrsJsonAny::str("the api version 1.0"));
return srs_api_response(w, r, obj->dumps());
}
SrsGoApiV1::SrsGoApiV1()
{
}
SrsGoApiV1::~SrsGoApiV1()
{
}
int SrsGoApiV1::serve_http(ISrsHttpResponseWriter* w, ISrsHttpMessage* r)
{
SrsStatistic* stat = SrsStatistic::instance();
SrsJsonObject* obj = SrsJsonAny::object();
SrsAutoFree(SrsJsonObject, obj);
obj->set("code", SrsJsonAny::integer(ERROR_SUCCESS));
obj->set("server", SrsJsonAny::integer(stat->server_id()));
SrsJsonObject* urls = SrsJsonAny::object();
obj->set("urls", urls);
urls->set("versions", SrsJsonAny::str("the version of SRS"));
urls->set("summaries", SrsJsonAny::str("the summary(pid, argv, pwd, cpu, mem) of SRS"));
urls->set("rusages", SrsJsonAny::str("the rusage of SRS"));
urls->set("self_proc_stats", SrsJsonAny::str("the self process stats"));
urls->set("system_proc_stats", SrsJsonAny::str("the system process stats"));
urls->set("meminfos", SrsJsonAny::str("the meminfo of system"));
urls->set("authors", SrsJsonAny::str("the license, copyright, authors and contributors"));
urls->set("features", SrsJsonAny::str("the supported features of SRS"));
urls->set("requests", SrsJsonAny::str("the request itself, for http debug"));
urls->set("vhosts", SrsJsonAny::str("manage all vhosts or specified vhost"));
urls->set("streams", SrsJsonAny::str("manage all streams or specified stream"));
urls->set("clients", SrsJsonAny::str("manage all clients or specified client, default query top 10 clients"));
urls->set("raw", SrsJsonAny::str("raw api for srs, support CUID srs for instance the config"));
SrsJsonObject* tests = SrsJsonAny::object();
obj->set("tests", tests);
tests->set("requests", SrsJsonAny::str("show the request info"));
tests->set("errors", SrsJsonAny::str("always return an error 100"));
tests->set("redirects", SrsJsonAny::str("always redirect to /api/v1/test/errors"));
tests->set("[vhost]", SrsJsonAny::str("http vhost for http://error.srs.com:1985/api/v1/tests/errors"));
return srs_api_response(w, r, obj->dumps());
}
SrsGoApiVersion::SrsGoApiVersion()
{
}
SrsGoApiVersion::~SrsGoApiVersion()
{
}
int SrsGoApiVersion::serve_http(ISrsHttpResponseWriter* w, ISrsHttpMessage* r)
{
SrsStatistic* stat = SrsStatistic::instance();
SrsJsonObject* obj = SrsJsonAny::object();
SrsAutoFree(SrsJsonObject, obj);
obj->set("code", SrsJsonAny::integer(ERROR_SUCCESS));
obj->set("server", SrsJsonAny::integer(stat->server_id()));
SrsJsonObject* data = SrsJsonAny::object();
obj->set("data", data);
data->set("major", SrsJsonAny::integer(VERSION_MAJOR));
data->set("minor", SrsJsonAny::integer(VERSION_MINOR));
data->set("revision", SrsJsonAny::integer(VERSION_REVISION));
data->set("version", SrsJsonAny::str(RTMP_SIG_SRS_VERSION));
return srs_api_response(w, r, obj->dumps());
}
SrsGoApiSummaries::SrsGoApiSummaries()
{
}
SrsGoApiSummaries::~SrsGoApiSummaries()
{
}
int SrsGoApiSummaries::serve_http(ISrsHttpResponseWriter* w, ISrsHttpMessage* r)
{
SrsJsonObject* obj = SrsJsonAny::object();
SrsAutoFree(SrsJsonObject, obj);
srs_api_dump_summaries(obj);
return srs_api_response(w, r, obj->dumps());
}
SrsGoApiRusages::SrsGoApiRusages()
{
}
SrsGoApiRusages::~SrsGoApiRusages()
{
}
int SrsGoApiRusages::serve_http(ISrsHttpResponseWriter* w, ISrsHttpMessage* r)
{
SrsStatistic* stat = SrsStatistic::instance();
SrsJsonObject* obj = SrsJsonAny::object();
SrsAutoFree(SrsJsonObject, obj);
obj->set("code", SrsJsonAny::integer(ERROR_SUCCESS));
obj->set("server", SrsJsonAny::integer(stat->server_id()));
SrsJsonObject* data = SrsJsonAny::object();
obj->set("data", data);
SrsRusage* ru = srs_get_system_rusage();
data->set("ok", SrsJsonAny::boolean(ru->ok));
data->set("sample_time", SrsJsonAny::integer(ru->sample_time));
data->set("ru_utime", SrsJsonAny::integer(ru->r.ru_utime.tv_sec));
data->set("ru_stime", SrsJsonAny::integer(ru->r.ru_stime.tv_sec));
data->set("ru_maxrss", SrsJsonAny::integer(ru->r.ru_maxrss));
data->set("ru_ixrss", SrsJsonAny::integer(ru->r.ru_ixrss));
data->set("ru_idrss", SrsJsonAny::integer(ru->r.ru_idrss));
data->set("ru_isrss", SrsJsonAny::integer(ru->r.ru_isrss));
data->set("ru_minflt", SrsJsonAny::integer(ru->r.ru_minflt));
data->set("ru_majflt", SrsJsonAny::integer(ru->r.ru_majflt));
data->set("ru_nswap", SrsJsonAny::integer(ru->r.ru_nswap));
data->set("ru_inblock", SrsJsonAny::integer(ru->r.ru_inblock));
data->set("ru_oublock", SrsJsonAny::integer(ru->r.ru_oublock));
data->set("ru_msgsnd", SrsJsonAny::integer(ru->r.ru_msgsnd));
data->set("ru_msgrcv", SrsJsonAny::integer(ru->r.ru_msgrcv));
data->set("ru_nsignals", SrsJsonAny::integer(ru->r.ru_nsignals));
data->set("ru_nvcsw", SrsJsonAny::integer(ru->r.ru_nvcsw));
data->set("ru_nivcsw", SrsJsonAny::integer(ru->r.ru_nivcsw));
return srs_api_response(w, r, obj->dumps());
}
SrsGoApiSelfProcStats::SrsGoApiSelfProcStats()
{
}
SrsGoApiSelfProcStats::~SrsGoApiSelfProcStats()
{
}
int SrsGoApiSelfProcStats::serve_http(ISrsHttpResponseWriter* w, ISrsHttpMessage* r)
{
SrsStatistic* stat = SrsStatistic::instance();
SrsJsonObject* obj = SrsJsonAny::object();
SrsAutoFree(SrsJsonObject, obj);
obj->set("code", SrsJsonAny::integer(ERROR_SUCCESS));
obj->set("server", SrsJsonAny::integer(stat->server_id()));
SrsJsonObject* data = SrsJsonAny::object();
obj->set("data", data);
SrsProcSelfStat* u = srs_get_self_proc_stat();
string state;
state += (char)u->state;
data->set("ok", SrsJsonAny::boolean(u->ok));
data->set("sample_time", SrsJsonAny::integer(u->sample_time));
data->set("percent", SrsJsonAny::number(u->percent));
data->set("pid", SrsJsonAny::integer(u->pid));
data->set("comm", SrsJsonAny::str(u->comm));
data->set("state", SrsJsonAny::str(state.c_str()));
data->set("ppid", SrsJsonAny::integer(u->ppid));
data->set("pgrp", SrsJsonAny::integer(u->pgrp));
data->set("session", SrsJsonAny::integer(u->session));
data->set("tty_nr", SrsJsonAny::integer(u->tty_nr));
data->set("tpgid", SrsJsonAny::integer(u->tpgid));
data->set("flags", SrsJsonAny::integer(u->flags));
data->set("minflt", SrsJsonAny::integer(u->minflt));
data->set("cminflt", SrsJsonAny::integer(u->cminflt));
data->set("majflt", SrsJsonAny::integer(u->majflt));
data->set("cmajflt", SrsJsonAny::integer(u->cmajflt));
data->set("utime", SrsJsonAny::integer(u->utime));
data->set("stime", SrsJsonAny::integer(u->stime));
data->set("cutime", SrsJsonAny::integer(u->cutime));
data->set("cstime", SrsJsonAny::integer(u->cstime));
data->set("priority", SrsJsonAny::integer(u->priority));
data->set("nice", SrsJsonAny::integer(u->nice));
data->set("num_threads", SrsJsonAny::integer(u->num_threads));
data->set("itrealvalue", SrsJsonAny::integer(u->itrealvalue));
data->set("starttime", SrsJsonAny::integer(u->starttime));
data->set("vsize", SrsJsonAny::integer(u->vsize));
data->set("rss", SrsJsonAny::integer(u->rss));
data->set("rsslim", SrsJsonAny::integer(u->rsslim));
data->set("startcode", SrsJsonAny::integer(u->startcode));
data->set("endcode", SrsJsonAny::integer(u->endcode));
data->set("startstack", SrsJsonAny::integer(u->startstack));
data->set("kstkesp", SrsJsonAny::integer(u->kstkesp));
data->set("kstkeip", SrsJsonAny::integer(u->kstkeip));
data->set("signal", SrsJsonAny::integer(u->signal));
data->set("blocked", SrsJsonAny::integer(u->blocked));
data->set("sigignore", SrsJsonAny::integer(u->sigignore));
data->set("sigcatch", SrsJsonAny::integer(u->sigcatch));
data->set("wchan", SrsJsonAny::integer(u->wchan));
data->set("nswap", SrsJsonAny::integer(u->nswap));
data->set("cnswap", SrsJsonAny::integer(u->cnswap));
data->set("exit_signal", SrsJsonAny::integer(u->exit_signal));
data->set("processor", SrsJsonAny::integer(u->processor));
data->set("rt_priority", SrsJsonAny::integer(u->rt_priority));
data->set("policy", SrsJsonAny::integer(u->policy));
data->set("delayacct_blkio_ticks", SrsJsonAny::integer(u->delayacct_blkio_ticks));
data->set("guest_time", SrsJsonAny::integer(u->guest_time));
data->set("cguest_time", SrsJsonAny::integer(u->cguest_time));
return srs_api_response(w, r, obj->dumps());
}
SrsGoApiSystemProcStats::SrsGoApiSystemProcStats()
{
}
SrsGoApiSystemProcStats::~SrsGoApiSystemProcStats()
{
}
int SrsGoApiSystemProcStats::serve_http(ISrsHttpResponseWriter* w, ISrsHttpMessage* r)
{
SrsStatistic* stat = SrsStatistic::instance();
SrsJsonObject* obj = SrsJsonAny::object();
SrsAutoFree(SrsJsonObject, obj);
obj->set("code", SrsJsonAny::integer(ERROR_SUCCESS));
obj->set("server", SrsJsonAny::integer(stat->server_id()));
SrsJsonObject* data = SrsJsonAny::object();
obj->set("data", data);
SrsProcSystemStat* s = srs_get_system_proc_stat();
data->set("ok", SrsJsonAny::boolean(s->ok));
data->set("sample_time", SrsJsonAny::integer(s->sample_time));
data->set("percent", SrsJsonAny::number(s->percent));
data->set("user", SrsJsonAny::integer(s->user));
data->set("nice", SrsJsonAny::integer(s->nice));
data->set("sys", SrsJsonAny::integer(s->sys));
data->set("idle", SrsJsonAny::integer(s->idle));
data->set("iowait", SrsJsonAny::integer(s->iowait));
data->set("irq", SrsJsonAny::integer(s->irq));
data->set("softirq", SrsJsonAny::integer(s->softirq));
data->set("steal", SrsJsonAny::integer(s->steal));
data->set("guest", SrsJsonAny::integer(s->guest));
return srs_api_response(w, r, obj->dumps());
}
SrsGoApiMemInfos::SrsGoApiMemInfos()
{
}
SrsGoApiMemInfos::~SrsGoApiMemInfos()
{
}
int SrsGoApiMemInfos::serve_http(ISrsHttpResponseWriter* w, ISrsHttpMessage* r)
{
SrsStatistic* stat = SrsStatistic::instance();
SrsJsonObject* obj = SrsJsonAny::object();
SrsAutoFree(SrsJsonObject, obj);
obj->set("code", SrsJsonAny::integer(ERROR_SUCCESS));
obj->set("server", SrsJsonAny::integer(stat->server_id()));
SrsJsonObject* data = SrsJsonAny::object();
obj->set("data", data);
SrsMemInfo* m = srs_get_meminfo();
data->set("ok", SrsJsonAny::boolean(m->ok));
data->set("sample_time", SrsJsonAny::integer(m->sample_time));
data->set("percent_ram", SrsJsonAny::number(m->percent_ram));
data->set("percent_swap", SrsJsonAny::number(m->percent_swap));
data->set("MemActive", SrsJsonAny::integer(m->MemActive));
data->set("RealInUse", SrsJsonAny::integer(m->RealInUse));
data->set("NotInUse", SrsJsonAny::integer(m->NotInUse));
data->set("MemTotal", SrsJsonAny::integer(m->MemTotal));
data->set("MemFree", SrsJsonAny::integer(m->MemFree));
data->set("Buffers", SrsJsonAny::integer(m->Buffers));
data->set("Cached", SrsJsonAny::integer(m->Cached));
data->set("SwapTotal", SrsJsonAny::integer(m->SwapTotal));
data->set("SwapFree", SrsJsonAny::integer(m->SwapFree));
return srs_api_response(w, r, obj->dumps());
}
SrsGoApiAuthors::SrsGoApiAuthors()
{
}
SrsGoApiAuthors::~SrsGoApiAuthors()
{
}
int SrsGoApiAuthors::serve_http(ISrsHttpResponseWriter* w, ISrsHttpMessage* r)
{
SrsStatistic* stat = SrsStatistic::instance();
SrsJsonObject* obj = SrsJsonAny::object();
SrsAutoFree(SrsJsonObject, obj);
obj->set("code", SrsJsonAny::integer(ERROR_SUCCESS));
obj->set("server", SrsJsonAny::integer(stat->server_id()));
SrsJsonObject* data = SrsJsonAny::object();
obj->set("data", data);
data->set("primary", SrsJsonAny::str(RTMP_SIG_SRS_PRIMARY));
data->set("license", SrsJsonAny::str(RTMP_SIG_SRS_LICENSE));
data->set("copyright", SrsJsonAny::str(RTMP_SIG_SRS_COPYRIGHT));
data->set("authors", SrsJsonAny::str(RTMP_SIG_SRS_AUTHROS));
data->set("contributors_link", SrsJsonAny::str(RTMP_SIG_SRS_CONTRIBUTORS_URL));
data->set("contributors", SrsJsonAny::str(SRS_AUTO_CONSTRIBUTORS));
return srs_api_response(w, r, obj->dumps());
}
SrsGoApiFeatures::SrsGoApiFeatures()
{
}
SrsGoApiFeatures::~SrsGoApiFeatures()
{
}
int SrsGoApiFeatures::serve_http(ISrsHttpResponseWriter* w, ISrsHttpMessage* r)
{
SrsStatistic* stat = SrsStatistic::instance();
SrsJsonObject* obj = SrsJsonAny::object();
SrsAutoFree(SrsJsonObject, obj);
obj->set("code", SrsJsonAny::integer(ERROR_SUCCESS));
obj->set("server", SrsJsonAny::integer(stat->server_id()));
SrsJsonObject* data = SrsJsonAny::object();
obj->set("data", data);
data->set("options", SrsJsonAny::str(SRS_AUTO_USER_CONFIGURE));
data->set("options2", SrsJsonAny::str(SRS_AUTO_CONFIGURE));
data->set("build", SrsJsonAny::str(SRS_AUTO_BUILD_DATE));
data->set("build2", SrsJsonAny::str(SRS_AUTO_BUILD_TS));
SrsJsonObject* features = SrsJsonAny::object();
data->set("features", features);
#ifdef SRS_AUTO_SSL
features->set("ssl", SrsJsonAny::boolean(true));
#else
features->set("ssl", SrsJsonAny::boolean(false));
#endif
#ifdef SRS_AUTO_HLS
features->set("hls", SrsJsonAny::boolean(true));
#else
features->set("hls", SrsJsonAny::boolean(false));
#endif
#ifdef SRS_AUTO_HDS
features->set("hds", SrsJsonAny::boolean(true));
#else
features->set("hds", SrsJsonAny::boolean(false));
#endif
#ifdef SRS_AUTO_HTTP_CALLBACK
features->set("callback", SrsJsonAny::boolean(true));
#else
features->set("callback", SrsJsonAny::boolean(false));
#endif
#ifdef SRS_AUTO_HTTP_API
features->set("api", SrsJsonAny::boolean(true));
#else
features->set("api", SrsJsonAny::boolean(false));
#endif
#ifdef SRS_AUTO_HTTP_SERVER
features->set("httpd", SrsJsonAny::boolean(true));
#else
features->set("httpd", SrsJsonAny::boolean(false));
#endif
#ifdef SRS_AUTO_DVR
features->set("dvr", SrsJsonAny::boolean(true));
#else
features->set("dvr", SrsJsonAny::boolean(false));
#endif
#ifdef SRS_AUTO_TRANSCODE
features->set("transcode", SrsJsonAny::boolean(true));
#else
features->set("transcode", SrsJsonAny::boolean(false));
#endif
#ifdef SRS_AUTO_INGEST
features->set("ingest", SrsJsonAny::boolean(true));
#else
features->set("ingest", SrsJsonAny::boolean(false));
#endif
#ifdef SRS_AUTO_STAT
features->set("stat", SrsJsonAny::boolean(true));
#else
features->set("stat", SrsJsonAny::boolean(false));
#endif
#ifdef SRS_AUTO_NGINX
features->set("nginx", SrsJsonAny::boolean(true));
#else
features->set("nginx", SrsJsonAny::boolean(false));
#endif
#ifdef SRS_AUTO_FFMPEG_TOOL
features->set("ffmpeg", SrsJsonAny::boolean(true));
#else
features->set("ffmpeg", SrsJsonAny::boolean(false));
#endif
#ifdef SRS_AUTO_STREAM_CASTER
features->set("caster", SrsJsonAny::boolean(true));
#else
features->set("caster", SrsJsonAny::boolean(false));
#endif
#ifdef SRS_PERF_COMPLEX_SEND
features->set("complex_send", SrsJsonAny::boolean(true));
#else
features->set("complex_send", SrsJsonAny::boolean(false));
#endif
#ifdef SRS_PERF_TCP_NODELAY
features->set("tcp_nodelay", SrsJsonAny::boolean(true));
#else
features->set("tcp_nodelay", SrsJsonAny::boolean(false));
#endif
#ifdef SRS_PERF_SO_SNDBUF_SIZE
features->set("so_sendbuf", SrsJsonAny::boolean(true));
#else
features->set("so_sendbuf", SrsJsonAny::boolean(false));
#endif
#ifdef SRS_PERF_MERGED_READ
features->set("mr", SrsJsonAny::boolean(true));
#else
features->set("mr", SrsJsonAny::boolean(false));
#endif
return srs_api_response(w, r, obj->dumps());
}
SrsGoApiRequests::SrsGoApiRequests()
{
}
SrsGoApiRequests::~SrsGoApiRequests()
{
}
int SrsGoApiRequests::serve_http(ISrsHttpResponseWriter* w, ISrsHttpMessage* r)
{
SrsStatistic* stat = SrsStatistic::instance();
SrsJsonObject* obj = SrsJsonAny::object();
SrsAutoFree(SrsJsonObject, obj);
obj->set("code", SrsJsonAny::integer(ERROR_SUCCESS));
obj->set("server", SrsJsonAny::integer(stat->server_id()));
SrsJsonObject* data = SrsJsonAny::object();
obj->set("data", data);
data->set("uri", SrsJsonAny::str(r->uri().c_str()));
data->set("path", SrsJsonAny::str(r->path().c_str()));
// method
data->set("METHOD", SrsJsonAny::str(r->method_str().c_str()));
// request headers
SrsJsonObject* headers = SrsJsonAny::object();
data->set("headers", headers);
for (int i = 0; i < r->request_header_count(); i++) {
std::string key = r->request_header_key_at(i);
std::string value = r->request_header_value_at(i);
headers->set(key, SrsJsonAny::str(value.c_str()));
}
// server informations
SrsJsonObject* server = SrsJsonAny::object();
data->set("headers", server);
server->set("sigature", SrsJsonAny::str(RTMP_SIG_SRS_KEY));
server->set("name", SrsJsonAny::str(RTMP_SIG_SRS_NAME));
server->set("version", SrsJsonAny::str(RTMP_SIG_SRS_VERSION));
server->set("link", SrsJsonAny::str(RTMP_SIG_SRS_URL));
server->set("time", SrsJsonAny::integer(srs_get_system_time_ms()));
return srs_api_response(w, r, obj->dumps());
}
SrsGoApiVhosts::SrsGoApiVhosts()
{
}
SrsGoApiVhosts::~SrsGoApiVhosts()
{
}
int SrsGoApiVhosts::serve_http(ISrsHttpResponseWriter* w, ISrsHttpMessage* r)
{
int ret = ERROR_SUCCESS;
SrsStatistic* stat = SrsStatistic::instance();
// path: {pattern}{vhost_id}
// e.g. /api/v1/vhosts/100 pattern= /api/v1/vhosts/, vhost_id=100
int vid = r->parse_rest_id(entry->pattern);
SrsStatisticVhost* vhost = NULL;
if (vid > 0 && (vhost = stat->find_vhost(vid)) == NULL) {
ret = ERROR_RTMP_VHOST_NOT_FOUND;
srs_error("vhost id=%d not found. ret=%d", vid, ret);
return srs_api_response_code(w, r, ret);
}
SrsJsonObject* obj = SrsJsonAny::object();
SrsAutoFree(SrsJsonObject, obj);
obj->set("code", SrsJsonAny::integer(ERROR_SUCCESS));
obj->set("server", SrsJsonAny::integer(stat->server_id()));
if (r->is_http_get()) {
if (!vhost) {
SrsJsonArray* data = SrsJsonAny::array();
obj->set("vhosts", data);
if ((ret = stat->dumps_vhosts(data)) != ERROR_SUCCESS) {
return srs_api_response_code(w, r, ret);
}
} else {
SrsJsonObject* data = SrsJsonAny::object();
obj->set("vhost", data);;
if ((ret = vhost->dumps(data)) != ERROR_SUCCESS) {
return srs_api_response_code(w, r, ret);
}
}
} else {
return srs_go_http_error(w, SRS_CONSTS_HTTP_MethodNotAllowed);
}
return srs_api_response(w, r, obj->dumps());
}
SrsGoApiStreams::SrsGoApiStreams()
{
}
SrsGoApiStreams::~SrsGoApiStreams()
{
}
int SrsGoApiStreams::serve_http(ISrsHttpResponseWriter* w, ISrsHttpMessage* r)
{
int ret = ERROR_SUCCESS;
SrsStatistic* stat = SrsStatistic::instance();
// path: {pattern}{stream_id}
// e.g. /api/v1/streams/100 pattern= /api/v1/streams/, stream_id=100
int sid = r->parse_rest_id(entry->pattern);
SrsStatisticStream* stream = NULL;
if (sid >= 0 && (stream = stat->find_stream(sid)) == NULL) {
ret = ERROR_RTMP_STREAM_NOT_FOUND;
srs_error("stream id=%d not found. ret=%d", sid, ret);
return srs_api_response_code(w, r, ret);
}
SrsJsonObject* obj = SrsJsonAny::object();
SrsAutoFree(SrsJsonObject, obj);
obj->set("code", SrsJsonAny::integer(ERROR_SUCCESS));
obj->set("server", SrsJsonAny::integer(stat->server_id()));
if (r->is_http_get()) {
if (!stream) {
SrsJsonArray* data = SrsJsonAny::array();
obj->set("streams", data);
if ((ret = stat->dumps_streams(data)) != ERROR_SUCCESS) {
return srs_api_response_code(w, r, ret);
}
} else {
SrsJsonObject* data = SrsJsonAny::object();
obj->set("stream", data);;
if ((ret = stream->dumps(data)) != ERROR_SUCCESS) {
return srs_api_response_code(w, r, ret);
}
}
} else {
return srs_go_http_error(w, SRS_CONSTS_HTTP_MethodNotAllowed);
}
return srs_api_response(w, r, obj->dumps());
}
SrsGoApiClients::SrsGoApiClients()
{
}
SrsGoApiClients::~SrsGoApiClients()
{
}
int SrsGoApiClients::serve_http(ISrsHttpResponseWriter* w, ISrsHttpMessage* r)
{
int ret = ERROR_SUCCESS;
SrsStatistic* stat = SrsStatistic::instance();
// path: {pattern}{client_id}
// e.g. /api/v1/clients/100 pattern= /api/v1/clients/, client_id=100
int cid = r->parse_rest_id(entry->pattern);
SrsStatisticClient* client = NULL;
if (cid >= 0 && (client = stat->find_client(cid)) == NULL) {
ret = ERROR_RTMP_CLIENT_NOT_FOUND;
srs_error("client id=%d not found. ret=%d", cid, ret);
return srs_api_response_code(w, r, ret);
}
SrsJsonObject* obj = SrsJsonAny::object();
SrsAutoFree(SrsJsonObject, obj);
obj->set("code", SrsJsonAny::integer(ERROR_SUCCESS));
obj->set("server", SrsJsonAny::integer(stat->server_id()));
if (r->is_http_get()) {
if (!client) {
SrsJsonArray* data = SrsJsonAny::array();
obj->set("clients", data);
if ((ret = stat->dumps_clients(data, 0, 10)) != ERROR_SUCCESS) {
return srs_api_response_code(w, r, ret);
}
} else {
SrsJsonObject* data = SrsJsonAny::object();
obj->set("client", data);;
if ((ret = client->dumps(data)) != ERROR_SUCCESS) {
return srs_api_response_code(w, r, ret);
}
}
} else if (r->is_http_delete()) {
if (!client) {
ret = ERROR_RTMP_CLIENT_NOT_FOUND;
srs_error("client id=%d not found. ret=%d", cid, ret);
return srs_api_response_code(w, r, ret);
}
client->conn->expire();
srs_warn("kickoff client id=%d", cid);
} else {
return srs_go_http_error(w, SRS_CONSTS_HTTP_MethodNotAllowed);
}
return srs_api_response(w, r, obj->dumps());
}
SrsGoApiRaw::SrsGoApiRaw(SrsServer* svr)
{
server = svr;
raw_api = _srs_config->get_raw_api();
allow_reload = _srs_config->get_raw_api_allow_reload();
allow_query = _srs_config->get_raw_api_allow_query();
allow_update = _srs_config->get_raw_api_allow_update();
_srs_config->subscribe(this);
}
SrsGoApiRaw::~SrsGoApiRaw()
{
_srs_config->unsubscribe(this);
}
int SrsGoApiRaw::serve_http(ISrsHttpResponseWriter* w, ISrsHttpMessage* r)
{
int ret = ERROR_SUCCESS;
std::string rpc = r->query_get("rpc");
// the object to return for request.
SrsJsonObject* obj = SrsJsonAny::object();
SrsAutoFree(SrsJsonObject, obj);
obj->set("code", SrsJsonAny::integer(ERROR_SUCCESS));
// for rpc=raw, to query the raw api config for http api.
if (rpc == "raw") {
// query global scope.
if ((ret = _srs_config->raw_to_json(obj)) != ERROR_SUCCESS) {
srs_error("raw api rpc raw failed. ret=%d", ret);
return srs_api_response_code(w, r, ret);
}
return srs_api_response(w, r, obj->dumps());
}
// whether enabled the HTTP RAW API.
if (!raw_api) {
ret = ERROR_SYSTEM_CONFIG_RAW_DISABLED;
srs_warn("raw api disabled. ret=%d", ret);
return srs_api_response_code(w, r, ret);
}
//////////////////////////////////////////////////////////////////////////
// the rpc is required.
// the allowd rpc method check.
if (rpc.empty() || (rpc != "reload" && rpc != "query" && rpc != "raw" && rpc != "update")) {
ret = ERROR_SYSTEM_CONFIG_RAW;
srs_error("raw api invalid rpc=%s. ret=%d", rpc.c_str(), ret);
return srs_api_response_code(w, r, ret);
}
// for rpc=reload, trigger the server to reload the config.
if (rpc == "reload") {
if (!allow_reload) {
ret = ERROR_SYSTEM_CONFIG_RAW_DISABLED;
srs_error("raw api reload disabled rpc=%s. ret=%d", rpc.c_str(), ret);
return srs_api_response_code(w, r, ret);
}
srs_trace("raw api trigger reload. ret=%d", ret);
server->on_signal(SRS_SIGNAL_RELOAD);
return srs_api_response_code(w, r, ret);
}
// for rpc=query, to get the configs of server.
// @param scope the scope to query for config, it can be:
// global, the configs belongs to the root, donot includes any sub directives.
// minimal, the minimal summary of server, for preview stream to got the port serving.
// vhost, the configs for specified vhost by @param vhost.
// @param vhost the vhost name for @param scope is vhost to query config.
// for the default vhost, must be __defaultVhost__
if (rpc == "query") {
if (!allow_query) {
ret = ERROR_SYSTEM_CONFIG_RAW_DISABLED;
srs_error("raw api allow_query disabled rpc=%s. ret=%d", rpc.c_str(), ret);
return srs_api_response_code(w, r, ret);
}
std::string scope = r->query_get("scope");
std::string vhost = r->query_get("vhost");
if (scope.empty() || (scope != "global" && scope != "vhost" && scope != "minimal")) {
ret = ERROR_SYSTEM_CONFIG_RAW_NOT_ALLOWED;
srs_error("raw api query invalid scope=%s. ret=%d", scope.c_str(), ret);
return srs_api_response_code(w, r, ret);
}
if (scope == "vhost") {
// query vhost scope.
if (vhost.empty()) {
ret = ERROR_SYSTEM_CONFIG_RAW_PARAMS;
srs_error("raw api query vhost invalid vhost=%s. ret=%d", vhost.c_str(), ret);
return srs_api_response_code(w, r, ret);
}
SrsConfDirective* root = _srs_config->get_root();
SrsConfDirective* conf = root->get("vhost", vhost);
if (!conf) {
ret = ERROR_SYSTEM_CONFIG_RAW_PARAMS;
srs_error("raw api query vhost invalid vhost=%s. ret=%d", vhost.c_str(), ret);
return srs_api_response_code(w, r, ret);
}
SrsJsonObject* data = SrsJsonAny::object();
obj->set("vhost", data);
if ((ret = _srs_config->vhost_to_json(conf, data)) != ERROR_SUCCESS) {
srs_error("raw api query vhost failed. ret=%d", ret);
return srs_api_response_code(w, r, ret);
}
} else if (scope == "minimal") {
SrsJsonObject* data = SrsJsonAny::object();
obj->set("minimal", data);
// query minimal scope.
if ((ret = _srs_config->minimal_to_json(data)) != ERROR_SUCCESS) {
srs_error("raw api query global failed. ret=%d", ret);
return srs_api_response_code(w, r, ret);
}
} else {
SrsJsonObject* data = SrsJsonAny::object();
obj->set("global", data);
// query global scope.
if ((ret = _srs_config->global_to_json(data)) != ERROR_SUCCESS) {
srs_error("raw api query global failed. ret=%d", ret);
return srs_api_response_code(w, r, ret);
}
}
return srs_api_response(w, r, obj->dumps());
}
// for rpc=update, to update the configs of server.
// @scope the scope to update for config.
// @value the updated value for scope.
// @param the extra param for scope.
// @data the extra data for scope.
// possible updates:
// @scope @value value-description
// listen 1935,1936 the port list.
// pid ./objs/srs.pid the pid file of srs.
// chunk_size 60000 the global RTMP chunk_size.
// ff_log_dir ./objs the dir for ffmpeg log.
// srs_log_tank file the tank to log, file or console.
// srs_log_level trace the level of log, verbose, info, trace, warn, error.
// srs_log_file ./objs/srs.log the log file when tank is file.
// max_connections 1000 the max connections of srs.
// utc_time false whether enable utc time.
// pithy_print_ms 10000 the pithy print interval in ms.
// vhost specified updates:
// @scope @value @param @data description
// vhost ossrs.net create - create vhost ossrs.net
// vhost ossrs.net update new.ossrs.net the new name to update vhost
// dvr specified updates:
// @scope @value @param @data description
// dvr ossrs.net enable live/livestream enable the dvr of stream
// dvr ossrs.net disable live/livestream disable the dvr of stream
if (rpc == "update") {
if (!allow_update) {
ret = ERROR_SYSTEM_CONFIG_RAW_DISABLED;
srs_error("raw api allow_update disabled rpc=%s. ret=%d", rpc.c_str(), ret);
return srs_api_response_code(w, r, ret);
}
std::string scope = r->query_get("scope");
std::string value = r->query_get("value");
if (scope.empty()) {
ret = ERROR_SYSTEM_CONFIG_RAW_NOT_ALLOWED;
srs_error("raw api query invalid empty scope. ret=%d", ret);
return srs_api_response_code(w, r, ret);
}
if (scope != "listen" && scope != "pid" && scope != "chunk_size"
&& scope != "ff_log_dir" && scope != "srs_log_tank" && scope != "srs_log_level"
&& scope != "srs_log_file" && scope != "max_connections" && scope != "utc_time"
&& scope != "pithy_print_ms" && scope != "vhost" && scope != "dvr"
) {
ret = ERROR_SYSTEM_CONFIG_RAW_NOT_ALLOWED;
srs_error("raw api query invalid scope=%s. ret=%d", scope.c_str(), ret);
return srs_api_response_code(w, r, ret);
}
bool applied = false;
string extra = "";
if (scope == "listen") {
vector<string> eps = srs_string_split(value, ",");
bool invalid = eps.empty();
for (int i = 0; i < (int)eps.size(); i++) {
string ep = eps.at(i);
int port = ::atoi(ep.c_str());
if (port <= 2 || port >= 65535) {
invalid = true;
break;
}
}
if (invalid) {
ret = ERROR_SYSTEM_CONFIG_RAW_PARAMS;
srs_error("raw api update check listen=%s failed. ret=%d", value.c_str(), ret);
return srs_api_response_code(w, r, ret);
}
if ((ret = _srs_config->raw_set_listen(eps, applied)) != ERROR_SUCCESS) {
srs_error("raw api update listen=%s failed. ret=%d", value.c_str(), ret);
return srs_api_response_code(w, r, ret);
}
} else if (scope == "pid") {
if (value.empty() || !srs_string_starts_with(value, "./", "/tmp/", "/var/") || !srs_string_ends_with(value, ".pid")) {
ret = ERROR_SYSTEM_CONFIG_RAW_PARAMS;
srs_error("raw api update check pid=%s failed. ret=%d", value.c_str(), ret);
return srs_api_response_code(w, r, ret);
}
if ((ret = _srs_config->raw_set_pid(value, applied)) != ERROR_SUCCESS) {
srs_error("raw api update pid=%s failed. ret=%d", value.c_str(), ret);
return srs_api_response_code(w, r, ret);
}
} else if (scope == "chunk_size") {
int csv = ::atoi(value.c_str());
if (csv < 128 || csv > 65535 || !srs_is_digit_number(value)) {
ret = ERROR_SYSTEM_CONFIG_RAW_PARAMS;
srs_error("raw api update check chunk_size=%s/%d failed. ret=%d", value.c_str(), csv, ret);
return srs_api_response_code(w, r, ret);
}
if ((ret = _srs_config->raw_set_chunk_size(value, applied)) != ERROR_SUCCESS) {
srs_error("raw api update chunk_size=%s/%d failed. ret=%d", value.c_str(), csv, ret);
return srs_api_response_code(w, r, ret);
}
} else if (scope == "ff_log_dir") {
if (value.empty() || (value != "/dev/null" && !srs_string_starts_with(value, "./", "/tmp/", "/var/"))) {
ret = ERROR_SYSTEM_CONFIG_RAW_PARAMS;
srs_error("raw api update check ff_log_dir=%s failed. ret=%d", value.c_str(), ret);
return srs_api_response_code(w, r, ret);
}
if ((ret = _srs_config->raw_set_ff_log_dir(value, applied)) != ERROR_SUCCESS) {
srs_error("raw api update ff_log_dir=%s failed. ret=%d", value.c_str(), ret);
return srs_api_response_code(w, r, ret);
}
} else if (scope == "srs_log_tank") {
if (value.empty() || (value != "file" && value != "console")) {
ret = ERROR_SYSTEM_CONFIG_RAW_PARAMS;
srs_error("raw api update check srs_log_tank=%s failed. ret=%d", value.c_str(), ret);
return srs_api_response_code(w, r, ret);
}
if ((ret = _srs_config->raw_set_srs_log_tank(value, applied)) != ERROR_SUCCESS) {
srs_error("raw api update srs_log_tank=%s failed. ret=%d", value.c_str(), ret);
return srs_api_response_code(w, r, ret);
}
} else if (scope == "srs_log_level") {
if (value != "verbose" && value != "info" && value != "trace" && value != "warn" && value != "error") {
ret = ERROR_SYSTEM_CONFIG_RAW_PARAMS;
srs_error("raw api update check srs_log_level=%s failed. ret=%d", value.c_str(), ret);
return srs_api_response_code(w, r, ret);
}
if ((ret = _srs_config->raw_set_srs_log_level(value, applied)) != ERROR_SUCCESS) {
srs_error("raw api update srs_log_level=%s failed. ret=%d", value.c_str(), ret);
return srs_api_response_code(w, r, ret);
}
} else if (scope == "srs_log_file") {
if (value.empty() || !srs_string_starts_with(value, "./", "/tmp/", "/var/") || !srs_string_ends_with(value, ".log")) {
ret = ERROR_SYSTEM_CONFIG_RAW_PARAMS;
srs_error("raw api update check srs_log_file=%s failed. ret=%d", value.c_str(), ret);
return srs_api_response_code(w, r, ret);
}
if ((ret = _srs_config->raw_set_srs_log_file(value, applied)) != ERROR_SUCCESS) {
srs_error("raw api update srs_log_file=%s failed. ret=%d", value.c_str(), ret);
return srs_api_response_code(w, r, ret);
}
} else if (scope == "max_connections") {
int mcv = ::atoi(value.c_str());
if (mcv < 10 || mcv > 65535 || !srs_is_digit_number(value)) {
ret = ERROR_SYSTEM_CONFIG_RAW_PARAMS;
srs_error("raw api update check max_connections=%s/%d failed. ret=%d", value.c_str(), mcv, ret);
return srs_api_response_code(w, r, ret);
}
if ((ret = _srs_config->raw_set_max_connections(value, applied)) != ERROR_SUCCESS) {
srs_error("raw api update max_connections=%s/%d failed. ret=%d", value.c_str(), mcv, ret);
return srs_api_response_code(w, r, ret);
}
} else if (scope == "utc_time") {
if (!srs_is_boolean(value)) {
ret = ERROR_SYSTEM_CONFIG_RAW_PARAMS;
srs_error("raw api update check utc_time=%s failed. ret=%d", value.c_str(), ret);
return srs_api_response_code(w, r, ret);
}
if ((ret = _srs_config->raw_set_utc_time(srs_config_bool2switch(value), applied)) != ERROR_SUCCESS) {
srs_error("raw api update utc_time=%s failed. ret=%d", value.c_str(), ret);
return srs_api_response_code(w, r, ret);
}
} else if (scope == "pithy_print_ms") {
int ppmv = ::atoi(value.c_str());
if (ppmv < 100 || ppmv > 300000 || !srs_is_digit_number(value)) {
ret = ERROR_SYSTEM_CONFIG_RAW_PARAMS;
srs_error("raw api update check pithy_print_ms=%s/%d failed. ret=%d", value.c_str(), ppmv, ret);
return srs_api_response_code(w, r, ret);
}
if ((ret = _srs_config->raw_set_pithy_print_ms(value, applied)) != ERROR_SUCCESS) {
srs_error("raw api update pithy_print_ms=%s/%d failed. ret=%d", value.c_str(), ppmv, ret);
return srs_api_response_code(w, r, ret);
}
} else if (scope == "vhost") {
std::string param = r->query_get("param");
std::string data = r->query_get("data");
if (param != "create" && param != "update" && param != "delete" && param != "disable" && param != "enable") {
ret = ERROR_SYSTEM_CONFIG_RAW_NOT_ALLOWED;
srs_error("raw api query invalid scope=%s, param=%s. ret=%d", scope.c_str(), param.c_str(), ret);
return srs_api_response_code(w, r, ret);
}
extra += " " + param;
if (param == "create") {
// when create, the vhost must not exists.
if (param.empty() || _srs_config->get_vhost(value, false)) {
ret = ERROR_SYSTEM_CONFIG_RAW_PARAMS;
srs_error("raw api update check vhost=%s, param=%s failed. ret=%d", value.c_str(), param.c_str(), ret);
return srs_api_response_code(w, r, ret);
}
if ((ret = _srs_config->raw_create_vhost(value, applied)) != ERROR_SUCCESS) {
srs_error("raw api update vhost=%s, param=%s failed. ret=%d", value.c_str(), param.c_str(), ret);
return srs_api_response_code(w, r, ret);
}
} else if (param == "update") {
extra += " to " + data;
// when update, the vhost must exists and disabled.
SrsConfDirective* vhost = _srs_config->get_vhost(value, false);
if (data.empty() || data == value || param.empty() || !vhost || _srs_config->get_vhost_enabled(vhost)) {
ret = ERROR_SYSTEM_CONFIG_RAW_PARAMS;
srs_error("raw api update check vhost=%s, param=%s, data=%s failed. ret=%d", value.c_str(), param.c_str(), data.c_str(), ret);
return srs_api_response_code(w, r, ret);
}
if ((ret = _srs_config->raw_update_vhost(value, data, applied)) != ERROR_SUCCESS) {
srs_error("raw api update vhost=%s, param=%s, data=%s failed. ret=%d", value.c_str(), param.c_str(), data.c_str(), ret);
return srs_api_response_code(w, r, ret);
}
} else if (param == "delete") {
// when delete, the vhost must exists and disabled.
SrsConfDirective* vhost = _srs_config->get_vhost(value, false);
if (param.empty() || !vhost || _srs_config->get_vhost_enabled(vhost)) {
ret = ERROR_SYSTEM_CONFIG_RAW_PARAMS;
srs_error("raw api update check vhost=%s, param=%s failed. ret=%d", value.c_str(), param.c_str(), ret);
return srs_api_response_code(w, r, ret);
}
if ((ret = _srs_config->raw_delete_vhost(value, applied)) != ERROR_SUCCESS) {
srs_error("raw api update vhost=%s, param=%s failed. ret=%d", value.c_str(), param.c_str(), ret);
return srs_api_response_code(w, r, ret);
}
} else if (param == "disable") {
// when disable, the vhost must exists and enabled.
SrsConfDirective* vhost = _srs_config->get_vhost(value, false);
if (param.empty() || !vhost || !_srs_config->get_vhost_enabled(vhost)) {
ret = ERROR_SYSTEM_CONFIG_RAW_PARAMS;
srs_error("raw api update check vhost=%s, param=%s failed. ret=%d", value.c_str(), param.c_str(), ret);
return srs_api_response_code(w, r, ret);
}
if ((ret = _srs_config->raw_disable_vhost(value, applied)) != ERROR_SUCCESS) {
srs_error("raw api update vhost=%s, param=%s failed. ret=%d", value.c_str(), param.c_str(), ret);
return srs_api_response_code(w, r, ret);
}
} else if (param == "enable") {
// when enable, the vhost must exists and disabled.
SrsConfDirective* vhost = _srs_config->get_vhost(value, false);
if (param.empty() || !vhost || _srs_config->get_vhost_enabled(vhost)) {
ret = ERROR_SYSTEM_CONFIG_RAW_PARAMS;
srs_error("raw api update check vhost=%s, param=%s failed. ret=%d", value.c_str(), param.c_str(), ret);
return srs_api_response_code(w, r, ret);
}
if ((ret = _srs_config->raw_enable_vhost(value, applied)) != ERROR_SUCCESS) {
srs_error("raw api update vhost=%s, param=%s failed. ret=%d", value.c_str(), param.c_str(), ret);
return srs_api_response_code(w, r, ret);
}
} else {
// TODO: support other param.
}
} else if (scope == "dvr") {
std::string action = r->query_get("param");
std::string stream = r->query_get("data");
extra += "/" + stream + " to " + action;
if (action != "enable" && action != "disable") {
ret = ERROR_SYSTEM_CONFIG_RAW_NOT_ALLOWED;
srs_error("raw api query invalid scope=%s, param=%s. ret=%d", scope.c_str(), action.c_str(), ret);
return srs_api_response_code(w, r, ret);
}
if (!_srs_config->get_dvr_enabled(value)) {
ret = ERROR_SYSTEM_CONFIG_RAW_NOT_ALLOWED;
srs_error("raw api query invalid scope=%s, value=%s, param=%s. ret=%d", scope.c_str(), value.c_str(), action.c_str(), ret);
return srs_api_response_code(w, r, ret);
}
if (action == "enable") {
if ((ret = _srs_config->raw_enable_dvr(value, stream, applied)) != ERROR_SUCCESS) {
srs_error("raw api update dvr=%s/%s, param=%s failed. ret=%d", value.c_str(), stream.c_str(), action.c_str(), ret);
return srs_api_response_code(w, r, ret);
}
} else {
if ((ret = _srs_config->raw_disable_dvr(value, stream, applied)) != ERROR_SUCCESS) {
srs_error("raw api update dvr=%s/%s, param=%s failed. ret=%d", value.c_str(), stream.c_str(), action.c_str(), ret);
return srs_api_response_code(w, r, ret);
}
}
} else {
// TODO: support other scope.
}
// whether the config applied.
if (applied) {
server->on_signal(SRS_SIGNAL_PERSISTENCE_CONFIG);
srs_trace("raw api update %s=%s%s ok.", scope.c_str(), value.c_str(), extra.c_str());
} else {
srs_warn("raw api update not applied %s=%s%s.", scope.c_str(), value.c_str(), extra.c_str());
}
return srs_api_response(w, r, obj->dumps());
}
return ret;
}
int SrsGoApiRaw::on_reload_http_api_raw_api()
{
raw_api = _srs_config->get_raw_api();
allow_reload = _srs_config->get_raw_api_allow_reload();
allow_query = _srs_config->get_raw_api_allow_query();
allow_update = _srs_config->get_raw_api_allow_update();
return ERROR_SUCCESS;
}
SrsGoApiError::SrsGoApiError()
{
}
SrsGoApiError::~SrsGoApiError()
{
}
int SrsGoApiError::serve_http(ISrsHttpResponseWriter* w, ISrsHttpMessage* r)
{
return srs_api_response_code(w, r, 100);
}
SrsHttpApi::SrsHttpApi(IConnectionManager* cm, st_netfd_t fd, SrsHttpServeMux* m)
: SrsConnection(cm, fd)
{
mux = m;
parser = new SrsHttpParser();
crossdomain_required = false;
_srs_config->subscribe(this);
}
SrsHttpApi::~SrsHttpApi()
{
srs_freep(parser);
_srs_config->unsubscribe(this);
}
void SrsHttpApi::resample()
{
// TODO: FIXME: implements it
}
int64_t SrsHttpApi::get_send_bytes_delta()
{
// TODO: FIXME: implements it
return 0;
}
int64_t SrsHttpApi::get_recv_bytes_delta()
{
// TODO: FIXME: implements it
return 0;
}
void SrsHttpApi::cleanup()
{
// TODO: FIXME: implements it
}
int SrsHttpApi::do_cycle()
{
int ret = ERROR_SUCCESS;
srs_trace("api get peer ip success. ip=%s", ip.c_str());
// initialize parser
if ((ret = parser->initialize(HTTP_REQUEST, true)) != ERROR_SUCCESS) {
srs_error("api initialize http parser failed. ret=%d", ret);
return ret;
}
// underlayer socket
SrsStSocket skt(stfd);
// set the recv timeout, for some clients never disconnect the connection.
// @see https://github.com/simple-rtmp-server/srs/issues/398
skt.set_recv_timeout(SRS_HTTP_RECV_TIMEOUT_US);
// initialize the crossdomain
crossdomain_enabled = _srs_config->get_http_api_crossdomain();
// process http messages.
while(!disposed) {
ISrsHttpMessage* req = NULL;
// get a http message
if ((ret = parser->parse_message(&skt, this, &req)) != ERROR_SUCCESS) {
return ret;
}
// if SUCCESS, always NOT-NULL.
srs_assert(req);
// always free it in this scope.
SrsAutoFree(ISrsHttpMessage, req);
// ok, handle http request.
SrsHttpResponseWriter writer(&skt);
if ((ret = process_request(&writer, req)) != ERROR_SUCCESS) {
return ret;
}
// read all rest bytes in request body.
char buf[SRS_HTTP_READ_CACHE_BYTES];
ISrsHttpResponseReader* br = req->body_reader();
while (!br->eof()) {
if ((ret = br->read(buf, SRS_HTTP_READ_CACHE_BYTES, NULL)) != ERROR_SUCCESS) {
return ret;
}
}
// donot keep alive, disconnect it.
// @see https://github.com/simple-rtmp-server/srs/issues/399
if (!req->is_keep_alive()) {
break;
}
}
return ret;
}
int SrsHttpApi::process_request(ISrsHttpResponseWriter* w, ISrsHttpMessage* r)
{
int ret = ERROR_SUCCESS;
srs_trace("HTTP %s %s, content-length=%"PRId64"",
r->method_str().c_str(), r->url().c_str(), r->content_length());
// method is OPTIONS and enable crossdomain, required crossdomain header.
if (r->is_http_options() && _srs_config->get_http_api_crossdomain()) {
crossdomain_required = true;
}
// whenever crossdomain required, set crossdomain header.
if (crossdomain_required) {
w->header()->set("Access-Control-Allow-Origin", "*");
w->header()->set("Access-Control-Allow-Methods", "GET, POST, HEAD, PUT, DELETE");
w->header()->set("Access-Control-Allow-Headers", "Cache-Control,X-Proxy-Authorization,X-Requested-With,Content-Type");
}
// handle the http options.
if (r->is_http_options()) {
w->header()->set_content_length(0);
if (_srs_config->get_http_api_crossdomain()) {
w->write_header(SRS_CONSTS_HTTP_OK);
} else {
w->write_header(SRS_CONSTS_HTTP_MethodNotAllowed);
}
return w->final_request();
}
// use default server mux to serve http request.
if ((ret = mux->serve_http(w, r)) != ERROR_SUCCESS) {
if (!srs_is_client_gracefully_close(ret)) {
srs_error("serve http msg failed. ret=%d", ret);
}
return ret;
}
return ret;
}
int SrsHttpApi::on_reload_http_api_crossdomain()
{
crossdomain_enabled = _srs_config->get_http_api_crossdomain();
return ERROR_SUCCESS;
}
#endif
| {
"content_hash": "2f3317cf73efb320970212d1fc4b44f8",
"timestamp": "",
"source": "github",
"line_count": 1436,
"max_line_length": 146,
"avg_line_length": 37.34818941504178,
"alnum_prop": 0.5742094272076372,
"repo_name": "myself659/simple-rtmp-server",
"id": "40fecd9290d918e2d6d571892c7dd64b8bb932c5",
"size": "54732",
"binary": false,
"copies": "4",
"ref": "refs/heads/develop",
"path": "trunk/src/app/srs_app_http_api.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "89221"
},
{
"name": "Assembly",
"bytes": "3935"
},
{
"name": "C",
"bytes": "191615"
},
{
"name": "C++",
"bytes": "3441502"
},
{
"name": "CMake",
"bytes": "4269"
},
{
"name": "HTML",
"bytes": "107145"
},
{
"name": "JavaScript",
"bytes": "76794"
},
{
"name": "Makefile",
"bytes": "10041"
},
{
"name": "Python",
"bytes": "36962"
},
{
"name": "QMake",
"bytes": "704"
},
{
"name": "Shell",
"bytes": "172800"
}
],
"symlink_target": ""
} |
import numpy as np
import os
import dill
import tempfile
import tensorflow as tf
import zipfile
import baselines.common.tf_util as U
from baselines import logger
from baselines.common.schedules import LinearSchedule
from baselines import deepq
from baselines.deepq.replay_buffer import ReplayBuffer, PrioritizedReplayBuffer
from pysc2.lib import actions as sc2_actions
from pysc2.env import environment
from pysc2.lib import features
from pysc2.lib import actions
from defeat_zerglings import common
import gflags as flags
_PLAYER_RELATIVE = features.SCREEN_FEATURES.player_relative.index
_UNIT_TYPE = features.SCREEN_FEATURES.unit_type.index
_SELECTED = features.SCREEN_FEATURES.selected.index
_PLAYER_FRIENDLY = 1
_PLAYER_NEUTRAL = 3 # beacon/minerals
_PLAYER_HOSTILE = 4
_NO_OP = actions.FUNCTIONS.no_op.id
_SELECT_UNIT_ID = 1
_CONTROL_GROUP_SET = 1
_CONTROL_GROUP_RECALL = 0
_SELECT_CONTROL_GROUP = actions.FUNCTIONS.select_control_group.id
_MOVE_SCREEN = actions.FUNCTIONS.Move_screen.id
_ATTACK_SCREEN = actions.FUNCTIONS.Attack_screen.id
_SELECT_ARMY = actions.FUNCTIONS.select_army.id
_SELECT_UNIT = actions.FUNCTIONS.select_unit.id
_SELECT_POINT = actions.FUNCTIONS.select_point.id
_NOT_QUEUED = [0]
_SELECT_ALL = [0]
UP, DOWN, LEFT, RIGHT = 'up', 'down', 'left', 'right'
FLAGS = flags.FLAGS
class ActWrapper(object):
def __init__(self, act):
self._act = act
#self._act_params = act_params
@staticmethod
def load(path, act_params, num_cpu=16):
with open(path, "rb") as f:
model_data = dill.load(f)
act = deepq.build_act(**act_params)
sess = U.make_session(num_cpu=num_cpu)
sess.__enter__()
with tempfile.TemporaryDirectory() as td:
arc_path = os.path.join(td, "packed.zip")
with open(arc_path, "wb") as f:
f.write(model_data)
zipfile.ZipFile(arc_path, 'r', zipfile.ZIP_DEFLATED).extractall(td)
U.load_state(os.path.join(td, "model"))
return ActWrapper(act)
def __call__(self, *args, **kwargs):
return self._act(*args, **kwargs)
def save(self, path):
"""Save model to a pickle located at `path`"""
with tempfile.TemporaryDirectory() as td:
U.save_state(os.path.join(td, "model"))
arc_name = os.path.join(td, "packed.zip")
with zipfile.ZipFile(arc_name, 'w') as zipf:
for root, dirs, files in os.walk(td):
for fname in files:
file_path = os.path.join(root, fname)
if file_path != arc_name:
zipf.write(file_path, os.path.relpath(file_path, td))
with open(arc_name, "rb") as f:
model_data = f.read()
with open(path, "wb") as f:
dill.dump((model_data), f)
def load(path, act_params, num_cpu=16):
"""Load act function that was returned by learn function.
Parameters
----------
path: str
path to the act function pickle
num_cpu: int
number of cpus to use for executing the policy
Returns
-------
act: ActWrapper
function that takes a batch of observations
and returns actions.
"""
return ActWrapper.load(path, num_cpu=num_cpu, act_params=act_params)
def learn(env,
q_func,
num_actions=3,
lr=5e-4,
max_timesteps=100000,
buffer_size=50000,
exploration_fraction=0.1,
exploration_final_eps=0.02,
train_freq=1,
batch_size=32,
print_freq=1,
checkpoint_freq=10000,
learning_starts=1000,
gamma=1.0,
target_network_update_freq=500,
prioritized_replay=False,
prioritized_replay_alpha=0.6,
prioritized_replay_beta0=0.4,
prioritized_replay_beta_iters=None,
prioritized_replay_eps=1e-6,
num_cpu=16,
param_noise=False,
param_noise_threshold=0.05,
callback=None,
demo_replay=[]
):
"""Train a deepq model.
Parameters
-------
env: pysc2.env.SC2Env
environment to train on
q_func: (tf.Variable, int, str, bool) -> tf.Variable
the model that takes the following inputs:
observation_in: object
the output of observation placeholder
num_actions: int
number of actions
scope: str
reuse: bool
should be passed to outer variable scope
and returns a tensor of shape (batch_size, num_actions) with values of every action.
lr: float
learning rate for adam optimizer
max_timesteps: int
number of env steps to optimizer for
buffer_size: int
size of the replay buffer
exploration_fraction: float
fraction of entire training period over which the exploration rate is annealed
exploration_final_eps: float
final value of random action probability
train_freq: int
update the model every `train_freq` steps.
set to None to disable printing
batch_size: int
size of a batched sampled from replay buffer for training
print_freq: int
how often to print out training progress
set to None to disable printing
checkpoint_freq: int
how often to save the model. This is so that the best version is restored
at the end of the training. If you do not wish to restore the best version at
the end of the training set this variable to None.
learning_starts: int
how many steps of the model to collect transitions for before learning starts
gamma: float
discount factor
target_network_update_freq: int
update the target network every `target_network_update_freq` steps.
prioritized_replay: True
if True prioritized replay buffer will be used.
prioritized_replay_alpha: float
alpha parameter for prioritized replay buffer
prioritized_replay_beta0: float
initial value of beta for prioritized replay buffer
prioritized_replay_beta_iters: int
number of iterations over which beta will be annealed from initial value
to 1.0. If set to None equals to max_timesteps.
prioritized_replay_eps: float
epsilon to add to the TD errors when updating priorities.
num_cpu: int
number of cpus to use for training
callback: (locals, globals) -> None
function called at every steps with state of the algorithm.
If callback returns true training stops.
Returns
-------
act: ActWrapper
Wrapper over act function. Adds ability to save it and load it.
See header of baselines/deepq/categorical.py for details on the act function.
"""
# Create all the functions necessary to train the model
sess = U.make_session(num_cpu=num_cpu)
sess.__enter__()
def make_obs_ph(name):
return U.BatchInput((64, 64), name=name)
act, train, update_target, debug = deepq.build_train(
make_obs_ph=make_obs_ph,
q_func=q_func,
num_actions=num_actions,
optimizer=tf.train.AdamOptimizer(learning_rate=lr),
gamma=gamma,
grad_norm_clipping=10
)
act_params = {
'make_obs_ph': make_obs_ph,
'q_func': q_func,
'num_actions': num_actions,
}
# Create the replay buffer
if prioritized_replay:
replay_buffer = PrioritizedReplayBuffer(buffer_size, alpha=prioritized_replay_alpha)
if prioritized_replay_beta_iters is None:
prioritized_replay_beta_iters = max_timesteps
beta_schedule = LinearSchedule(prioritized_replay_beta_iters,
initial_p=prioritized_replay_beta0,
final_p=1.0)
else:
replay_buffer = ReplayBuffer(buffer_size)
beta_schedule = None
# Create the schedule for exploration starting from 1.
exploration = LinearSchedule(schedule_timesteps=int(exploration_fraction * max_timesteps),
initial_p=1.0,
final_p=exploration_final_eps)
# Initialize the parameters and copy them to the target network.
U.initialize()
update_target()
episode_rewards = [0.0]
saved_mean_reward = None
obs = env.reset()
# Select all marines first
player_relative = obs[0].observation["screen"][_PLAYER_RELATIVE]
screen = player_relative
obs = common.init(env, player_relative, obs)
group_id = 0
reset = True
with tempfile.TemporaryDirectory() as td:
model_saved = False
model_file = os.path.join(td, "model")
for t in range(max_timesteps):
if callback is not None:
if callback(locals(), globals()):
break
# Take action and update exploration to the newest value
kwargs = {}
if not param_noise:
update_eps = exploration.value(t)
update_param_noise_threshold = 0.
else:
update_eps = 0.
if param_noise_threshold >= 0.:
update_param_noise_threshold = param_noise_threshold
else:
# Compute the threshold such that the KL divergence between perturbed and non-perturbed
# policy is comparable to eps-greedy exploration with eps = exploration.value(t).
# See Appendix C.1 in Parameter Space Noise for Exploration, Plappert et al., 2017
# for detailed explanation.
update_param_noise_threshold = -np.log(1. - exploration.value(t) + exploration.value(t) / float(num_actions))
kwargs['reset'] = reset
kwargs['update_param_noise_threshold'] = update_param_noise_threshold
kwargs['update_param_noise_scale'] = True
# custom process for DefeatZerglingsAndBanelings
obs, screen, player = common.select_marine(env, obs)
action = act(np.array(screen)[None], update_eps=update_eps, **kwargs)[0]
reset = False
rew = 0
new_action = None
obs, new_action = common.marine_action(env, obs, player, action)
army_count = env._obs.observation.player_common.army_count
try:
if army_count > 0 and _ATTACK_SCREEN in obs[0].observation["available_actions"]:
obs = env.step(actions=new_action)
else:
new_action = [sc2_actions.FunctionCall(_NO_OP, [])]
obs = env.step(actions=new_action)
except Exception as e:
#print(e)
1 # Do nothing
player_relative = obs[0].observation["screen"][_PLAYER_RELATIVE]
new_screen = player_relative
rew += obs[0].reward
done = obs[0].step_type == environment.StepType.LAST
selected = obs[0].observation["screen"][_SELECTED]
player_y, player_x = (selected == _PLAYER_FRIENDLY).nonzero()
if(len(player_y)>0):
player = [int(player_x.mean()), int(player_y.mean())]
if(len(player) == 2):
if(player[0]>32):
new_screen = common.shift(LEFT, player[0]-32, new_screen)
elif(player[0]<32):
new_screen = common.shift(RIGHT, 32 - player[0], new_screen)
if(player[1]>32):
new_screen = common.shift(UP, player[1]-32, new_screen)
elif(player[1]<32):
new_screen = common.shift(DOWN, 32 - player[1], new_screen)
# Store transition in the replay buffer.
replay_buffer.add(screen, action, rew, new_screen, float(done))
screen = new_screen
episode_rewards[-1] += rew
if done:
print("Episode Reward : %s" % episode_rewards[-1])
obs = env.reset()
player_relative = obs[0].observation["screen"][_PLAYER_RELATIVE]
screen = player_relative
group_list = common.init(env, player_relative, obs)
# Select all marines first
#env.step(actions=[sc2_actions.FunctionCall(_SELECT_UNIT, [_SELECT_ALL])])
episode_rewards.append(0.0)
reset = True
if t > learning_starts and t % train_freq == 0:
# Minimize the error in Bellman's equation on a batch sampled from replay buffer.
if prioritized_replay:
experience = replay_buffer.sample(batch_size, beta=beta_schedule.value(t))
(obses_t, actions, rewards, obses_tp1, dones, weights, batch_idxes) = experience
else:
obses_t, actions, rewards, obses_tp1, dones = replay_buffer.sample(batch_size)
weights, batch_idxes = np.ones_like(rewards), None
td_errors = train(obses_t, actions, rewards, obses_tp1, dones, weights)
if prioritized_replay:
new_priorities = np.abs(td_errors) + prioritized_replay_eps
replay_buffer.update_priorities(batch_idxes, new_priorities)
if t > learning_starts and t % target_network_update_freq == 0:
# Update target network periodically.
update_target()
mean_100ep_reward = round(np.mean(episode_rewards[-101:-1]), 1)
num_episodes = len(episode_rewards)
if done and print_freq is not None and len(episode_rewards) % print_freq == 0:
logger.record_tabular("steps", t)
logger.record_tabular("episodes", num_episodes)
logger.record_tabular("mean 100 episode reward", mean_100ep_reward)
logger.record_tabular("% time spent exploring", int(100 * exploration.value(t)))
logger.dump_tabular()
if (checkpoint_freq is not None and t > learning_starts and
num_episodes > 100 and t % checkpoint_freq == 0):
if saved_mean_reward is None or mean_100ep_reward > saved_mean_reward:
if print_freq is not None:
logger.log("Saving model due to mean reward increase: {} -> {}".format(
saved_mean_reward, mean_100ep_reward))
U.save_state(model_file)
model_saved = True
saved_mean_reward = mean_100ep_reward
if model_saved:
if print_freq is not None:
logger.log("Restored model with mean reward: {}".format(saved_mean_reward))
U.load_state(model_file)
return ActWrapper(act)
| {
"content_hash": "b105ed8717cd7bb36f56a9a2a592eece",
"timestamp": "",
"source": "github",
"line_count": 397,
"max_line_length": 119,
"avg_line_length": 34.31486146095718,
"alnum_prop": 0.6489025912060485,
"repo_name": "pangzhenjia/pysc2-source",
"id": "b06a36aa5f62969965d3afa697655daf218151b5",
"size": "13623",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "chris_example/defeat_zerglings/dqfd.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "433447"
}
],
"symlink_target": ""
} |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Class User
*/
class User extends MY_Controller {
public function __construct() {
parent::__construct();
$this->load->language('user');
$this->load->model('group_model');
}
public function index() {
$cur_page = $this->get_cur_page();
$name = $this->input->get_post('name', TRUE);
$where = array();
if ($name)
$where['name'] = $name;
$this->data['name'] = $name;
$result = $this->user_model->page_lists($where, 'uid DESC', self::PER_PAGE_NUM, $cur_page);
$this->data['page'] = $this->pagination($result['count'], site_url('user/index'));
$this->data->set($result);
$this->data['group_list'] = $this->group_model->lists(NULL, NULL, NULL, 'gid');
$this->data['add_pri'] = $this->has_privileges('user', 'add');
$this->data['edit_pri'] = $this->has_privileges('user', 'edit');
$this->data['set_status_pri'] = $this->has_privileges('user', 'set_status');
$this->data['acl_ctl_pri'] = $this->has_privileges('user', 'acl_ctl');
$this->load->view('user/index', $this->data->all());
}
public function add() {
$account = $this->input->post('name', TRUE);
$gid = $this->input->post('gid', TRUE);
$password = $this->input->post('pwd', TRUE);
$email = $this->input->post('email', TRUE);
$svn_account = $this->input->post('svn_account', TRUE);
if (empty($account) || empty($gid) || empty($password) || empty($email))
self::json(lang('miss_parameter'));
$user_info = $this->user_model->info($account, 'name');
if (!empty($user_info))
self::json(sprintf(lang('account_exists'), $account));
$user_info = $this->user_model->info($email, 'email');
if (!empty($user_info))
self::json(sprintf(lang('email_exists'), $email));
$salt = self::make_salt();
$data = array(
'name' => $account,
'gid' => $gid,
'pwd' => $this->encrypt_pwd($password, $salt),
'salt' => $salt,
'email' => $email,
'svn_account' => $svn_account,
'add_time' => date('Y-m-d H:i:s', time()),
);
$uid = $this->user_model->add($data);
self::record_log('user', lang('log_add_account_title'), sprintf(lang('log_add_account_content'), $account), $uid, $uid);
if ($uid)
self::json(lang('operation_success'), self::SUCCESS_STATUS);
else
self::json(lang('operation_fail'));
}
public function edit() {
$uid = $this->input->post('uid', TRUE);
$gid = $this->input->post('gid', TRUE);
$password = $this->input->post('pwd', TRUE);
$email = $this->input->post('email', TRUE);
$svn_account = $this->input->post('svn_account', TRUE);
if (empty($uid) || empty($gid) || empty($password) || empty($email))
self::json(lang('miss_parameter'));
$user_info = $this->user_model->info($uid, 'uid');
if (empty($user_info))
self::json(lang('account_not_exists'));
if ($email != $user_info['email']) {
$user_info = $this->user_model->info($email, 'email');
if (!empty($user_info))
self::json(sprintf(lang('email_exists'), $email));
}
$update_data = array(
'gid' => $gid,
'email' => $email,
'svn_account' => $svn_account,
);
if ($password != $user_info['pwd']) {
$salt = self::make_salt();
$update_data['salt'] = $salt;
$update_data['pwd'] = $this->encrypt_pwd($password, $salt);
}
$this->user_model->update(array('uid'=>$uid), $update_data);
self::record_log('user', lang('log_edit_account_title'), sprintf(lang('log_edit_account_content'), $user_info['name']), $uid);
self::json(lang('operation_success'), self::SUCCESS_STATUS);
}
public function set_status() {
$status = $this->input->post('status', TRUE);
$uid = $this->input->post('uid', TRUE);
if (!in_array($status, array(1, 2)))
self::json(lang('miss_parameter'));
$user_info = $this->user_model->info($uid, 'uid');
if (empty($user_info))
self::json(lang('account_not_exists'));
$res = $this->user_model->update(array('uid'=>$uid), array(
'status' => $status
));
self::record_log('user', lang('log_edit_account_title'), ($status == 1 ? sprintf(lang('account_set_open'), $user_info['name']) : sprintf(lang('account_set_close'), $user_info['name'])), $uid, $res);
if ($res)
self::json(lang('operation_success'), self::SUCCESS_STATUS);
else
self::json(lang('operation_fail'));
}
public function acl_ctl() {
$uid = $this->input->get('uid', TRUE);
$module_config = $this->module_model->get_module_lists();
$user_info = $this->user_model->info(array('uid'=>$uid),'uid');
$channel_list = $this->channel_model->lists();
$this->data->set(array(
'module_config' => $module_config,
'user' => $user_info,
'my_module_rights' => explode(',',$user_info['module_rights']),
'my_action_rights' => explode(',',$user_info['action_rights']),
'my_project_rights' => explode(',',$user_info['project_rights']),
'channel_list' => $channel_list,
));
$this->data['set_acl_pri'] = $this->has_privileges('user', 'set_acl');
$this->load->view('user/acl_ctl', $this->data->all());
}
public function set_acl() {
$uid = $this->input->get('uid', TRUE);
$module = $this->input->get('module', TRUE);
$action = $this->input->get('action', TRUE);
$project = $this->input->get('project', TRUE);
if (empty($uid) || empty($module) || empty($action))
self::json(lang('miss_parameter'));
$user_info = $this->user_model->info($uid, 'uid');
if (empty($user_info))
self::json(lang('account_not_exists'));
$res = $this->user_model->update(array('uid'=>$uid), array(
'module_rights' => $module,
'action_rights' => $action,
'project_rights' => $project,
));
self::record_log('acl', lang('log_permission_title'), sprintf(lang('log_permission_content'), $module, $action, $project), $uid, $res);
if ($res)
self::json(lang('operation_success'), self::SUCCESS_STATUS);
else
self::json(lang('operation_fail'));
}
} | {
"content_hash": "45b10698d1d8c1c2dfad17633f0666fe",
"timestamp": "",
"source": "github",
"line_count": 163,
"max_line_length": 206,
"avg_line_length": 41.24539877300614,
"alnum_prop": 0.522832069016808,
"repo_name": "iris-xie/supperWalle",
"id": "c54da4bd35a3f922a8c5608df8e10ac644c5ecab",
"size": "6723",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "consult/application/controllers/user.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "515"
},
{
"name": "CSS",
"bytes": "519443"
},
{
"name": "HTML",
"bytes": "1277417"
},
{
"name": "JavaScript",
"bytes": "1141745"
},
{
"name": "PHP",
"bytes": "2067949"
},
{
"name": "Shell",
"bytes": "84"
}
],
"symlink_target": ""
} |
#include <config.h>
#include "compat.h"
#include "timer.h"
double
timer_get_time( void )
{
return compat_timer_get_time();
}
void
timer_sleep( int ms )
{
compat_timer_sleep( ms );
}
| {
"content_hash": "8f901b0824daa81b339453542c3b7488",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 33,
"avg_line_length": 10.105263157894736,
"alnum_prop": 0.6458333333333334,
"repo_name": "FinnAngelo/Tomfoolery",
"id": "65ae2913daac027ddcf5f0d273ef256e92fe25ae",
"size": "1107",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "ZX/Fuse-Spectrum/fuse/timer/native.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "2582"
},
{
"name": "AutoHotkey",
"bytes": "7089"
},
{
"name": "Batchfile",
"bytes": "242"
},
{
"name": "C",
"bytes": "3631617"
},
{
"name": "C#",
"bytes": "4036348"
},
{
"name": "C++",
"bytes": "113526"
},
{
"name": "CSS",
"bytes": "253"
},
{
"name": "CoffeeScript",
"bytes": "3821"
},
{
"name": "F#",
"bytes": "1942"
},
{
"name": "HTML",
"bytes": "66835"
},
{
"name": "Java",
"bytes": "641016"
},
{
"name": "Lex",
"bytes": "4989"
},
{
"name": "M4",
"bytes": "231887"
},
{
"name": "Makefile",
"bytes": "91421"
},
{
"name": "Objective-C",
"bytes": "88666"
},
{
"name": "Perl",
"bytes": "152182"
},
{
"name": "Perl 6",
"bytes": "8131"
},
{
"name": "PowerShell",
"bytes": "12075"
},
{
"name": "Roff",
"bytes": "202777"
},
{
"name": "Shell",
"bytes": "25482"
},
{
"name": "Yacc",
"bytes": "10585"
}
],
"symlink_target": ""
} |
name: Primary Brand
---<a href="#" class="primary-brand--anchor"></a> | {
"content_hash": "26cd927a4d8e195c6963ba4234165494",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 49,
"avg_line_length": 34.5,
"alnum_prop": 0.6521739130434783,
"repo_name": "martinmcloughlin/novatapestry",
"id": "96d3f9673a5f7246c7f455d31953d917b41ea305",
"size": "74",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/patterns/2.Elements/3.Links/2.AnchorAndLinkModifiers/8.Primary-brand.md",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "315974"
},
{
"name": "HTML",
"bytes": "104903"
},
{
"name": "JavaScript",
"bytes": "29989"
}
],
"symlink_target": ""
} |
package org.openprovenance.prov.notation;
import java.util.List;
public interface TreeConstructor {
/* Component 1 */
public Object convertEntity(Object id, Object attrs);
public Object convertActivity(Object id,Object startTime,Object endTime, Object aAttrs);
public Object convertStart(String start);
public Object convertEnd(String end);
public Object convertUsed(Object id, Object id2,Object id1, Object time, Object aAttrs);
public Object convertWasGeneratedBy(Object id, Object id2,Object id1, Object time, Object aAttrs);
public Object convertWasStartedBy(Object id, Object id2,Object id1, Object id3, Object time, Object aAttrs);
public Object convertWasEndedBy(Object id, Object id2,Object id1, Object id3, Object time, Object aAttrs);
public Object convertWasInvalidatedBy(Object id, Object id2,Object id1, Object time, Object aAttrs);
public Object convertWasInformedBy(Object id, Object id2, Object id1, Object aAttrs);
/* Component 2 */
public Object convertAgent(Object id, Object attrs);
public Object convertWasAttributedTo(Object id, Object id2,Object id1, Object aAttrs);
public Object convertWasAssociatedWith(Object id, Object id2,Object id1, Object pl, Object aAttrs);
public Object convertActedOnBehalfOf(Object id, Object id2,Object id1, Object a, Object aAttrs);
/* Component 3 */
public Object convertWasDerivedFrom(Object id, Object id2,Object id1, Object pe, Object q2, Object q1, Object dAttrs);
public Object convertWasRevisionOf(Object id, Object id2,Object id1, Object pe, Object q2, Object q1, Object dAttrs);
public Object convertWasQuotedFrom(Object id, Object id2,Object id1, Object pe, Object q2, Object q1, Object dAttrs);
public Object convertHadOriginalSource(Object id, Object id2,Object id1, Object pe, Object q2, Object q1, Object dAttrs);
public Object convertTracedTo(Object id, Object id2, Object id1, Object dAttrs);
/* Component 4 */
public Object convertAlternateOf(Object id2,Object id1);
public Object convertSpecializationOf(Object id2,Object id1);
/* Component 5 */
public Object convertInsertion(Object id, Object id2, Object id1, Object map, Object dAttrs);
public Object convertRemoval(Object id, Object id2, Object id1, Object keyset, Object dAttrs);
public Object convertEntry(Object o1, Object o2);
public Object convertKeyEntitySet(List<Object> o);
public Object convertKeys(List<Object> o);
public Object convertMemberOf(Object id, Object id2, Object map, Object complete, Object dAttrs);
/* Component 6 */
public Object convertNote(Object id, Object attrs);
public Object convertHasAnnotation(Object something, Object note);
public Object convertHasProvenanceIn(Object uid,Object su, Object bu, Object ta, Object se, Object pr, Object dAttrs);
/* Other conversions */
public Object convertBundle(Object nss, List<Object> records, List<Object> bundles);
public Object convertNamedBundle(Object id, Object nss, List<Object> records);
public Object convertAttributes(List<Object> attributes);
public Object convertId(String id);
public Object convertAttribute(Object name, Object value);
public Object convertString(String s);
public Object convertInt(int i);
public Object convertQualifiedName(String qname);
public Object convertIRI(String iri);
public Object convertPrefix(String pre);
public Object convertTypedLiteral(String datatype, Object value);
public Object convertNamespace(Object pre, Object iri);
public Object convertDefaultNamespace(Object iri);
public Object convertNamespaces(List<Object> namespaces);
} | {
"content_hash": "02e8cdf79f3bce98361aaa3950186284",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 125,
"avg_line_length": 50.6986301369863,
"alnum_prop": 0.7584436638746285,
"repo_name": "weishi423/ProvToolboxWithNeo4j",
"id": "d7051262835a93a38c2e17d7afd82aa56dca1106",
"size": "3701",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "asn/src/main/java/org/openprovenance/prov/notation/TreeConstructor.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "336086"
},
{
"name": "JavaScript",
"bytes": "19681"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>2. Installation — The Vortex OpenSplice LabVIEW Guide</title>
<link rel="stylesheet" href="_static/vortex.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '6.x',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<link rel="top" title="The Vortex OpenSplice LabVIEW Guide" href="index.html" />
<link rel="next" title="3. Vortex DDS Virtual Instruments (VIs)" href="dds_vis.html" />
<link rel="prev" title="1. Introduction" href="introduction.html" />
</head>
<body>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="dds_vis.html" title="3. Vortex DDS Virtual Instruments (VIs)"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="introduction.html" title="1. Introduction"
accesskey="P">previous</a> |</li>
<li><a href="index.html">OpenSplice LabVIEW Guide</a> »</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body">
<div class="section" id="installation">
<span id="id1"></span><h1>2. Installation<a class="headerlink" href="#installation" title="Permalink to this headline">¶</a></h1>
<p>This section describes the procedure to install the Vortex DDS LabVIEW Integration on a Linux or Windows platform.</p>
<div class="section" id="system-requirements">
<h2>2.1. System Requirements<a class="headerlink" href="#system-requirements" title="Permalink to this headline">¶</a></h2>
<ul class="simple">
<li>Operating System: Windows or Linux</li>
<li>LabVIEW 2017 installed</li>
</ul>
</div>
<div class="section" id="opensplice-ospl-and-dds-labview-installation">
<h2>2.2. OpenSplice (OSPL) and DDS LabVIEW Installation<a class="headerlink" href="#opensplice-ospl-and-dds-labview-installation" title="Permalink to this headline">¶</a></h2>
<p>Steps:</p>
<ol class="arabic simple">
<li>Install OSPL. The DDS LabVIEW Integration is included in this installer.</li>
<li>Setup OSPL license. Copy the license.lic file into the appropriate license directory.</li>
</ol>
<blockquote>
<div><em>/INSTALLDIR/ADLINK/Vortex_v2/license</em></div></blockquote>
<ol class="arabic simple" start="3">
<li>LabVIEW installation files are contained in a tools/labview folder.</li>
</ol>
<blockquote>
<div>Example:
<em>/INSTALLDIR/ADLINK/Vortex_v2/Device/VortexOpenSplice/6.9.x/HDE/x86_64.linux/tools/labview</em></div></blockquote>
</div>
<div class="section" id="opensplice-ospl-configuration">
<h2>2.3. OpenSplice (OSPL) Configuration<a class="headerlink" href="#opensplice-ospl-configuration" title="Permalink to this headline">¶</a></h2>
<p>By default OSPL uses single process configuration.</p>
</div>
<div class="section" id="dds-labview-installation">
<h2>2.4. DDS LabVIEW Installation<a class="headerlink" href="#dds-labview-installation" title="Permalink to this headline">¶</a></h2>
<div class="section" id="linux">
<h3>2.4.1. Linux<a class="headerlink" href="#linux" title="Permalink to this headline">¶</a></h3>
<ol class="arabic">
<li><p class="first">Open a command shell and navigate to</p>
<p><em>/INSTALLDIR/ADLINK/Vortex_v2/Device/VortexOpenSplice/6.9.x/HDE/x86_64.linux/tools/labview</em></p>
</li>
<li><p class="first">Unzip the “adlink-dds-labview-linux-install.tar.gz”.</p>
</li>
<li><p class="first">Run the install_vortex_dds_ubuntu.sh script as a super user.</p>
<p>sudo ./install_vortex_dds_ubuntu.sh</p>
<p><em>NOTE: The installer sets the default LabVIEW installation path to /usr/local/natinst/LabVIEW-2017-64.</em> <em>To override this installation directory, run the install script and pass the install directory as an argument:</em></p>
<p><em>sudo ./install_vortex_dds_ubuntu.sh /path/to/your/LabVIEW/installation</em></p>
</li>
<li><p class="first">LabVIEW will open and allow the installation Virtual Instrument (VI) run to completion.</p>
</li>
<li><p class="first">After the installation is complete close LabVIEW. Installation takes effect the next time you start LabVIEW.</p>
</li>
</ol>
</div>
<div class="section" id="windows">
<h3>2.4.2. Windows<a class="headerlink" href="#windows" title="Permalink to this headline">¶</a></h3>
<ol class="arabic">
<li><p class="first">In a file browser, navigate to</p>
<p><em>/INSTALLDIR/ADLINK/Vortex_v2/Device/VortexOpenSplice/6.9.x/HDE/x86_64.windows/tools/labview</em></p>
</li>
<li><p class="first">Double click on the file “adlink_lib_vortexdds-1.0.0.1”. This will bring up the VI Package Manager installer dialog box. Select the LabVIEW version to install (32-bit or 64-bit). Select <strong>Install</strong>.</p>
</li>
</ol>
<div class="figure">
<img alt="DDS windows install" src="_images/windowsInstall1.png" />
</div>
<ol class="arabic simple" start="3">
<li>After the installation is complete close LabVIEW. Installation takes effect the next time you start LabVIEW.</li>
</ol>
</div>
</div>
<div class="section" id="running-labview">
<h2>2.5. Running LabVIEW<a class="headerlink" href="#running-labview" title="Permalink to this headline">¶</a></h2>
<p>Steps:</p>
<ol class="arabic">
<li><p class="first">Open command shell and run script to setup environment variables.</p>
<blockquote>
<div><p><strong>Linux</strong></p>
<ul>
<li><p class="first">Open a Linux terminal.</p>
</li>
<li><p class="first">Navigate to directory containing release.com file.</p>
<p><em>/INSTALLDIR/ADLINK/Vortex_v2/Device/VortexOpenSplice/6.9.x/HDE/x86_64.linux</em></p>
</li>
<li><p class="first">Run release.com. (Type in “. release.com” at command line.)</p>
</li>
</ul>
<p><strong>Windows</strong></p>
<ul>
<li><p class="first">Open a command prompt.</p>
</li>
<li><p class="first">Navigate to directory containing release.bat file.</p>
<p><em>INSTALLDIR/ADLINK/Vortex_v2/Device/VortexOpenSplice/6.9.x/HDE/x86_64.win64</em></p>
</li>
<li><p class="first">Run release.bat. (Type in “release.bat” at command line.)</p>
</li>
</ul>
</div></blockquote>
</li>
<li><p class="first">Start LabVIEW using the <strong>SAME</strong> command shell used in Step 1.</p>
<blockquote>
<div><p><em>NOTE: If LabVIEW is NOT started from a command shell with the correct OSPL environment variables set, errors will occur when attempting to use DDS LabVIEW virtual instruments.</em></p>
</div></blockquote>
</li>
</ol>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar">
<div class="sphinxsidebarwrapper">
<p class="logo"><a href="index.html">
<img class="logo" src="_static/Vortex_logo_2014.png" alt="Logo"/>
</a></p>
<h3><a href="index.html">Table Of Contents</a></h3>
<ul>
<li><a class="reference internal" href="#">2. Installation</a><ul>
<li><a class="reference internal" href="#system-requirements">2.1. System Requirements</a></li>
<li><a class="reference internal" href="#opensplice-ospl-and-dds-labview-installation">2.2. OpenSplice (OSPL) and DDS LabVIEW Installation</a></li>
<li><a class="reference internal" href="#opensplice-ospl-configuration">2.3. OpenSplice (OSPL) Configuration</a></li>
<li><a class="reference internal" href="#dds-labview-installation">2.4. DDS LabVIEW Installation</a><ul>
<li><a class="reference internal" href="#linux">2.4.1. Linux</a></li>
<li><a class="reference internal" href="#windows">2.4.2. Windows</a></li>
</ul>
</li>
<li><a class="reference internal" href="#running-labview">2.5. Running LabVIEW</a></li>
</ul>
</li>
</ul>
<h4>Previous topic</h4>
<p class="topless"><a href="introduction.html"
title="previous chapter">1. Introduction</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="dds_vis.html"
title="next chapter">3. Vortex DDS Virtual Instruments (VIs)</a></p>
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="_sources/installation.txt"
rel="nofollow">Show Source</a></li>
</ul>
<div id="searchbox" style="display: none">
<h3>Quick search</h3>
<form class="search" action="search.html" method="get">
<input type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
<p class="searchtip" style="font-size: 90%">
Enter search terms or a module, class or function name.
</p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="General Index"
>index</a></li>
<li class="right" >
<a href="dds_vis.html" title="3. Vortex DDS Virtual Instruments (VIs)"
>next</a> |</li>
<li class="right" >
<a href="introduction.html" title="1. Introduction"
>previous</a> |</li>
<li><a href="index.html">OpenSplice LabVIEW Guide</a> »</li>
</ul>
</div>
<div class="footer">
© Copyright 2018, ADLINK Technology Limited.
</div>
</body>
</html> | {
"content_hash": "a21c2c414105ca886c58ca402be4774f",
"timestamp": "",
"source": "github",
"line_count": 229,
"max_line_length": 239,
"avg_line_length": 44.06113537117904,
"alnum_prop": 0.6578790882061447,
"repo_name": "osrf/opensplice",
"id": "c7e5d958baa4c75f82c5d5838be476c4f053da15",
"size": "10110",
"binary": false,
"copies": "2",
"ref": "refs/heads/osrf-6.9.0",
"path": "docs/html/DDSLabVIEWGuide/installation.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "16400"
},
{
"name": "Batchfile",
"bytes": "192174"
},
{
"name": "C",
"bytes": "19618578"
},
{
"name": "C#",
"bytes": "2428591"
},
{
"name": "C++",
"bytes": "8036199"
},
{
"name": "CMake",
"bytes": "35186"
},
{
"name": "CSS",
"bytes": "41427"
},
{
"name": "HTML",
"bytes": "457045"
},
{
"name": "Java",
"bytes": "5184488"
},
{
"name": "JavaScript",
"bytes": "540355"
},
{
"name": "LLVM",
"bytes": "13059"
},
{
"name": "Lex",
"bytes": "51476"
},
{
"name": "Makefile",
"bytes": "513684"
},
{
"name": "Objective-C",
"bytes": "38424"
},
{
"name": "Perl",
"bytes": "164028"
},
{
"name": "Python",
"bytes": "915683"
},
{
"name": "Shell",
"bytes": "363583"
},
{
"name": "TeX",
"bytes": "8134"
},
{
"name": "Visual Basic",
"bytes": "290"
},
{
"name": "Yacc",
"bytes": "202848"
}
],
"symlink_target": ""
} |
function getDomainProtocol($url){
$protoArr = array("https","http");
foreach($protoArr as $proto){
$gUrl = sprintf("%s://%s",$proto,$url);
if($curl = curl_init()) {
curl_setopt($curl, CURLOPT_URL, $gUrl);
curl_setopt($curl, CURLOPT_TIMEOUT, 15);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_FAILONERROR, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_exec($curl);
$errNumb = curl_errno($curl);
curl_close ($curl);
if($errNumb == 0){
return $gUrl;
}
}else echo "ERROR INIT CURL!<br/>\r\n";
$errNumb = 0;
}
return sprintf("http://%s",$url);
}
| {
"content_hash": "a16bf3e0466715b43f80265e45555c84",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 53,
"avg_line_length": 31.363636363636363,
"alnum_prop": 0.6289855072463768,
"repo_name": "ReaGed/functions",
"id": "42f75547f64a0311b1880e075b5749d853ef7210",
"size": "753",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "getDomainProtocol.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "1943"
}
],
"symlink_target": ""
} |
@implementation BDVRClientUIManager
#pragma mark - init & dealloc
- (id)init
{
self = [super init];
if (self)
{
//
}
return self;
}
+ (BDVRClientUIManager *)sharedInstance
{
static BDVRClientUIManager *_sharedInstance = nil;
if (_sharedInstance == nil)
_sharedInstance = [[BDVRClientUIManager alloc] init];
return _sharedInstance;
}
#pragma mark - UIManager Methods
- (CGRect)VRBackgroundFrame
{
return [UIScreen mainScreen].applicationFrame;
}
- (CGRect)VRRecordTintWordFrame
{
return CGRectMake(0.0f, 0.0f, 260.0f, 42.0f);
}
- (CGRect)VRRecognizeTintWordFrame
{
return CGRectMake(0.0f, 0.0f, 260.0f, 42.0f);
}
- (CGRect)VRLeftButtonFrame
{
return CGRectMake(0.0f, 214.0f - 58.0f, 144.0f, 52.0f);
}
- (CGRect)VRRightButtonFrame
{
return CGRectMake(144.0f, 214.0f - 58.0f, 145.0f, 52.0f);
}
- (CGRect)VRCenterButtonFrame
{
return CGRectMake(0.0f, 0.0f, 260.0f, 52.0f);
}
#pragma mark center point
- (CGPoint)VRRecordBackgroundCenter
{
return CGPointMake(145.0f, 56.0f);
}
- (CGPoint)VRRecognizeBackgroundCenter
{
return CGPointMake(145.0f, 46.0f);
}
- (CGPoint)VRTintWordCenter
{
return CGPointMake(145.0f, 120.0f);
}
- (CGPoint)VRCenterButtonCenter
{
return CGPointMake(145.0f, 182.0f);
}
- (CGRect)VRDemoWebViewFrame
{
return CGRectMake(13.0f, 302.0f, 294.0f, 147.0f);
}
- (CGRect)VRDemoPicerViewFrame
{
CGSize screenSize = [UIScreen mainScreen].bounds.size;
return CGRectMake((screenSize.width - 320) / 2, screenSize.height - 261, 320, 261);
}
- (CGRect)VRDemoPicerBackgroundViewFrame
{
return [UIScreen mainScreen].applicationFrame;
}
@end // BDVRClientUIManager
| {
"content_hash": "7b04432eb3c9c68e6015ef1101b81b7a",
"timestamp": "",
"source": "github",
"line_count": 93,
"max_line_length": 87,
"avg_line_length": 17.70967741935484,
"alnum_prop": 0.7049180327868853,
"repo_name": "ascode/jif-BaiduASR",
"id": "12f2bb5b343536cb2cf817dcd569e88792a32dc0",
"size": "1834",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "BDVRClientSample/BDVRClientSample/Classes/Views/CustomRecognitionView/BDVRClientUIManager.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "39014"
},
{
"name": "C++",
"bytes": "92918"
},
{
"name": "Objective-C",
"bytes": "264927"
},
{
"name": "Objective-C++",
"bytes": "25018"
},
{
"name": "Swift",
"bytes": "4988"
}
],
"symlink_target": ""
} |
from unittest import mock
import pytest
import stripe
from model_mommy import mommy
from rest_framework.reverse import reverse
from restframework_stripe import models
from restframework_stripe.test import get_mock_resource
@mock.patch("stripe.Customer.retrieve")
@mock.patch("stripe.ListObject.create")
@pytest.mark.django_db
def test_create_subscription(create_sub, retrieve_customer, plan, customer, api_client):
create_sub.return_value = get_mock_resource("Subscription", plan=plan.source)
retrieve_customer.return_value = get_mock_resource("Customer")
api_client.force_authenticate(customer.owner)
data = {
"plan": plan.id,
"coupon": None
}
uri = reverse("rf_stripe:subscription-list")
response = api_client.post(uri, data=data, format="json")
assert response.status_code == 201, response.data
assert 0 < customer.owner.stripe_subscriptions.count()
@mock.patch("stripe.Customer.retrieve")
@mock.patch("stripe.ListObject.create")
@pytest.mark.django_db
def test_create_subscription_with_coupon(create_sub, retrieve_customer, plan, coupon,
customer, api_client):
create_sub.return_value = get_mock_resource("Subscription",
plan=plan.source,
discount={"coupon": coupon.source})
retrieve_customer.return_value = get_mock_resource("Customer")
api_client.force_authenticate(customer.owner)
data = {
"plan": plan.id,
"coupon": coupon.id
}
uri = reverse("rf_stripe:subscription-list")
response = api_client.post(uri, data=data, format="json")
assert response.status_code == 201, response.data
assert 0 < customer.owner.stripe_subscriptions.count()
@mock.patch("stripe.Customer.retrieve")
@mock.patch("stripe.Subscription.save")
@mock.patch("stripe.ListObject.retrieve")
@pytest.mark.django_db
def test_update_subscription(
sub_retrieve,
sub_update,
customer_retrieve,
customer,
subscription,
api_client,
coupon):
subscription.owner = customer.owner
subscription.save()
api_client.force_authenticate(customer.owner)
data = {
"coupon": coupon.id
}
customer_retrieve.return_value = customer.source
sub_retrieve.return_value = subscription.source
sub_update.return_value = get_mock_resource("Subscription",
plan=subscription.plan.source,
discount={"coupon": coupon.source})
uri = reverse("rf_stripe:subscription-detail", kwargs={"pk": subscription.pk})
response = api_client.patch(uri, data=data, format="json")
assert response.status_code == 200, response.data
@pytest.mark.django_db
def test_options(customer, api_client):
api_client.force_authenticate(customer.owner)
uri = reverse("rf_stripe:subscription-list")
response = api_client.options(uri)
assert response.status_code == 200, response.data
| {
"content_hash": "22ff6043dd254df7b7ba9bbf9059aa33",
"timestamp": "",
"source": "github",
"line_count": 92,
"max_line_length": 88,
"avg_line_length": 32.44565217391305,
"alnum_prop": 0.678391959798995,
"repo_name": "andrewyoung1991/django-restframework-stripe",
"id": "851a29286438440c6cd9d1078814707ee3b9f46c",
"size": "2985",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/test_subscription.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Python",
"bytes": "138282"
}
],
"symlink_target": ""
} |
<section class="u-section-separator">
<h2 class="hidden">Introduction</h2>
<p>Paracetamol is a common painkiller used to treat aches and pain. It can also be used to reduce fever (a temperature above 38C).</p>
<p>It's also available combined with other painkillers and anti-sickness medicines. It is an ingredient in a wide range of cold and flu remedies.</p>
<p>It may be called by a brand name such as Disprol, Hedex, Medinol and Panadol.</p>
<p>For under-16s read our information on '<a href="/paracetamol/tabbed-children">Paracetamol for children</a>'.</p>
</section>
| {
"content_hash": "e129b48a6855994c9e26521029c9490f",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 151,
"avg_line_length": 83.14285714285714,
"alnum_prop": 0.7422680412371134,
"repo_name": "NHSChoices/medicines-alpha",
"id": "d208d0fb32ffeecbb3b4c24d31411d130beacba6",
"size": "582",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/views/paracetamol/includes/adults/intro.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "67457"
},
{
"name": "HTML",
"bytes": "1956816"
},
{
"name": "JavaScript",
"bytes": "58684"
},
{
"name": "Shell",
"bytes": "649"
}
],
"symlink_target": ""
} |
//>>built
define("dojox/grid/DataGrid", [
"../main",
"dojo/_base/array",
"dojo/_base/lang",
"dojo/_base/json",
"dojo/_base/sniff",
"dojo/_base/declare",
"./_Grid",
"./DataSelection",
"dojo/_base/html"
], function(dojox, array, lang, json, has, declare, _Grid, DataSelection, html){
/*=====
declare("dojox.grid.__DataCellDef", dojox.grid.__CellDef, {
constructor: function(){
// field: String?
// The attribute to read from the dojo.data item for the row.
// fields: String[]?
// An array of fields to grab the values of and pass as an array to the grid
// get: Function?
// function(rowIndex, item?){} rowIndex is of type Integer, item is of type
// Object. This function will be called when a cell requests data. Returns
// the unformatted data for the cell.
}
});
=====*/
/*=====
declare("dojox.grid.__DataViewDef", dojox.grid.__ViewDef, {
constructor: function(){
// cells: dojox.grid.__DataCellDef[]|Array[dojox.grid.__DataCellDef[]]?
// The structure of the cells within this grid.
// defaultCell: dojox.grid.__DataCellDef?
// A cell definition with default values for all cells in this view. If
// a property is defined in a cell definition in the "cells" array and
// this property, the cell definition's property will override this
// property's property.
}
});
=====*/
var DataGrid = declare("dojox.grid.DataGrid", _Grid, {
store: null,
query: null,
queryOptions: null,
fetchText: '...',
sortFields: null,
// updateDelay: int
// Time, in milliseconds, to delay updates automatically so that multiple
// calls to onSet/onNew/onDelete don't keep rerendering the grid. Set
// to 0 to immediately cause updates. A higher value will result in
// better performance at the expense of responsiveness of the grid.
updateDelay: 1,
/*=====
// structure: dojox.grid.__DataViewDef|dojox.grid.__DataViewDef[]|dojox.grid.__DataCellDef[]|Array[dojox.grid.__DataCellDef[]]
// View layout defintion.
structure: '',
=====*/
// You can specify items instead of a query, if you like. They do not need
// to be loaded - but the must be items in the store
items: null,
_store_connects: null,
_by_idty: null,
_by_idx: null,
_cache: null,
_pages: null,
_pending_requests: null,
_bop: -1,
_eop: -1,
_requests: 0,
rowCount: 0,
_isLoaded: false,
_isLoading: false,
//keepSelection: Boolean
// Whether keep selection after sort, filter etc.
keepSelection: false,
postCreate: function(){
this._pages = [];
this._store_connects = [];
this._by_idty = {};
this._by_idx = [];
this._cache = [];
this._pending_requests = {};
this._setStore(this.store);
this.inherited(arguments);
},
destroy: function(){
this.selection.destroy();
this.inherited(arguments);
},
createSelection: function(){
this.selection = new DataSelection(this);
},
get: function(inRowIndex, inItem){
// summary: Default data getter.
// description:
// Provides data to display in a grid cell. Called in grid cell context.
// So this.cell.index is the column index.
// inRowIndex: Integer
// Row for which to provide data
// returns:
// Data to display for a given grid cell.
if(inItem && this.field == "_item" && !this.fields){
return inItem;
}else if(inItem && this.fields){
var ret = [];
var s = this.grid.store;
array.forEach(this.fields, function(f){
ret = ret.concat(s.getValues(inItem, f));
});
return ret;
}else if(!inItem && typeof inRowIndex === "string"){
return this.inherited(arguments);
}
return (!inItem ? this.defaultValue : (!this.field ? this.value : (this.field == "_item" ? inItem : this.grid.store.getValue(inItem, this.field))));
},
_checkUpdateStatus: function(){
if(this.updateDelay > 0){
var iStarted = false;
if(this._endUpdateDelay){
clearTimeout(this._endUpdateDelay);
delete this._endUpdateDelay;
iStarted = true;
}
if(!this.updating){
this.beginUpdate();
iStarted = true;
}
if(iStarted){
var _this = this;
this._endUpdateDelay = setTimeout(function(){
delete _this._endUpdateDelay;
_this.endUpdate();
}, this.updateDelay);
}
}
},
_onSet: function(item, attribute, oldValue, newValue){
this._checkUpdateStatus();
var idx = this.getItemIndex(item);
if(idx>-1){
this.updateRow(idx);
}
},
_createItem: function(item, index){
var idty = this._hasIdentity ? this.store.getIdentity(item) : json.toJson(this.query) + ":idx:" + index + ":sort:" + json.toJson(this.getSortProps());
var o = this._by_idty[idty] = { idty: idty, item: item };
return o;
},
_addItem: function(item, index, noUpdate){
this._by_idx[index] = this._createItem(item, index);
if(!noUpdate){
this.updateRow(index);
}
},
_onNew: function(item, parentInfo){
this._checkUpdateStatus();
var rowCount = this.get('rowCount');
this._addingItem = true;
this.updateRowCount(rowCount+1);
this._addingItem = false;
this._addItem(item, rowCount);
this.showMessage();
},
_onDelete: function(item){
this._checkUpdateStatus();
var idx = this._getItemIndex(item, true);
if(idx >= 0){
// When a row is deleted, all rest rows are shifted down,
// and migrate from page to page. If some page is not
// loaded yet empty rows can migrate to initialized pages
// without refreshing. It causes empty rows in some pages, see:
// http://bugs.dojotoolkit.org/ticket/6818
// this code fix this problem by reseting loaded page info
this._pages = [];
this._bop = -1;
this._eop = -1;
var o = this._by_idx[idx];
this._by_idx.splice(idx, 1);
delete this._by_idty[o.idty];
this.updateRowCount(this.get('rowCount')-1);
if(this.get('rowCount') === 0){
this.showMessage(this.noDataMessage);
}
}
if(this.selection.isSelected(idx)){
this.selection.deselect(idx);
this.selection.selected.splice(idx, 1);
}
},
_onRevert: function(){
this._refresh();
},
setStore: function(store, query, queryOptions){
if(this._requestsPending(0)){
return;
}
this._setQuery(query, queryOptions);
this._setStore(store);
this._refresh(true);
},
setQuery: function(query, queryOptions){
if(this._requestsPending(0)){
return;
}
this._setQuery(query, queryOptions);
this._refresh(true);
},
setItems: function(items){
this.items = items;
this._setStore(this.store);
this._refresh(true);
},
_setQuery: function(query, queryOptions){
this.query = query;
this.queryOptions = queryOptions || this.queryOptions;
},
_setStore: function(store){
if(this.store && this._store_connects){
array.forEach(this._store_connects, this.disconnect, this);
}
this.store = store;
if(this.store){
var f = this.store.getFeatures();
var h = [];
this._canEdit = !!f["dojo.data.api.Write"] && !!f["dojo.data.api.Identity"];
this._hasIdentity = !!f["dojo.data.api.Identity"];
if(!!f["dojo.data.api.Notification"] && !this.items){
h.push(this.connect(this.store, "onSet", "_onSet"));
h.push(this.connect(this.store, "onNew", "_onNew"));
h.push(this.connect(this.store, "onDelete", "_onDelete"));
}
if(this._canEdit){
h.push(this.connect(this.store, "revert", "_onRevert"));
}
this._store_connects = h;
}
},
_onFetchBegin: function(size, req){
if(!this.scroller){ return; }
if(this.rowCount != size){
if(req.isRender){
this.scroller.init(size, this.keepRows, this.rowsPerPage);
this.rowCount = size;
this._setAutoHeightAttr(this.autoHeight, true);
this._skipRowRenormalize = true;
this.prerender();
this._skipRowRenormalize = false;
}else{
this.updateRowCount(size);
}
}
if(!size){
this.views.render();
this._resize();
this.showMessage(this.noDataMessage);
this.focus.initFocusView();
}else{
this.showMessage();
}
},
_onFetchComplete: function(items, req){
if(!this.scroller){ return; }
if(items && items.length > 0){
//console.log(items);
array.forEach(items, function(item, idx){
this._addItem(item, req.start+idx, true);
}, this);
this.updateRows(req.start, items.length);
if(req.isRender){
this.setScrollTop(0);
this.postrender();
}else if(this._lastScrollTop){
this.setScrollTop(this._lastScrollTop);
}
if(has("ie")){
html.setSelectable(this.domNode, this.selectable);
}
}
delete this._lastScrollTop;
if(!this._isLoaded){
this._isLoading = false;
this._isLoaded = true;
}
this._pending_requests[req.start] = false;
},
_onFetchError: function(err, req){
console.log(err);
delete this._lastScrollTop;
if(!this._isLoaded){
this._isLoading = false;
this._isLoaded = true;
this.showMessage(this.errorMessage);
}
this._pending_requests[req.start] = false;
this.onFetchError(err, req);
},
onFetchError: function(err, req){
},
_fetch: function(start, isRender){
start = start || 0;
if(this.store && !this._pending_requests[start]){
if(!this._isLoaded && !this._isLoading){
this._isLoading = true;
this.showMessage(this.loadingMessage);
}
this._pending_requests[start] = true;
//console.log("fetch: ", start);
try{
if(this.items){
var items = this.items;
var store = this.store;
this.rowsPerPage = items.length;
var req = {
start: start,
count: this.rowsPerPage,
isRender: isRender
};
this._onFetchBegin(items.length, req);
// Load them if we need to
var waitCount = 0;
array.forEach(items, function(i){
if(!store.isItemLoaded(i)){ waitCount++; }
});
if(waitCount === 0){
this._onFetchComplete(items, req);
}else{
var onItem = function(item){
waitCount--;
if(waitCount === 0){
this._onFetchComplete(items, req);
}
};
array.forEach(items, function(i){
if(!store.isItemLoaded(i)){
store.loadItem({item: i, onItem: onItem, scope: this});
}
}, this);
}
}else{
this.store.fetch({
start: start,
count: this.rowsPerPage,
query: this.query,
sort: this.getSortProps(),
queryOptions: this.queryOptions,
isRender: isRender,
onBegin: lang.hitch(this, "_onFetchBegin"),
onComplete: lang.hitch(this, "_onFetchComplete"),
onError: lang.hitch(this, "_onFetchError")
});
}
}catch(e){
this._onFetchError(e, {start: start, count: this.rowsPerPage});
}
}
},
_clearData: function(){
this.updateRowCount(0);
this._by_idty = {};
this._by_idx = [];
this._pages = [];
this._bop = this._eop = -1;
this._isLoaded = false;
this._isLoading = false;
},
getItem: function(idx){
var data = this._by_idx[idx];
if(!data||(data&&!data.item)){
this._preparePage(idx);
return null;
}
return data.item;
},
getItemIndex: function(item){
return this._getItemIndex(item, false);
},
_getItemIndex: function(item, isDeleted){
if(!isDeleted && !this.store.isItem(item)){
return -1;
}
var idty = this._hasIdentity ? this.store.getIdentity(item) : null;
for(var i=0, l=this._by_idx.length; i<l; i++){
var d = this._by_idx[i];
if(d && ((idty && d.idty == idty) || (d.item === item))){
return i;
}
}
return -1;
},
filter: function(query, reRender){
this.query = query;
if(reRender){
this._clearData();
}
this._fetch();
},
_getItemAttr: function(idx, attr){
var item = this.getItem(idx);
return (!item ? this.fetchText : this.store.getValue(item, attr));
},
// rendering
_render: function(){
if(this.domNode.parentNode){
this.scroller.init(this.get('rowCount'), this.keepRows, this.rowsPerPage);
this.prerender();
this._fetch(0, true);
}
},
// paging
_requestsPending: function(inRowIndex){
return this._pending_requests[inRowIndex];
},
_rowToPage: function(inRowIndex){
return (this.rowsPerPage ? Math.floor(inRowIndex / this.rowsPerPage) : inRowIndex);
},
_pageToRow: function(inPageIndex){
return (this.rowsPerPage ? this.rowsPerPage * inPageIndex : inPageIndex);
},
_preparePage: function(inRowIndex){
if((inRowIndex < this._bop || inRowIndex >= this._eop) && !this._addingItem){
var pageIndex = this._rowToPage(inRowIndex);
this._needPage(pageIndex);
this._bop = pageIndex * this.rowsPerPage;
this._eop = this._bop + (this.rowsPerPage || this.get('rowCount'));
}
},
_needPage: function(inPageIndex){
if(!this._pages[inPageIndex]){
this._pages[inPageIndex] = true;
this._requestPage(inPageIndex);
}
},
_requestPage: function(inPageIndex){
var row = this._pageToRow(inPageIndex);
var count = Math.min(this.rowsPerPage, this.get('rowCount') - row);
if(count > 0){
this._requests++;
if(!this._requestsPending(row)){
setTimeout(lang.hitch(this, "_fetch", row, false), 1);
//this.requestRows(row, count);
}
}
},
getCellName: function(inCell){
return inCell.field;
//console.log(inCell);
},
_refresh: function(isRender){
this._clearData();
this._fetch(0, isRender);
},
sort: function(){
this.edit.apply();
this._lastScrollTop = this.scrollTop;
this._refresh();
},
canSort: function(){
return (!this._isLoading);
},
getSortProps: function(){
var c = this.getCell(this.getSortIndex());
if(!c){
if(this.sortFields){
return this.sortFields;
}
return null;
}else{
var desc = c["sortDesc"];
var si = !(this.sortInfo>0);
if(typeof desc == "undefined"){
desc = si;
}else{
desc = si ? !desc : desc;
}
return [{ attribute: c.field, descending: desc }];
}
},
styleRowState: function(inRow){
// summary: Perform row styling
if(this.store && this.store.getState){
var states=this.store.getState(inRow.index), c='';
for(var i=0, ss=["inflight", "error", "inserting"], s; s=ss[i]; i++){
if(states[s]){
c = ' dojoxGridRow-' + s;
break;
}
}
inRow.customClasses += c;
}
},
onStyleRow: function(inRow){
this.styleRowState(inRow);
this.inherited(arguments);
},
// editing
canEdit: function(inCell, inRowIndex){
return this._canEdit;
},
_copyAttr: function(idx, attr){
var row = {};
var backstop = {};
var src = this.getItem(idx);
return this.store.getValue(src, attr);
},
doStartEdit: function(inCell, inRowIndex){
if(!this._cache[inRowIndex]){
this._cache[inRowIndex] = this._copyAttr(inRowIndex, inCell.field);
}
this.onStartEdit(inCell, inRowIndex);
},
doApplyCellEdit: function(inValue, inRowIndex, inAttrName){
this.store.fetchItemByIdentity({
identity: this._by_idx[inRowIndex].idty,
onItem: lang.hitch(this, function(item){
var oldValue = this.store.getValue(item, inAttrName);
if(typeof oldValue == 'number'){
inValue = isNaN(inValue) ? inValue : parseFloat(inValue);
}else if(typeof oldValue == 'boolean'){
inValue = inValue == 'true' ? true : inValue == 'false' ? false : inValue;
}else if(oldValue instanceof Date){
var asDate = new Date(inValue);
inValue = isNaN(asDate.getTime()) ? inValue : asDate;
}
this.store.setValue(item, inAttrName, inValue);
this.onApplyCellEdit(inValue, inRowIndex, inAttrName);
})
});
},
doCancelEdit: function(inRowIndex){
var cache = this._cache[inRowIndex];
if(cache){
this.updateRow(inRowIndex);
delete this._cache[inRowIndex];
}
this.onCancelEdit.apply(this, arguments);
},
doApplyEdit: function(inRowIndex, inDataAttr){
var cache = this._cache[inRowIndex];
/*if(cache){
var data = this.getItem(inRowIndex);
if(this.store.getValue(data, inDataAttr) != cache){
this.update(cache, data, inRowIndex);
}
delete this._cache[inRowIndex];
}*/
this.onApplyEdit(inRowIndex);
},
removeSelectedRows: function(){
// summary:
// Remove the selected rows from the grid.
if(this._canEdit){
this.edit.apply();
var fx = lang.hitch(this, function(items){
if(items.length){
array.forEach(items, this.store.deleteItem, this.store);
this.selection.clear();
}
});
if(this.allItemsSelected){
this.store.fetch({
query: this.query,
queryOptions: this.queryOptions,
onComplete: fx});
}else{
fx(this.selection.getSelected());
}
}
}
});
DataGrid.cell_markupFactory = function(cellFunc, node, cellDef){
var field = lang.trim(html.attr(node, "field")||"");
if(field){
cellDef.field = field;
}
cellDef.field = cellDef.field||cellDef.name;
var fields = lang.trim(html.attr(node, "fields")||"");
if(fields){
cellDef.fields = fields.split(",");
}
if(cellFunc){
cellFunc(node, cellDef);
}
};
DataGrid.markupFactory = function(props, node, ctor, cellFunc){
return _Grid.markupFactory(props, node, ctor,
lang.partial(DataGrid.cell_markupFactory, cellFunc));
};
return DataGrid;
}); | {
"content_hash": "2e0153c043e516fa31f2bd8d96cd6615",
"timestamp": "",
"source": "github",
"line_count": 660,
"max_line_length": 152,
"avg_line_length": 25.43030303030303,
"alnum_prop": 0.6416229742612012,
"repo_name": "Appudo/Appudo.github.io",
"id": "63d20bb3f999da182371dadab0e5f2ce6139c30c",
"size": "16784",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "static/release/dojox/grid/DataGrid.js.uncompressed.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ActionScript",
"bytes": "17567"
},
{
"name": "AngelScript",
"bytes": "2387"
},
{
"name": "Batchfile",
"bytes": "963"
},
{
"name": "C",
"bytes": "4472258"
},
{
"name": "C++",
"bytes": "8096232"
},
{
"name": "CSS",
"bytes": "1598579"
},
{
"name": "HTML",
"bytes": "22733727"
},
{
"name": "JavaScript",
"bytes": "26918138"
},
{
"name": "Objective-C",
"bytes": "231"
},
{
"name": "PHP",
"bytes": "38090"
},
{
"name": "PLpgSQL",
"bytes": "48798"
},
{
"name": "Python",
"bytes": "5025"
},
{
"name": "SQLPL",
"bytes": "877"
},
{
"name": "Shell",
"bytes": "3787"
},
{
"name": "Swift",
"bytes": "465672"
},
{
"name": "TSQL",
"bytes": "12185"
},
{
"name": "XSLT",
"bytes": "47380"
}
],
"symlink_target": ""
} |
package cloudfront
import (
"net/http"
"time"
"github.com/kuxuxun/aws-sdk-go/aws"
"github.com/kuxuxun/aws-sdk-go/gen/endpoints"
)
import (
"bytes"
"encoding/xml"
"fmt"
"io"
"io/ioutil"
"net/url"
"strconv"
"strings"
)
// CloudFront is a client for Amazon CloudFront.
type CloudFront struct {
client *aws.RestClient
}
// New returns a new CloudFront client.
func New(creds aws.CredentialsProvider, region string, client *http.Client) *CloudFront {
if client == nil {
client = http.DefaultClient
}
endpoint, service, region := endpoints.Lookup("cloudfront", region)
return &CloudFront{
client: &aws.RestClient{
Context: aws.Context{
Credentials: creds,
Service: service,
Region: region,
},
Client: client,
Endpoint: endpoint,
APIVersion: "2014-10-21",
},
}
}
// CreateCloudFrontOriginAccessIdentity is undocumented.
func (c *CloudFront) CreateCloudFrontOriginAccessIdentity(req *CreateCloudFrontOriginAccessIdentityRequest) (resp *CreateCloudFrontOriginAccessIdentityResult, err error) {
resp = &CreateCloudFrontOriginAccessIdentityResult{}
var body io.Reader
var contentType string
contentType = "application/xml"
if req.CloudFrontOriginAccessIdentityConfig != nil {
req.CloudFrontOriginAccessIdentityConfig.XMLName = xml.Name{
Space: "http://cloudfront.amazonaws.com/doc/2014-10-21/",
Local: "CloudFrontOriginAccessIdentityConfig",
}
}
b, err := xml.Marshal(req.CloudFrontOriginAccessIdentityConfig)
if err != nil {
return
}
body = bytes.NewReader(b)
uri := c.client.Endpoint + "/2014-10-21/origin-access-identity/cloudfront"
q := url.Values{}
if len(q) > 0 {
uri += "?" + q.Encode()
}
httpReq, err := http.NewRequest("POST", uri, body)
if err != nil {
return
}
if contentType != "" {
httpReq.Header.Set("Content-Type", contentType)
}
httpResp, err := c.client.Do(httpReq)
if err != nil {
return
}
defer httpResp.Body.Close()
if e := xml.NewDecoder(httpResp.Body).Decode(resp); e != nil && e != io.EOF {
err = e
return
}
if s := httpResp.Header.Get("ETag"); s != "" {
resp.ETag = &s
}
if s := httpResp.Header.Get("Location"); s != "" {
resp.Location = &s
}
return
}
// CreateDistribution is undocumented.
func (c *CloudFront) CreateDistribution(req *CreateDistributionRequest) (resp *CreateDistributionResult, err error) {
resp = &CreateDistributionResult{}
var body io.Reader
var contentType string
contentType = "application/xml"
if req.DistributionConfig != nil {
req.DistributionConfig.XMLName = xml.Name{
Space: "http://cloudfront.amazonaws.com/doc/2014-10-21/",
Local: "DistributionConfig",
}
}
b, err := xml.Marshal(req.DistributionConfig)
if err != nil {
return
}
body = bytes.NewReader(b)
uri := c.client.Endpoint + "/2014-10-21/distribution"
q := url.Values{}
if len(q) > 0 {
uri += "?" + q.Encode()
}
httpReq, err := http.NewRequest("POST", uri, body)
if err != nil {
return
}
if contentType != "" {
httpReq.Header.Set("Content-Type", contentType)
}
httpResp, err := c.client.Do(httpReq)
if err != nil {
return
}
defer httpResp.Body.Close()
if e := xml.NewDecoder(httpResp.Body).Decode(resp); e != nil && e != io.EOF {
err = e
return
}
if s := httpResp.Header.Get("ETag"); s != "" {
resp.ETag = &s
}
if s := httpResp.Header.Get("Location"); s != "" {
resp.Location = &s
}
return
}
// CreateInvalidation is undocumented.
func (c *CloudFront) CreateInvalidation(req *CreateInvalidationRequest) (resp *CreateInvalidationResult, err error) {
resp = &CreateInvalidationResult{}
var body io.Reader
var contentType string
contentType = "application/xml"
if req.InvalidationBatch != nil {
req.InvalidationBatch.XMLName = xml.Name{
Space: "http://cloudfront.amazonaws.com/doc/2014-10-21/",
Local: "InvalidationBatch",
}
}
b, err := xml.Marshal(req.InvalidationBatch)
if err != nil {
return
}
body = bytes.NewReader(b)
uri := c.client.Endpoint + "/2014-10-21/distribution/{DistributionId}/invalidation"
if req.DistributionID != nil {
uri = strings.Replace(uri, "{"+"DistributionId"+"}", aws.EscapePath(*req.DistributionID), -1)
uri = strings.Replace(uri, "{"+"DistributionId+"+"}", aws.EscapePath(*req.DistributionID), -1)
}
q := url.Values{}
if len(q) > 0 {
uri += "?" + q.Encode()
}
httpReq, err := http.NewRequest("POST", uri, body)
if err != nil {
return
}
if contentType != "" {
httpReq.Header.Set("Content-Type", contentType)
}
httpResp, err := c.client.Do(httpReq)
if err != nil {
return
}
defer httpResp.Body.Close()
if e := xml.NewDecoder(httpResp.Body).Decode(resp); e != nil && e != io.EOF {
err = e
return
}
if s := httpResp.Header.Get("Location"); s != "" {
resp.Location = &s
}
return
}
// CreateStreamingDistribution is undocumented.
func (c *CloudFront) CreateStreamingDistribution(req *CreateStreamingDistributionRequest) (resp *CreateStreamingDistributionResult, err error) {
resp = &CreateStreamingDistributionResult{}
var body io.Reader
var contentType string
contentType = "application/xml"
if req.StreamingDistributionConfig != nil {
req.StreamingDistributionConfig.XMLName = xml.Name{
Space: "http://cloudfront.amazonaws.com/doc/2014-10-21/",
Local: "StreamingDistributionConfig",
}
}
b, err := xml.Marshal(req.StreamingDistributionConfig)
if err != nil {
return
}
body = bytes.NewReader(b)
uri := c.client.Endpoint + "/2014-10-21/streaming-distribution"
q := url.Values{}
if len(q) > 0 {
uri += "?" + q.Encode()
}
httpReq, err := http.NewRequest("POST", uri, body)
if err != nil {
return
}
if contentType != "" {
httpReq.Header.Set("Content-Type", contentType)
}
httpResp, err := c.client.Do(httpReq)
if err != nil {
return
}
defer httpResp.Body.Close()
if e := xml.NewDecoder(httpResp.Body).Decode(resp); e != nil && e != io.EOF {
err = e
return
}
if s := httpResp.Header.Get("ETag"); s != "" {
resp.ETag = &s
}
if s := httpResp.Header.Get("Location"); s != "" {
resp.Location = &s
}
return
}
// DeleteCloudFrontOriginAccessIdentity is undocumented.
func (c *CloudFront) DeleteCloudFrontOriginAccessIdentity(req *DeleteCloudFrontOriginAccessIdentityRequest) (err error) {
// NRE
var body io.Reader
var contentType string
uri := c.client.Endpoint + "/2014-10-21/origin-access-identity/cloudfront/{Id}"
if req.ID != nil {
uri = strings.Replace(uri, "{"+"Id"+"}", aws.EscapePath(*req.ID), -1)
uri = strings.Replace(uri, "{"+"Id+"+"}", aws.EscapePath(*req.ID), -1)
}
q := url.Values{}
if len(q) > 0 {
uri += "?" + q.Encode()
}
httpReq, err := http.NewRequest("DELETE", uri, body)
if err != nil {
return
}
if contentType != "" {
httpReq.Header.Set("Content-Type", contentType)
}
if req.IfMatch != nil {
httpReq.Header.Set("If-Match", *req.IfMatch)
}
httpResp, err := c.client.Do(httpReq)
if err != nil {
return
}
defer httpResp.Body.Close()
return
}
// DeleteDistribution is undocumented.
func (c *CloudFront) DeleteDistribution(req *DeleteDistributionRequest) (err error) {
// NRE
var body io.Reader
var contentType string
uri := c.client.Endpoint + "/2014-10-21/distribution/{Id}"
if req.ID != nil {
uri = strings.Replace(uri, "{"+"Id"+"}", aws.EscapePath(*req.ID), -1)
uri = strings.Replace(uri, "{"+"Id+"+"}", aws.EscapePath(*req.ID), -1)
}
q := url.Values{}
if len(q) > 0 {
uri += "?" + q.Encode()
}
httpReq, err := http.NewRequest("DELETE", uri, body)
if err != nil {
return
}
if contentType != "" {
httpReq.Header.Set("Content-Type", contentType)
}
if req.IfMatch != nil {
httpReq.Header.Set("If-Match", *req.IfMatch)
}
httpResp, err := c.client.Do(httpReq)
if err != nil {
return
}
defer httpResp.Body.Close()
return
}
// DeleteStreamingDistribution is undocumented.
func (c *CloudFront) DeleteStreamingDistribution(req *DeleteStreamingDistributionRequest) (err error) {
// NRE
var body io.Reader
var contentType string
uri := c.client.Endpoint + "/2014-10-21/streaming-distribution/{Id}"
if req.ID != nil {
uri = strings.Replace(uri, "{"+"Id"+"}", aws.EscapePath(*req.ID), -1)
uri = strings.Replace(uri, "{"+"Id+"+"}", aws.EscapePath(*req.ID), -1)
}
q := url.Values{}
if len(q) > 0 {
uri += "?" + q.Encode()
}
httpReq, err := http.NewRequest("DELETE", uri, body)
if err != nil {
return
}
if contentType != "" {
httpReq.Header.Set("Content-Type", contentType)
}
if req.IfMatch != nil {
httpReq.Header.Set("If-Match", *req.IfMatch)
}
httpResp, err := c.client.Do(httpReq)
if err != nil {
return
}
defer httpResp.Body.Close()
return
}
// GetCloudFrontOriginAccessIdentity get the information about an origin
// access identity.
func (c *CloudFront) GetCloudFrontOriginAccessIdentity(req *GetCloudFrontOriginAccessIdentityRequest) (resp *GetCloudFrontOriginAccessIdentityResult, err error) {
resp = &GetCloudFrontOriginAccessIdentityResult{}
var body io.Reader
var contentType string
uri := c.client.Endpoint + "/2014-10-21/origin-access-identity/cloudfront/{Id}"
if req.ID != nil {
uri = strings.Replace(uri, "{"+"Id"+"}", aws.EscapePath(*req.ID), -1)
uri = strings.Replace(uri, "{"+"Id+"+"}", aws.EscapePath(*req.ID), -1)
}
q := url.Values{}
if len(q) > 0 {
uri += "?" + q.Encode()
}
httpReq, err := http.NewRequest("GET", uri, body)
if err != nil {
return
}
if contentType != "" {
httpReq.Header.Set("Content-Type", contentType)
}
httpResp, err := c.client.Do(httpReq)
if err != nil {
return
}
defer httpResp.Body.Close()
if e := xml.NewDecoder(httpResp.Body).Decode(resp); e != nil && e != io.EOF {
err = e
return
}
if s := httpResp.Header.Get("ETag"); s != "" {
resp.ETag = &s
}
return
}
// GetCloudFrontOriginAccessIdentityConfig get the configuration
// information about an origin access identity.
func (c *CloudFront) GetCloudFrontOriginAccessIdentityConfig(req *GetCloudFrontOriginAccessIdentityConfigRequest) (resp *GetCloudFrontOriginAccessIdentityConfigResult, err error) {
resp = &GetCloudFrontOriginAccessIdentityConfigResult{}
var body io.Reader
var contentType string
uri := c.client.Endpoint + "/2014-10-21/origin-access-identity/cloudfront/{Id}/config"
if req.ID != nil {
uri = strings.Replace(uri, "{"+"Id"+"}", aws.EscapePath(*req.ID), -1)
uri = strings.Replace(uri, "{"+"Id+"+"}", aws.EscapePath(*req.ID), -1)
}
q := url.Values{}
if len(q) > 0 {
uri += "?" + q.Encode()
}
httpReq, err := http.NewRequest("GET", uri, body)
if err != nil {
return
}
if contentType != "" {
httpReq.Header.Set("Content-Type", contentType)
}
httpResp, err := c.client.Do(httpReq)
if err != nil {
return
}
defer httpResp.Body.Close()
if e := xml.NewDecoder(httpResp.Body).Decode(resp); e != nil && e != io.EOF {
err = e
return
}
if s := httpResp.Header.Get("ETag"); s != "" {
resp.ETag = &s
}
return
}
// GetDistribution is undocumented.
func (c *CloudFront) GetDistribution(req *GetDistributionRequest) (resp *GetDistributionResult, err error) {
resp = &GetDistributionResult{}
var body io.Reader
var contentType string
uri := c.client.Endpoint + "/2014-10-21/distribution/{Id}"
if req.ID != nil {
uri = strings.Replace(uri, "{"+"Id"+"}", aws.EscapePath(*req.ID), -1)
uri = strings.Replace(uri, "{"+"Id+"+"}", aws.EscapePath(*req.ID), -1)
}
q := url.Values{}
if len(q) > 0 {
uri += "?" + q.Encode()
}
httpReq, err := http.NewRequest("GET", uri, body)
if err != nil {
return
}
if contentType != "" {
httpReq.Header.Set("Content-Type", contentType)
}
httpResp, err := c.client.Do(httpReq)
if err != nil {
return
}
defer httpResp.Body.Close()
if e := xml.NewDecoder(httpResp.Body).Decode(resp); e != nil && e != io.EOF {
err = e
return
}
if s := httpResp.Header.Get("ETag"); s != "" {
resp.ETag = &s
}
return
}
// GetDistributionConfig get the configuration information about a
// distribution.
func (c *CloudFront) GetDistributionConfig(req *GetDistributionConfigRequest) (resp *GetDistributionConfigResult, err error) {
resp = &GetDistributionConfigResult{}
var body io.Reader
var contentType string
uri := c.client.Endpoint + "/2014-10-21/distribution/{Id}/config"
if req.ID != nil {
uri = strings.Replace(uri, "{"+"Id"+"}", aws.EscapePath(*req.ID), -1)
uri = strings.Replace(uri, "{"+"Id+"+"}", aws.EscapePath(*req.ID), -1)
}
q := url.Values{}
if len(q) > 0 {
uri += "?" + q.Encode()
}
httpReq, err := http.NewRequest("GET", uri, body)
if err != nil {
return
}
if contentType != "" {
httpReq.Header.Set("Content-Type", contentType)
}
httpResp, err := c.client.Do(httpReq)
if err != nil {
return
}
defer httpResp.Body.Close()
if e := xml.NewDecoder(httpResp.Body).Decode(resp); e != nil && e != io.EOF {
err = e
return
}
if s := httpResp.Header.Get("ETag"); s != "" {
resp.ETag = &s
}
return
}
// GetInvalidation is undocumented.
func (c *CloudFront) GetInvalidation(req *GetInvalidationRequest) (resp *GetInvalidationResult, err error) {
resp = &GetInvalidationResult{}
var body io.Reader
var contentType string
uri := c.client.Endpoint + "/2014-10-21/distribution/{DistributionId}/invalidation/{Id}"
if req.DistributionID != nil {
uri = strings.Replace(uri, "{"+"DistributionId"+"}", aws.EscapePath(*req.DistributionID), -1)
uri = strings.Replace(uri, "{"+"DistributionId+"+"}", aws.EscapePath(*req.DistributionID), -1)
}
if req.ID != nil {
uri = strings.Replace(uri, "{"+"Id"+"}", aws.EscapePath(*req.ID), -1)
uri = strings.Replace(uri, "{"+"Id+"+"}", aws.EscapePath(*req.ID), -1)
}
q := url.Values{}
if len(q) > 0 {
uri += "?" + q.Encode()
}
httpReq, err := http.NewRequest("GET", uri, body)
if err != nil {
return
}
if contentType != "" {
httpReq.Header.Set("Content-Type", contentType)
}
httpResp, err := c.client.Do(httpReq)
if err != nil {
return
}
defer httpResp.Body.Close()
if e := xml.NewDecoder(httpResp.Body).Decode(resp); e != nil && e != io.EOF {
err = e
return
}
return
}
// GetStreamingDistribution get the information about a streaming
// distribution.
func (c *CloudFront) GetStreamingDistribution(req *GetStreamingDistributionRequest) (resp *GetStreamingDistributionResult, err error) {
resp = &GetStreamingDistributionResult{}
var body io.Reader
var contentType string
uri := c.client.Endpoint + "/2014-10-21/streaming-distribution/{Id}"
if req.ID != nil {
uri = strings.Replace(uri, "{"+"Id"+"}", aws.EscapePath(*req.ID), -1)
uri = strings.Replace(uri, "{"+"Id+"+"}", aws.EscapePath(*req.ID), -1)
}
q := url.Values{}
if len(q) > 0 {
uri += "?" + q.Encode()
}
httpReq, err := http.NewRequest("GET", uri, body)
if err != nil {
return
}
if contentType != "" {
httpReq.Header.Set("Content-Type", contentType)
}
httpResp, err := c.client.Do(httpReq)
if err != nil {
return
}
defer httpResp.Body.Close()
if e := xml.NewDecoder(httpResp.Body).Decode(resp); e != nil && e != io.EOF {
err = e
return
}
if s := httpResp.Header.Get("ETag"); s != "" {
resp.ETag = &s
}
return
}
// GetStreamingDistributionConfig get the configuration information about a
// streaming distribution.
func (c *CloudFront) GetStreamingDistributionConfig(req *GetStreamingDistributionConfigRequest) (resp *GetStreamingDistributionConfigResult, err error) {
resp = &GetStreamingDistributionConfigResult{}
var body io.Reader
var contentType string
uri := c.client.Endpoint + "/2014-10-21/streaming-distribution/{Id}/config"
if req.ID != nil {
uri = strings.Replace(uri, "{"+"Id"+"}", aws.EscapePath(*req.ID), -1)
uri = strings.Replace(uri, "{"+"Id+"+"}", aws.EscapePath(*req.ID), -1)
}
q := url.Values{}
if len(q) > 0 {
uri += "?" + q.Encode()
}
httpReq, err := http.NewRequest("GET", uri, body)
if err != nil {
return
}
if contentType != "" {
httpReq.Header.Set("Content-Type", contentType)
}
httpResp, err := c.client.Do(httpReq)
if err != nil {
return
}
defer httpResp.Body.Close()
if e := xml.NewDecoder(httpResp.Body).Decode(resp); e != nil && e != io.EOF {
err = e
return
}
if s := httpResp.Header.Get("ETag"); s != "" {
resp.ETag = &s
}
return
}
// ListCloudFrontOriginAccessIdentities is undocumented.
func (c *CloudFront) ListCloudFrontOriginAccessIdentities(req *ListCloudFrontOriginAccessIdentitiesRequest) (resp *ListCloudFrontOriginAccessIdentitiesResult, err error) {
resp = &ListCloudFrontOriginAccessIdentitiesResult{}
var body io.Reader
var contentType string
uri := c.client.Endpoint + "/2014-10-21/origin-access-identity/cloudfront"
q := url.Values{}
if req.Marker != nil {
q.Set("Marker", *req.Marker)
}
if req.MaxItems != nil {
q.Set("MaxItems", *req.MaxItems)
}
if len(q) > 0 {
uri += "?" + q.Encode()
}
httpReq, err := http.NewRequest("GET", uri, body)
if err != nil {
return
}
if contentType != "" {
httpReq.Header.Set("Content-Type", contentType)
}
httpResp, err := c.client.Do(httpReq)
if err != nil {
return
}
defer httpResp.Body.Close()
if e := xml.NewDecoder(httpResp.Body).Decode(resp); e != nil && e != io.EOF {
err = e
return
}
return
}
// ListDistributions is undocumented.
func (c *CloudFront) ListDistributions(req *ListDistributionsRequest) (resp *ListDistributionsResult, err error) {
resp = &ListDistributionsResult{}
var body io.Reader
var contentType string
uri := c.client.Endpoint + "/2014-10-21/distribution"
q := url.Values{}
if req.Marker != nil {
q.Set("Marker", *req.Marker)
}
if req.MaxItems != nil {
q.Set("MaxItems", *req.MaxItems)
}
if len(q) > 0 {
uri += "?" + q.Encode()
}
httpReq, err := http.NewRequest("GET", uri, body)
if err != nil {
return
}
if contentType != "" {
httpReq.Header.Set("Content-Type", contentType)
}
httpResp, err := c.client.Do(httpReq)
if err != nil {
return
}
defer httpResp.Body.Close()
if e := xml.NewDecoder(httpResp.Body).Decode(resp); e != nil && e != io.EOF {
err = e
return
}
return
}
// ListInvalidations is undocumented.
func (c *CloudFront) ListInvalidations(req *ListInvalidationsRequest) (resp *ListInvalidationsResult, err error) {
resp = &ListInvalidationsResult{}
var body io.Reader
var contentType string
uri := c.client.Endpoint + "/2014-10-21/distribution/{DistributionId}/invalidation"
if req.DistributionID != nil {
uri = strings.Replace(uri, "{"+"DistributionId"+"}", aws.EscapePath(*req.DistributionID), -1)
uri = strings.Replace(uri, "{"+"DistributionId+"+"}", aws.EscapePath(*req.DistributionID), -1)
}
q := url.Values{}
if req.Marker != nil {
q.Set("Marker", *req.Marker)
}
if req.MaxItems != nil {
q.Set("MaxItems", *req.MaxItems)
}
if len(q) > 0 {
uri += "?" + q.Encode()
}
httpReq, err := http.NewRequest("GET", uri, body)
if err != nil {
return
}
if contentType != "" {
httpReq.Header.Set("Content-Type", contentType)
}
httpResp, err := c.client.Do(httpReq)
if err != nil {
return
}
defer httpResp.Body.Close()
if e := xml.NewDecoder(httpResp.Body).Decode(resp); e != nil && e != io.EOF {
err = e
return
}
return
}
// ListStreamingDistributions is undocumented.
func (c *CloudFront) ListStreamingDistributions(req *ListStreamingDistributionsRequest) (resp *ListStreamingDistributionsResult, err error) {
resp = &ListStreamingDistributionsResult{}
var body io.Reader
var contentType string
uri := c.client.Endpoint + "/2014-10-21/streaming-distribution"
q := url.Values{}
if req.Marker != nil {
q.Set("Marker", *req.Marker)
}
if req.MaxItems != nil {
q.Set("MaxItems", *req.MaxItems)
}
if len(q) > 0 {
uri += "?" + q.Encode()
}
httpReq, err := http.NewRequest("GET", uri, body)
if err != nil {
return
}
if contentType != "" {
httpReq.Header.Set("Content-Type", contentType)
}
httpResp, err := c.client.Do(httpReq)
if err != nil {
return
}
defer httpResp.Body.Close()
if e := xml.NewDecoder(httpResp.Body).Decode(resp); e != nil && e != io.EOF {
err = e
return
}
return
}
// UpdateCloudFrontOriginAccessIdentity is undocumented.
func (c *CloudFront) UpdateCloudFrontOriginAccessIdentity(req *UpdateCloudFrontOriginAccessIdentityRequest) (resp *UpdateCloudFrontOriginAccessIdentityResult, err error) {
resp = &UpdateCloudFrontOriginAccessIdentityResult{}
var body io.Reader
var contentType string
contentType = "application/xml"
if req.CloudFrontOriginAccessIdentityConfig != nil {
req.CloudFrontOriginAccessIdentityConfig.XMLName = xml.Name{
Space: "http://cloudfront.amazonaws.com/doc/2014-10-21/",
Local: "CloudFrontOriginAccessIdentityConfig",
}
}
b, err := xml.Marshal(req.CloudFrontOriginAccessIdentityConfig)
if err != nil {
return
}
body = bytes.NewReader(b)
uri := c.client.Endpoint + "/2014-10-21/origin-access-identity/cloudfront/{Id}/config"
if req.ID != nil {
uri = strings.Replace(uri, "{"+"Id"+"}", aws.EscapePath(*req.ID), -1)
uri = strings.Replace(uri, "{"+"Id+"+"}", aws.EscapePath(*req.ID), -1)
}
q := url.Values{}
if len(q) > 0 {
uri += "?" + q.Encode()
}
httpReq, err := http.NewRequest("PUT", uri, body)
if err != nil {
return
}
if contentType != "" {
httpReq.Header.Set("Content-Type", contentType)
}
if req.IfMatch != nil {
httpReq.Header.Set("If-Match", *req.IfMatch)
}
httpResp, err := c.client.Do(httpReq)
if err != nil {
return
}
defer httpResp.Body.Close()
if e := xml.NewDecoder(httpResp.Body).Decode(resp); e != nil && e != io.EOF {
err = e
return
}
if s := httpResp.Header.Get("ETag"); s != "" {
resp.ETag = &s
}
return
}
// UpdateDistribution is undocumented.
func (c *CloudFront) UpdateDistribution(req *UpdateDistributionRequest) (resp *UpdateDistributionResult, err error) {
resp = &UpdateDistributionResult{}
var body io.Reader
var contentType string
contentType = "application/xml"
if req.DistributionConfig != nil {
req.DistributionConfig.XMLName = xml.Name{
Space: "http://cloudfront.amazonaws.com/doc/2014-10-21/",
Local: "DistributionConfig",
}
}
b, err := xml.Marshal(req.DistributionConfig)
if err != nil {
return
}
body = bytes.NewReader(b)
uri := c.client.Endpoint + "/2014-10-21/distribution/{Id}/config"
if req.ID != nil {
uri = strings.Replace(uri, "{"+"Id"+"}", aws.EscapePath(*req.ID), -1)
uri = strings.Replace(uri, "{"+"Id+"+"}", aws.EscapePath(*req.ID), -1)
}
q := url.Values{}
if len(q) > 0 {
uri += "?" + q.Encode()
}
httpReq, err := http.NewRequest("PUT", uri, body)
if err != nil {
return
}
if contentType != "" {
httpReq.Header.Set("Content-Type", contentType)
}
if req.IfMatch != nil {
httpReq.Header.Set("If-Match", *req.IfMatch)
}
httpResp, err := c.client.Do(httpReq)
if err != nil {
return
}
defer httpResp.Body.Close()
if e := xml.NewDecoder(httpResp.Body).Decode(resp); e != nil && e != io.EOF {
err = e
return
}
if s := httpResp.Header.Get("ETag"); s != "" {
resp.ETag = &s
}
return
}
// UpdateStreamingDistribution is undocumented.
func (c *CloudFront) UpdateStreamingDistribution(req *UpdateStreamingDistributionRequest) (resp *UpdateStreamingDistributionResult, err error) {
resp = &UpdateStreamingDistributionResult{}
var body io.Reader
var contentType string
contentType = "application/xml"
if req.StreamingDistributionConfig != nil {
req.StreamingDistributionConfig.XMLName = xml.Name{
Space: "http://cloudfront.amazonaws.com/doc/2014-10-21/",
Local: "StreamingDistributionConfig",
}
}
b, err := xml.Marshal(req.StreamingDistributionConfig)
if err != nil {
return
}
body = bytes.NewReader(b)
uri := c.client.Endpoint + "/2014-10-21/streaming-distribution/{Id}/config"
if req.ID != nil {
uri = strings.Replace(uri, "{"+"Id"+"}", aws.EscapePath(*req.ID), -1)
uri = strings.Replace(uri, "{"+"Id+"+"}", aws.EscapePath(*req.ID), -1)
}
q := url.Values{}
if len(q) > 0 {
uri += "?" + q.Encode()
}
httpReq, err := http.NewRequest("PUT", uri, body)
if err != nil {
return
}
if contentType != "" {
httpReq.Header.Set("Content-Type", contentType)
}
if req.IfMatch != nil {
httpReq.Header.Set("If-Match", *req.IfMatch)
}
httpResp, err := c.client.Do(httpReq)
if err != nil {
return
}
defer httpResp.Body.Close()
if e := xml.NewDecoder(httpResp.Body).Decode(resp); e != nil && e != io.EOF {
err = e
return
}
if s := httpResp.Header.Get("ETag"); s != "" {
resp.ETag = &s
}
return
}
// ActiveTrustedSigners is undocumented.
type ActiveTrustedSigners struct {
XMLName xml.Name
Enabled aws.BooleanValue `xml:"Enabled"`
Items []Signer `xml:"Items>Signer,omitempty"`
Quantity aws.IntegerValue `xml:"Quantity"`
}
func (v *ActiveTrustedSigners) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// Aliases is undocumented.
type Aliases struct {
XMLName xml.Name
Items []string `xml:"Items>CNAME,omitempty"`
Quantity aws.IntegerValue `xml:"Quantity"`
}
func (v *Aliases) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// AllowedMethods is undocumented.
type AllowedMethods struct {
XMLName xml.Name
CachedMethods *CachedMethods `xml:"CachedMethods,omitempty"`
Items []string `xml:"Items>Method,omitempty"`
Quantity aws.IntegerValue `xml:"Quantity"`
}
func (v *AllowedMethods) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// CacheBehavior is undocumented.
type CacheBehavior struct {
XMLName xml.Name
AllowedMethods *AllowedMethods `xml:"AllowedMethods,omitempty"`
ForwardedValues *ForwardedValues `xml:"ForwardedValues,omitempty"`
MinTTL aws.LongValue `xml:"MinTTL"`
PathPattern aws.StringValue `xml:"PathPattern"`
SmoothStreaming aws.BooleanValue `xml:"SmoothStreaming"`
TargetOriginID aws.StringValue `xml:"TargetOriginId"`
TrustedSigners *TrustedSigners `xml:"TrustedSigners,omitempty"`
ViewerProtocolPolicy aws.StringValue `xml:"ViewerProtocolPolicy"`
}
func (v *CacheBehavior) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// CacheBehaviors is undocumented.
type CacheBehaviors struct {
XMLName xml.Name
Items []CacheBehavior `xml:"Items>CacheBehavior,omitempty"`
Quantity aws.IntegerValue `xml:"Quantity"`
}
func (v *CacheBehaviors) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// CachedMethods is undocumented.
type CachedMethods struct {
XMLName xml.Name
Items []string `xml:"Items>Method,omitempty"`
Quantity aws.IntegerValue `xml:"Quantity"`
}
func (v *CachedMethods) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// CloudFrontOriginAccessIdentity is undocumented.
type CloudFrontOriginAccessIdentity struct {
XMLName xml.Name
CloudFrontOriginAccessIdentityConfig *CloudFrontOriginAccessIdentityConfig `xml:"CloudFrontOriginAccessIdentityConfig,omitempty"`
ID aws.StringValue `xml:"Id"`
S3CanonicalUserID aws.StringValue `xml:"S3CanonicalUserId"`
}
func (v *CloudFrontOriginAccessIdentity) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// CloudFrontOriginAccessIdentityConfig is undocumented.
type CloudFrontOriginAccessIdentityConfig struct {
XMLName xml.Name
CallerReference aws.StringValue `xml:"CallerReference"`
Comment aws.StringValue `xml:"Comment"`
}
func (v *CloudFrontOriginAccessIdentityConfig) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// CloudFrontOriginAccessIdentityList is undocumented.
type CloudFrontOriginAccessIdentityList struct {
XMLName xml.Name
IsTruncated aws.BooleanValue `xml:"IsTruncated"`
Items []CloudFrontOriginAccessIdentitySummary `xml:"Items>CloudFrontOriginAccessIdentitySummary,omitempty"`
Marker aws.StringValue `xml:"Marker"`
MaxItems aws.IntegerValue `xml:"MaxItems"`
NextMarker aws.StringValue `xml:"NextMarker"`
Quantity aws.IntegerValue `xml:"Quantity"`
}
func (v *CloudFrontOriginAccessIdentityList) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// CloudFrontOriginAccessIdentitySummary is undocumented.
type CloudFrontOriginAccessIdentitySummary struct {
XMLName xml.Name
Comment aws.StringValue `xml:"Comment"`
ID aws.StringValue `xml:"Id"`
S3CanonicalUserID aws.StringValue `xml:"S3CanonicalUserId"`
}
func (v *CloudFrontOriginAccessIdentitySummary) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// CookieNames is undocumented.
type CookieNames struct {
XMLName xml.Name
Items []string `xml:"Items>Name,omitempty"`
Quantity aws.IntegerValue `xml:"Quantity"`
}
func (v *CookieNames) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// CookiePreference is undocumented.
type CookiePreference struct {
XMLName xml.Name
Forward aws.StringValue `xml:"Forward"`
WhitelistedNames *CookieNames `xml:"WhitelistedNames,omitempty"`
}
func (v *CookiePreference) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// CreateCloudFrontOriginAccessIdentityRequest is undocumented.
type CreateCloudFrontOriginAccessIdentityRequest struct {
XMLName xml.Name
CloudFrontOriginAccessIdentityConfig *CloudFrontOriginAccessIdentityConfig `xml:"CloudFrontOriginAccessIdentityConfig,omitempty"`
}
func (v *CreateCloudFrontOriginAccessIdentityRequest) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// CreateCloudFrontOriginAccessIdentityResult is undocumented.
type CreateCloudFrontOriginAccessIdentityResult struct {
XMLName xml.Name
CloudFrontOriginAccessIdentity *CloudFrontOriginAccessIdentity `xml:"CloudFrontOriginAccessIdentity,omitempty"`
ETag aws.StringValue `xml:"-"`
Location aws.StringValue `xml:"-"`
}
func (v *CreateCloudFrontOriginAccessIdentityResult) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// CreateDistributionRequest is undocumented.
type CreateDistributionRequest struct {
XMLName xml.Name
DistributionConfig *DistributionConfig `xml:"DistributionConfig,omitempty"`
}
func (v *CreateDistributionRequest) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// CreateDistributionResult is undocumented.
type CreateDistributionResult struct {
XMLName xml.Name
Distribution *Distribution `xml:"Distribution,omitempty"`
ETag aws.StringValue `xml:"-"`
Location aws.StringValue `xml:"-"`
}
func (v *CreateDistributionResult) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// CreateInvalidationRequest is undocumented.
type CreateInvalidationRequest struct {
XMLName xml.Name
DistributionID aws.StringValue `xml:"-"`
InvalidationBatch *InvalidationBatch `xml:"InvalidationBatch,omitempty"`
}
func (v *CreateInvalidationRequest) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// CreateInvalidationResult is undocumented.
type CreateInvalidationResult struct {
XMLName xml.Name
Invalidation *Invalidation `xml:"Invalidation,omitempty"`
Location aws.StringValue `xml:"-"`
}
func (v *CreateInvalidationResult) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// CreateStreamingDistributionRequest is undocumented.
type CreateStreamingDistributionRequest struct {
XMLName xml.Name
StreamingDistributionConfig *StreamingDistributionConfig `xml:"StreamingDistributionConfig,omitempty"`
}
func (v *CreateStreamingDistributionRequest) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// CreateStreamingDistributionResult is undocumented.
type CreateStreamingDistributionResult struct {
XMLName xml.Name
ETag aws.StringValue `xml:"-"`
Location aws.StringValue `xml:"-"`
StreamingDistribution *StreamingDistribution `xml:"StreamingDistribution,omitempty"`
}
func (v *CreateStreamingDistributionResult) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// CustomErrorResponse is undocumented.
type CustomErrorResponse struct {
XMLName xml.Name
ErrorCachingMinTTL aws.LongValue `xml:"ErrorCachingMinTTL"`
ErrorCode aws.IntegerValue `xml:"ErrorCode"`
ResponseCode aws.StringValue `xml:"ResponseCode"`
ResponsePagePath aws.StringValue `xml:"ResponsePagePath"`
}
func (v *CustomErrorResponse) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// CustomErrorResponses is undocumented.
type CustomErrorResponses struct {
XMLName xml.Name
Items []CustomErrorResponse `xml:"Items>CustomErrorResponse,omitempty"`
Quantity aws.IntegerValue `xml:"Quantity"`
}
func (v *CustomErrorResponses) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// CustomOriginConfig is undocumented.
type CustomOriginConfig struct {
XMLName xml.Name
HTTPPort aws.IntegerValue `xml:"HTTPPort"`
HTTPSPort aws.IntegerValue `xml:"HTTPSPort"`
OriginProtocolPolicy aws.StringValue `xml:"OriginProtocolPolicy"`
}
func (v *CustomOriginConfig) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// DefaultCacheBehavior is undocumented.
type DefaultCacheBehavior struct {
XMLName xml.Name
AllowedMethods *AllowedMethods `xml:"AllowedMethods,omitempty"`
ForwardedValues *ForwardedValues `xml:"ForwardedValues,omitempty"`
MinTTL aws.LongValue `xml:"MinTTL"`
SmoothStreaming aws.BooleanValue `xml:"SmoothStreaming"`
TargetOriginID aws.StringValue `xml:"TargetOriginId"`
TrustedSigners *TrustedSigners `xml:"TrustedSigners,omitempty"`
ViewerProtocolPolicy aws.StringValue `xml:"ViewerProtocolPolicy"`
}
func (v *DefaultCacheBehavior) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// DeleteCloudFrontOriginAccessIdentityRequest is undocumented.
type DeleteCloudFrontOriginAccessIdentityRequest struct {
XMLName xml.Name
ID aws.StringValue `xml:"-"`
IfMatch aws.StringValue `xml:"-"`
}
func (v *DeleteCloudFrontOriginAccessIdentityRequest) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// DeleteDistributionRequest is undocumented.
type DeleteDistributionRequest struct {
XMLName xml.Name
ID aws.StringValue `xml:"-"`
IfMatch aws.StringValue `xml:"-"`
}
func (v *DeleteDistributionRequest) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// DeleteStreamingDistributionRequest is undocumented.
type DeleteStreamingDistributionRequest struct {
XMLName xml.Name
ID aws.StringValue `xml:"-"`
IfMatch aws.StringValue `xml:"-"`
}
func (v *DeleteStreamingDistributionRequest) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// Distribution is undocumented.
type Distribution struct {
XMLName xml.Name
ActiveTrustedSigners *ActiveTrustedSigners `xml:"ActiveTrustedSigners,omitempty"`
DistributionConfig *DistributionConfig `xml:"DistributionConfig,omitempty"`
DomainName aws.StringValue `xml:"DomainName"`
ID aws.StringValue `xml:"Id"`
InProgressInvalidationBatches aws.IntegerValue `xml:"InProgressInvalidationBatches"`
LastModifiedTime time.Time `xml:"LastModifiedTime"`
Status aws.StringValue `xml:"Status"`
}
func (v *Distribution) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// DistributionConfig is undocumented.
type DistributionConfig struct {
XMLName xml.Name
Aliases *Aliases `xml:"Aliases,omitempty"`
CacheBehaviors *CacheBehaviors `xml:"CacheBehaviors,omitempty"`
CallerReference aws.StringValue `xml:"CallerReference"`
Comment aws.StringValue `xml:"Comment"`
CustomErrorResponses *CustomErrorResponses `xml:"CustomErrorResponses,omitempty"`
DefaultCacheBehavior *DefaultCacheBehavior `xml:"DefaultCacheBehavior,omitempty"`
DefaultRootObject aws.StringValue `xml:"DefaultRootObject"`
Enabled aws.BooleanValue `xml:"Enabled"`
Logging *LoggingConfig `xml:"Logging,omitempty"`
Origins *Origins `xml:"Origins,omitempty"`
PriceClass aws.StringValue `xml:"PriceClass"`
Restrictions *Restrictions `xml:"Restrictions,omitempty"`
ViewerCertificate *ViewerCertificate `xml:"ViewerCertificate,omitempty"`
}
func (v *DistributionConfig) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// DistributionList is undocumented.
type DistributionList struct {
XMLName xml.Name
IsTruncated aws.BooleanValue `xml:"IsTruncated"`
Items []DistributionSummary `xml:"Items>DistributionSummary,omitempty"`
Marker aws.StringValue `xml:"Marker"`
MaxItems aws.IntegerValue `xml:"MaxItems"`
NextMarker aws.StringValue `xml:"NextMarker"`
Quantity aws.IntegerValue `xml:"Quantity"`
}
func (v *DistributionList) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// DistributionSummary is undocumented.
type DistributionSummary struct {
XMLName xml.Name
Aliases *Aliases `xml:"Aliases,omitempty"`
CacheBehaviors *CacheBehaviors `xml:"CacheBehaviors,omitempty"`
Comment aws.StringValue `xml:"Comment"`
CustomErrorResponses *CustomErrorResponses `xml:"CustomErrorResponses,omitempty"`
DefaultCacheBehavior *DefaultCacheBehavior `xml:"DefaultCacheBehavior,omitempty"`
DomainName aws.StringValue `xml:"DomainName"`
Enabled aws.BooleanValue `xml:"Enabled"`
ID aws.StringValue `xml:"Id"`
LastModifiedTime time.Time `xml:"LastModifiedTime"`
Origins *Origins `xml:"Origins,omitempty"`
PriceClass aws.StringValue `xml:"PriceClass"`
Restrictions *Restrictions `xml:"Restrictions,omitempty"`
Status aws.StringValue `xml:"Status"`
ViewerCertificate *ViewerCertificate `xml:"ViewerCertificate,omitempty"`
}
func (v *DistributionSummary) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// ForwardedValues is undocumented.
type ForwardedValues struct {
XMLName xml.Name
Cookies *CookiePreference `xml:"Cookies,omitempty"`
Headers *Headers `xml:"Headers,omitempty"`
QueryString aws.BooleanValue `xml:"QueryString"`
}
func (v *ForwardedValues) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// GeoRestriction is undocumented.
type GeoRestriction struct {
XMLName xml.Name
Items []string `xml:"Items>Location,omitempty"`
Quantity aws.IntegerValue `xml:"Quantity"`
RestrictionType aws.StringValue `xml:"RestrictionType"`
}
func (v *GeoRestriction) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// Possible values for CloudFront.
const (
GeoRestrictionTypeBlacklist = "blacklist"
GeoRestrictionTypeNone = "none"
GeoRestrictionTypeWhitelist = "whitelist"
)
// GetCloudFrontOriginAccessIdentityConfigRequest is undocumented.
type GetCloudFrontOriginAccessIdentityConfigRequest struct {
XMLName xml.Name
ID aws.StringValue `xml:"-"`
}
func (v *GetCloudFrontOriginAccessIdentityConfigRequest) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// GetCloudFrontOriginAccessIdentityConfigResult is undocumented.
type GetCloudFrontOriginAccessIdentityConfigResult struct {
XMLName xml.Name
CloudFrontOriginAccessIdentityConfig *CloudFrontOriginAccessIdentityConfig `xml:"CloudFrontOriginAccessIdentityConfig,omitempty"`
ETag aws.StringValue `xml:"-"`
}
func (v *GetCloudFrontOriginAccessIdentityConfigResult) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// GetCloudFrontOriginAccessIdentityRequest is undocumented.
type GetCloudFrontOriginAccessIdentityRequest struct {
XMLName xml.Name
ID aws.StringValue `xml:"-"`
}
func (v *GetCloudFrontOriginAccessIdentityRequest) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// GetCloudFrontOriginAccessIdentityResult is undocumented.
type GetCloudFrontOriginAccessIdentityResult struct {
XMLName xml.Name
CloudFrontOriginAccessIdentity *CloudFrontOriginAccessIdentity `xml:"CloudFrontOriginAccessIdentity,omitempty"`
ETag aws.StringValue `xml:"-"`
}
func (v *GetCloudFrontOriginAccessIdentityResult) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// GetDistributionConfigRequest is undocumented.
type GetDistributionConfigRequest struct {
XMLName xml.Name
ID aws.StringValue `xml:"-"`
}
func (v *GetDistributionConfigRequest) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// GetDistributionConfigResult is undocumented.
type GetDistributionConfigResult struct {
XMLName xml.Name
DistributionConfig *DistributionConfig `xml:"DistributionConfig,omitempty"`
ETag aws.StringValue `xml:"-"`
}
func (v *GetDistributionConfigResult) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// GetDistributionRequest is undocumented.
type GetDistributionRequest struct {
XMLName xml.Name
ID aws.StringValue `xml:"-"`
}
func (v *GetDistributionRequest) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// GetDistributionResult is undocumented.
type GetDistributionResult struct {
XMLName xml.Name
Distribution *Distribution `xml:"Distribution,omitempty"`
ETag aws.StringValue `xml:"-"`
}
func (v *GetDistributionResult) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// GetInvalidationRequest is undocumented.
type GetInvalidationRequest struct {
XMLName xml.Name
DistributionID aws.StringValue `xml:"-"`
ID aws.StringValue `xml:"-"`
}
func (v *GetInvalidationRequest) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// GetInvalidationResult is undocumented.
type GetInvalidationResult struct {
XMLName xml.Name
Invalidation *Invalidation `xml:"Invalidation,omitempty"`
}
func (v *GetInvalidationResult) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// GetStreamingDistributionConfigRequest is undocumented.
type GetStreamingDistributionConfigRequest struct {
XMLName xml.Name
ID aws.StringValue `xml:"-"`
}
func (v *GetStreamingDistributionConfigRequest) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// GetStreamingDistributionConfigResult is undocumented.
type GetStreamingDistributionConfigResult struct {
XMLName xml.Name
ETag aws.StringValue `xml:"-"`
StreamingDistributionConfig *StreamingDistributionConfig `xml:"StreamingDistributionConfig,omitempty"`
}
func (v *GetStreamingDistributionConfigResult) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// GetStreamingDistributionRequest is undocumented.
type GetStreamingDistributionRequest struct {
XMLName xml.Name
ID aws.StringValue `xml:"-"`
}
func (v *GetStreamingDistributionRequest) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// GetStreamingDistributionResult is undocumented.
type GetStreamingDistributionResult struct {
XMLName xml.Name
ETag aws.StringValue `xml:"-"`
StreamingDistribution *StreamingDistribution `xml:"StreamingDistribution,omitempty"`
}
func (v *GetStreamingDistributionResult) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// Headers is undocumented.
type Headers struct {
XMLName xml.Name
Items []string `xml:"Items>Name,omitempty"`
Quantity aws.IntegerValue `xml:"Quantity"`
}
func (v *Headers) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// Invalidation is undocumented.
type Invalidation struct {
XMLName xml.Name
CreateTime time.Time `xml:"CreateTime"`
ID aws.StringValue `xml:"Id"`
InvalidationBatch *InvalidationBatch `xml:"InvalidationBatch,omitempty"`
Status aws.StringValue `xml:"Status"`
}
func (v *Invalidation) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// InvalidationBatch is undocumented.
type InvalidationBatch struct {
XMLName xml.Name
CallerReference aws.StringValue `xml:"CallerReference"`
Paths *Paths `xml:"Paths,omitempty"`
}
func (v *InvalidationBatch) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// InvalidationList is undocumented.
type InvalidationList struct {
XMLName xml.Name
IsTruncated aws.BooleanValue `xml:"IsTruncated"`
Items []InvalidationSummary `xml:"Items>InvalidationSummary,omitempty"`
Marker aws.StringValue `xml:"Marker"`
MaxItems aws.IntegerValue `xml:"MaxItems"`
NextMarker aws.StringValue `xml:"NextMarker"`
Quantity aws.IntegerValue `xml:"Quantity"`
}
func (v *InvalidationList) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// InvalidationSummary is undocumented.
type InvalidationSummary struct {
XMLName xml.Name
CreateTime time.Time `xml:"CreateTime"`
ID aws.StringValue `xml:"Id"`
Status aws.StringValue `xml:"Status"`
}
func (v *InvalidationSummary) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// Possible values for CloudFront.
const (
ItemSelectionAll = "all"
ItemSelectionNone = "none"
ItemSelectionWhitelist = "whitelist"
)
// KeyPairIDs is undocumented.
type KeyPairIDs struct {
XMLName xml.Name
Items []string `xml:"Items>KeyPairId,omitempty"`
Quantity aws.IntegerValue `xml:"Quantity"`
}
func (v *KeyPairIDs) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// ListCloudFrontOriginAccessIdentitiesRequest is undocumented.
type ListCloudFrontOriginAccessIdentitiesRequest struct {
XMLName xml.Name
Marker aws.StringValue `xml:"-"`
MaxItems aws.StringValue `xml:"-"`
}
func (v *ListCloudFrontOriginAccessIdentitiesRequest) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// ListCloudFrontOriginAccessIdentitiesResult is undocumented.
type ListCloudFrontOriginAccessIdentitiesResult struct {
XMLName xml.Name
CloudFrontOriginAccessIdentityList *CloudFrontOriginAccessIdentityList `xml:"CloudFrontOriginAccessIdentityList,omitempty"`
}
func (v *ListCloudFrontOriginAccessIdentitiesResult) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// ListDistributionsRequest is undocumented.
type ListDistributionsRequest struct {
XMLName xml.Name
Marker aws.StringValue `xml:"-"`
MaxItems aws.StringValue `xml:"-"`
}
func (v *ListDistributionsRequest) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// ListDistributionsResult is undocumented.
type ListDistributionsResult struct {
XMLName xml.Name
DistributionList *DistributionList `xml:"DistributionList,omitempty"`
}
func (v *ListDistributionsResult) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// ListInvalidationsRequest is undocumented.
type ListInvalidationsRequest struct {
XMLName xml.Name
DistributionID aws.StringValue `xml:"-"`
Marker aws.StringValue `xml:"-"`
MaxItems aws.StringValue `xml:"-"`
}
func (v *ListInvalidationsRequest) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// ListInvalidationsResult is undocumented.
type ListInvalidationsResult struct {
XMLName xml.Name
InvalidationList *InvalidationList `xml:"InvalidationList,omitempty"`
}
func (v *ListInvalidationsResult) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// ListStreamingDistributionsRequest is undocumented.
type ListStreamingDistributionsRequest struct {
XMLName xml.Name
Marker aws.StringValue `xml:"-"`
MaxItems aws.StringValue `xml:"-"`
}
func (v *ListStreamingDistributionsRequest) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// ListStreamingDistributionsResult is undocumented.
type ListStreamingDistributionsResult struct {
XMLName xml.Name
StreamingDistributionList *StreamingDistributionList `xml:"StreamingDistributionList,omitempty"`
}
func (v *ListStreamingDistributionsResult) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// LoggingConfig is undocumented.
type LoggingConfig struct {
XMLName xml.Name
Bucket aws.StringValue `xml:"Bucket"`
Enabled aws.BooleanValue `xml:"Enabled"`
IncludeCookies aws.BooleanValue `xml:"IncludeCookies"`
Prefix aws.StringValue `xml:"Prefix"`
}
func (v *LoggingConfig) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// Possible values for CloudFront.
const (
MethodDelete = "DELETE"
MethodGet = "GET"
MethodHead = "HEAD"
MethodOptions = "OPTIONS"
MethodPatch = "PATCH"
MethodPost = "POST"
MethodPut = "PUT"
)
// Possible values for CloudFront.
const (
MinimumProtocolVersionSSLv3 = "SSLv3"
MinimumProtocolVersionTLSv1 = "TLSv1"
)
// Origin is undocumented.
type Origin struct {
XMLName xml.Name
CustomOriginConfig *CustomOriginConfig `xml:"CustomOriginConfig,omitempty"`
DomainName aws.StringValue `xml:"DomainName"`
ID aws.StringValue `xml:"Id"`
S3OriginConfig *S3OriginConfig `xml:"S3OriginConfig,omitempty"`
}
func (v *Origin) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// Possible values for CloudFront.
const (
OriginProtocolPolicyHTTPOnly = "http-only"
OriginProtocolPolicyMatchViewer = "match-viewer"
)
// Origins is undocumented.
type Origins struct {
XMLName xml.Name
Items []Origin `xml:"Items>Origin,omitempty"`
Quantity aws.IntegerValue `xml:"Quantity"`
}
func (v *Origins) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// Paths is undocumented.
type Paths struct {
XMLName xml.Name
Items []string `xml:"Items>Path,omitempty"`
Quantity aws.IntegerValue `xml:"Quantity"`
}
func (v *Paths) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// Possible values for CloudFront.
const (
PriceClassPriceClass100 = "PriceClass_100"
PriceClassPriceClass200 = "PriceClass_200"
PriceClassPriceClassAll = "PriceClass_All"
)
// Restrictions is undocumented.
type Restrictions struct {
XMLName xml.Name
GeoRestriction *GeoRestriction `xml:"GeoRestriction,omitempty"`
}
func (v *Restrictions) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// S3Origin is undocumented.
type S3Origin struct {
XMLName xml.Name
DomainName aws.StringValue `xml:"DomainName"`
OriginAccessIdentity aws.StringValue `xml:"OriginAccessIdentity"`
}
func (v *S3Origin) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// S3OriginConfig is undocumented.
type S3OriginConfig struct {
XMLName xml.Name
OriginAccessIdentity aws.StringValue `xml:"OriginAccessIdentity"`
}
func (v *S3OriginConfig) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// Possible values for CloudFront.
const (
SSLSupportMethodSNIOnly = "sni-only"
SSLSupportMethodVIP = "vip"
)
// Signer is undocumented.
type Signer struct {
XMLName xml.Name
AWSAccountNumber aws.StringValue `xml:"AwsAccountNumber"`
KeyPairIDs *KeyPairIDs `xml:"KeyPairIds,omitempty"`
}
func (v *Signer) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// StreamingDistribution is undocumented.
type StreamingDistribution struct {
XMLName xml.Name
ActiveTrustedSigners *ActiveTrustedSigners `xml:"ActiveTrustedSigners,omitempty"`
DomainName aws.StringValue `xml:"DomainName"`
ID aws.StringValue `xml:"Id"`
LastModifiedTime time.Time `xml:"LastModifiedTime"`
Status aws.StringValue `xml:"Status"`
StreamingDistributionConfig *StreamingDistributionConfig `xml:"StreamingDistributionConfig,omitempty"`
}
func (v *StreamingDistribution) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// StreamingDistributionConfig is undocumented.
type StreamingDistributionConfig struct {
XMLName xml.Name
Aliases *Aliases `xml:"Aliases,omitempty"`
CallerReference aws.StringValue `xml:"CallerReference"`
Comment aws.StringValue `xml:"Comment"`
Enabled aws.BooleanValue `xml:"Enabled"`
Logging *StreamingLoggingConfig `xml:"Logging,omitempty"`
PriceClass aws.StringValue `xml:"PriceClass"`
S3Origin *S3Origin `xml:"S3Origin,omitempty"`
TrustedSigners *TrustedSigners `xml:"TrustedSigners,omitempty"`
}
func (v *StreamingDistributionConfig) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// StreamingDistributionList is undocumented.
type StreamingDistributionList struct {
XMLName xml.Name
IsTruncated aws.BooleanValue `xml:"IsTruncated"`
Items []StreamingDistributionSummary `xml:"Items>StreamingDistributionSummary,omitempty"`
Marker aws.StringValue `xml:"Marker"`
MaxItems aws.IntegerValue `xml:"MaxItems"`
NextMarker aws.StringValue `xml:"NextMarker"`
Quantity aws.IntegerValue `xml:"Quantity"`
}
func (v *StreamingDistributionList) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// StreamingDistributionSummary is undocumented.
type StreamingDistributionSummary struct {
XMLName xml.Name
Aliases *Aliases `xml:"Aliases,omitempty"`
Comment aws.StringValue `xml:"Comment"`
DomainName aws.StringValue `xml:"DomainName"`
Enabled aws.BooleanValue `xml:"Enabled"`
ID aws.StringValue `xml:"Id"`
LastModifiedTime time.Time `xml:"LastModifiedTime"`
PriceClass aws.StringValue `xml:"PriceClass"`
S3Origin *S3Origin `xml:"S3Origin,omitempty"`
Status aws.StringValue `xml:"Status"`
TrustedSigners *TrustedSigners `xml:"TrustedSigners,omitempty"`
}
func (v *StreamingDistributionSummary) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// StreamingLoggingConfig is undocumented.
type StreamingLoggingConfig struct {
XMLName xml.Name
Bucket aws.StringValue `xml:"Bucket"`
Enabled aws.BooleanValue `xml:"Enabled"`
Prefix aws.StringValue `xml:"Prefix"`
}
func (v *StreamingLoggingConfig) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// TrustedSigners is undocumented.
type TrustedSigners struct {
XMLName xml.Name
Enabled aws.BooleanValue `xml:"Enabled"`
Items []string `xml:"Items>AwsAccountNumber,omitempty"`
Quantity aws.IntegerValue `xml:"Quantity"`
}
func (v *TrustedSigners) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// UpdateCloudFrontOriginAccessIdentityRequest is undocumented.
type UpdateCloudFrontOriginAccessIdentityRequest struct {
XMLName xml.Name
CloudFrontOriginAccessIdentityConfig *CloudFrontOriginAccessIdentityConfig `xml:"CloudFrontOriginAccessIdentityConfig,omitempty"`
ID aws.StringValue `xml:"-"`
IfMatch aws.StringValue `xml:"-"`
}
func (v *UpdateCloudFrontOriginAccessIdentityRequest) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// UpdateCloudFrontOriginAccessIdentityResult is undocumented.
type UpdateCloudFrontOriginAccessIdentityResult struct {
XMLName xml.Name
CloudFrontOriginAccessIdentity *CloudFrontOriginAccessIdentity `xml:"CloudFrontOriginAccessIdentity,omitempty"`
ETag aws.StringValue `xml:"-"`
}
func (v *UpdateCloudFrontOriginAccessIdentityResult) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// UpdateDistributionRequest is undocumented.
type UpdateDistributionRequest struct {
XMLName xml.Name
DistributionConfig *DistributionConfig `xml:"DistributionConfig,omitempty"`
ID aws.StringValue `xml:"-"`
IfMatch aws.StringValue `xml:"-"`
}
func (v *UpdateDistributionRequest) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// UpdateDistributionResult is undocumented.
type UpdateDistributionResult struct {
XMLName xml.Name
Distribution *Distribution `xml:"Distribution,omitempty"`
ETag aws.StringValue `xml:"-"`
}
func (v *UpdateDistributionResult) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// UpdateStreamingDistributionRequest is undocumented.
type UpdateStreamingDistributionRequest struct {
XMLName xml.Name
ID aws.StringValue `xml:"-"`
IfMatch aws.StringValue `xml:"-"`
StreamingDistributionConfig *StreamingDistributionConfig `xml:"StreamingDistributionConfig,omitempty"`
}
func (v *UpdateStreamingDistributionRequest) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// UpdateStreamingDistributionResult is undocumented.
type UpdateStreamingDistributionResult struct {
XMLName xml.Name
ETag aws.StringValue `xml:"-"`
StreamingDistribution *StreamingDistribution `xml:"StreamingDistribution,omitempty"`
}
func (v *UpdateStreamingDistributionResult) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// ViewerCertificate is undocumented.
type ViewerCertificate struct {
XMLName xml.Name
CloudFrontDefaultCertificate aws.BooleanValue `xml:"CloudFrontDefaultCertificate"`
IAMCertificateID aws.StringValue `xml:"IAMCertificateId"`
MinimumProtocolVersion aws.StringValue `xml:"MinimumProtocolVersion"`
SSLSupportMethod aws.StringValue `xml:"SSLSupportMethod"`
}
func (v *ViewerCertificate) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return aws.MarshalXML(v, e, start)
}
// Possible values for CloudFront.
const (
ViewerProtocolPolicyAllowAll = "allow-all"
ViewerProtocolPolicyHTTPSOnly = "https-only"
ViewerProtocolPolicyRedirectToHTTPS = "redirect-to-https"
)
// avoid errors if the packages aren't referenced
var _ time.Time
var _ bytes.Reader
var _ url.URL
var _ fmt.Stringer
var _ strings.Reader
var _ strconv.NumError
var _ = ioutil.Discard
| {
"content_hash": "cd55961d279b547ec6c3f3d8ff30dc63",
"timestamp": "",
"source": "github",
"line_count": 2310,
"max_line_length": 180,
"avg_line_length": 26.523809523809526,
"alnum_prop": 0.7020891137587727,
"repo_name": "kuxuxun/aws-sdk-go",
"id": "28b55a5aeb0d701fcbe8d5d630aab2251588f5d1",
"size": "61388",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gen/cloudfront/cloudfront.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "2297710"
},
{
"name": "Makefile",
"bytes": "118"
}
],
"symlink_target": ""
} |
FROM golang:1.5.2
MAINTAINER wencan <[email protected]>
RUN apt-get update \
&& apt-get install -y --no-install-recommends autoconf automake libtool unzip \
&& rm -rf /var/lib/apt/lists/*
ENV PROTOBUF_VERSION 3.0.0-beta-1
RUN curl -L https://github.com/google/protobuf/archive/v$PROTOBUF_VERSION.tar.gz -o protobuf-$PROTOBUF_VERSION.tar.gz \
&& tar xzf protobuf-$PROTOBUF_VERSION.tar.gz \
&& cd protobuf-$PROTOBUF_VERSION \
&& ./autogen.sh \
&& ./configure \
&& make \
&& make check \
&& make install \
&& cd ../ \
&& rm -rf protobuf-$PROTOBUF_VERSION.tar.gz protobuf-$PROTOBUF_VERSION \
&& ldconfig
RUN go get -v github.com/golang/protobuf/protoc-gen-go
WORKDIR /
| {
"content_hash": "28397c2b13ebf4e611c8ee54af854c9a",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 119,
"avg_line_length": 29.75,
"alnum_prop": 0.6554621848739496,
"repo_name": "wencan/docker-library",
"id": "ec4be7a41fa1adb3d9fe5d53e758c7369f064f36",
"size": "714",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "protobuf/3.0.0-beta-1-golang1.5.2/Dockerfile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "24647"
}
],
"symlink_target": ""
} |
<?php
namespace Concerto\PanelBundle\Repository;
/**
* TestNodeRepository
*/
class TestNodeRepository extends AEntityRepository
{
}
| {
"content_hash": "ddd346b27b7b176534899d6c650666c0",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 50,
"avg_line_length": 12.454545454545455,
"alnum_prop": 0.7737226277372263,
"repo_name": "campsych/concerto-platform",
"id": "a4a7650d7b0c5303666b0b797562726c5c08c9d2",
"size": "137",
"binary": false,
"copies": "1",
"ref": "refs/heads/5.0-dev",
"path": "src/Concerto/PanelBundle/Repository/TestNodeRepository.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "25675"
},
{
"name": "Dockerfile",
"bytes": "7973"
},
{
"name": "HTML",
"bytes": "69682"
},
{
"name": "JavaScript",
"bytes": "30943"
},
{
"name": "PHP",
"bytes": "1041928"
},
{
"name": "R",
"bytes": "151645"
},
{
"name": "Shell",
"bytes": "2915"
},
{
"name": "Smarty",
"bytes": "1502"
},
{
"name": "Twig",
"bytes": "293442"
}
],
"symlink_target": ""
} |
package me.scylla.fframework.utils.http;
import java.util.HashMap;
import java.util.Map;
import me.scylla.fframework.model.entity.Module;
/**
* @author Ray Liu
*
*/
public class SessionHelper {
public static final String KEY_MODULE = "_app";
public static final String KEY_PRIVILEGE = "_privilege";
public static final String KEY_LOGIN_USER = "_login_user";
public static final String KEY_CART = "_cart";
private static final ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal<Map<String, Object>>();
private static final Map<String, Object> defaultValues = new HashMap<String, Object>();
static Map<String, Object> getDefaultvalues() {
return defaultValues;
}
public static void setObject(String key, Object value) {
if (threadLocal.get() == null) {
Map<String, Object> map = new HashMap<String, Object>();
threadLocal.set(map);
}
threadLocal.get().put(key, value);
}
public static Map<String, Object> getSessionMap() {
return threadLocal.get();
}
public static Object getObject(String key) {
Map<String, Object> map = threadLocal.get();
Object value = null;
if (map != null) {
value = map.get(key);
}
if (value == null) {
value = defaultValues.get(key);
}
return value;
}
public static void clearObjects() {
threadLocal.remove();
}
public static void setModule(Module module) {
setObject(KEY_MODULE, module);
}
public static Module getModule() {
return (Module) getObject(KEY_MODULE);
}
} | {
"content_hash": "45cbb3d08df5bd8f618d54fe560915a0",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 108,
"avg_line_length": 24.65,
"alnum_prop": 0.7004732927653821,
"repo_name": "scyllor/fframework",
"id": "5c67e454ca4e7e31aa2f1e9a63485a4ca14faf79",
"size": "1479",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/me/scylla/fframework/utils/http/SessionHelper.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "32247"
}
],
"symlink_target": ""
} |
package org.jamesframework.examples.clique;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
/**
* Reads a graph from a text file. Each line contains two vertex IDs separated by
* one or more spaces, indicating that these vertices are connected in the graph.
*
* @author <a href="mailto:[email protected]">Herman De Beukelaer</a>
*/
public class CliqueFileReader {
public CliqueData read(String filePath) throws FileNotFoundException{
Scanner sc = new Scanner(new File(filePath));
sc.useLocale(Locale.US);
Map<Integer, Set<Integer>> adj = new HashMap<>();
while(sc.hasNext()){
int v1 = sc.nextInt();
int v2 = sc.nextInt();
adj.putIfAbsent(v1, new HashSet<>());
adj.putIfAbsent(v2, new HashSet<>());
adj.get(v1).add(v2);
adj.get(v2).add(v1);
}
return new CliqueData(adj);
}
}
| {
"content_hash": "2074a4c6d814d132cf13562d69e35014",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 81,
"avg_line_length": 29.35135135135135,
"alnum_prop": 0.6500920810313076,
"repo_name": "hdbeukel/james-examples",
"id": "53473c434ab18485d8666e75c17022f00c0407f0",
"size": "1706",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/jamesframework/examples/clique/CliqueFileReader.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "175132"
},
{
"name": "Python",
"bytes": "1311"
}
],
"symlink_target": ""
} |
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.streamdataio.android.github.CommitsActivity">
</menu>
| {
"content_hash": "108bb2f46a4789164c8556b14b9eb942",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 68,
"avg_line_length": 42.333333333333336,
"alnum_prop": 0.7244094488188977,
"repo_name": "streamdataio/github-android",
"id": "be5fb6fc78c5c4a89eb7e3930d7475c3f719f931",
"size": "254",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/menu/menu_commits.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "71019"
}
],
"symlink_target": ""
} |
@implementation SLPlayerView
+ (Class)layerClass {
return [AVPlayerLayer class];
}
- (AVPlayer *)mPlayer {
return [(AVPlayerLayer *)[self layer] player];
}
- (void)setMPlayer:(AVPlayer *)mPlayer {
[(AVPlayerLayer *)[self layer] setPlayer:mPlayer];
}
- (void)dealloc {
self.mPlayer = nil;
}
@end
@interface SLAVPlayerViewController ()
@end
@implementation SLAVPlayerViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self.view addSubview:self.mPlayerView];
[self.view addSubview:self.startPlayer];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
#pragma mark - setter & getter
- (SLPlayerView *)mPlayerView {
if (!_mPlayerView) {
CGFloat positionY = 60;
_mPlayerView = [[SLPlayerView alloc] initWithFrame:CGRectMake(0, positionY, SCREEN_WIDTH, SCREEN_HEIGHT - 60 - 240)];
_mPlayerView.autoresizesSubviews = YES;
[_mPlayerView sizeToFit];
_mPlayerView.backgroundColor = [UIColor yellowColor];
}
return _mPlayerView;
}
- (UIButton *)startPlayer {
if (!_startPlayer) {
CGFloat positionX = (SCREEN_WIDTH - 60)/2;
CGFloat positionY = self.mPlayerView.bounds.size.height + 20;
_startPlayer = [[UIButton alloc] initWithFrame:CGRectMake(positionX, positionY, 60, 35)];
_startPlayer.backgroundColor = [UIColor redColor];
_startPlayer.alpha = 0.5f;
[_startPlayer setTitle:@"播放" forState:UIControlStateNormal];
}
return _startPlayer;
}
@end
| {
"content_hash": "487b7e942a7d3957254277ba0d822ff4",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 125,
"avg_line_length": 24.126984126984127,
"alnum_prop": 0.6730263157894737,
"repo_name": "boilWater/FeiYuePlayer",
"id": "37864e68d1bf094a4ea6c3305b30d2094e0f3c8d",
"size": "1748",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Example/FeiYuePlayer/Utilities/FYPlayerView/SLAVPlayerViewController.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "383"
},
{
"name": "Objective-C",
"bytes": "1566404"
},
{
"name": "Ruby",
"bytes": "1838"
},
{
"name": "Shell",
"bytes": "17868"
},
{
"name": "Swift",
"bytes": "6169"
}
],
"symlink_target": ""
} |
<md-toolbar>
<br>
<div class="md-toolbar-tools">
<md-button class="button-small" ng-click="tbc.toggleSidenav('left')" aria-label="Menu">
<ng-md-icon icon="menu"></ng-md-icon>
</md-button>
<span class="md-heading">
Dashboard
</span>
<span flex></span>
<md-button class="button-small" aria-label="Open Settings" ng-click="tbc.showListBottomSheet($event)">
<ng-md-icon icon="more_vert"></ng-md-icon>
</md-button>
</div>
<div>
<md-tabs class="md-primary" md-stretch-tabs="always">
<md-tab id="tab1" aria-controls="tab1-content" md-on-select="tbc.go('main.dashboard.recent')">
Latest
</md-tab>
<md-tab id="tab2" aria-controls="tab2-content" md-on-select="tbc.go('main.dashboard.favorites')">
Favorites
</md-tab>
</md-tabs>
</div>
</md-toolbar>
| {
"content_hash": "76d87d39bae8f04126e69093f4ea2956",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 112,
"avg_line_length": 39.64,
"alnum_prop": 0.5186680121089808,
"repo_name": "jouke/ionic-ngmaterial-startapp",
"id": "ad5e4af127d2a7c4ae2c0988e91c7ba324973aa2",
"size": "991",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/toolbar/toolbar.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1622759"
},
{
"name": "HTML",
"bytes": "80276"
},
{
"name": "JavaScript",
"bytes": "2686402"
}
],
"symlink_target": ""
} |
var fs = require("fs");
var zlib = require('zlib');
// Decompress the file input.txt.gz to input.txt
fs.createReadStream('input.txt.gz')
.pipe(zlib.createGunzip())
.pipe(fs.createWriteStream('input.txt'));
console.log("File Decompressed."); | {
"content_hash": "8b2a38755a75dbb98d2f5328200d7aee",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 48,
"avg_line_length": 27.77777777777778,
"alnum_prop": 0.696,
"repo_name": "acelaya/angular-course-webstorm",
"id": "596b53ddfc153ee57048dfbc530a025d0ee065cf",
"size": "250",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "first_project/API_STREAMS/streamsUnzip.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "347"
},
{
"name": "CSS",
"bytes": "105163"
},
{
"name": "HTML",
"bytes": "2288052"
},
{
"name": "JavaScript",
"bytes": "8027829"
},
{
"name": "Shell",
"bytes": "5093"
}
],
"symlink_target": ""
} |
<?php
namespace ProjectAgeAnalyzer\Log;
use Psr\Log\LoggerInterface;
class LoggerSpy implements LoggerInterface
{
/** @var array */
private $logMessages = [];
/**
* System is unusable.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function emergency($message, array $context = array())
{
$this->logMessages[] = [__FUNCTION__ => func_get_args()];
}
/**
* Action must be taken immediately.
*
* Example: Entire website down, database unavailable, etc. This should
* trigger the SMS alerts and wake you up.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function alert($message, array $context = array())
{
$this->logMessages[] = [__FUNCTION__ => func_get_args()];
}
/**
* Critical conditions.
*
* Example: Application component unavailable, unexpected exception.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function critical($message, array $context = array())
{
$this->logMessages[] = [__FUNCTION__ => func_get_args()];
}
/**
* Runtime errors that do not require immediate action but should typically
* be logged and monitored.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function error($message, array $context = array())
{
$this->logMessages[] = [__FUNCTION__ => func_get_args()];
}
/**
* Exceptional occurrences that are not errors.
*
* Example: Use of deprecated APIs, poor use of an API, undesirable things
* that are not necessarily wrong.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function warning($message, array $context = array())
{
$this->logMessages[] = [__FUNCTION__ => func_get_args()];
}
/**
* Normal but significant events.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function notice($message, array $context = array())
{
$this->logMessages[] = [__FUNCTION__ => func_get_args()];
}
/**
* Interesting events.
*
* Example: User logs in, SQL logs.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function info($message, array $context = array())
{
$this->logMessages[] = [__FUNCTION__ => func_get_args()];
}
/**
* Detailed debug information.
*
* @param string $message
* @param array $context
*
* @return void
*/
public function debug($message, array $context = array())
{
$this->logMessages[] = [__FUNCTION__ => func_get_args()];
}
/**
* Logs with an arbitrary level.
*
* @param mixed $level
* @param string $message
* @param array $context
*
* @return void
*/
public function log($level, $message, array $context = array())
{
$this->logMessages[] = [__FUNCTION__ => func_get_args()];
}
/**
* @return array
*/
public function getLogMessages(): array
{
return $this->logMessages;
}
}
| {
"content_hash": "20c563cb77bee3b16fb7af39da76b79f",
"timestamp": "",
"source": "github",
"line_count": 148,
"max_line_length": 79,
"avg_line_length": 22.783783783783782,
"alnum_prop": 0.5444839857651246,
"repo_name": "cbergau/project_age_analyzer",
"id": "6a3afa9aeb9732c65fc1c8dc87cec5c9b2c515e8",
"size": "3372",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/ProjectAgeAnalyzer/Log/LoggerSpy.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "43575"
}
],
"symlink_target": ""
} |
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/*jslint node: true, nomen: true, stupid: true */
'use strict';
// Variables
const fs = require('fs'),
path = require('path'),
_ = require('lodash');
// Export module
_.forEach(fs.readdirSync(__dirname), function (filename) {
if ('index.js' === filename) {
return;
}
const extension = path.extname(filename),
name = filename.replace(extension, '');
module.exports[name] = require(path.join(__dirname, name));
});
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* c-hanging-comment-ender-p: nil
* End:
*/
| {
"content_hash": "0a92a23c935a614f155e87f5340922ad",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 63,
"avg_line_length": 18.114285714285714,
"alnum_prop": 0.6088328075709779,
"repo_name": "eq-inc/eq-web",
"id": "c2007ec42630dbfd94a9c19c3ea95e0e5aa72fd1",
"size": "634",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/middleware/cache/index.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "39033"
}
],
"symlink_target": ""
} |
package frontend
import (
"context"
"golang.org/x/pkgsite/internal"
"golang.org/x/pkgsite/internal/log"
"golang.org/x/pkgsite/internal/middleware"
)
// GetLatestInfo returns various pieces of information about the latest
// versions of a unit and module:
// - The linkable form of the minor version of the unit.
// - The latest module path and the full unit path of any major version found given the
// fullPath and the modulePath.
//
// It returns empty strings on error.
// It is intended to be used as an argument to middleware.LatestVersions.
func (s *Server) GetLatestInfo(ctx context.Context, unitPath, modulePath string, latestUnitMeta *internal.UnitMeta) internal.LatestInfo {
defer middleware.ElapsedStat(ctx, "GetLatestInfo")()
// It is okay to use a different DataSource (DB connection) than the rest of the
// request, because this makes self-contained calls on the DB.
ds := s.getDataSource(ctx)
latest, err := ds.GetLatestInfo(ctx, unitPath, modulePath, latestUnitMeta)
if err != nil {
log.Errorf(ctx, "Server.GetLatestInfo: %v", err)
} else {
latest.MinorVersion = linkVersion(latest.MinorModulePath, latest.MinorVersion, latest.MinorVersion)
}
return latest
}
| {
"content_hash": "6d4604fb318cd035e35e3926dbf75462",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 137,
"avg_line_length": 36.54545454545455,
"alnum_prop": 0.7504145936981758,
"repo_name": "golang/pkgsite",
"id": "e3e4b73028fc11ef791979635dceb7a41344cabd",
"size": "1366",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "internal/frontend/latest_version.go",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "100038"
},
{
"name": "Go",
"bytes": "2047042"
},
{
"name": "JavaScript",
"bytes": "419"
},
{
"name": "PLpgSQL",
"bytes": "171250"
},
{
"name": "Shell",
"bytes": "34094"
},
{
"name": "TypeScript",
"bytes": "111908"
}
],
"symlink_target": ""
} |
[jvm]
Content
abstract fun [outerType](outer-type.md)(value: [Type](https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Type.html)?): [S](index.md)
More info
See [TypeDeclaration.outerType](../outer-type.md)
| {
"content_hash": "1d780df316d910ab37bb9f54af0116f1",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 143,
"avg_line_length": 19.416666666666668,
"alnum_prop": 0.6824034334763949,
"repo_name": "JonathanxD/CodeAPI",
"id": "cb66c964acc0c3f076dd07a5041fe7898d46b7c2",
"size": "408",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/-kores/com.github.jonathanxd.kores.base/-type-declaration/-builder/outer-type.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "350769"
},
{
"name": "Kotlin",
"bytes": "830039"
}
],
"symlink_target": ""
} |
<?php
namespace Diskerror\Utilities;
class Registry extends Stack
{
/**#@+
* @access protected
*/
/**
* Singleton instance of this class.
* @var Diskerror\Utilities\Registry
* @static
*/
private static $_instance;
/**
* Create static instance if it doesn't exist.
*/
final private static function _checkInstance()
{
if ( !isset(self::$_instance) ) {
self::$_instance = new self();
}
}
/**
* Retrieves the static instance when for use as a singleton.
*
* @return Diskerror\Utilities\Registry
*/
final public static function getInstance()
{
self::_checkInstance();
return self::$_instance;
}
/**
* Unset the default stack instance.
* Primarily used in tearDown() in unit tests.
* @returns void
*/
final public static function unsetInstance()
{
if ( isset(self::$_instance) ) {
self::$_instance = null; // can't unset a static property
}
}
/**
* Gets data from singleton instance.
*
* @param string|int $key
* @return mixed
*/
final public static function get($key)
{
self::_checkInstance();
return self::$_instance->offsetGet($key);
}
/**
* Sets data to singleton instance.
*
* @param string|int $key
* @param mixed $value
*/
final public static function set($key, $value)
{
self::_checkInstance();
self::$_instance->offsetSet($key, $value);
}
}
| {
"content_hash": "05361ee35c45f207642e5d87cf579925",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 62,
"avg_line_length": 17.61038961038961,
"alnum_prop": 0.6364306784660767,
"repo_name": "diskerror/Utilities",
"id": "5809a2128b3520726c605f0ac5eed2cc2efaf8ff",
"size": "1765",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Registry.php",
"mode": "33261",
"license": "bsd-2-clause",
"language": [
{
"name": "PHP",
"bytes": "27720"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"
default-lazy-init="true">
<!-- Activates scanning of @Autowired -->
<context:annotation-config/>
<!-- Activates scanning of @Repository and @Service -->
<context:component-scan base-package="com.vnpt.spdv"/>
<!-- Add new DAOs here -->
<!-- Add new Managers here -->
</beans> | {
"content_hash": "65828366668e31ee521bdcd1652ed843",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 131,
"avg_line_length": 45.94117647058823,
"alnum_prop": 0.6965428937259923,
"repo_name": "hungcuongbsm/spdv",
"id": "caa1c49b952780c3ac258a80c013a7297591e164",
"size": "781",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/src/main/resources/applicationContext.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "4835"
},
{
"name": "Java",
"bytes": "289347"
},
{
"name": "JavaScript",
"bytes": "3350"
}
],
"symlink_target": ""
} |
package com.vincent.filepicker.activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.vincent.filepicker.Constant;
import com.vincent.filepicker.DividerGridItemDecoration;
import com.vincent.filepicker.R;
import com.vincent.filepicker.adapter.FolderListAdapter;
import com.vincent.filepicker.adapter.ImagePickAdapter;
import com.vincent.filepicker.adapter.OnSelectStateListener;
import com.vincent.filepicker.filter.FileFilter;
import com.vincent.filepicker.filter.callback.FilterResultCallback;
import com.vincent.filepicker.filter.entity.Directory;
import com.vincent.filepicker.filter.entity.ImageFile;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Vincent Woo
* Date: 2016/10/12
* Time: 16:41
*/
public class ImagePickActivity extends BaseActivity {
public static final String IS_NEED_CAMERA = "IsNeedCamera";
public static final String IS_NEED_IMAGE_PAGER = "IsNeedImagePager";
public static final String IS_TAKEN_AUTO_SELECTED = "IsTakenAutoSelected";
public static final int DEFAULT_MAX_NUMBER = 9;
public static final int COLUMN_NUMBER = 3;
private int mMaxNumber;
private int mCurrentNumber = 0;
private RecyclerView mRecyclerView;
private ImagePickAdapter mAdapter;
private boolean isNeedCamera;
private boolean isNeedImagePager;
private boolean isTakenAutoSelected;
public ArrayList<ImageFile> mSelectedList = new ArrayList<>();
private List<Directory<ImageFile>> mAll;
private TextView tv_count;
private TextView tv_folder;
private LinearLayout ll_folder;
private RelativeLayout rl_done;
private RelativeLayout tb_pick;
@Override
void permissionGranted() {
loadData();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.vw_activity_image_pick);
mMaxNumber = getIntent().getIntExtra(Constant.MAX_NUMBER, DEFAULT_MAX_NUMBER);
isNeedCamera = getIntent().getBooleanExtra(IS_NEED_CAMERA, false);
isNeedImagePager = getIntent().getBooleanExtra(IS_NEED_IMAGE_PAGER, true);
isTakenAutoSelected = getIntent().getBooleanExtra(IS_TAKEN_AUTO_SELECTED, true);
initView();
}
private void initView() {
tv_count = (TextView) findViewById(R.id.tv_count);
tv_count.setText(mCurrentNumber + "/" + mMaxNumber);
mRecyclerView = (RecyclerView) findViewById(R.id.rv_image_pick);
final GridLayoutManager layoutManager = new GridLayoutManager(this, COLUMN_NUMBER);
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.addItemDecoration(new DividerGridItemDecoration(this));
mAdapter = new ImagePickAdapter(this, isNeedCamera, isNeedImagePager, mMaxNumber);
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnSelectStateListener(new OnSelectStateListener<ImageFile>() {
@Override
public void OnSelectStateChanged(boolean state, ImageFile file) {
if (state) {
mSelectedList.add(file);
mCurrentNumber++;
} else {
mSelectedList.remove(file);
mCurrentNumber--;
}
tv_count.setText(mCurrentNumber + "/" + mMaxNumber);
}
});
rl_done = (RelativeLayout) findViewById(R.id.rl_done);
rl_done.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putParcelableArrayListExtra(Constant.RESULT_PICK_IMAGE, mSelectedList);
setResult(RESULT_OK, intent);
finish();
}
});
tb_pick = (RelativeLayout) findViewById(R.id.tb_pick);
ll_folder = (LinearLayout) findViewById(R.id.ll_folder);
if (isNeedFolderList) {
ll_folder.setVisibility(View.VISIBLE);
ll_folder.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mFolderHelper.toggle(tb_pick);
}
});
tv_folder = (TextView) findViewById(R.id.tv_folder);
tv_folder.setText(getResources().getString(R.string.vw_all));
mFolderHelper.setFolderListListener(new FolderListAdapter.FolderListListener() {
@Override
public void onFolderListClick(Directory directory) {
mFolderHelper.toggle(tb_pick);
tv_folder.setText(directory.getName());
if (TextUtils.isEmpty(directory.getPath())) { //All
refreshData(mAll);
} else {
for (Directory<ImageFile> dir : mAll) {
if (dir.getPath().equals(directory.getPath())) {
List<Directory<ImageFile>> list = new ArrayList<>();
list.add(dir);
refreshData(list);
break;
}
}
}
}
});
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case Constant.REQUEST_CODE_TAKE_IMAGE:
if (resultCode == RESULT_OK) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File file = new File(mAdapter.mImagePath);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
sendBroadcast(mediaScanIntent);
loadData();
} else {
//Delete the record in Media DB, when user select "Cancel" during take picture
getApplicationContext().getContentResolver().delete(mAdapter.mImageUri, null, null);
}
break;
case Constant.REQUEST_CODE_BROWSER_IMAGE:
if (resultCode == RESULT_OK) {
ArrayList<ImageFile> list = data.getParcelableArrayListExtra(Constant.RESULT_BROWSER_IMAGE);
mCurrentNumber = list.size();
mAdapter.setCurrentNumber(mCurrentNumber);
tv_count.setText(mCurrentNumber + "/" + mMaxNumber);
mSelectedList.clear();
mSelectedList.addAll(list);
for (ImageFile file : mAdapter.getDataSet()) {
if (mSelectedList.contains(file)) {
file.setSelected(true);
} else {
file.setSelected(false);
}
}
mAdapter.notifyDataSetChanged();
}
break;
}
}
private void loadData() {
FileFilter.getImages(this, new FilterResultCallback<ImageFile>() {
@Override
public void onResult(List<Directory<ImageFile>> directories) {
// Refresh folder list
if (isNeedFolderList) {
ArrayList<Directory> list = new ArrayList<>();
Directory all = new Directory();
all.setName(getResources().getString(R.string.vw_all));
list.add(all);
list.addAll(directories);
mFolderHelper.fillData(list);
}
mAll = directories;
refreshData(directories);
}
});
}
private void refreshData(List<Directory<ImageFile>> directories) {
boolean tryToFindTakenImage = isTakenAutoSelected;
// if auto-select taken image is enabled, make sure requirements are met
if (tryToFindTakenImage && !TextUtils.isEmpty(mAdapter.mImagePath)) {
File takenImageFile = new File(mAdapter.mImagePath);
tryToFindTakenImage = !mAdapter.isUpToMax() && takenImageFile.exists(); // try to select taken image only if max isn't reached and the file exists
}
List<ImageFile> list = new ArrayList<>();
for (Directory<ImageFile> directory : directories) {
list.addAll(directory.getFiles());
// auto-select taken images?
if (tryToFindTakenImage) {
findAndAddTakenImage(directory.getFiles()); // if taken image was found, we're done
}
}
for (ImageFile file : mSelectedList) {
int index = list.indexOf(file);
if (index != -1) {
list.get(index).setSelected(true);
}
}
mAdapter.refresh(list);
}
private boolean findAndAddTakenImage(List<ImageFile> list) {
for (ImageFile imageFile : list) {
if (imageFile.getPath().equals(mAdapter.mImagePath)) {
mSelectedList.add(imageFile);
mCurrentNumber++;
mAdapter.setCurrentNumber(mCurrentNumber);
tv_count.setText(mCurrentNumber + "/" + mMaxNumber);
return true; // taken image was found and added
}
}
return false; // taken image wasn't found
}
private void refreshSelectedList(List<ImageFile> list) {
for (ImageFile file : list) {
if(file.isSelected() && !mSelectedList.contains(file)) {
mSelectedList.add(file);
}
}
}
}
| {
"content_hash": "23d860fcb1dff4a14243e6220d50afce",
"timestamp": "",
"source": "github",
"line_count": 256,
"max_line_length": 158,
"avg_line_length": 39.4609375,
"alnum_prop": 0.590972084735696,
"repo_name": "fishwjy/MultiType-FilePicker",
"id": "04ad15d1bdbc21966b64ca2346067d079b16ab28",
"size": "10102",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "filepicker/src/main/java/com/vincent/filepicker/activity/ImagePickActivity.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "147486"
}
],
"symlink_target": ""
} |
@interface SSZipArchive : NSObject {
}
+ (BOOL)unzipFileAtPath:(NSString *)path toDestination:(NSString *)destination;
+ (BOOL)unzipFileAtPath:(NSString *)path toDestination:(NSString *)destination overwrite:(BOOL)overwrite password:(NSString *)password error:(NSError **)error;
@end
| {
"content_hash": "0bc25db38402239c0c30489906bc3e41",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 159,
"avg_line_length": 35.875,
"alnum_prop": 0.7700348432055749,
"repo_name": "wallclimber21/ssziparchive",
"id": "9e0e5d566c52355e7f6ea2c7823f1e085e2864a5",
"size": "498",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SSZipArchive.h",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
RingClock::RingClock(
unsigned long leds[][3],
unsigned int ledCount,
unsigned int displayedHours,
PatternCreator patternCreators[],
unsigned int patternCount
) :
leds{leds},
ledCount{ledCount},
displayedHours{displayedHours},
ledsPerHour{ledCount/displayedHours},
patternCreators{patternCreators},
patternCount{patternCount}
{}
RingClock::~RingClock() {
delete currentPattern;
}
void RingClock::init() {
currentPattern = new SplashPattern(this);
currentPattern->init();
}
void RingClock::tick() {
int second = Time.second();
unsigned long milliseconds = millis();
if ( initializing || second != lastSecond ) {
lastSecond = second;
if ( initializing ) {
initializing = false;
calculating = true;
return;
}
// millis() must be offset on second change since it's from device power on
millisecondsOffset = milliseconds;
// NeoPixel library stops some vital interupts that leave millis() pretty slow
// so we find out how much time has to be made up for here and use that to speed up millis()
if ( lastMilliseconds != 0 ) {
lostMillisecondsMultiplicator = 1000.0 / (float)lastMilliseconds;
}
if (calculating) {
calculating = false;
return;
}
if ( !ready ) {
selectRandomPattern();
ready = true;
}
}
lastMilliseconds = milliseconds - millisecondsOffset;
now.milliseconds = (unsigned long) lastMilliseconds * lostMillisecondsMultiplicator;//(timestamp % SECOND);
now.seconds = (unsigned long) second;//((timestamp / SECOND) % SECONDS_PER_MINUTE);
now.minutes = (unsigned long) Time.minute();//((timestamp / MINUTE) % MINUTES_PER_HOUR);
now.hours24 = (unsigned long) Time.hour();//((timestamp / HOUR ) % HOURS_PER_DAY);
now.hours12 = (unsigned long) Time.hourFormat12();//( now.hours24 >= HOURS_ON_CLOCK ) ? now.hours24 - HOURS_ON_CLOCK : now.hours24;
// Time as percents, easier to work with
now.percentSecond = (float)now.milliseconds / SECOND;
now.percentMinute = ((float)now.seconds / SECONDS_PER_MINUTE) + ((float)now.percentSecond / SECONDS_PER_MINUTE);
now.percentHour = ((float)now.minutes / MINUTES_PER_HOUR) + ((float)now.percentMinute / MINUTES_PER_HOUR);
now.percentClock = ((float)now.hours12 / HOURS_ON_CLOCK) + ((float)now.percentHour / HOURS_ON_CLOCK );
now.percentDay = ((float)now.hours24 / HOURS_PER_DAY) + ((float)now.percentHour / HOURS_PER_DAY );
// Copy now to last for the first run
if ( firstRun ) {
last = now;
firstRun = false;
}
// Update the current clock pattern
currentPattern->tick();
// Save last time to detect changes in the pattern classes
last = now;
}
void RingClock::selectRandomPattern() {
if ( currentPattern ) {
delete currentPattern;
}
currentPattern = patternCreators[random(patternCount)](this);
currentPattern->init();
}
| {
"content_hash": "f71e494bfc1c95646c50cace4e093d5e",
"timestamp": "",
"source": "github",
"line_count": 90,
"max_line_length": 133,
"avg_line_length": 31.866666666666667,
"alnum_prop": 0.6868898186889819,
"repo_name": "ubald/neopixels-ring-clock",
"id": "69e5b58031b3a83bf0e5b78c9625820614a57e2d",
"size": "2928",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "RingClock.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Arduino",
"bytes": "1835"
},
{
"name": "C",
"bytes": "623"
},
{
"name": "C++",
"bytes": "66629"
}
],
"symlink_target": ""
} |
<script src="socket.js"></script>
<script>
alert('hi');
window.ss = 'dsf';
console.log(window.io);
var socket = io('http://localhost:1415');
socket.on('news', function (data) {
console.log(data);
alert(data);
socket.emit('my other event', { my: 'datasss' });
});
</script>
| {
"content_hash": "f5894b4c35344c61043cc2c890893a0f",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 53,
"avg_line_length": 17,
"alnum_prop": 0.5784313725490197,
"repo_name": "mohanaravind/ninjatools",
"id": "f4a857cf9acd70018622e2d5406d410ef4ccabc9",
"size": "306",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "UI/socket.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2157"
},
{
"name": "HTML",
"bytes": "30098"
},
{
"name": "JavaScript",
"bytes": "574522"
}
],
"symlink_target": ""
} |
class FuzzedDataProvider;
namespace net {
class IOBuffer;
// A SourceStream implementation used in tests. This allows tests to specify
// what data to return for each Read() call.
class FuzzedSourceStream : public SourceStream {
public:
// |data_provider| is used to determine behavior of the FuzzedSourceStream.
// It must remain valid until after the FuzzedSocket is destroyed.
explicit FuzzedSourceStream(FuzzedDataProvider* data_provider);
FuzzedSourceStream(const FuzzedSourceStream&) = delete;
FuzzedSourceStream& operator=(const FuzzedSourceStream&) = delete;
~FuzzedSourceStream() override;
// SourceStream implementation
int Read(IOBuffer* dest_buffer,
int buffer_size,
CompletionOnceCallback callback) override;
std::string Description() const override;
bool MayHaveMoreBytes() const override;
private:
void OnReadComplete(CompletionOnceCallback callback,
const std::string& fuzzed_data,
scoped_refptr<IOBuffer> read_buf,
int result);
FuzzedDataProvider* data_provider_;
// Whether there is a pending Read().
bool read_pending_;
// Last result returned by Read() is an error or 0.
bool end_returned_;
};
} // namespace net
#endif // NET_FILTER_FUZZED_SOURCE_STREAM_H_
| {
"content_hash": "60da3742ab92308cfaac1ab1f8a9b348",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 77,
"avg_line_length": 29.863636363636363,
"alnum_prop": 0.7115677321156774,
"repo_name": "ric2b/Vivaldi-browser",
"id": "5e575200116dc753a07c0dd122b38cad01153a8c",
"size": "1709",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "chromium/net/filter/fuzzed_source_stream.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
namespace bp = boost::python;
struct LightSource_wrapper : osg::LightSource, bp::wrapper< osg::LightSource > {
LightSource_wrapper( )
: osg::LightSource( )
, bp::wrapper< osg::LightSource >(){
// null constructor
}
virtual void accept( ::osg::NodeVisitor & nv ) {
if( bp::override func_accept = this->get_override( "accept" ) )
func_accept( boost::ref(nv) );
else{
this->osg::LightSource::accept( boost::ref(nv) );
}
}
void default_accept( ::osg::NodeVisitor & nv ) {
osg::LightSource::accept( boost::ref(nv) );
}
virtual char const * className( ) const {
if( bp::override func_className = this->get_override( "className" ) )
return func_className( );
else{
return this->osg::LightSource::className( );
}
}
char const * default_className( ) const {
return osg::LightSource::className( );
}
virtual ::osg::Object * clone( ::osg::CopyOp const & copyop ) const {
if( bp::override func_clone = this->get_override( "clone" ) )
return func_clone( boost::ref(copyop) );
else{
return this->osg::LightSource::clone( boost::ref(copyop) );
}
}
::osg::Object * default_clone( ::osg::CopyOp const & copyop ) const {
return osg::LightSource::clone( boost::ref(copyop) );
}
virtual ::osg::Object * cloneType( ) const {
if( bp::override func_cloneType = this->get_override( "cloneType" ) )
return func_cloneType( );
else{
return this->osg::LightSource::cloneType( );
}
}
::osg::Object * default_cloneType( ) const {
return osg::LightSource::cloneType( );
}
virtual ::osg::BoundingSphere computeBound( ) const {
if( bp::override func_computeBound = this->get_override( "computeBound" ) )
return func_computeBound( );
else{
return this->osg::LightSource::computeBound( );
}
}
::osg::BoundingSphere default_computeBound( ) const {
return osg::LightSource::computeBound( );
}
virtual bool isSameKindAs( ::osg::Object const * obj ) const {
if( bp::override func_isSameKindAs = this->get_override( "isSameKindAs" ) )
return func_isSameKindAs( boost::python::ptr(obj) );
else{
return this->osg::LightSource::isSameKindAs( boost::python::ptr(obj) );
}
}
bool default_isSameKindAs( ::osg::Object const * obj ) const {
return osg::LightSource::isSameKindAs( boost::python::ptr(obj) );
}
virtual char const * libraryName( ) const {
if( bp::override func_libraryName = this->get_override( "libraryName" ) )
return func_libraryName( );
else{
return this->osg::LightSource::libraryName( );
}
}
char const * default_libraryName( ) const {
return osg::LightSource::libraryName( );
}
virtual void setThreadSafeRefUnref( bool threadSafe ) {
if( bp::override func_setThreadSafeRefUnref = this->get_override( "setThreadSafeRefUnref" ) )
func_setThreadSafeRefUnref( threadSafe );
else{
this->osg::LightSource::setThreadSafeRefUnref( threadSafe );
}
}
void default_setThreadSafeRefUnref( bool threadSafe ) {
osg::LightSource::setThreadSafeRefUnref( threadSafe );
}
virtual bool addChild( ::osg::Node * child ) {
if( bp::override func_addChild = this->get_override( "addChild" ) )
return func_addChild( boost::python::ptr(child) );
else{
return this->osg::Group::addChild( boost::python::ptr(child) );
}
}
bool default_addChild( ::osg::Node * child ) {
return osg::Group::addChild( boost::python::ptr(child) );
}
virtual ::osg::Camera * asCamera( ) {
if( bp::override func_asCamera = this->get_override( "asCamera" ) )
return func_asCamera( );
else{
return this->osg::Node::asCamera( );
}
}
::osg::Camera * default_asCamera( ) {
return osg::Node::asCamera( );
}
virtual ::osg::Camera const * asCamera( ) const {
if( bp::override func_asCamera = this->get_override( "asCamera" ) )
return func_asCamera( );
else{
return this->osg::Node::asCamera( );
}
}
::osg::Camera const * default_asCamera( ) const {
return osg::Node::asCamera( );
}
virtual ::osg::Geode * asGeode( ) {
if( bp::override func_asGeode = this->get_override( "asGeode" ) )
return func_asGeode( );
else{
return this->osg::Node::asGeode( );
}
}
::osg::Geode * default_asGeode( ) {
return osg::Node::asGeode( );
}
virtual ::osg::Geode const * asGeode( ) const {
if( bp::override func_asGeode = this->get_override( "asGeode" ) )
return func_asGeode( );
else{
return this->osg::Node::asGeode( );
}
}
::osg::Geode const * default_asGeode( ) const {
return osg::Node::asGeode( );
}
virtual ::osg::Group * asGroup( ) {
if( bp::override func_asGroup = this->get_override( "asGroup" ) )
return func_asGroup( );
else{
return this->osg::Group::asGroup( );
}
}
::osg::Group * default_asGroup( ) {
return osg::Group::asGroup( );
}
virtual ::osg::Group const * asGroup( ) const {
if( bp::override func_asGroup = this->get_override( "asGroup" ) )
return func_asGroup( );
else{
return this->osg::Group::asGroup( );
}
}
::osg::Group const * default_asGroup( ) const {
return osg::Group::asGroup( );
}
virtual ::osg::Switch * asSwitch( ) {
if( bp::override func_asSwitch = this->get_override( "asSwitch" ) )
return func_asSwitch( );
else{
return this->osg::Node::asSwitch( );
}
}
::osg::Switch * default_asSwitch( ) {
return osg::Node::asSwitch( );
}
virtual ::osg::Switch const * asSwitch( ) const {
if( bp::override func_asSwitch = this->get_override( "asSwitch" ) )
return func_asSwitch( );
else{
return this->osg::Node::asSwitch( );
}
}
::osg::Switch const * default_asSwitch( ) const {
return osg::Node::asSwitch( );
}
virtual ::osg::Transform * asTransform( ) {
if( bp::override func_asTransform = this->get_override( "asTransform" ) )
return func_asTransform( );
else{
return this->osg::Node::asTransform( );
}
}
::osg::Transform * default_asTransform( ) {
return osg::Node::asTransform( );
}
virtual ::osg::Transform const * asTransform( ) const {
if( bp::override func_asTransform = this->get_override( "asTransform" ) )
return func_asTransform( );
else{
return this->osg::Node::asTransform( );
}
}
::osg::Transform const * default_asTransform( ) const {
return osg::Node::asTransform( );
}
virtual void ascend( ::osg::NodeVisitor & nv ) {
if( bp::override func_ascend = this->get_override( "ascend" ) )
func_ascend( boost::ref(nv) );
else{
this->osg::Node::ascend( boost::ref(nv) );
}
}
void default_ascend( ::osg::NodeVisitor & nv ) {
osg::Node::ascend( boost::ref(nv) );
}
virtual void computeDataVariance( ) {
if( bp::override func_computeDataVariance = this->get_override( "computeDataVariance" ) )
func_computeDataVariance( );
else{
this->osg::Object::computeDataVariance( );
}
}
void default_computeDataVariance( ) {
osg::Object::computeDataVariance( );
}
virtual ::osg::Referenced * getUserData( ) {
if( bp::override func_getUserData = this->get_override( "getUserData" ) )
return func_getUserData( );
else{
return this->osg::Object::getUserData( );
}
}
::osg::Referenced * default_getUserData( ) {
return osg::Object::getUserData( );
}
virtual ::osg::Referenced const * getUserData( ) const {
if( bp::override func_getUserData = this->get_override( "getUserData" ) )
return func_getUserData( );
else{
return this->osg::Object::getUserData( );
}
}
::osg::Referenced const * default_getUserData( ) const {
return osg::Object::getUserData( );
}
virtual bool insertChild( unsigned int index, ::osg::Node * child ) {
if( bp::override func_insertChild = this->get_override( "insertChild" ) )
return func_insertChild( index, boost::python::ptr(child) );
else{
return this->osg::Group::insertChild( index, boost::python::ptr(child) );
}
}
bool default_insertChild( unsigned int index, ::osg::Node * child ) {
return osg::Group::insertChild( index, boost::python::ptr(child) );
}
virtual bool removeChildren( unsigned int pos, unsigned int numChildrenToRemove ) {
if( bp::override func_removeChildren = this->get_override( "removeChildren" ) )
return func_removeChildren( pos, numChildrenToRemove );
else{
return this->osg::Group::removeChildren( pos, numChildrenToRemove );
}
}
bool default_removeChildren( unsigned int pos, unsigned int numChildrenToRemove ) {
return osg::Group::removeChildren( pos, numChildrenToRemove );
}
virtual bool replaceChild( ::osg::Node * origChild, ::osg::Node * newChild ) {
if( bp::override func_replaceChild = this->get_override( "replaceChild" ) )
return func_replaceChild( boost::python::ptr(origChild), boost::python::ptr(newChild) );
else{
return this->osg::Group::replaceChild( boost::python::ptr(origChild), boost::python::ptr(newChild) );
}
}
bool default_replaceChild( ::osg::Node * origChild, ::osg::Node * newChild ) {
return osg::Group::replaceChild( boost::python::ptr(origChild), boost::python::ptr(newChild) );
}
virtual void resizeGLObjectBuffers( unsigned int maxSize ) {
if( bp::override func_resizeGLObjectBuffers = this->get_override( "resizeGLObjectBuffers" ) )
func_resizeGLObjectBuffers( maxSize );
else{
this->osg::Group::resizeGLObjectBuffers( maxSize );
}
}
void default_resizeGLObjectBuffers( unsigned int maxSize ) {
osg::Group::resizeGLObjectBuffers( maxSize );
}
virtual bool setChild( unsigned int i, ::osg::Node * node ) {
if( bp::override func_setChild = this->get_override( "setChild" ) )
return func_setChild( i, boost::python::ptr(node) );
else{
return this->osg::Group::setChild( i, boost::python::ptr(node) );
}
}
bool default_setChild( unsigned int i, ::osg::Node * node ) {
return osg::Group::setChild( i, boost::python::ptr(node) );
}
virtual void setName( ::std::string const & name ) {
if( bp::override func_setName = this->get_override( "setName" ) )
func_setName( name );
else{
this->osg::Object::setName( name );
}
}
void default_setName( ::std::string const & name ) {
osg::Object::setName( name );
}
virtual void setUserData( ::osg::Referenced * obj ) {
if( bp::override func_setUserData = this->get_override( "setUserData" ) )
func_setUserData( boost::python::ptr(obj) );
else{
this->osg::Object::setUserData( boost::python::ptr(obj) );
}
}
void default_setUserData( ::osg::Referenced * obj ) {
osg::Object::setUserData( boost::python::ptr(obj) );
}
virtual void traverse( ::osg::NodeVisitor & nv ) {
if( bp::override func_traverse = this->get_override( "traverse" ) )
func_traverse( boost::ref(nv) );
else{
this->osg::Group::traverse( boost::ref(nv) );
}
}
void default_traverse( ::osg::NodeVisitor & nv ) {
osg::Group::traverse( boost::ref(nv) );
}
};
void register_LightSource_class(){
{ //::osg::LightSource
typedef bp::class_< LightSource_wrapper, bp::bases< osg::Group >, osg::ref_ptr< ::osg::LightSource >, boost::noncopyable > LightSource_exposer_t;
LightSource_exposer_t LightSource_exposer = LightSource_exposer_t( "LightSource", "\n Leaf Node for defining a light in the scene.\n", bp::no_init );
bp::scope LightSource_scope( LightSource_exposer );
bp::enum_< osg::LightSource::ReferenceFrame>("ReferenceFrame")
.value("RELATIVE_RF", osg::LightSource::RELATIVE_RF)
.value("ABSOLUTE_RF", osg::LightSource::ABSOLUTE_RF)
.export_values()
;
LightSource_exposer.def( bp::init< >("\n Leaf Node for defining a light in the scene.\n") );
{ //::osg::LightSource::accept
typedef void ( ::osg::LightSource::*accept_function_type)( ::osg::NodeVisitor & ) ;
typedef void ( LightSource_wrapper::*default_accept_function_type)( ::osg::NodeVisitor & ) ;
LightSource_exposer.def(
"accept"
, accept_function_type(&::osg::LightSource::accept)
, default_accept_function_type(&LightSource_wrapper::default_accept)
, ( bp::arg("nv") ) );
}
{ //::osg::LightSource::className
typedef char const * ( ::osg::LightSource::*className_function_type)( ) const;
typedef char const * ( LightSource_wrapper::*default_className_function_type)( ) const;
LightSource_exposer.def(
"className"
, className_function_type(&::osg::LightSource::className)
, default_className_function_type(&LightSource_wrapper::default_className) );
}
{ //::osg::LightSource::clone
typedef ::osg::Object * ( ::osg::LightSource::*clone_function_type)( ::osg::CopyOp const & ) const;
typedef ::osg::Object * ( LightSource_wrapper::*default_clone_function_type)( ::osg::CopyOp const & ) const;
LightSource_exposer.def(
"clone"
, clone_function_type(&::osg::LightSource::clone)
, default_clone_function_type(&LightSource_wrapper::default_clone)
, ( bp::arg("copyop") )
, bp::return_value_policy< bp::reference_existing_object >() );
}
{ //::osg::LightSource::cloneType
typedef ::osg::Object * ( ::osg::LightSource::*cloneType_function_type)( ) const;
typedef ::osg::Object * ( LightSource_wrapper::*default_cloneType_function_type)( ) const;
LightSource_exposer.def(
"cloneType"
, cloneType_function_type(&::osg::LightSource::cloneType)
, default_cloneType_function_type(&LightSource_wrapper::default_cloneType)
, bp::return_value_policy< bp::reference_existing_object >() );
}
{ //::osg::LightSource::computeBound
typedef ::osg::BoundingSphere ( ::osg::LightSource::*computeBound_function_type)( ) const;
typedef ::osg::BoundingSphere ( LightSource_wrapper::*default_computeBound_function_type)( ) const;
LightSource_exposer.def(
"computeBound"
, computeBound_function_type(&::osg::LightSource::computeBound)
, default_computeBound_function_type(&LightSource_wrapper::default_computeBound) );
}
{ //::osg::LightSource::getLight
typedef ::osg::Light * ( ::osg::LightSource::*getLight_function_type)( ) ;
LightSource_exposer.def(
"getLight"
, getLight_function_type( &::osg::LightSource::getLight )
, bp::return_internal_reference< >()
, " Get the attached light." );
}
{ //::osg::LightSource::getLight
typedef ::osg::Light const * ( ::osg::LightSource::*getLight_function_type)( ) const;
LightSource_exposer.def(
"getLight"
, getLight_function_type( &::osg::LightSource::getLight )
, bp::return_internal_reference< >()
, " Get the const attached light." );
}
{ //::osg::LightSource::getReferenceFrame
typedef ::osg::LightSource::ReferenceFrame ( ::osg::LightSource::*getReferenceFrame_function_type)( ) const;
LightSource_exposer.def(
"getReferenceFrame"
, getReferenceFrame_function_type( &::osg::LightSource::getReferenceFrame ) );
}
{ //::osg::LightSource::isSameKindAs
typedef bool ( ::osg::LightSource::*isSameKindAs_function_type)( ::osg::Object const * ) const;
typedef bool ( LightSource_wrapper::*default_isSameKindAs_function_type)( ::osg::Object const * ) const;
LightSource_exposer.def(
"isSameKindAs"
, isSameKindAs_function_type(&::osg::LightSource::isSameKindAs)
, default_isSameKindAs_function_type(&LightSource_wrapper::default_isSameKindAs)
, ( bp::arg("obj") ) );
}
{ //::osg::LightSource::libraryName
typedef char const * ( ::osg::LightSource::*libraryName_function_type)( ) const;
typedef char const * ( LightSource_wrapper::*default_libraryName_function_type)( ) const;
LightSource_exposer.def(
"libraryName"
, libraryName_function_type(&::osg::LightSource::libraryName)
, default_libraryName_function_type(&LightSource_wrapper::default_libraryName) );
}
{ //::osg::LightSource::setLight
typedef void ( ::osg::LightSource::*setLight_function_type)( ::osg::Light * ) ;
LightSource_exposer.def(
"setLight"
, setLight_function_type( &::osg::LightSource::setLight )
, ( bp::arg("light") )
, " Set the attached light." );
}
{ //::osg::LightSource::setLocalStateSetModes
typedef void ( ::osg::LightSource::*setLocalStateSetModes_function_type)( unsigned int ) ;
LightSource_exposer.def(
"setLocalStateSetModes"
, setLocalStateSetModes_function_type( &::osg::LightSource::setLocalStateSetModes )
, ( bp::arg("value")=(unsigned int)(ON) )
, " Set up the local StateSet." );
}
{ //::osg::LightSource::setReferenceFrame
typedef void ( ::osg::LightSource::*setReferenceFrame_function_type)( ::osg::LightSource::ReferenceFrame ) ;
LightSource_exposer.def(
"setReferenceFrame"
, setReferenceFrame_function_type( &::osg::LightSource::setReferenceFrame )
, ( bp::arg("rf") )
, " Set the light sourcess ReferenceFrame, either to be relative to its\n parent reference frame, or relative to an absolute coordinate\n frame. RELATIVE_RF is the default.\n Note: setting the ReferenceFrame to be ABSOLUTE_RF will\n also set the CullingActive flag on the light source, and hence all\n of its parents, to false, thereby disabling culling of it and\n all its parents. This is necessary to prevent inappropriate\n culling, but may impact cull times if the absolute light source is\n deep in the scene graph. It is therefore recommended to only use\n absolute light source at the top of the scene." );
}
{ //::osg::LightSource::setStateSetModes
typedef void ( ::osg::LightSource::*setStateSetModes_function_type)( ::osg::StateSet &,unsigned int ) const;
LightSource_exposer.def(
"setStateSetModes"
, setStateSetModes_function_type( &::osg::LightSource::setStateSetModes )
, ( bp::arg("arg0"), bp::arg("arg1") )
, " Set the GLModes on StateSet associated with the LightSource." );
}
{ //::osg::LightSource::setThreadSafeRefUnref
typedef void ( ::osg::LightSource::*setThreadSafeRefUnref_function_type)( bool ) ;
typedef void ( LightSource_wrapper::*default_setThreadSafeRefUnref_function_type)( bool ) ;
LightSource_exposer.def(
"setThreadSafeRefUnref"
, setThreadSafeRefUnref_function_type(&::osg::LightSource::setThreadSafeRefUnref)
, default_setThreadSafeRefUnref_function_type(&LightSource_wrapper::default_setThreadSafeRefUnref)
, ( bp::arg("threadSafe") ) );
}
{ //::osg::Group::addChild
typedef bool ( ::osg::Group::*addChild_function_type)( ::osg::Node * ) ;
typedef bool ( LightSource_wrapper::*default_addChild_function_type)( ::osg::Node * ) ;
LightSource_exposer.def(
"addChild"
, addChild_function_type(&::osg::Group::addChild)
, default_addChild_function_type(&LightSource_wrapper::default_addChild)
, ( bp::arg("child") ) );
}
{ //::osg::Node::asCamera
typedef ::osg::Camera * ( ::osg::Node::*asCamera_function_type)( ) ;
typedef ::osg::Camera * ( LightSource_wrapper::*default_asCamera_function_type)( ) ;
LightSource_exposer.def(
"asCamera"
, asCamera_function_type(&::osg::Node::asCamera)
, default_asCamera_function_type(&LightSource_wrapper::default_asCamera)
, bp::return_internal_reference< >() );
}
{ //::osg::Node::asCamera
typedef ::osg::Camera const * ( ::osg::Node::*asCamera_function_type)( ) const;
typedef ::osg::Camera const * ( LightSource_wrapper::*default_asCamera_function_type)( ) const;
LightSource_exposer.def(
"asCamera"
, asCamera_function_type(&::osg::Node::asCamera)
, default_asCamera_function_type(&LightSource_wrapper::default_asCamera)
, bp::return_internal_reference< >() );
}
{ //::osg::Node::asGeode
typedef ::osg::Geode * ( ::osg::Node::*asGeode_function_type)( ) ;
typedef ::osg::Geode * ( LightSource_wrapper::*default_asGeode_function_type)( ) ;
LightSource_exposer.def(
"asGeode"
, asGeode_function_type(&::osg::Node::asGeode)
, default_asGeode_function_type(&LightSource_wrapper::default_asGeode)
, bp::return_internal_reference< >() );
}
{ //::osg::Node::asGeode
typedef ::osg::Geode const * ( ::osg::Node::*asGeode_function_type)( ) const;
typedef ::osg::Geode const * ( LightSource_wrapper::*default_asGeode_function_type)( ) const;
LightSource_exposer.def(
"asGeode"
, asGeode_function_type(&::osg::Node::asGeode)
, default_asGeode_function_type(&LightSource_wrapper::default_asGeode)
, bp::return_internal_reference< >() );
}
{ //::osg::Group::asGroup
typedef ::osg::Group * ( ::osg::Group::*asGroup_function_type)( ) ;
typedef ::osg::Group * ( LightSource_wrapper::*default_asGroup_function_type)( ) ;
LightSource_exposer.def(
"asGroup"
, asGroup_function_type(&::osg::Group::asGroup)
, default_asGroup_function_type(&LightSource_wrapper::default_asGroup)
, bp::return_internal_reference< >() );
}
{ //::osg::Group::asGroup
typedef ::osg::Group const * ( ::osg::Group::*asGroup_function_type)( ) const;
typedef ::osg::Group const * ( LightSource_wrapper::*default_asGroup_function_type)( ) const;
LightSource_exposer.def(
"asGroup"
, asGroup_function_type(&::osg::Group::asGroup)
, default_asGroup_function_type(&LightSource_wrapper::default_asGroup)
, bp::return_internal_reference< >() );
}
{ //::osg::Node::asSwitch
typedef ::osg::Switch * ( ::osg::Node::*asSwitch_function_type)( ) ;
typedef ::osg::Switch * ( LightSource_wrapper::*default_asSwitch_function_type)( ) ;
LightSource_exposer.def(
"asSwitch"
, asSwitch_function_type(&::osg::Node::asSwitch)
, default_asSwitch_function_type(&LightSource_wrapper::default_asSwitch)
, bp::return_internal_reference< >() );
}
{ //::osg::Node::asSwitch
typedef ::osg::Switch const * ( ::osg::Node::*asSwitch_function_type)( ) const;
typedef ::osg::Switch const * ( LightSource_wrapper::*default_asSwitch_function_type)( ) const;
LightSource_exposer.def(
"asSwitch"
, asSwitch_function_type(&::osg::Node::asSwitch)
, default_asSwitch_function_type(&LightSource_wrapper::default_asSwitch)
, bp::return_internal_reference< >() );
}
{ //::osg::Node::asTransform
typedef ::osg::Transform * ( ::osg::Node::*asTransform_function_type)( ) ;
typedef ::osg::Transform * ( LightSource_wrapper::*default_asTransform_function_type)( ) ;
LightSource_exposer.def(
"asTransform"
, asTransform_function_type(&::osg::Node::asTransform)
, default_asTransform_function_type(&LightSource_wrapper::default_asTransform)
, bp::return_internal_reference< >() );
}
{ //::osg::Node::asTransform
typedef ::osg::Transform const * ( ::osg::Node::*asTransform_function_type)( ) const;
typedef ::osg::Transform const * ( LightSource_wrapper::*default_asTransform_function_type)( ) const;
LightSource_exposer.def(
"asTransform"
, asTransform_function_type(&::osg::Node::asTransform)
, default_asTransform_function_type(&LightSource_wrapper::default_asTransform)
, bp::return_internal_reference< >() );
}
{ //::osg::Node::ascend
typedef void ( ::osg::Node::*ascend_function_type)( ::osg::NodeVisitor & ) ;
typedef void ( LightSource_wrapper::*default_ascend_function_type)( ::osg::NodeVisitor & ) ;
LightSource_exposer.def(
"ascend"
, ascend_function_type(&::osg::Node::ascend)
, default_ascend_function_type(&LightSource_wrapper::default_ascend)
, ( bp::arg("nv") ) );
}
{ //::osg::Object::computeDataVariance
typedef void ( ::osg::Object::*computeDataVariance_function_type)( ) ;
typedef void ( LightSource_wrapper::*default_computeDataVariance_function_type)( ) ;
LightSource_exposer.def(
"computeDataVariance"
, computeDataVariance_function_type(&::osg::Object::computeDataVariance)
, default_computeDataVariance_function_type(&LightSource_wrapper::default_computeDataVariance) );
}
{ //::osg::Object::getUserData
typedef ::osg::Referenced * ( ::osg::Object::*getUserData_function_type)( ) ;
typedef ::osg::Referenced * ( LightSource_wrapper::*default_getUserData_function_type)( ) ;
LightSource_exposer.def(
"getUserData"
, getUserData_function_type(&::osg::Object::getUserData)
, default_getUserData_function_type(&LightSource_wrapper::default_getUserData)
, bp::return_internal_reference< >() );
}
{ //::osg::Object::getUserData
typedef ::osg::Referenced const * ( ::osg::Object::*getUserData_function_type)( ) const;
typedef ::osg::Referenced const * ( LightSource_wrapper::*default_getUserData_function_type)( ) const;
LightSource_exposer.def(
"getUserData"
, getUserData_function_type(&::osg::Object::getUserData)
, default_getUserData_function_type(&LightSource_wrapper::default_getUserData)
, bp::return_internal_reference< >() );
}
{ //::osg::Group::insertChild
typedef bool ( ::osg::Group::*insertChild_function_type)( unsigned int,::osg::Node * ) ;
typedef bool ( LightSource_wrapper::*default_insertChild_function_type)( unsigned int,::osg::Node * ) ;
LightSource_exposer.def(
"insertChild"
, insertChild_function_type(&::osg::Group::insertChild)
, default_insertChild_function_type(&LightSource_wrapper::default_insertChild)
, ( bp::arg("index"), bp::arg("child") ) );
}
{ //::osg::Group::removeChildren
typedef bool ( ::osg::Group::*removeChildren_function_type)( unsigned int,unsigned int ) ;
typedef bool ( LightSource_wrapper::*default_removeChildren_function_type)( unsigned int,unsigned int ) ;
LightSource_exposer.def(
"removeChildren"
, removeChildren_function_type(&::osg::Group::removeChildren)
, default_removeChildren_function_type(&LightSource_wrapper::default_removeChildren)
, ( bp::arg("pos"), bp::arg("numChildrenToRemove") ) );
}
{ //::osg::Group::replaceChild
typedef bool ( ::osg::Group::*replaceChild_function_type)( ::osg::Node *,::osg::Node * ) ;
typedef bool ( LightSource_wrapper::*default_replaceChild_function_type)( ::osg::Node *,::osg::Node * ) ;
LightSource_exposer.def(
"replaceChild"
, replaceChild_function_type(&::osg::Group::replaceChild)
, default_replaceChild_function_type(&LightSource_wrapper::default_replaceChild)
, ( bp::arg("origChild"), bp::arg("newChild") ) );
}
{ //::osg::Group::resizeGLObjectBuffers
typedef void ( ::osg::Group::*resizeGLObjectBuffers_function_type)( unsigned int ) ;
typedef void ( LightSource_wrapper::*default_resizeGLObjectBuffers_function_type)( unsigned int ) ;
LightSource_exposer.def(
"resizeGLObjectBuffers"
, resizeGLObjectBuffers_function_type(&::osg::Group::resizeGLObjectBuffers)
, default_resizeGLObjectBuffers_function_type(&LightSource_wrapper::default_resizeGLObjectBuffers)
, ( bp::arg("maxSize") ) );
}
{ //::osg::Group::setChild
typedef bool ( ::osg::Group::*setChild_function_type)( unsigned int,::osg::Node * ) ;
typedef bool ( LightSource_wrapper::*default_setChild_function_type)( unsigned int,::osg::Node * ) ;
LightSource_exposer.def(
"setChild"
, setChild_function_type(&::osg::Group::setChild)
, default_setChild_function_type(&LightSource_wrapper::default_setChild)
, ( bp::arg("i"), bp::arg("node") ) );
}
{ //::osg::Object::setName
typedef void ( ::osg::Object::*setName_function_type)( ::std::string const & ) ;
typedef void ( LightSource_wrapper::*default_setName_function_type)( ::std::string const & ) ;
LightSource_exposer.def(
"setName"
, setName_function_type(&::osg::Object::setName)
, default_setName_function_type(&LightSource_wrapper::default_setName)
, ( bp::arg("name") ) );
}
{ //::osg::Object::setName
typedef void ( ::osg::Object::*setName_function_type)( char const * ) ;
LightSource_exposer.def(
"setName"
, setName_function_type( &::osg::Object::setName )
, ( bp::arg("name") )
, " Set the name of object using a C style string." );
}
{ //::osg::Object::setUserData
typedef void ( ::osg::Object::*setUserData_function_type)( ::osg::Referenced * ) ;
typedef void ( LightSource_wrapper::*default_setUserData_function_type)( ::osg::Referenced * ) ;
LightSource_exposer.def(
"setUserData"
, setUserData_function_type(&::osg::Object::setUserData)
, default_setUserData_function_type(&LightSource_wrapper::default_setUserData)
, ( bp::arg("obj") ) );
}
{ //::osg::Group::traverse
typedef void ( ::osg::Group::*traverse_function_type)( ::osg::NodeVisitor & ) ;
typedef void ( LightSource_wrapper::*default_traverse_function_type)( ::osg::NodeVisitor & ) ;
LightSource_exposer.def(
"traverse"
, traverse_function_type(&::osg::Group::traverse)
, default_traverse_function_type(&LightSource_wrapper::default_traverse)
, ( bp::arg("nv") ) );
}
}
}
| {
"content_hash": "6386cb2daaf4b67f9791cf48f908d077",
"timestamp": "",
"source": "github",
"line_count": 855,
"max_line_length": 632,
"avg_line_length": 40.771929824561404,
"alnum_prop": 0.5454962707974756,
"repo_name": "JaneliaSciComp/osgpyplusplus",
"id": "5ba804e1e7ad9330822f8373475abf8a7df01dcc",
"size": "35014",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/modules/osg/generated_code/LightSource.pypp.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "5836"
},
{
"name": "C++",
"bytes": "15619800"
},
{
"name": "CMake",
"bytes": "40664"
},
{
"name": "Python",
"bytes": "181050"
}
],
"symlink_target": ""
} |
set -e
__NDK_Version=r21
usage()
{
echo "Creates a toolchain and sysroot used for cross-compiling for Android."
echo.
echo "Usage: $0 [BuildArch] [ApiLevel]"
echo.
echo "BuildArch is the target architecture of Android. Currently only arm64 is supported."
echo "ApiLevel is the target Android API level. API levels usually match to Android releases. See https://source.android.com/source/build-numbers.html"
echo.
echo "By default, the toolchain and sysroot will be generated in cross/android-rootfs/toolchain/[BuildArch]. You can change this behavior"
echo "by setting the TOOLCHAIN_DIR environment variable"
echo.
echo "By default, the NDK will be downloaded into the cross/android-rootfs/android-ndk-$__NDK_Version directory. If you already have an NDK installation,"
echo "you can set the NDK_DIR environment variable to have this script use that installation of the NDK."
echo "By default, this script will generate a file, android_platform, in the root of the ROOTFS_DIR directory that contains the RID for the supported and tested Android build: android.28-arm64. This file is to replace '/etc/os-release', which is not available for Android."
exit 1
}
__ApiLevel=28 # The minimum platform for arm64 is API level 21 but the minimum version that support glob(3) is 28. See $ANDROID_NDK/toolchains/llvm/prebuilt/linux-x86_64/sysroot/usr/include/glob.h
__BuildArch=arm64
__AndroidArch=aarch64
__AndroidToolchain=aarch64-linux-android
for i in "$@"
do
lowerI="$(echo $i | awk '{print tolower($0)}')"
case $lowerI in
-?|-h|--help)
usage
exit 1
;;
arm64)
__BuildArch=arm64
__AndroidArch=aarch64
__AndroidToolchain=aarch64-linux-android
;;
arm)
__BuildArch=arm
__AndroidArch=arm
__AndroidToolchain=arm-linux-androideabi
;;
*[0-9])
__ApiLevel=$i
;;
*)
__UnprocessedBuildArgs="$__UnprocessedBuildArgs $i"
;;
esac
done
# Obtain the location of the bash script to figure out where the root of the repo is.
__ScriptBaseDir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
__CrossDir="$__ScriptBaseDir/../../../.tools/android-rootfs"
if [[ ! -f "$__CrossDir" ]]; then
mkdir -p "$__CrossDir"
fi
# Resolve absolute path to avoid `../` in build logs
__CrossDir="$( cd "$__CrossDir" && pwd )"
__NDK_Dir="$__CrossDir/android-ndk-$__NDK_Version"
__lldb_Dir="$__CrossDir/lldb"
__ToolchainDir="$__CrossDir/android-ndk-$__NDK_Version"
if [[ -n "$TOOLCHAIN_DIR" ]]; then
__ToolchainDir=$TOOLCHAIN_DIR
fi
if [[ -n "$NDK_DIR" ]]; then
__NDK_Dir=$NDK_DIR
fi
echo "Target API level: $__ApiLevel"
echo "Target architecture: $__BuildArch"
echo "NDK location: $__NDK_Dir"
echo "Target Toolchain location: $__ToolchainDir"
# Download the NDK if required
if [ ! -d $__NDK_Dir ]; then
echo Downloading the NDK into $__NDK_Dir
mkdir -p $__NDK_Dir
wget -q --progress=bar:force:noscroll --show-progress https://dl.google.com/android/repository/android-ndk-$__NDK_Version-linux-x86_64.zip -O $__CrossDir/android-ndk-$__NDK_Version-linux-x86_64.zip
unzip -q $__CrossDir/android-ndk-$__NDK_Version-linux-x86_64.zip -d $__CrossDir
fi
if [ ! -d $__lldb_Dir ]; then
mkdir -p $__lldb_Dir
echo Downloading LLDB into $__lldb_Dir
wget -q --progress=bar:force:noscroll --show-progress https://dl.google.com/android/repository/lldb-2.3.3614996-linux-x86_64.zip -O $__CrossDir/lldb-2.3.3614996-linux-x86_64.zip
unzip -q $__CrossDir/lldb-2.3.3614996-linux-x86_64.zip -d $__lldb_Dir
fi
echo "Download dependencies..."
__TmpDir=$__CrossDir/tmp/$__BuildArch/
mkdir -p "$__TmpDir"
# combined dependencies for coreclr, installer and libraries
__AndroidPackages="libicu"
__AndroidPackages+=" libandroid-glob"
__AndroidPackages+=" liblzma"
__AndroidPackages+=" krb5"
__AndroidPackages+=" openssl"
for path in $(wget -qO- http://termux.net/dists/stable/main/binary-$__AndroidArch/Packages |\
grep -A15 "Package: \(${__AndroidPackages// /\\|}\)" | grep -v "static\|tool" | grep Filename); do
if [[ "$path" != "Filename:" ]]; then
echo "Working on: $path"
wget -qO- http://termux.net/$path | dpkg -x - "$__TmpDir"
fi
done
cp -R "$__TmpDir/data/data/com.termux/files/usr/"* "$__ToolchainDir/sysroot/usr/"
# Generate platform file for build.sh script to assign to __DistroRid
echo "Generating platform file..."
echo "RID=android.${__ApiLevel}-${__BuildArch}" > $__ToolchainDir/sysroot/android_platform
echo "Now to build coreclr, libraries and installers; run:"
echo ROOTFS_DIR=\$\(realpath $__ToolchainDir/sysroot\) ./build.sh --cross --arch $__BuildArch \
--subsetCategory coreclr
echo ROOTFS_DIR=\$\(realpath $__ToolchainDir/sysroot\) ./build.sh --cross --arch $__BuildArch \
--subsetCategory libraries
echo ROOTFS_DIR=\$\(realpath $__ToolchainDir/sysroot\) ./build.sh --cross --arch $__BuildArch \
--subsetCategory installer
| {
"content_hash": "757b94b35591bb2a9d099a22f36a4ecb",
"timestamp": "",
"source": "github",
"line_count": 130,
"max_line_length": 277,
"avg_line_length": 39.07692307692308,
"alnum_prop": 0.6625984251968504,
"repo_name": "StephenBonikowsky/wcf",
"id": "e7f12edb565a9b26cbf84653c7e7a8d29dc5cd7b",
"size": "5100",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "eng/common/cross/build-android-rootfs.sh",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "17012"
},
{
"name": "Batchfile",
"bytes": "39629"
},
{
"name": "C#",
"bytes": "7873087"
},
{
"name": "CMake",
"bytes": "5469"
},
{
"name": "PowerShell",
"bytes": "147157"
},
{
"name": "Shell",
"bytes": "90862"
},
{
"name": "VBScript",
"bytes": "251"
}
],
"symlink_target": ""
} |
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */
#pragma once
#include <vector>
#include <map>
#include <sstream>
#include <string>
#include "ifcpp/model/GlobalDefines.h"
#include "ifcpp/model/BasicTypes.h"
#include "ifcpp/model/BuildingObject.h"
namespace IFC4X3
{
// TYPE IfcWorkPlanTypeEnum = ENUMERATION OF (ACTUAL ,BASELINE ,PLANNED ,USERDEFINED ,NOTDEFINED);
class IFCQUERY_EXPORT IfcWorkPlanTypeEnum : virtual public BuildingObject
{
public:
enum IfcWorkPlanTypeEnumEnum
{
ENUM_ACTUAL,
ENUM_BASELINE,
ENUM_PLANNED,
ENUM_USERDEFINED,
ENUM_NOTDEFINED
};
IfcWorkPlanTypeEnum() = default;
IfcWorkPlanTypeEnum( IfcWorkPlanTypeEnumEnum e ) { m_enum = e; }
virtual uint32_t classID() const { return 2706281606; }
virtual shared_ptr<BuildingObject> getDeepCopy( BuildingCopyOptions& options );
virtual void getStepParameter( std::stringstream& stream, bool is_select_type = false ) const;
static shared_ptr<IfcWorkPlanTypeEnum> createObjectFromSTEP( const std::string& arg, const std::map<int,shared_ptr<BuildingEntity> >& map, std::stringstream& errorStream );
IfcWorkPlanTypeEnumEnum m_enum;
};
}
| {
"content_hash": "efcb7b3b698fb6654bbacf0b8acaea6a",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 174,
"avg_line_length": 32.27777777777778,
"alnum_prop": 0.7573149741824441,
"repo_name": "ifcquery/ifcplusplus",
"id": "53d71e3ccd38e071b79d922a713ade1a926146ca",
"size": "1162",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "IfcPlusPlus/src/ifcpp/IFC4X3/include/IfcWorkPlanTypeEnum.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "1270"
},
{
"name": "C++",
"bytes": "10988148"
},
{
"name": "CMake",
"bytes": "6507"
},
{
"name": "Dockerfile",
"bytes": "951"
}
],
"symlink_target": ""
} |
// -*- C++ -*-
// Copyright (C) 2007-2016 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library 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, or (at your option) any later
// version.
// This library 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.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
/** @file parallel/balanced_quicksort.h
* @brief Implementation of a dynamically load-balanced parallel quicksort.
*
* It works in-place and needs only logarithmic extra memory.
* The algorithm is similar to the one proposed in
*
* P. Tsigas and Y. Zhang.
* A simple, fast parallel implementation of quicksort and
* its performance evaluation on SUN enterprise 10000.
* In 11th Euromicro Conference on Parallel, Distributed and
* Network-Based Processing, page 372, 2003.
*
* This file is a GNU parallel extension to the Standard C++ Library.
*/
// Written by Johannes Singler.
#ifndef _GLIBCXX_PARALLEL_BALANCED_QUICKSORT_H
#define _GLIBCXX_PARALLEL_BALANCED_QUICKSORT_H 1
#include <parallel/basic_iterator.h>
#include <bits/stl_algo.h>
#include <bits/stl_function.h>
#include <parallel/settings.h>
#include <parallel/partition.h>
#include <parallel/random_number.h>
#include <parallel/queue.h>
#if _GLIBCXX_ASSERTIONS
#include <parallel/checkers.h>
#ifdef _GLIBCXX_HAVE_UNISTD_H
#include <unistd.h>
#endif
#endif
namespace __gnu_parallel
{
/** @brief Information local to one thread in the parallel quicksort run. */
template<typename _RAIter>
struct _QSBThreadLocal
{
typedef std::iterator_traits<_RAIter> _TraitsType;
typedef typename _TraitsType::difference_type _DifferenceType;
/** @brief Continuous part of the sequence, described by an
iterator pair. */
typedef std::pair<_RAIter, _RAIter> _Piece;
/** @brief Initial piece to work on. */
_Piece _M_initial;
/** @brief Work-stealing queue. */
_RestrictedBoundedConcurrentQueue<_Piece> _M_leftover_parts;
/** @brief Number of threads involved in this algorithm. */
_ThreadIndex _M_num_threads;
/** @brief Pointer to a counter of elements left over to sort. */
volatile _DifferenceType* _M_elements_leftover;
/** @brief The complete sequence to sort. */
_Piece _M_global;
/** @brief Constructor.
* @param __queue_size size of the work-stealing queue. */
_QSBThreadLocal(int __queue_size) : _M_leftover_parts(__queue_size) { }
};
/** @brief Balanced quicksort divide step.
* @param __begin Begin iterator of subsequence.
* @param __end End iterator of subsequence.
* @param __comp Comparator.
* @param __num_threads Number of threads that are allowed to work on
* this part.
* @pre @c (__end-__begin)>=1 */
template<typename _RAIter, typename _Compare>
typename std::iterator_traits<_RAIter>::difference_type
__qsb_divide(_RAIter __begin, _RAIter __end,
_Compare __comp, _ThreadIndex __num_threads)
{
_GLIBCXX_PARALLEL_ASSERT(__num_threads > 0);
typedef std::iterator_traits<_RAIter> _TraitsType;
typedef typename _TraitsType::value_type _ValueType;
typedef typename _TraitsType::difference_type _DifferenceType;
_RAIter __pivot_pos =
__median_of_three_iterators(__begin, __begin + (__end - __begin) / 2,
__end - 1, __comp);
#if defined(_GLIBCXX_ASSERTIONS)
// Must be in between somewhere.
_DifferenceType __n = __end - __begin;
_GLIBCXX_PARALLEL_ASSERT((!__comp(*__pivot_pos, *__begin)
&& !__comp(*(__begin + __n / 2),
*__pivot_pos))
|| (!__comp(*__pivot_pos, *__begin)
&& !__comp(*(__end - 1), *__pivot_pos))
|| (!__comp(*__pivot_pos, *(__begin + __n / 2))
&& !__comp(*__begin, *__pivot_pos))
|| (!__comp(*__pivot_pos, *(__begin + __n / 2))
&& !__comp(*(__end - 1), *__pivot_pos))
|| (!__comp(*__pivot_pos, *(__end - 1))
&& !__comp(*__begin, *__pivot_pos))
|| (!__comp(*__pivot_pos, *(__end - 1))
&& !__comp(*(__begin + __n / 2),
*__pivot_pos)));
#endif
// Swap pivot value to end.
if (__pivot_pos != (__end - 1))
std::iter_swap(__pivot_pos, __end - 1);
__pivot_pos = __end - 1;
__gnu_parallel::__binder2nd<_Compare, _ValueType, _ValueType, bool>
__pred(__comp, *__pivot_pos);
// Divide, returning __end - __begin - 1 in the worst case.
_DifferenceType __split_pos = __parallel_partition(__begin, __end - 1,
__pred,
__num_threads);
// Swap back pivot to middle.
std::iter_swap(__begin + __split_pos, __pivot_pos);
__pivot_pos = __begin + __split_pos;
#if _GLIBCXX_ASSERTIONS
_RAIter __r;
for (__r = __begin; __r != __pivot_pos; ++__r)
_GLIBCXX_PARALLEL_ASSERT(__comp(*__r, *__pivot_pos));
for (; __r != __end; ++__r)
_GLIBCXX_PARALLEL_ASSERT(!__comp(*__r, *__pivot_pos));
#endif
return __split_pos;
}
/** @brief Quicksort conquer step.
* @param __tls Array of thread-local storages.
* @param __begin Begin iterator of subsequence.
* @param __end End iterator of subsequence.
* @param __comp Comparator.
* @param __iam Number of the thread processing this function.
* @param __num_threads
* Number of threads that are allowed to work on this part. */
template<typename _RAIter, typename _Compare>
void
__qsb_conquer(_QSBThreadLocal<_RAIter>** __tls,
_RAIter __begin, _RAIter __end,
_Compare __comp,
_ThreadIndex __iam, _ThreadIndex __num_threads,
bool __parent_wait)
{
typedef std::iterator_traits<_RAIter> _TraitsType;
typedef typename _TraitsType::value_type _ValueType;
typedef typename _TraitsType::difference_type _DifferenceType;
_DifferenceType __n = __end - __begin;
if (__num_threads <= 1 || __n <= 1)
{
__tls[__iam]->_M_initial.first = __begin;
__tls[__iam]->_M_initial.second = __end;
__qsb_local_sort_with_helping(__tls, __comp, __iam, __parent_wait);
return;
}
// Divide step.
_DifferenceType __split_pos =
__qsb_divide(__begin, __end, __comp, __num_threads);
#if _GLIBCXX_ASSERTIONS
_GLIBCXX_PARALLEL_ASSERT(0 <= __split_pos &&
__split_pos < (__end - __begin));
#endif
_ThreadIndex
__num_threads_leftside = std::max<_ThreadIndex>
(1, std::min<_ThreadIndex>(__num_threads - 1, __split_pos
* __num_threads / __n));
# pragma omp atomic
*__tls[__iam]->_M_elements_leftover -= (_DifferenceType)1;
// Conquer step.
# pragma omp parallel num_threads(2)
{
bool __wait;
if(omp_get_num_threads() < 2)
__wait = false;
else
__wait = __parent_wait;
# pragma omp sections
{
# pragma omp section
{
__qsb_conquer(__tls, __begin, __begin + __split_pos, __comp,
__iam, __num_threads_leftside, __wait);
__wait = __parent_wait;
}
// The pivot_pos is left in place, to ensure termination.
# pragma omp section
{
__qsb_conquer(__tls, __begin + __split_pos + 1, __end, __comp,
__iam + __num_threads_leftside,
__num_threads - __num_threads_leftside, __wait);
__wait = __parent_wait;
}
}
}
}
/**
* @brief Quicksort step doing load-balanced local sort.
* @param __tls Array of thread-local storages.
* @param __comp Comparator.
* @param __iam Number of the thread processing this function.
*/
template<typename _RAIter, typename _Compare>
void
__qsb_local_sort_with_helping(_QSBThreadLocal<_RAIter>** __tls,
_Compare& __comp, _ThreadIndex __iam,
bool __wait)
{
typedef std::iterator_traits<_RAIter> _TraitsType;
typedef typename _TraitsType::value_type _ValueType;
typedef typename _TraitsType::difference_type _DifferenceType;
typedef std::pair<_RAIter, _RAIter> _Piece;
_QSBThreadLocal<_RAIter>& __tl = *__tls[__iam];
_DifferenceType
__base_case_n = _Settings::get().sort_qsb_base_case_maximal_n;
if (__base_case_n < 2)
__base_case_n = 2;
_ThreadIndex __num_threads = __tl._M_num_threads;
// Every thread has its own random number generator.
_RandomNumber __rng(__iam + 1);
_Piece __current = __tl._M_initial;
_DifferenceType __elements_done = 0;
#if _GLIBCXX_ASSERTIONS
_DifferenceType __total_elements_done = 0;
#endif
for (;;)
{
// Invariant: __current must be a valid (maybe empty) range.
_RAIter __begin = __current.first, __end = __current.second;
_DifferenceType __n = __end - __begin;
if (__n > __base_case_n)
{
// Divide.
_RAIter __pivot_pos = __begin + __rng(__n);
// Swap __pivot_pos value to end.
if (__pivot_pos != (__end - 1))
std::iter_swap(__pivot_pos, __end - 1);
__pivot_pos = __end - 1;
__gnu_parallel::__binder2nd
<_Compare, _ValueType, _ValueType, bool>
__pred(__comp, *__pivot_pos);
// Divide, leave pivot unchanged in last place.
_RAIter __split_pos1, __split_pos2;
__split_pos1 = __gnu_sequential::partition(__begin, __end - 1,
__pred);
// Left side: < __pivot_pos; __right side: >= __pivot_pos.
#if _GLIBCXX_ASSERTIONS
_GLIBCXX_PARALLEL_ASSERT(__begin <= __split_pos1
&& __split_pos1 < __end);
#endif
// Swap pivot back to middle.
if (__split_pos1 != __pivot_pos)
std::iter_swap(__split_pos1, __pivot_pos);
__pivot_pos = __split_pos1;
// In case all elements are equal, __split_pos1 == 0.
if ((__split_pos1 + 1 - __begin) < (__n >> 7)
|| (__end - __split_pos1) < (__n >> 7))
{
// Very unequal split, one part smaller than one 128th
// elements not strictly larger than the pivot.
__gnu_parallel::__unary_negate<__gnu_parallel::__binder1st
<_Compare, _ValueType, _ValueType, bool>, _ValueType>
__pred(__gnu_parallel::__binder1st
<_Compare, _ValueType, _ValueType, bool>
(__comp, *__pivot_pos));
// Find other end of pivot-equal range.
__split_pos2 = __gnu_sequential::partition(__split_pos1 + 1,
__end, __pred);
}
else
// Only skip the pivot.
__split_pos2 = __split_pos1 + 1;
// Elements equal to pivot are done.
__elements_done += (__split_pos2 - __split_pos1);
#if _GLIBCXX_ASSERTIONS
__total_elements_done += (__split_pos2 - __split_pos1);
#endif
// Always push larger part onto stack.
if (((__split_pos1 + 1) - __begin) < (__end - (__split_pos2)))
{
// Right side larger.
if ((__split_pos2) != __end)
__tl._M_leftover_parts.push_front
(std::make_pair(__split_pos2, __end));
//__current.first = __begin; //already set anyway
__current.second = __split_pos1;
continue;
}
else
{
// Left side larger.
if (__begin != __split_pos1)
__tl._M_leftover_parts.push_front(std::make_pair
(__begin, __split_pos1));
__current.first = __split_pos2;
//__current.second = __end; //already set anyway
continue;
}
}
else
{
__gnu_sequential::sort(__begin, __end, __comp);
__elements_done += __n;
#if _GLIBCXX_ASSERTIONS
__total_elements_done += __n;
#endif
// Prefer own stack, small pieces.
if (__tl._M_leftover_parts.pop_front(__current))
continue;
# pragma omp atomic
*__tl._M_elements_leftover -= __elements_done;
__elements_done = 0;
#if _GLIBCXX_ASSERTIONS
double __search_start = omp_get_wtime();
#endif
// Look for new work.
bool __successfully_stolen = false;
while (__wait && *__tl._M_elements_leftover > 0
&& !__successfully_stolen
#if _GLIBCXX_ASSERTIONS
// Possible dead-lock.
&& (omp_get_wtime() < (__search_start + 1.0))
#endif
)
{
_ThreadIndex __victim;
__victim = __rng(__num_threads);
// Large pieces.
__successfully_stolen = (__victim != __iam)
&& __tls[__victim]->_M_leftover_parts.pop_back(__current);
if (!__successfully_stolen)
__yield();
#if !defined(__ICC) && !defined(__ECC)
# pragma omp flush
#endif
}
#if _GLIBCXX_ASSERTIONS
if (omp_get_wtime() >= (__search_start + 1.0))
{
sleep(1);
_GLIBCXX_PARALLEL_ASSERT(omp_get_wtime()
< (__search_start + 1.0));
}
#endif
if (!__successfully_stolen)
{
#if _GLIBCXX_ASSERTIONS
_GLIBCXX_PARALLEL_ASSERT(*__tl._M_elements_leftover == 0);
#endif
return;
}
}
}
}
/** @brief Top-level quicksort routine.
* @param __begin Begin iterator of sequence.
* @param __end End iterator of sequence.
* @param __comp Comparator.
* @param __num_threads Number of threads that are allowed to work on
* this part.
*/
template<typename _RAIter, typename _Compare>
void
__parallel_sort_qsb(_RAIter __begin, _RAIter __end,
_Compare __comp, _ThreadIndex __num_threads)
{
_GLIBCXX_CALL(__end - __begin)
typedef std::iterator_traits<_RAIter> _TraitsType;
typedef typename _TraitsType::value_type _ValueType;
typedef typename _TraitsType::difference_type _DifferenceType;
typedef std::pair<_RAIter, _RAIter> _Piece;
typedef _QSBThreadLocal<_RAIter> _TLSType;
_DifferenceType __n = __end - __begin;
if (__n <= 1)
return;
// At least one element per processor.
if (__num_threads > __n)
__num_threads = static_cast<_ThreadIndex>(__n);
// Initialize thread local storage
_TLSType** __tls = new _TLSType*[__num_threads];
_DifferenceType __queue_size = (__num_threads
* (_ThreadIndex)(__rd_log2(__n) + 1));
for (_ThreadIndex __t = 0; __t < __num_threads; ++__t)
__tls[__t] = new _QSBThreadLocal<_RAIter>(__queue_size);
// There can never be more than ceil(__rd_log2(__n)) ranges on the
// stack, because
// 1. Only one processor pushes onto the stack
// 2. The largest range has at most length __n
// 3. Each range is larger than half of the range remaining
volatile _DifferenceType __elements_leftover = __n;
for (_ThreadIndex __i = 0; __i < __num_threads; ++__i)
{
__tls[__i]->_M_elements_leftover = &__elements_leftover;
__tls[__i]->_M_num_threads = __num_threads;
__tls[__i]->_M_global = std::make_pair(__begin, __end);
// Just in case nothing is left to assign.
__tls[__i]->_M_initial = std::make_pair(__end, __end);
}
// Main recursion call.
__qsb_conquer(__tls, __begin, __begin + __n, __comp, 0,
__num_threads, true);
#if _GLIBCXX_ASSERTIONS
// All stack must be empty.
_Piece __dummy;
for (_ThreadIndex __i = 1; __i < __num_threads; ++__i)
_GLIBCXX_PARALLEL_ASSERT(
!__tls[__i]->_M_leftover_parts.pop_back(__dummy));
#endif
for (_ThreadIndex __i = 0; __i < __num_threads; ++__i)
delete __tls[__i];
delete[] __tls;
}
} // namespace __gnu_parallel
#endif /* _GLIBCXX_PARALLEL_BALANCED_QUICKSORT_H */
| {
"content_hash": "255353a08bb95bf6328d3e2b85d90de0",
"timestamp": "",
"source": "github",
"line_count": 495,
"max_line_length": 78,
"avg_line_length": 34.01010101010101,
"alnum_prop": 0.555034155034155,
"repo_name": "ATM-HSW/mbed_target",
"id": "16ef1efe8889d8f84c2b9ae561f7cd30a717bca0",
"size": "16835",
"binary": false,
"copies": "15",
"ref": "refs/heads/master",
"path": "buildtools/gcc-arm-none-eabi-6-2017-q2/arm-none-eabi/include/c++/6.3.1/parallel/balanced_quicksort.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "29493"
},
{
"name": "Batchfile",
"bytes": "948"
},
{
"name": "C",
"bytes": "3167609"
},
{
"name": "C++",
"bytes": "12419698"
},
{
"name": "HTML",
"bytes": "27891106"
},
{
"name": "MATLAB",
"bytes": "230413"
},
{
"name": "Makefile",
"bytes": "2798"
},
{
"name": "Python",
"bytes": "225136"
},
{
"name": "Shell",
"bytes": "50803"
},
{
"name": "XC",
"bytes": "9173"
},
{
"name": "XS",
"bytes": "9123"
}
],
"symlink_target": ""
} |
#ifndef _IPHLPAPI_H
#define _IPHLPAPI_H
#if __GNUC__ >=3
#pragma GCC system_header
#endif
#include <iprtrmib.h>
#include <ipexport.h>
#include <iptypes.h>
#ifdef __cplusplus
extern "C" {
#endif
DWORD WINAPI AddIPAddress(IPAddr,IPMask,DWORD,PULONG,PULONG);
DWORD WINAPI CreateIpForwardEntry(PMIB_IPFORWARDROW);
DWORD WINAPI CreateIpNetEntry(PMIB_IPNETROW);
DWORD WINAPI CreateProxyArpEntry(DWORD,DWORD,DWORD);
DWORD WINAPI DeleteIPAddress(ULONG);
DWORD WINAPI DeleteIpForwardEntry(PMIB_IPFORWARDROW);
DWORD WINAPI DeleteIpNetEntry(PMIB_IPNETROW);
DWORD WINAPI DeleteProxyArpEntry(DWORD,DWORD,DWORD);
DWORD WINAPI EnableRouter(HANDLE*,OVERLAPPED*);
DWORD WINAPI FlushIpNetTable(DWORD);
DWORD WINAPI GetAdapterIndex(LPWSTR,PULONG);
DWORD WINAPI GetAdaptersInfo(PIP_ADAPTER_INFO,PULONG);
DWORD WINAPI GetBestInterface(IPAddr,PDWORD);
DWORD WINAPI GetBestRoute(DWORD,DWORD,PMIB_IPFORWARDROW);
DWORD WINAPI GetFriendlyIfIndex(DWORD);
DWORD WINAPI GetIcmpStatistics(PMIB_ICMP);
DWORD WINAPI GetIfEntry(PMIB_IFROW);
DWORD WINAPI GetIfTable(PMIB_IFTABLE,PULONG,BOOL);
DWORD WINAPI GetInterfaceInfo(PIP_INTERFACE_INFO,PULONG);
DWORD WINAPI GetIpAddrTable(PMIB_IPADDRTABLE,PULONG,BOOL);
DWORD WINAPI GetIpForwardTable(PMIB_IPFORWARDTABLE,PULONG,BOOL);
DWORD WINAPI GetIpNetTable(PMIB_IPNETTABLE,PULONG,BOOL);
DWORD WINAPI GetIpStatistics(PMIB_IPSTATS);
DWORD WINAPI GetNetworkParams(PFIXED_INFO,PULONG);
DWORD WINAPI GetNumberOfInterfaces(PDWORD);
DWORD WINAPI GetPerAdapterInfo(ULONG,PIP_PER_ADAPTER_INFO, PULONG);
BOOL WINAPI GetRTTAndHopCount(IPAddr,PULONG,ULONG,PULONG);
DWORD WINAPI GetTcpStatistics(PMIB_TCPSTATS);
DWORD WINAPI GetTcpTable(PMIB_TCPTABLE,PDWORD,BOOL);
DWORD WINAPI GetUniDirectionalAdapterInfo(PIP_UNIDIRECTIONAL_ADAPTER_ADDRESS,PULONG);
DWORD WINAPI GetUdpStatistics(PMIB_UDPSTATS);
DWORD WINAPI GetUdpTable(PMIB_UDPTABLE,PDWORD,BOOL);
DWORD WINAPI IpReleaseAddress(PIP_ADAPTER_INDEX_MAP);
DWORD WINAPI IpRenewAddress(PIP_ADAPTER_INDEX_MAP);
DWORD WINAPI NotifyAddrChange(PHANDLE,LPOVERLAPPED);
DWORD WINAPI NotifyRouteChange(PHANDLE,LPOVERLAPPED);
DWORD WINAPI SendARP(IPAddr,IPAddr,PULONG,PULONG);
DWORD WINAPI SetIfEntry(PMIB_IFROW);
DWORD WINAPI SetIpForwardEntry(PMIB_IPFORWARDROW);
DWORD WINAPI SetIpNetEntry(PMIB_IPNETROW);
DWORD WINAPI SetIpStatistics(PMIB_IPSTATS);
DWORD WINAPI SetIpTTL(UINT);
DWORD WINAPI SetTcpEntry(PMIB_TCPROW);
DWORD WINAPI UnenableRouter(OVERLAPPED*, LPDWORD);
#ifdef __cplusplus
}
#endif
#endif /* _IPHLPAPI_H */
| {
"content_hash": "07d232b694621fafb149499004378a63",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 85,
"avg_line_length": 41,
"alnum_prop": 0.8268292682926829,
"repo_name": "andersonsilvade/python_C",
"id": "214c53ef718e4b11e5b5b8fbca59b2f9e2063144",
"size": "2460",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "Dev-Cpp/include/iphlpapi.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "6031642"
},
{
"name": "C#",
"bytes": "9892"
},
{
"name": "C++",
"bytes": "1800118"
},
{
"name": "CSS",
"bytes": "126965"
},
{
"name": "F#",
"bytes": "4611"
},
{
"name": "JavaScript",
"bytes": "296535"
},
{
"name": "Objective-C",
"bytes": "272866"
},
{
"name": "Python",
"bytes": "1949327"
},
{
"name": "Shell",
"bytes": "54613"
},
{
"name": "Tcl",
"bytes": "3155560"
}
],
"symlink_target": ""
} |
import traceback
import json
import requests
from .models import (
Log,
RequestLog,
EventLog,
)
class NoRequestException(Exception):
pass
class NoExceptionException(Exception):
pass
class ObjectLogger(object):
def log_request(self, log=None, request=None, request_body=None):
# -- General info
log.request_url = request.get_full_path()
log.request_method = request.method
log.get_data = json.dumps(request.GET)
log.request_body = request_body
log.cookies = json.dumps(request.COOKIES)
# --- Request meta info
log.meta = ','.join('"%s": "%s"' % (k, str(v)) for k, v in list(request.META.items()))
log.meta = '{%s}' % log.meta
log.meta = log.meta.replace('\\', '|')
# --- User info
if request.user and request.user.is_authenticated:
log.user_id = request.user.id
log.user_name = request.user.email
# --- User agent info
user_agent = request.user_agent
# Browser
log.request_browser = user_agent.browser
# OS
log.request_os = user_agent.os
# Device
log.request_device = user_agent.device
# Device type
log.is_mobile = user_agent.is_mobile
log.is_tablet = user_agent.is_tablet
log.is_touch_capable = user_agent.is_touch_capable
log.is_pc = user_agent.is_pc
log.is_bot = user_agent.is_bot
return log
def log_response(self, log, data, status=None, template_name=None, headers=None, content_type=None):
log.response_body = json.dumps(data)
log.response_status = status if status else 'None'
log.response_headers = json.dumps(headers)
log.response_content_type = content_type if content_type else 'None'
return log
def log_exception(self, log=None, exception=None):
# --- Exception info
log.exception_type = type(exception).__name__
log.message = str(exception)
log.stack_trace = traceback.format_exc()
return log
class Logger(object):
@staticmethod
def log_error(request=None, request_body=None, exception=None):
if request and exception:
log = Log(
log_level=Log.ERROR)
obj_logger = ObjectLogger()
log = obj_logger.log_exception(log, exception)
log = obj_logger.log_request(log, request, request_body)
# --- Save
log.save()
elif request is None:
raise NoRequestException('No http request found')
elif exception is None:
raise NoExceptionException('No exception found')
return log
@staticmethod
def log_debug(request=None, message=None):
stack_trace = ''.join(line for line in traceback.format_stack())
message = message if message else ""
if request:
# -- General info
log = Log(
log_level=Log.DEBUG,
message=message,
stack_trace=stack_trace)
obj_logger = ObjectLogger()
log = obj_logger.log_request(log, request, request.body)
# --- Save
log.save()
return log
else:
raise NoRequestException('No http request found')
@staticmethod
def log_warn(request=None, message=None):
stack_trace = ''.join(line for line in traceback.format_stack())
message = message if message else ""
if request:
# -- General info
log = Log(
log_level=Log.WARN,
message=message,
stack_trace=stack_trace)
obj_logger = ObjectLogger()
log = obj_logger.log_request(log, request, request.body)
# --- Save
log.save()
return log
else:
raise NoRequestException('No http request found')
@staticmethod
def log_info(request=None, message=None):
stack_trace = ''.join(line for line in traceback.format_stack())
message = message if message else ""
if request:
# -- General info
log = Log(
log_level=Log.INFO,
message=message,
stack_trace=stack_trace)
obj_logger = ObjectLogger()
log = obj_logger.log_request(log, request, request.body)
# --- Save
log.save()
return log
else:
raise NoRequestException('No http request found')
@staticmethod
def non_request_log(log_level=None, message=None):
stack_trace = ''.join(line for line in traceback.format_stack())
message = message if message else ""
# -- General info
log = Log(
log_level=log_level if log_level else Log.INFO,
message=message,
stack_trace=stack_trace)
# --- Save
log.save()
return log
class RequestObjectLogger(object):
def log_request(self, log, request, data):
# --- Request data
log.method = request.method
log.url = request.url
log.request_data = data if isinstance(data, str) else json.dumps(data)
headers = {val[0]: val[1] for val in list(request.headers.items())}
log.request_headers = json.dumps(headers)
return log
def log_response(self, log, response, user, message):
# --- Response data
log.response_text = response.text
log.response_status = response.status_code
log.response_reason = response.reason
log.response_time = response.elapsed.microseconds / 1000
# --- User data
if user:
if user.is_authenticated:
log.user_id = user.id
log.user_name = user.email
log.message = message if message else ''
return log
class RequestLogger(object):
@staticmethod
def get(url, params=None, user=None, message=None, **kwargs):
response = requests.get(url, params=params, **kwargs)
log = RequestLog()
obj_logger = RequestObjectLogger()
log = obj_logger.log_request(log, response.request, params)
log = obj_logger.log_response(log, response, user, message)
# --- Save
log.save()
return response
@staticmethod
def post(url, data=None, json=None, user=None, message=None, **kwargs):
response = requests.post(url, data=data, json=None, **kwargs)
log = RequestLog()
obj_logger = RequestObjectLogger()
log = obj_logger.log_request(log, response.request, data)
log = obj_logger.log_response(log, response, user, message)
# --- Save
log.save()
return response
@staticmethod
def put(url, data=None, json=None, user=None, message=None, **kwargs):
response = requests.put(url, data=data, json=None, **kwargs)
log = RequestLog()
obj_logger = RequestObjectLogger()
log = obj_logger.log_request(log, response.request, data)
log = obj_logger.log_response(log, response, user, message)
# --- Save
log.save()
return response
@staticmethod
def delete(url, user=None, message=None, **kwargs):
response = requests.delete(url, **kwargs)
log = RequestLog()
obj_logger = RequestObjectLogger()
log = obj_logger.log_request(log, response.request, None)
log = obj_logger.log_response(log, response, user, message)
# --- Save
log.save()
return response
@staticmethod
def patch(url, data=None, json=None, user=None, message=None, **kwargs):
response = requests.patch(url, data=data, json=None, **kwargs)
log = RequestLog()
obj_logger = RequestObjectLogger()
log = obj_logger.log_request(log, response.request, data)
log = obj_logger.log_response(log, response, user, message)
# --- Save
log.save()
return response
@staticmethod
def head(url, user=None, message=None, **kwargs):
response = requests.head(url, **kwargs)
log = RequestLog()
obj_logger = RequestObjectLogger()
log = obj_logger.log_request(log, response.request, None)
log = obj_logger.log_response(log, response, user, message)
# --- Save
log.save()
return response
class EventLogger(object):
@staticmethod
def _log_event(log_level, message, tag=''):
stack_trace = ''.join(line for line in traceback.format_stack())
log = EventLog(
log_level=log_level,
message=message,
stack_trace=stack_trace,
tag=tag)
log.save()
@staticmethod
def log_error(message, tag=''):
EventLogger._log_event(
log_level=EventLog.ERROR,
message=message,
tag=tag)
@staticmethod
def log_debug(message, tag=''):
EventLogger._log_event(
log_level=EventLog.DEBUG,
message=message,
tag=tag)
@staticmethod
def log_warn(message, tag=''):
EventLogger._log_event(
log_level=EventLog.WARN,
message=message,
tag=tag)
@staticmethod
def log_info(message, tag=''):
EventLogger._log_event(
log_level=EventLog.INFO,
message=message,
tag=tag)
| {
"content_hash": "ca297587f4b5e5ddebcd4104d7e33dd0",
"timestamp": "",
"source": "github",
"line_count": 324,
"max_line_length": 104,
"avg_line_length": 29.246913580246915,
"alnum_prop": 0.575981426762347,
"repo_name": "eshandas/simple_django_logger",
"id": "3ee66ffd486118036f315c4d5cd3a3e2898da99f",
"size": "9476",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "django_project/simple_django_logger/utils.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "66656"
},
{
"name": "JavaScript",
"bytes": "6820"
},
{
"name": "Python",
"bytes": "77742"
}
],
"symlink_target": ""
} |
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
namespace Microsoft.CodeAnalysis.WorkspaceServices
{
internal interface IWorkspaceServiceProvider
{
string Kind { get; }
IWorkspaceServiceProviderFactory Factory { get; }
TWorkspaceService GetService<TWorkspaceService>() where TWorkspaceService : IWorkspaceService;
IEnumerable<Lazy<T>> GetServiceExtensions<T>() where T : class;
IEnumerable<Lazy<TExtension, TMetadata>> GetServiceExtensions<TExtension, TMetadata>() where TExtension : class;
}
} | {
"content_hash": "6e5a0551864c2aba43850f2e6ad65470",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 184,
"avg_line_length": 43.1764705882353,
"alnum_prop": 0.7506811989100818,
"repo_name": "binsys/roslyn_java",
"id": "2206cc843683b10487061b6177667b93d70a75b0",
"size": "736",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Src/Workspaces/Core/Workspace/WorkspaceServices/IWorkspaceServiceProvider.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "5789"
},
{
"name": "C#",
"bytes": "10877035"
},
{
"name": "Java",
"bytes": "47225"
},
{
"name": "Visual Basic",
"bytes": "58529"
}
],
"symlink_target": ""
} |
/**
* @requires OpenLayers/Renderer/Elements.js
*/
/**
* Class: OpenLayers.Renderer.VML
* Render vector features in browsers with VML capability. Construct a new
* VML renderer with the <OpenLayers.Renderer.VML> constructor.
*
* Note that for all calculations in this class, we use toFixed() to round a
* float value to an integer. This is done because it seems that VML doesn't
* support float values.
*
* Inherits from:
* - <OpenLayers.Renderer.Elements>
*/
OpenLayers.Renderer.VML = OpenLayers.Class(OpenLayers.Renderer.Elements, {
/**
* Property: xmlns
* {String} XML Namespace URN
*/
xmlns: "urn:schemas-microsoft-com:vml",
/**
* Property: symbolCache
* {DOMElement} node holding symbols. This hash is keyed by symbol name,
* and each value is a hash with a "path" and an "extent" property.
*/
symbolCache: {},
/**
* Property: offset
* {Object} Hash with "x" and "y" properties
*/
offset: null,
/**
* Constructor: OpenLayers.Renderer.VML
* Create a new VML renderer.
*
* Parameters:
* containerID - {String} The id for the element that contains the renderer
*/
initialize: function(containerID) {
if (!this.supported()) {
return;
}
if (!document.namespaces.olv) {
document.namespaces.add("olv", this.xmlns);
var style = document.createStyleSheet();
var shapes = ['shape','rect', 'oval', 'fill', 'stroke', 'imagedata', 'group','textbox'];
for (var i = 0, len = shapes.length; i < len; i++) {
style.addRule('olv\\:' + shapes[i], "behavior: url(#default#VML); " +
"position: absolute; display: inline-block;");
}
}
OpenLayers.Renderer.Elements.prototype.initialize.apply(this,
arguments);
this.offset = {x: 0, y: 0};
},
/**
* APIMethod: destroy
* Deconstruct the renderer.
*/
destroy: function() {
OpenLayers.Renderer.Elements.prototype.destroy.apply(this, arguments);
},
/**
* APIMethod: supported
* Determine whether a browser supports this renderer.
*
* Returns:
* {Boolean} The browser supports the VML renderer
*/
supported: function() {
return !!(document.namespaces);
},
/**
* Method: setExtent
* Set the renderer's extent
*
* Parameters:
* extent - {<OpenLayers.Bounds>}
* resolutionChanged - {Boolean}
*
* Returns:
* {Boolean} true to notify the layer that the new extent does not exceed
* the coordinate range, and the features will not need to be redrawn.
*/
setExtent: function(extent, resolutionChanged) {
OpenLayers.Renderer.Elements.prototype.setExtent.apply(this,
arguments);
var resolution = this.getResolution();
var left = extent.left/resolution;
var top = extent.top/resolution - this.size.h;
if (resolutionChanged) {
this.offset = {x: left, y: top};
left = 0;
top = 0;
} else {
left = left - this.offset.x;
top = top - this.offset.y;
}
var org = left + " " + top;
this.root.coordorigin = org;
var roots = [this.root, this.vectorRoot, this.textRoot];
var root;
for(var i=0, len=roots.length; i<len; ++i) {
root = roots[i];
var size = this.size.w + " " + this.size.h;
root.coordsize = size;
}
// flip the VML display Y axis upside down so it
// matches the display Y axis of the map
this.root.style.flip = "y";
return true;
},
/**
* Method: setSize
* Set the size of the drawing surface
*
* Parameters:
* size - {<OpenLayers.Size>} the size of the drawing surface
*/
setSize: function(size) {
OpenLayers.Renderer.prototype.setSize.apply(this, arguments);
// setting width and height on all roots to avoid flicker which we
// would get with 100% width and height on child roots
var roots = [
this.rendererRoot,
this.root,
this.vectorRoot,
this.textRoot
];
var w = this.size.w + "px";
var h = this.size.h + "px";
var root;
for(var i=0, len=roots.length; i<len; ++i) {
root = roots[i];
root.style.width = w;
root.style.height = h;
}
},
/**
* Method: getNodeType
* Get the node type for a geometry and style
*
* Parameters:
* geometry - {<OpenLayers.Geometry>}
* style - {Object}
*
* Returns:
* {String} The corresponding node type for the specified geometry
*/
getNodeType: function(geometry, style) {
var nodeType = null;
switch (geometry.CLASS_NAME) {
case "OpenLayers.Geometry.Point":
if (style.externalGraphic) {
nodeType = "olv:rect";
} else if (this.isComplexSymbol(style.graphicName)) {
nodeType = "olv:shape";
} else {
nodeType = "olv:oval";
}
break;
case "OpenLayers.Geometry.Rectangle":
nodeType = "olv:rect";
break;
case "OpenLayers.Geometry.LineString":
case "OpenLayers.Geometry.LinearRing":
case "OpenLayers.Geometry.Polygon":
case "OpenLayers.Geometry.Curve":
case "OpenLayers.Geometry.Surface":
nodeType = "olv:shape";
break;
default:
break;
}
return nodeType;
},
/**
* Method: setStyle
* Use to set all the style attributes to a VML node.
*
* Parameters:
* node - {DOMElement} An VML element to decorate
* style - {Object}
* options - {Object} Currently supported options include
* 'isFilled' {Boolean} and
* 'isStroked' {Boolean}
* geometry - {<OpenLayers.Geometry>}
*/
setStyle: function(node, style, options, geometry) {
style = style || node._style;
options = options || node._options;
var widthFactor = 1;
if (node._geometryClass == "OpenLayers.Geometry.Point") {
if (style.externalGraphic) {
if (style.graphicTitle) {
node.title=style.graphicTitle;
}
var width = style.graphicWidth || style.graphicHeight;
var height = style.graphicHeight || style.graphicWidth;
width = width ? width : style.pointRadius*2;
height = height ? height : style.pointRadius*2;
var resolution = this.getResolution();
var xOffset = (style.graphicXOffset != undefined) ?
style.graphicXOffset : -(0.5 * width);
var yOffset = (style.graphicYOffset != undefined) ?
style.graphicYOffset : -(0.5 * height);
node.style.left = ((geometry.x/resolution - this.offset.x)+xOffset).toFixed();
node.style.top = ((geometry.y/resolution - this.offset.y)-(yOffset+height)).toFixed();
node.style.width = width + "px";
node.style.height = height + "px";
node.style.flip = "y";
// modify style/options for fill and stroke styling below
style.fillColor = "none";
options.isStroked = false;
} else if (this.isComplexSymbol(style.graphicName)) {
var cache = this.importSymbol(style.graphicName);
node.path = cache.path;
node.coordorigin = cache.left + "," + cache.bottom;
var size = cache.size;
node.coordsize = size + "," + size;
this.drawCircle(node, geometry, style.pointRadius);
node.style.flip = "y";
} else {
this.drawCircle(node, geometry, style.pointRadius);
}
}
// fill
if (options.isFilled) {
node.fillcolor = style.fillColor;
} else {
node.filled = "false";
}
var fills = node.getElementsByTagName("fill");
var fill = (fills.length == 0) ? null : fills[0];
if (!options.isFilled) {
if (fill) {
node.removeChild(fill);
}
} else {
if (!fill) {
fill = this.createNode('olv:fill', node.id + "_fill");
}
fill.opacity = style.fillOpacity;
if (node._geometryClass == "OpenLayers.Geometry.Point" &&
style.externalGraphic) {
// override fillOpacity
if (style.graphicOpacity) {
fill.opacity = style.graphicOpacity;
}
fill.src = style.externalGraphic;
fill.type = "frame";
if (!(style.graphicWidth && style.graphicHeight)) {
fill.aspect = "atmost";
}
}
if (fill.parentNode != node) {
node.appendChild(fill);
}
}
// additional rendering for rotated graphics or symbols
if (typeof style.rotation != "undefined") {
if (style.externalGraphic) {
this.graphicRotate(node, xOffset, yOffset);
// make the fill fully transparent, because we now have
// the graphic as imagedata element. We cannot just remove
// the fill, because this is part of the hack described
// in graphicRotate
fill.opacity = 0;
} else {
node.style.rotation = style.rotation;
}
}
// stroke
if (options.isStroked) {
node.strokecolor = style.strokeColor;
node.strokeweight = style.strokeWidth + "px";
} else {
node.stroked = false;
}
var strokes = node.getElementsByTagName("stroke");
var stroke = (strokes.length == 0) ? null : strokes[0];
if (!options.isStroked) {
if (stroke) {
node.removeChild(stroke);
}
} else {
if (!stroke) {
stroke = this.createNode('olv:stroke', node.id + "_stroke");
node.appendChild(stroke);
}
stroke.opacity = style.strokeOpacity;
stroke.endcap = !style.strokeLinecap || style.strokeLinecap == 'butt' ? 'flat' : style.strokeLinecap;
stroke.dashstyle = this.dashStyle(style);
}
if (style.cursor != "inherit" && style.cursor != null) {
node.style.cursor = style.cursor;
}
return node;
},
/**
* Method: graphicRotate
* If a point is to be styled with externalGraphic and rotation, VML fills
* cannot be used to display the graphic, because rotation of graphic
* fills is not supported by the VML implementation of Internet Explorer.
* This method creates a olv:imagedata element inside the VML node,
* DXImageTransform.Matrix and BasicImage filters for rotation and
* opacity, and a 3-step hack to remove rendering artefacts from the
* graphic and preserve the ability of graphics to trigger events.
* Finally, OpenLayers methods are used to determine the correct
* insertion point of the rotated image, because DXImageTransform.Matrix
* does the rotation without the ability to specify a rotation center
* point.
*
* Parameters:
* node - {DOMElement}
* xOffset - {Number} rotation center relative to image, x coordinate
* yOffset - {Number} rotation center relative to image, y coordinate
*/
graphicRotate: function(node, xOffset, yOffset) {
var style = style || node._style;
var options = node._options;
var aspectRatio, size;
if (!(style.graphicWidth && style.graphicHeight)) {
// load the image to determine its size
var img = new Image();
img.onreadystatechange = OpenLayers.Function.bind(function() {
if(img.readyState == "complete" ||
img.readyState == "interactive") {
aspectRatio = img.width / img.height;
size = Math.max(style.pointRadius * 2,
style.graphicWidth || 0,
style.graphicHeight || 0);
xOffset = xOffset * aspectRatio;
style.graphicWidth = size * aspectRatio;
style.graphicHeight = size;
this.graphicRotate(node, xOffset, yOffset);
}
}, this);
img.src = style.externalGraphic;
// will be called again by the onreadystate handler
return;
} else {
size = Math.max(style.graphicWidth, style.graphicHeight);
aspectRatio = style.graphicWidth / style.graphicHeight;
}
var width = Math.round(style.graphicWidth || size * aspectRatio);
var height = Math.round(style.graphicHeight || size);
node.style.width = width + "px";
node.style.height = height + "px";
// Three steps are required to remove artefacts for images with
// transparent backgrounds (resulting from using DXImageTransform
// filters on svg objects), while preserving awareness for browser
// events on images:
// - Use the fill as usual (like for unrotated images) to handle
// events
// - specify an imagedata element with the same src as the fill
// - style the imagedata element with an AlphaImageLoader filter
// with empty src
var image = document.getElementById(node.id + "_image");
if (!image) {
image = this.createNode("olv:imagedata", node.id + "_image");
node.appendChild(image);
}
image.style.width = width + "px";
image.style.height = height + "px";
image.src = style.externalGraphic;
image.style.filter =
"progid:DXImageTransform.Microsoft.AlphaImageLoader(" +
"src='', sizingMethod='scale')";
var rotation = style.rotation * Math.PI / 180;
var sintheta = Math.sin(rotation);
var costheta = Math.cos(rotation);
// do the rotation on the image
var filter =
"progid:DXImageTransform.Microsoft.Matrix(M11=" + costheta +
",M12=" + (-sintheta) + ",M21=" + sintheta + ",M22=" + costheta +
",SizingMethod='auto expand')\n";
// set the opacity (needed for the imagedata)
var opacity = style.graphicOpacity || style.fillOpacity;
if (opacity && opacity != 1) {
filter +=
"progid:DXImageTransform.Microsoft.BasicImage(opacity=" +
opacity+")\n";
}
node.style.filter = filter;
// do the rotation again on a box, so we know the insertion point
var centerPoint = new OpenLayers.Geometry.Point(-xOffset, -yOffset);
var imgBox = new OpenLayers.Bounds(0, 0, width, height).toGeometry();
imgBox.rotate(style.rotation, centerPoint);
var imgBounds = imgBox.getBounds();
node.style.left = Math.round(
parseInt(node.style.left) + imgBounds.left) + "px";
node.style.top = Math.round(
parseInt(node.style.top) - imgBounds.bottom) + "px";
},
/**
* Method: postDraw
* Some versions of Internet Explorer seem to be unable to set fillcolor
* and strokecolor to "none" correctly before the fill node is appended to
* a visible vml node. This method takes care of that and sets fillcolor
* and strokecolor again if needed.
*
* Parameters:
* node - {DOMElement}
*/
postDraw: function(node) {
var fillColor = node._style.fillColor;
var strokeColor = node._style.strokeColor;
if (fillColor == "none" &&
node.fillcolor != fillColor) {
node.fillcolor = fillColor;
}
if (strokeColor == "none" &&
node.strokecolor != strokeColor) {
node.strokecolor = strokeColor;
}
},
/**
* Method: setNodeDimension
* Get the geometry's bounds, convert it to our vml coordinate system,
* then set the node's position, size, and local coordinate system.
*
* Parameters:
* node - {DOMElement}
* geometry - {<OpenLayers.Geometry>}
*/
setNodeDimension: function(node, geometry) {
var bbox = geometry.getBounds();
if(bbox) {
var resolution = this.getResolution();
var scaledBox =
new OpenLayers.Bounds((bbox.left/resolution - this.offset.x).toFixed(),
(bbox.bottom/resolution - this.offset.y).toFixed(),
(bbox.right/resolution - this.offset.x).toFixed(),
(bbox.top/resolution - this.offset.y).toFixed());
// Set the internal coordinate system to draw the path
node.style.left = scaledBox.left + "px";
node.style.top = scaledBox.top + "px";
node.style.width = scaledBox.getWidth() + "px";
node.style.height = scaledBox.getHeight() + "px";
node.coordorigin = scaledBox.left + " " + scaledBox.top;
node.coordsize = scaledBox.getWidth()+ " " + scaledBox.getHeight();
}
},
/**
* Method: dashStyle
*
* Parameters:
* style - {Object}
*
* Returns:
* {String} A VML compliant 'stroke-dasharray' value
*/
dashStyle: function(style) {
var dash = style.strokeDashstyle;
switch (dash) {
case 'solid':
case 'dot':
case 'dash':
case 'dashdot':
case 'longdash':
case 'longdashdot':
return dash;
default:
// very basic guessing of dash style patterns
var parts = dash.split(/[ ,]/);
if (parts.length == 2) {
if (1*parts[0] >= 2*parts[1]) {
return "longdash";
}
return (parts[0] == 1 || parts[1] == 1) ? "dot" : "dash";
} else if (parts.length == 4) {
return (1*parts[0] >= 2*parts[1]) ? "longdashdot" :
"dashdot";
}
return "solid";
}
},
/**
* Method: createNode
* Create a new node
*
* Parameters:
* type - {String} Kind of node to draw
* id - {String} Id for node
*
* Returns:
* {DOMElement} A new node of the given type and id
*/
createNode: function(type, id) {
var node = document.createElement(type);
if (id) {
node.id = id;
}
// IE hack to make elements unselectable, to prevent 'blue flash'
// while dragging vectors; #1410
node.unselectable = 'on';
node.onselectstart = function() { return(false); };
return node;
},
/**
* Method: nodeTypeCompare
* Determine whether a node is of a given type
*
* Parameters:
* node - {DOMElement} An VML element
* type - {String} Kind of node
*
* Returns:
* {Boolean} Whether or not the specified node is of the specified type
*/
nodeTypeCompare: function(node, type) {
//split type
var subType = type;
var splitIndex = subType.indexOf(":");
if (splitIndex != -1) {
subType = subType.substr(splitIndex+1);
}
//split nodeName
var nodeName = node.nodeName;
splitIndex = nodeName.indexOf(":");
if (splitIndex != -1) {
nodeName = nodeName.substr(splitIndex+1);
}
return (subType == nodeName);
},
/**
* Method: createRenderRoot
* Create the renderer root
*
* Returns:
* {DOMElement} The specific render engine's root element
*/
createRenderRoot: function() {
return this.nodeFactory(this.container.id + "_vmlRoot", "div");
},
/**
* Method: createRoot
* Create the main root element
*
* Parameters:
* suffix - {String} suffix to append to the id
*
* Returns:
* {DOMElement}
*/
createRoot: function(suffix) {
return this.nodeFactory(this.container.id + suffix, "olv:group");
},
/**************************************
* *
* GEOMETRY DRAWING FUNCTIONS *
* *
**************************************/
/**
* Method: drawPoint
* Render a point
*
* Parameters:
* node - {DOMElement}
* geometry - {<OpenLayers.Geometry>}
*
* Returns:
* {DOMElement} or false if the point could not be drawn
*/
drawPoint: function(node, geometry) {
return this.drawCircle(node, geometry, 1);
},
/**
* Method: drawCircle
* Render a circle.
* Size and Center a circle given geometry (x,y center) and radius
*
* Parameters:
* node - {DOMElement}
* geometry - {<OpenLayers.Geometry>}
* radius - {float}
*
* Returns:
* {DOMElement} or false if the circle could not ne drawn
*/
drawCircle: function(node, geometry, radius) {
if(!isNaN(geometry.x)&& !isNaN(geometry.y)) {
var resolution = this.getResolution();
node.style.left = ((geometry.x /resolution - this.offset.x).toFixed() - radius) + "px";
node.style.top = ((geometry.y /resolution - this.offset.y).toFixed() - radius) + "px";
var diameter = radius * 2;
node.style.width = diameter + "px";
node.style.height = diameter + "px";
return node;
}
return false;
},
/**
* Method: drawLineString
* Render a linestring.
*
* Parameters:
* node - {DOMElement}
* geometry - {<OpenLayers.Geometry>}
*
* Returns:
* {DOMElement}
*/
drawLineString: function(node, geometry) {
return this.drawLine(node, geometry, false);
},
/**
* Method: drawLinearRing
* Render a linearring
*
* Parameters:
* node - {DOMElement}
* geometry - {<OpenLayers.Geometry>}
*
* Returns:
* {DOMElement}
*/
drawLinearRing: function(node, geometry) {
return this.drawLine(node, geometry, true);
},
/**
* Method: DrawLine
* Render a line.
*
* Parameters:
* node - {DOMElement}
* geometry - {<OpenLayers.Geometry>}
* closeLine - {Boolean} Close the line? (make it a ring?)
*
* Returns:
* {DOMElement}
*/
drawLine: function(node, geometry, closeLine) {
this.setNodeDimension(node, geometry);
var resolution = this.getResolution();
var numComponents = geometry.components.length;
var parts = new Array(numComponents);
var comp, x, y;
for (var i = 0; i < numComponents; i++) {
comp = geometry.components[i];
x = (comp.x/resolution - this.offset.x);
y = (comp.y/resolution - this.offset.y);
parts[i] = " " + x.toFixed() + "," + y.toFixed() + " l ";
}
var end = (closeLine) ? " x e" : " e";
node.path = "m" + parts.join("") + end;
return node;
},
/**
* Method: drawPolygon
* Render a polygon
*
* Parameters:
* node - {DOMElement}
* geometry - {<OpenLayers.Geometry>}
*
* Returns:
* {DOMElement}
*/
drawPolygon: function(node, geometry) {
this.setNodeDimension(node, geometry);
var resolution = this.getResolution();
var path = [];
var linearRing, i, j, len, ilen, comp, x, y;
for (j = 0, len=geometry.components.length; j<len; j++) {
linearRing = geometry.components[j];
path.push("m");
for (i=0, ilen=linearRing.components.length; i<ilen; i++) {
comp = linearRing.components[i];
x = comp.x / resolution - this.offset.x;
y = comp.y / resolution - this.offset.y;
path.push(" " + x.toFixed() + "," + y.toFixed());
if (i==0) {
path.push(" l");
}
}
path.push(" x ");
}
path.push("e");
node.path = path.join("");
return node;
},
/**
* Method: drawRectangle
* Render a rectangle
*
* Parameters:
* node - {DOMElement}
* geometry - {<OpenLayers.Geometry>}
*
* Returns:
* {DOMElement}
*/
drawRectangle: function(node, geometry) {
var resolution = this.getResolution();
node.style.left = (geometry.x/resolution - this.offset.x) + "px";
node.style.top = (geometry.y/resolution - this.offset.y) + "px";
node.style.width = geometry.width/resolution + "px";
node.style.height = geometry.height/resolution + "px";
return node;
},
/**
* Method: drawText
* This method is only called by the renderer itself.
*
* Parameters:
* featureId - {String}
* style -
* location - {<OpenLayers.Geometry.Point>}
*/
drawText: function(featureId, style, location) {
var label = this.nodeFactory(featureId + this.LABEL_ID_SUFFIX, "olv:rect");
var textbox = this.nodeFactory(featureId + this.LABEL_ID_SUFFIX + "_textbox", "olv:textbox");
var resolution = this.getResolution();
label.style.left = (location.x/resolution - this.offset.x).toFixed() + "px";
label.style.top = (location.y/resolution - this.offset.y).toFixed() + "px";
label.style.flip = "y";
textbox.innerText = style.label;
if (style.fillColor) {
textbox.style.color = style.fontColor;
}
if (style.fontFamily) {
textbox.style.fontFamily = style.fontFamily;
}
if (style.fontSize) {
textbox.style.fontSize = style.fontSize;
}
if (style.fontWeight) {
textbox.style.fontWeight = style.fontWeight;
}
textbox.style.whiteSpace = "nowrap";
// fun with IE: IE7 in standards compliant mode does not display any
// text with a left inset of 0. So we set this to 1px and subtract one
// pixel later when we set label.style.left
textbox.inset = "1px,0px,0px,0px";
if(!label.parentNode) {
label.appendChild(textbox);
this.textRoot.appendChild(label);
}
var align = style.labelAlign || "cm";
var xshift = textbox.clientWidth *
(OpenLayers.Renderer.VML.LABEL_SHIFT[align.substr(0,1)]);
var yshift = textbox.clientHeight *
(OpenLayers.Renderer.VML.LABEL_SHIFT[align.substr(1,1)]);
label.style.left = parseInt(label.style.left)-xshift-1+"px";
label.style.top = parseInt(label.style.top)+yshift+"px";
},
/**
* Method: drawSurface
*
* Parameters:
* node - {DOMElement}
* geometry - {<OpenLayers.Geometry>}
*
* Returns:
* {DOMElement}
*/
drawSurface: function(node, geometry) {
this.setNodeDimension(node, geometry);
var resolution = this.getResolution();
var path = [];
var comp, x, y;
for (var i=0, len=geometry.components.length; i<len; i++) {
comp = geometry.components[i];
x = comp.x / resolution - this.offset.x;
y = comp.y / resolution - this.offset.y;
if ((i%3)==0 && (i/3)==0) {
path.push("m");
} else if ((i%3)==1) {
path.push(" c");
}
path.push(" " + x + "," + y);
}
path.push(" x e");
node.path = path.join("");
return node;
},
/**
* Method: moveRoot
* moves this renderer's root to a different renderer.
*
* Parameters:
* renderer - {<OpenLayers.Renderer>} target renderer for the moved root
* root - {DOMElement} optional root node. To be used when this renderer
* holds roots from multiple layers to tell this method which one to
* detach
*
* Returns:
* {Boolean} true if successful, false otherwise
*/
moveRoot: function(renderer) {
var layer = this.map.getLayer(renderer.container.id);
if(layer instanceof OpenLayers.Layer.Vector.RootContainer) {
layer = this.map.getLayer(this.container.id);
}
layer && layer.renderer.clear();
OpenLayers.Renderer.Elements.prototype.moveRoot.apply(this, arguments);
layer && layer.redraw();
},
/**
* Method: importSymbol
* add a new symbol definition from the rendererer's symbol hash
*
* Parameters:
* graphicName - {String} name of the symbol to import
*
* Returns:
* {Object} - hash of {DOMElement} "symbol" and {Number} "size"
*/
importSymbol: function (graphicName) {
var id = this.container.id + "-" + graphicName;
// check if symbol already exists in the cache
var cache = this.symbolCache[id];
if (cache) {
return cache;
}
var symbol = OpenLayers.Renderer.symbol[graphicName];
if (!symbol) {
throw new Error(graphicName + ' is not a valid symbol name');
return;
}
var symbolExtent = new OpenLayers.Bounds(
Number.MAX_VALUE, Number.MAX_VALUE, 0, 0);
var pathitems = ["m"];
for (var i=0; i<symbol.length; i=i+2) {
x = symbol[i];
y = symbol[i+1];
symbolExtent.left = Math.min(symbolExtent.left, x);
symbolExtent.bottom = Math.min(symbolExtent.bottom, y);
symbolExtent.right = Math.max(symbolExtent.right, x);
symbolExtent.top = Math.max(symbolExtent.top, y);
pathitems.push(x);
pathitems.push(y);
if (i == 0) {
pathitems.push("l");
}
}
pathitems.push("x e");
var path = pathitems.join(" ");
var diff = (symbolExtent.getWidth() - symbolExtent.getHeight()) / 2;
if(diff > 0) {
symbolExtent.bottom = symbolExtent.bottom - diff;
symbolExtent.top = symbolExtent.top + diff;
} else {
symbolExtent.left = symbolExtent.left - diff;
symbolExtent.right = symbolExtent.right + diff;
}
cache = {
path: path,
size: symbolExtent.getWidth(), // equals getHeight() now
left: symbolExtent.left,
bottom: symbolExtent.bottom
};
this.symbolCache[id] = cache;
return cache;
},
CLASS_NAME: "OpenLayers.Renderer.VML"
});
/**
* Constant: OpenLayers.Renderer.VML.LABEL_SHIFT
* {Object}
*/
OpenLayers.Renderer.VML.LABEL_SHIFT = {
"l": 0,
"c": .5,
"r": 1,
"t": 0,
"m": .5,
"b": 1
};
| {
"content_hash": "493f2443d835eca0a399104b19d6d019",
"timestamp": "",
"source": "github",
"line_count": 977,
"max_line_length": 113,
"avg_line_length": 33.07369498464688,
"alnum_prop": 0.5265682542629901,
"repo_name": "mgiraldo/nypl-warper",
"id": "10d305e540ee818e12fcd48705f5a9a8f49e5b23",
"size": "32498",
"binary": false,
"copies": "14",
"ref": "refs/heads/master",
"path": "public/javascripts/openlayers/2.8/OpenLayers-2.8/lib/OpenLayers/Renderer/VML.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "28024"
},
{
"name": "CSS",
"bytes": "496362"
},
{
"name": "JavaScript",
"bytes": "16094449"
},
{
"name": "Perl",
"bytes": "859"
},
{
"name": "Python",
"bytes": "720628"
},
{
"name": "Ruby",
"bytes": "272361"
},
{
"name": "Shell",
"bytes": "10305"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>The source code</title>
<link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="../resources/prettify/prettify.js"></script>
<style type="text/css">
.highlight { display: block; background-color: #ddd; }
</style>
<script type="text/javascript">
function highlight() {
document.getElementById(location.hash.replace(/#/, "")).className = "highlight";
}
</script>
</head>
<body onload="prettyPrint(); highlight();">
<pre class="prettyprint lang-js"><span id='Ext-ux-grid-filter-BooleanFilter'>/**
</span> * @class Ext.ux.grid.filter.BooleanFilter
* @extends Ext.ux.grid.filter.Filter
* Boolean filters use unique radio group IDs (so you can have more than one!)
* <p><b><u>Example Usage:</u></b></p>
* <pre><code>
var filters = Ext.create('Ext.ux.grid.GridFilters', {
...
filters: [{
// required configs
type: 'boolean',
dataIndex: 'visible'
// optional configs
defaultValue: null, // leave unselected (false selected by default)
yesText: 'Yes', // default
noText: 'No' // default
}]
});
* </code></pre>
*/
Ext.define('Ext.ux.grid.filter.BooleanFilter', {
extend: 'Ext.ux.grid.filter.Filter',
alias: 'gridfilter.boolean',
<span id='Ext-ux-grid-filter-BooleanFilter-cfg-defaultValue'> /**
</span> * @cfg {Boolean} defaultValue
* Set this to null if you do not want either option to be checked by default. Defaults to false.
*/
defaultValue : false,
<span id='Ext-ux-grid-filter-BooleanFilter-cfg-yesText'> /**
</span> * @cfg {String} yesText
* Defaults to 'Yes'.
*/
yesText : 'Yes',
<span id='Ext-ux-grid-filter-BooleanFilter-cfg-noText'> /**
</span> * @cfg {String} noText
* Defaults to 'No'.
*/
noText : 'No',
<span id='Ext-ux-grid-filter-BooleanFilter-method-init'> /**
</span> * @private
* Template method that is to initialize the filter and install required menu items.
*/
init : function (config) {
var gId = Ext.id();
this.options = [
Ext.create('Ext.menu.CheckItem', {text: this.yesText, group: gId, checked: this.defaultValue === true}),
Ext.create('Ext.menu.CheckItem', {text: this.noText, group: gId, checked: this.defaultValue === false})];
this.menu.add(this.options[0], this.options[1]);
for(var i=0; i<this.options.length; i++){
this.options[i].on('click', this.fireUpdate, this);
this.options[i].on('checkchange', this.fireUpdate, this);
}
},
<span id='Ext-ux-grid-filter-BooleanFilter-method-getValue'> /**
</span> * @private
* Template method that is to get and return the value of the filter.
* @return {String} The value of this filter
*/
getValue : function () {
return this.options[0].checked;
},
<span id='Ext-ux-grid-filter-BooleanFilter-method-setValue'> /**
</span> * @private
* Template method that is to set the value of the filter.
* @param {Object} value The value to set the filter
*/
setValue : function (value) {
this.options[value ? 0 : 1].setChecked(true);
},
<span id='Ext-ux-grid-filter-BooleanFilter-method-getSerialArgs'> /**
</span> * @private
* Template method that is to get and return serialized filter data for
* transmission to the server.
* @return {Object/Array} An object or collection of objects containing
* key value pairs representing the current configuration of the filter.
*/
getSerialArgs : function () {
var args = {type: 'boolean', value: this.getValue()};
return args;
},
<span id='Ext-ux-grid-filter-BooleanFilter-method-validateRecord'> /**
</span> * Template method that is to validate the provided Ext.data.Record
* against the filters configuration.
* @param {Ext.data.Record} record The record to validate
* @return {Boolean} true if the record is valid within the bounds
* of the filter, false otherwise.
*/
validateRecord : function (record) {
return record.get(this.dataIndex) == this.getValue();
}
});
</pre>
</body>
</html>
| {
"content_hash": "6373aeb65f1fd8596d9a0e22ff2afce5",
"timestamp": "",
"source": "github",
"line_count": 120,
"max_line_length": 108,
"avg_line_length": 35.55,
"alnum_prop": 0.6507266760431317,
"repo_name": "crysfel/fundamentos-extjs",
"id": "21406d027e3988cc2725faa2dad98c5f51e16942",
"size": "4266",
"binary": false,
"copies": "11",
"ref": "refs/heads/master",
"path": "extjs-4.1.0/docs/source/BooleanFilter.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "212543079"
},
{
"name": "PHP",
"bytes": "156104"
},
{
"name": "Python",
"bytes": "4470"
},
{
"name": "Ruby",
"bytes": "13417"
},
{
"name": "Shell",
"bytes": "47"
}
],
"symlink_target": ""
} |
terbilang
===============
[](https://www.npmjs.org/package/terbilang)
JavaScript library to convert a number to its word representation in Bahasa Indonesia language
## Install
Download [manually](https://github.com/aredo/terbilang/releases) or with a package-manager.
``` js
$ npm install terbilang
```
```
$ bower install --save terbilang
```
## Usage
``` js
var Terbilang = require('terbilang');
Terbilang(943210) // sembilan ratus empat puluh tiga ribu dua ratus sepuluh
```
## TODO
- implement if a number more than 10 digits
| {
"content_hash": "a1a3424485720713b8815ed1c2b33e11",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 94,
"avg_line_length": 20.344827586206897,
"alnum_prop": 0.7084745762711865,
"repo_name": "aredo/terbilang",
"id": "b0715a8ca5890ed5fb9e47e5432af2326425e204",
"size": "590",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "5734"
}
],
"symlink_target": ""
} |
<?php declare(strict_types=1);
namespace PHPUnit\Event\Test;
use PHPUnit\Event\Subscriber;
/**
* @no-named-arguments Parameter names are not covered by the backward compatibility promise for PHPUnit
*/
interface FailedSubscriber extends Subscriber
{
public function notify(Failed $event): void;
}
| {
"content_hash": "e4c38c72223ac6b61ca1430968edd786",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 104,
"avg_line_length": 23.53846153846154,
"alnum_prop": 0.7679738562091504,
"repo_name": "sebastianbergmann/phpunit",
"id": "8da6a85f16d02a477c4fd8e2fef0ac5346baf93b",
"size": "527",
"binary": false,
"copies": "4",
"ref": "refs/heads/main",
"path": "src/Event/Events/Test/Outcome/FailedSubscriber.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "PHP",
"bytes": "3243994"
},
{
"name": "Smarty",
"bytes": "12553"
}
],
"symlink_target": ""
} |
;; This code can go into the .emacs file
;; This works with python-mode.el version 1.0
(defun py-insert-super ()
(interactive)
(let (methodname classname)
(save-excursion
(or (py-go-up-tree-to-keyword "def")
(error "Enclosing def not found"))
(or (looking-at "[ \t]*def[ \t]+\\([a-zA-Z0-9_]+\\)")
(error "Can't determine method name"))
(setq methodname (match-string 1))
(or (py-go-up-tree-to-keyword "class")
(error "Enclosing class not found"))
(or (looking-at "[ \t]*class[ \t]+\\([a-zA-Z0-9_]+\\)")
(error "Can't determine class name"))
(setq classname (match-string 1)))
(insert (format "super(%s,self).%s()" classname methodname))
(backward-char)))
;; Add a hook to bind a key to this function for Python buffers
(defun bind-super-key ()
(local-set-key "\C-c\C-f" 'py-insert-super))
(add-hook 'python-mode-hook 'bind-super-key)
| {
"content_hash": "6764f4a4b935fab59e95fa01a0abe60c",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 64,
"avg_line_length": 35.84615384615385,
"alnum_prop": 0.601931330472103,
"repo_name": "ActiveState/code",
"id": "31cebbca7589dca49bd9eb5b280f146b2f579db2",
"size": "932",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "recipes/Python/522990_Elisp_code_insert_super_calls/recipe-522990.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "35894"
},
{
"name": "C",
"bytes": "56048"
},
{
"name": "C++",
"bytes": "90880"
},
{
"name": "HTML",
"bytes": "11656"
},
{
"name": "Java",
"bytes": "57468"
},
{
"name": "JavaScript",
"bytes": "181218"
},
{
"name": "PHP",
"bytes": "250144"
},
{
"name": "Perl",
"bytes": "37296"
},
{
"name": "Perl 6",
"bytes": "9914"
},
{
"name": "Python",
"bytes": "17387779"
},
{
"name": "Ruby",
"bytes": "40233"
},
{
"name": "Shell",
"bytes": "190732"
},
{
"name": "Tcl",
"bytes": "674650"
}
],
"symlink_target": ""
} |
<?php
namespace Vanessa\SongBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\FormBuilderInterface;
use Doctrine\ORM\EntityRepository;
/**
* Vanessa\SongBundle\Form\SongShowType
*
* @author Mfana Ronald Conco <[email protected]>
* @package VanessaSongBundle
* @subpackage Form
* @version 0.0.1
*/
class SongShowType extends AbstractType
{
/**
* Build Form
*
* @param FormBuilder $builder
* @param array $options
* @return void
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title', 'text', array(
'label' => 'Title:',
'attr' => array('class' => 'span4' , 'disabled' => 'disabled')
))
->add('isrc', 'text', array(
'label' => 'ISRC:',
'attr' => array('class' => 'span4' , 'disabled' => 'disabled')
))
->add('featuredArtist', 'text', array(
'label' => 'Featured artist:',
'required' => false,
'attr' => array('class' => 'span4' , 'disabled' => 'disabled'),
))
->add('artist', 'entity', array(
'class' => 'VanessaCoreBundle:Artist',
'label' => 'Artist:',
'attr' => array('class' => 'span4 chosen', 'disabled' => 'disabled'),
))
->add('status', 'entity', array(
'class' => 'VanessaCoreBundle:Status',
'label' => 'Status:',
'attr' => array('class' => 'span4 chosen', 'disabled' => 'disabled'),
))
->add('genres', 'entity', array(
'class' => 'VanessaCoreBundle:Genre',
'label' => 'Genres:',
'multiple' => true ,
'attr' => array('class' => 'span4 chosen','disabled' => 'disabled'),
'empty_value' => 'Choose a genre',
))
;
}
/**
* Get name
* @return string
*/
public function getName()
{
return 'SongTemp';
}
public function getDefaultOptions(array $options)
{
return array(
'data_class' => 'Vanessa\CoreBundle\Entity\SongTemp',
);
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Vanessa\CoreBundle\Entity\SongTemp',
));
}
}
?>
| {
"content_hash": "b80c7df1894e3792c51128beb805913f",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 85,
"avg_line_length": 28.86813186813187,
"alnum_prop": 0.5131328511610201,
"repo_name": "sonnybrilliant/zeus-mobigospel",
"id": "1bb722a4998a786cb1e4518c0390a55a177b8b9e",
"size": "2627",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Vanessa/SongBundle/Form/SongShowType.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2204"
},
{
"name": "PHP",
"bytes": "47317"
}
],
"symlink_target": ""
} |
ngapp.service('hotkeyFactory', function() {
let factory = this,
ctrlDown = false;
// PUBLIC HOTKEYS
this.baseHotkeys = {
i: [{
modifiers: ['ctrlKey', 'shiftKey'],
callback: 'toggleDevTools'
}],
s: [{
modifiers: ['ctrlKey', 'shiftKey'],
callback: (scope) => scope.$broadcast('openModal', 'settings')
}, {
modifiers: ['ctrlKey'],
callback: (scope) => scope.$broadcast('save')
}],
h: [{
modifiers: ['ctrlKey', 'shiftKey'],
callback: (scope) => scope.$emit('openModal', 'help')
}],
e: [{
modifiers: ['ctrlKey', 'shiftKey'],
callback: (scope) => scope.$emit('openModal', 'manageExtensions')
}],
ctrl: (scope) => {
if (ctrlDown) return;
scope.$broadcast('controlKeyPressed');
ctrlDown = true;
},
escape: 'handleEscape'
};
this.baseHotkeysUp = {
ctrl: (scope) => {
scope.$broadcast('controlKeyReleased');
ctrlDown = false;
}
};
this.editViewHotkeys = {};
this.paneHotkeys = {
tab: [{
modifiers: ['ctrlKey', 'shiftKey'],
callback: 'previousTab'
}, {
modifiers: ['ctrlKey'],
callback: 'nextTab'
}],
t: [{
modifiers: ['ctrlKey'],
callback: 'newTab'
}],
w: [{
modifiers: ['ctrlKey'],
callback: 'closeCurrentTab'
}]
};
this.cleanViewHotkeys = {};
this.treeViewHotkeys = {
rightArrow: 'handleRightArrow',
leftArrow: 'handleLeftArrow',
upArrow: 'handleUpArrow',
downArrow: 'handleDownArrow',
pageUp: 'handlePageUp',
pageDown: 'handlePageDown',
enter: 'handleEnter',
delete: 'handleDelete',
insert: 'handleInsert',
f: [{
modifiers: ['ctrlKey', 'shiftKey'],
callback: 'openAdvancedSearchModal'
}, {
modifiers: ['ctrlKey'],
callback: 'toggleSearchBar'
}],
m: [{
modifiers: ['ctrlKey'],
callback: (scope) => scope.$emit('openModal', 'automate')
}],
e: [{
modifiers: ['ctrlKey'],
callback: 'enableEditing'
}],
s: [{
modifiers: ['ctrlKey', 'altKey'],
callback: 'savePluginAs'
}],
f2: 'refactor',
r: [{
modifiers: ['altKey', 'shiftKey'],
callback: 'refactor'
}],
c: [{
modifiers: ['ctrlKey', 'shiftKey'],
callback: 'copyPaths'
}, {
modifiers: ['ctrlKey', 'altKey'],
callback: 'copyInto'
}, {
modifiers: ['ctrlKey'],
callback: 'copyNodes'
}],
v: [{
modifiers: ['ctrlKey', 'shiftKey'],
callback: (scope) => scope.pasteNodes(false)
}, {
modifiers: ['ctrlKey'],
callback: (scope) => scope.pasteNodes(true)
}],
b: [{
modifiers: ['ctrlKey'],
callback: 'buildReferences'
}],
default: 'handleLetter'
};
this.recordViewHotkeys = {
leftArrow: [{
modifiers: ['altKey'],
callback: (scope) => scope.$broadcast('navBack')
}, {
modifiers: [],
callback: 'handleLeftArrow'
}],
rightArrow: [{
modifiers: ['altKey'],
callback: (scope) => scope.$broadcast('navForward')
}, {
modifiers: [],
callback: 'handleRightArrow'
}],
upArrow: 'handleUpArrow',
downArrow: 'handleDownArrow',
pageUp: 'handlePageUp',
pageDown: 'handlePageDown',
enter: 'handleEnter',
delete: 'deleteElements',
insert: 'handleInsert',
backspace: (scope) => scope.$broadcast('navBack'),
f: [{
modifiers: ['ctrlKey'],
callback: 'toggleSearchBar'
}],
r: [{
modifiers: ['ctrlKey'],
callback: 'toggleReplaceBar'
}],
f6: (scope) => scope.toggleAddressBar(true)
};
this.treeSearchHotkeys = {
escape: 'closeSearch',
enter: [{
modifiers: ['shiftKey'],
callback: 'previousResult'
}, {
modifiers: [],
callback: 'nextResult'
}],
x: [{
modifiers: ['altKey'],
callback: 'toggleExact'
}],
default: [{
modifiers: ['altKey'],
callback: 'setSearchBy'
}]
};
this.addressBarHotkeys = {
enter: 'go',
escape: 'closeBar'
};
this.recordSearchHotkeys = {
escape: 'closeSearch',
enter: [{
modifiers: ['shiftKey'],
callback: 'previousResult'
}, {
modifiers: [],
callback: 'nextResult'
}],
default: [{
modifiers: ['altKey'],
callback: 'setSearchBy'
}]
};
this.contextMenuHotkeys = {
rightArrow: 'handleRightArrow',
leftArrow: 'handleLeftArrow',
upArrow: 'handleUpArrow',
downArrow: 'handleDownArrow',
escape: 'closeMenu',
enter: 'clickItem'
};
this.dropdownHotkeys = {
downArrow: 'toggleDropdown',
enter: 'toggleDropdown'
};
this.dropdownItemsHotkeys = {
upArrow: 'handleUpArrow',
downArrow: 'handleDownArrow',
escape: 'handleEscape',
enter: 'handleEnter'
};
this.listViewHotkeys = {
upArrow: 'handleUpArrow',
downArrow: 'handleDownArrow',
space: 'handleSpace',
escape: 'clearSelection',
enter: 'handleEnter',
a: [{
modifiers: ['ctrlKey'],
callback: 'selectAll'
}]
};
this.automateModalHotkeys = {
enter: [{
modifiers: ['ctrlKey'],
callback: 'runScript'
}],
delete: [{
modifiers: ['ctrlKey'],
callback: 'deleteScript'
}],
f2: 'handleF2',
n: [{
modifiers: ['ctrlKey'],
callback: 'newScript'
}],
s: [{
modifiers: ['ctrlKey'],
callback: 'saveScript'
}]
};
this.editValueModalHotkeys = {
enter: [{
modifiers: ['ctrlKey'],
callback: 'applyValue'
}],
s: [{
modifiers: ['ctrlKey'],
callback: 'applyValue'
}],
default: (scope, event) => scope.$broadcast('keyDown', event)
};
this.resolveModalHotkeys = {
w: 'nextError',
rightArrow: 'nextError',
q: 'previousError',
leftArrow: 'previousError',
default: (scope, event) => scope.handleResolutionKey(event)
};
this.referencedByViewHotkeys = {
enter: 'handleEnter'
};
this.cellEditorHotkeys = {
enter: 'save',
escape: 'stopEditing',
default: 'stopPropagation'
};
// HELPER FUNCTIONS
let sortHotkeys = function(hotkeys) {
hotkeys.sort(function(a, b) {
return a.modifiers.length - b.modifiers.length;
});
};
let addHotkey = function(target, hotkeys, key) {
if (typeof target[key] === 'string') {
target[key] = [hotkeys[key], {
modifiers: [],
callback: target[key]
}];
} else {
target[key].push(hotkeys[key]);
sortHotkeys(target[key]);
}
};
// PUBLIC API
this.addHotkeys = function(label, hotkeys) {
let target = factory[`${label}Hotkeys`];
Object.keys(hotkeys).forEach(function(key) {
if (target.hasOwnProperty(key)) {
addHotkey(target, hotkeys, key);
} else {
target[key] = hotkeys[key];
}
});
};
});
| {
"content_hash": "31a384117a2c2dac74e1c08f85c390ce",
"timestamp": "",
"source": "github",
"line_count": 307,
"max_line_length": 77,
"avg_line_length": 26.547231270358306,
"alnum_prop": 0.4710429447852761,
"repo_name": "matortheeternal/zedit",
"id": "20bcb3f7e73041818ee7855b6763830963e34ba5",
"size": "8150",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/javascripts/Factories/hotkeyFactory.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "113"
},
{
"name": "CSS",
"bytes": "57826"
},
{
"name": "HTML",
"bytes": "153273"
},
{
"name": "JavaScript",
"bytes": "379921"
},
{
"name": "Shell",
"bytes": "349"
}
],
"symlink_target": ""
} |
package kerio.connect.admin.settings;
public class Version {
long ApiVersion;
ProductVersion productVersion;
public Version() {
}
public long getApiVersion() {
return ApiVersion;
}
public void setApiVersion(long apiVersion) {
ApiVersion = apiVersion;
}
public ProductVersion getProductVersion() {
return productVersion;
}
public void setProductVersion(ProductVersion productVersion) {
this.productVersion = productVersion;
}
public enum BuildType {
Alpha,
Beta,
Rc,
Final,
Patch
}
public static class ProductVersion {
String productName; ///< e.g. "Kerio Connect"
long major; ///< e.g. 7
long minor; ///< e.g. 4
long revision; ///< e.g. 0
long build; ///< e.g. 4528
long order; ///< e.g. 1 for alpha/beta/rc/patch 1
BuildType releaseType; ///< e.g. Patch
String displayNumber; ///< e.g. "7.4.0 patch 1"
public ProductVersion() {
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public long getMajor() {
return major;
}
public void setMajor(long major) {
this.major = major;
}
public long getMinor() {
return minor;
}
public void setMinor(long minor) {
this.minor = minor;
}
public long getRevision() {
return revision;
}
public void setRevision(long revision) {
this.revision = revision;
}
public long getBuild() {
return build;
}
public void setBuild(long build) {
this.build = build;
}
public long getOrder() {
return order;
}
public void setOrder(long order) {
this.order = order;
}
public BuildType getReleaseType() {
return releaseType;
}
public void setReleaseType(BuildType releaseType) {
this.releaseType = releaseType;
}
public String getDisplayNumber() {
return displayNumber;
}
public void setDisplayNumber(String displayNumber) {
this.displayNumber = displayNumber;
}
}
}
| {
"content_hash": "9288a54fd419aaf2eefad86dd33eeeb1",
"timestamp": "",
"source": "github",
"line_count": 120,
"max_line_length": 64,
"avg_line_length": 18.55,
"alnum_prop": 0.5956873315363881,
"repo_name": "pascalrobert/kerio-admin",
"id": "51e47e2c83898a923cf9c452974ab55b62b7ca08",
"size": "2226",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/kerio/connect/admin/settings/Version.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "296025"
}
],
"symlink_target": ""
} |
<!doctype html>
<title>Stick Figure Examples</title>
<h1>Stick Figure Examples</h1>
<ol>
<li value="0">
<a href="sticks0.html">Draw on a canvas</a> – see also <a href="lines-and-triangles.html">Lines and triangles</a>
<li><a href="sticks1.html">Draw a stick figure (or three)</a>
<li><a href="sticks2.html">Stick figures can turn around</a>
<li><a href="sticks3.html">Stick figures can walk</a>
<li><a href="sticks4.html">Animate walking</a>
<li><a href="sticks5.html">Stick figures can go where told</a>
<li><a href="sticks6.html">Stick figures can gather things</a>
<li><a href="sticks7.html">Diamond hunt!</a>
<li><a href="sticks8.html">Multiplayer!!!</a> (<a href="leaders">score board</a>)
</ol>
Other canvas examples:
<ul>
<li><a href="lines-and-triangles.html">Lines and triangles</a>
<li><a href="joins-n-dashes.html">Joins and continuing dashes</a>
<li><a href="draw-under.html">Drawing under text, finding element locations</a>
(and also <a href="draw-under-clickable.html">a clickable version</a>)
<li><a href="circles.html">Circles and Moire</a>
</ul>
| {
"content_hash": "9387f71c14e2cbc8f9ab38dd263c0a74",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 119,
"avg_line_length": 40.888888888888886,
"alnum_prop": 0.6793478260869565,
"repo_name": "portsoc/Web-Canvas-Stick-Figures",
"id": "61500ba554e3625bee97f8743e5302fa838fbafc",
"size": "1106",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "static/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "59234"
},
{
"name": "JavaScript",
"bytes": "14800"
}
],
"symlink_target": ""
} |
<?php
namespace Phlexible\Bundle\ElementBundle\Event;
use Phlexible\Bundle\ElementBundle\Entity\ElementVersion;
use Symfony\Component\EventDispatcher\Event;
/**
* Element version event
*
* @author Stephan Wentz <[email protected]>
*/
class ElementVersionEvent extends Event
{
/**
* @var ElementVersion
*/
private $elementVersion;
/**
* @param ElementVersion $elementVersion
*/
public function __construct(ElementVersion $elementVersion)
{
$this->elementVersion = $elementVersion;
}
/**
* @return ElementVersion
*/
public function getElementVersion()
{
return $this->elementVersion;
}
}
| {
"content_hash": "237d1b93c277ed9a1a52fa08761d1e24",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 63,
"avg_line_length": 18.43243243243243,
"alnum_prop": 0.6612903225806451,
"repo_name": "temp/phlexible",
"id": "e5cb000f3696f7f38397876843feba2dc140ad88",
"size": "908",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Phlexible/Bundle/ElementBundle/Event/ElementVersionEvent.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "342470"
},
{
"name": "HTML",
"bytes": "18492"
},
{
"name": "JavaScript",
"bytes": "5390477"
},
{
"name": "PHP",
"bytes": "2518383"
}
],
"symlink_target": ""
} |
using content::BrowserContext;
using extensions::Extension;
namespace {
// Root dirs for file systems expected by the test extensions.
// NOTE: Root dir for drive file system is set by Chrome's drive implementation,
// but the test will have to make sure the mount point is mounted before
// starting a test extension.
const char kDriveMountPointName[] = "drive";
const char kLocalMountPointName[] = "local";
const char kRestrictedMountPointName[] = "restricted";
// Default file content for the test files.
// The content format is influenced by fake drive service implementation which
// fills the file with 'x' characters until its size matches the size declared
// in the root feed.
// The size of the files in |kTestRootFeed| has to be set to the length of
// |kTestFileContent| string.
const char kTestFileContent[] = "xxxxxxxxxxxxx";
// Contains feed for drive file system. The file system hiearchy is the same for
// local and restricted file systems:
// test_dir/ - - subdir/
// |
// - empty_test_dir/
// |
// - empty_test_file.foo
// |
// - test_file.xul
// |
// - test_file.xul.foo
// |
// - test_file.tiff
// |
// - test_file.tiff.foo
//
// All files except test_dir/empty_file.foo, which is empty, initially contain
// kTestFileContent.
const char kTestRootFeed[] =
"chromeos/gdata/remote_file_system_apitest_root_feed.json";
// Creates a test file with predetermined content. Returns true on success.
bool CreateFileWithContent(const base::FilePath& path,
const std::string& content) {
int content_size = static_cast<int>(content.length());
int written = file_util::WriteFile(path, content.c_str(), content_size);
return written == content_size;
}
// Sets up the initial file system state for native local and restricted native
// local file systems. The hierarchy is the same as for the drive file system.
bool InitializeLocalFileSystem(base::ScopedTempDir* tmp_dir,
base::FilePath* mount_point_dir) {
if (!tmp_dir->CreateUniqueTempDir())
return false;
*mount_point_dir = tmp_dir->path().Append("mount");
// Create the mount point.
if (!file_util::CreateDirectory(*mount_point_dir))
return false;
base::FilePath test_dir = mount_point_dir->Append("test_dir");
if (!file_util::CreateDirectory(test_dir))
return false;
base::FilePath test_subdir = test_dir.Append("empty_test_dir");
if (!file_util::CreateDirectory(test_subdir))
return false;
test_subdir = test_dir.AppendASCII("subdir");
if (!file_util::CreateDirectory(test_subdir))
return false;
base::FilePath test_file = test_dir.AppendASCII("test_file.xul");
if (!CreateFileWithContent(test_file, kTestFileContent))
return false;
test_file = test_dir.AppendASCII("test_file.xul.foo");
if (!CreateFileWithContent(test_file, kTestFileContent))
return false;
test_file = test_dir.AppendASCII("test_file.tiff");
if (!CreateFileWithContent(test_file, kTestFileContent))
return false;
test_file = test_dir.AppendASCII("test_file.tiff.foo");
if (!CreateFileWithContent(test_file, kTestFileContent))
return false;
test_file = test_dir.AppendASCII("empty_test_file.foo");
if (!CreateFileWithContent(test_file, ""))
return false;
return true;
}
// Helper class used to wait for |OnFileSystemMounted| event from a drive file
// system.
class DriveMountPointWaiter : public drive::DriveFileSystemObserver {
public:
explicit DriveMountPointWaiter(drive::DriveFileSystemInterface* file_system)
: file_system_(file_system) {
file_system_->AddObserver(this);
}
virtual ~DriveMountPointWaiter() {
file_system_->RemoveObserver(this);
}
// DriveFileSystemObserver override.
virtual void OnFileSystemMounted() OVERRIDE {
// Note that it is OK for |run_loop_.Quit| to be called before
// |run_loop_.Run|. In this case |Run| will return immediately.
run_loop_.Quit();
}
// Runs loop until the file_system_ gets mounted.
void Wait() {
run_loop_.Run();
}
private:
drive::DriveFileSystemInterface* file_system_;
base::RunLoop run_loop_;
};
// Helper class to wait for a background page to load or close again.
class BackgroundObserver {
public:
BackgroundObserver()
: page_created_(chrome::NOTIFICATION_EXTENSION_BACKGROUND_PAGE_READY,
content::NotificationService::AllSources()),
page_closed_(chrome::NOTIFICATION_EXTENSION_HOST_DESTROYED,
content::NotificationService::AllSources()) {
}
void WaitUntilLoaded() {
page_created_.Wait();
}
void WaitUntilClosed() {
page_closed_.Wait();
}
private:
content::WindowedNotificationObserver page_created_;
content::WindowedNotificationObserver page_closed_;
};
// Base class for FileSystemExtensionApi tests.
class FileSystemExtensionApiTestBase : public ExtensionApiTest {
public:
enum Flags {
FLAGS_NONE = 0,
FLAGS_USE_FILE_HANDLER = 1 << 1,
FLAGS_LAZY_FILE_HANDLER = 1 << 2
};
FileSystemExtensionApiTestBase() {}
virtual ~FileSystemExtensionApiTestBase() {}
virtual void SetUp() OVERRIDE {
InitTestFileSystem();
ExtensionApiTest::SetUp();
}
virtual void SetUpOnMainThread() OVERRIDE {
AddTestMountPoint();
ExtensionApiTest::SetUpOnMainThread();
}
// Runs a file system extension API test.
// It loads test component extension at |filebrowser_path| with manifest
// at |filebrowser_manifest|. The |filebrowser_manifest| should be a path
// relative to |filebrowser_path|. The method waits until the test extension
// sends test succeed or fail message. It returns true if the test succeeds.
// If |FLAGS_USE_FILE_HANDLER| flag is set, the file handler extension at path
// |filehandler_path| will be loaded before the file browser extension.
// If the flag FLAGS_LAZY_FILE_HANDLER is set, the file handler extension must
// not have persistent background page. The test will wait until the file
// handler's background page is closed after initial load before the file
// browser extension is loaded.
// If |RunFileSystemExtensionApiTest| fails, |message_| will contain a failure
// message.
bool RunFileSystemExtensionApiTest(
const std::string& filebrowser_path,
const base::FilePath::CharType* filebrowser_manifest,
const std::string& filehandler_path,
int flags) {
if (flags & FLAGS_USE_FILE_HANDLER) {
if (filehandler_path.empty()) {
message_ = "Missing file handler path.";
return false;
}
BackgroundObserver page_complete;
const Extension* file_handler =
LoadExtension(test_data_dir_.AppendASCII(filehandler_path));
if (!file_handler)
return false;
if (flags & FLAGS_LAZY_FILE_HANDLER) {
page_complete.WaitUntilClosed();
} else {
page_complete.WaitUntilLoaded();
}
}
ResultCatcher catcher;
const Extension* file_browser = LoadExtensionAsComponentWithManifest(
test_data_dir_.AppendASCII(filebrowser_path),
filebrowser_manifest);
if (!file_browser)
return false;
if (!catcher.GetNextResult()) {
message_ = catcher.message();
return false;
}
return true;
}
protected:
// Sets up initial test file system hierarchy. See comment for kTestRootFeed
// for the actual hierarchy.
virtual void InitTestFileSystem() = 0;
// Registers mount point used in the test.
virtual void AddTestMountPoint() = 0;
};
// Tests for a native local file system.
class LocalFileSystemExtensionApiTest : public FileSystemExtensionApiTestBase {
public:
LocalFileSystemExtensionApiTest() {}
virtual ~LocalFileSystemExtensionApiTest() {}
// FileSystemExtensionApiTestBase OVERRIDE.
virtual void InitTestFileSystem() OVERRIDE {
ASSERT_TRUE(InitializeLocalFileSystem(&tmp_dir_, &mount_point_dir_))
<< "Failed to initialize file system.";
}
// FileSystemExtensionApiTestBase OVERRIDE.
virtual void AddTestMountPoint() OVERRIDE {
EXPECT_TRUE(content::BrowserContext::GetMountPoints(browser()->profile())->
RegisterFileSystem(kLocalMountPointName,
fileapi::kFileSystemTypeNativeLocal,
mount_point_dir_));
}
private:
base::ScopedTempDir tmp_dir_;
base::FilePath mount_point_dir_;
};
// Tests for restricted native local file systems.
class RestrictedFileSystemExtensionApiTest
: public FileSystemExtensionApiTestBase {
public:
RestrictedFileSystemExtensionApiTest() {}
virtual ~RestrictedFileSystemExtensionApiTest() {}
// FileSystemExtensionApiTestBase OVERRIDE.
virtual void InitTestFileSystem() OVERRIDE {
ASSERT_TRUE(InitializeLocalFileSystem(&tmp_dir_, &mount_point_dir_))
<< "Failed to initialize file system.";
}
// FileSystemExtensionApiTestBase OVERRIDE.
virtual void AddTestMountPoint() OVERRIDE {
EXPECT_TRUE(content::BrowserContext::GetMountPoints(browser()->profile())->
RegisterFileSystem(kRestrictedMountPointName,
fileapi::kFileSystemTypeRestrictedNativeLocal,
mount_point_dir_));
}
private:
base::ScopedTempDir tmp_dir_;
base::FilePath mount_point_dir_;
};
// Tests for a drive file system.
class DriveFileSystemExtensionApiTest : public FileSystemExtensionApiTestBase {
public:
DriveFileSystemExtensionApiTest() : fake_drive_service_(NULL) {}
virtual ~DriveFileSystemExtensionApiTest() {}
// FileSystemExtensionApiTestBase OVERRIDE.
virtual void InitTestFileSystem() OVERRIDE {
// Set up cache root and documents service to be used when creating gdata
// system service. This has to be done early on (before the browser is
// created) because the system service instance is initialized very early
// by FileManagerEventRouter.
base::FilePath tmp_dir_path;
PathService::Get(base::DIR_TEMP, &tmp_dir_path);
ASSERT_TRUE(test_cache_root_.CreateUniqueTempDirUnderPath(tmp_dir_path));
drive::DriveSystemServiceFactory::SetFactoryForTest(
base::Bind(&DriveFileSystemExtensionApiTest::CreateDriveSystemService,
base::Unretained(this)));
}
// FileSystemExtensionApiTestBase OVERRIDE.
virtual void AddTestMountPoint() OVERRIDE {
// Drive mount point is added by the browser when the drive system service
// is first initialized. It is done asynchronously after some other parts of
// the service are initialized (e.g. resource metadata and cache), thus racy
// with the test start. To handle this raciness, the test verifies that
// drive mount point is added before continuing. If this is not the case,
// drive file system is observed for FileSystemMounted event (by
// |mount_point_waiter|) and test continues once the event is encountered.
drive::DriveSystemService* system_service =
drive::DriveSystemServiceFactory::FindForProfileRegardlessOfStates(
browser()->profile());
ASSERT_TRUE(system_service && system_service->file_system());
DriveMountPointWaiter mount_point_waiter(system_service->file_system());
base::FilePath ignored;
// GetRegisteredPath succeeds iff the mount point exists.
if (!content::BrowserContext::GetMountPoints(browser()->profile())->
GetRegisteredPath(kDriveMountPointName, &ignored)) {
LOG(WARNING) << "Waiting for drive mount point to get mounted.";
mount_point_waiter.Wait();
LOG(WARNING) << "Drive mount point found.";
}
}
protected:
// DriveSystemService factory function for this test.
drive::DriveSystemService* CreateDriveSystemService(Profile* profile) {
fake_drive_service_ = new google_apis::FakeDriveService;
fake_drive_service_->LoadResourceListForWapi(kTestRootFeed);
fake_drive_service_->LoadAccountMetadataForWapi(
"chromeos/gdata/account_metadata.json");
fake_drive_service_->LoadAppListForDriveApi("chromeos/drive/applist.json");
return new drive::DriveSystemService(profile,
fake_drive_service_,
test_cache_root_.path(),
NULL);
}
base::ScopedTempDir test_cache_root_;
google_apis::FakeDriveService* fake_drive_service_;
};
//
// LocalFileSystemExtensionApiTests.
//
IN_PROC_BROWSER_TEST_F(LocalFileSystemExtensionApiTest, FileSystemOperations) {
EXPECT_TRUE(RunFileSystemExtensionApiTest(
"file_browser/filesystem_operations_test",
FILE_PATH_LITERAL("manifests_v1.json"),
"",
FLAGS_NONE)) << message_;
}
IN_PROC_BROWSER_TEST_F(LocalFileSystemExtensionApiTest,
FileSystemOperations_Packaged) {
EXPECT_TRUE(RunFileSystemExtensionApiTest(
"file_browser/filesystem_operations_test",
FILE_PATH_LITERAL("manifests_v2.json"),
"",
FLAGS_NONE)) << message_;
}
IN_PROC_BROWSER_TEST_F(LocalFileSystemExtensionApiTest, FileWatch) {
EXPECT_TRUE(RunFileSystemExtensionApiTest(
"file_browser/file_watcher_test",
FILE_PATH_LITERAL("manifest.json"),
"",
FLAGS_NONE)) << message_;
}
IN_PROC_BROWSER_TEST_F(LocalFileSystemExtensionApiTest, FileBrowserHandlers) {
EXPECT_TRUE(RunFileSystemExtensionApiTest(
"file_browser/handler_test_runner",
FILE_PATH_LITERAL("manifest_v1.json"),
"file_browser/file_browser_handler",
FLAGS_USE_FILE_HANDLER)) << message_;
}
IN_PROC_BROWSER_TEST_F(LocalFileSystemExtensionApiTest,
FileBrowserHandlers_Packaged) {
EXPECT_TRUE(RunFileSystemExtensionApiTest(
"file_browser/handler_test_runner",
FILE_PATH_LITERAL("manifest_v2.json"),
"file_browser/file_browser_handler",
FLAGS_USE_FILE_HANDLER)) << message_;
}
IN_PROC_BROWSER_TEST_F(LocalFileSystemExtensionApiTest,
FileBrowserHandlersLazy) {
EXPECT_TRUE(RunFileSystemExtensionApiTest(
"file_browser/handler_test_runner",
FILE_PATH_LITERAL("manifest_v1.json"),
"file_browser/file_browser_handler_lazy",
FLAGS_USE_FILE_HANDLER | FLAGS_LAZY_FILE_HANDLER)) << message_;
}
IN_PROC_BROWSER_TEST_F(LocalFileSystemExtensionApiTest,
FileBrowserHandlersLazy_Packaged) {
EXPECT_TRUE(RunFileSystemExtensionApiTest(
"file_browser/handler_test_runner",
FILE_PATH_LITERAL("manifest_v2.json"),
"file_browser/file_browser_handler_lazy",
FLAGS_USE_FILE_HANDLER | FLAGS_LAZY_FILE_HANDLER)) << message_;
}
IN_PROC_BROWSER_TEST_F(LocalFileSystemExtensionApiTest, AppFileHanlder) {
EXPECT_TRUE(RunFileSystemExtensionApiTest(
"file_browser/handler_test_runner",
FILE_PATH_LITERAL("manifest_v2.json"),
"file_browser/app_file_handler",
FLAGS_USE_FILE_HANDLER)) << message_;
}
//
// RestrictedFileSystemExtensionApiTests.
//
IN_PROC_BROWSER_TEST_F(RestrictedFileSystemExtensionApiTest,
FileSystemOperations) {
EXPECT_TRUE(RunFileSystemExtensionApiTest(
"file_browser/filesystem_operations_test",
FILE_PATH_LITERAL("manifests_v1.json"),
"",
FLAGS_NONE)) << message_;
}
IN_PROC_BROWSER_TEST_F(RestrictedFileSystemExtensionApiTest,
FileSystemOperations_Packaged) {
EXPECT_TRUE(RunFileSystemExtensionApiTest(
"file_browser/filesystem_operations_test",
FILE_PATH_LITERAL("manifests_v2.json"),
"",
FLAGS_NONE)) << message_;
}
//
// DriveFileSystemExtensionApiTests.
//
IN_PROC_BROWSER_TEST_F(DriveFileSystemExtensionApiTest, FileSystemOperations) {
EXPECT_TRUE(RunFileSystemExtensionApiTest(
"file_browser/filesystem_operations_test",
FILE_PATH_LITERAL("manifests_v1.json"),
"",
FLAGS_NONE)) << message_;
}
IN_PROC_BROWSER_TEST_F(DriveFileSystemExtensionApiTest,
FileSystemOperations_Packaged) {
EXPECT_TRUE(RunFileSystemExtensionApiTest(
"file_browser/filesystem_operations_test",
FILE_PATH_LITERAL("manifests_v2.json"),
"",
FLAGS_NONE)) << message_;
}
IN_PROC_BROWSER_TEST_F(DriveFileSystemExtensionApiTest, FileWatch) {
EXPECT_TRUE(RunFileSystemExtensionApiTest(
"file_browser/file_watcher_test",
FILE_PATH_LITERAL("manifest.json"),
"",
FLAGS_NONE)) << message_;
}
IN_PROC_BROWSER_TEST_F(DriveFileSystemExtensionApiTest, FileBrowserHandlers) {
EXPECT_TRUE(RunFileSystemExtensionApiTest(
"file_browser/handler_test_runner",
FILE_PATH_LITERAL("manifest_v1.json"),
"file_browser/file_browser_handler",
FLAGS_USE_FILE_HANDLER)) << message_;
}
IN_PROC_BROWSER_TEST_F(DriveFileSystemExtensionApiTest,
FileBrowserHandlers_Packaged) {
EXPECT_TRUE(RunFileSystemExtensionApiTest(
"file_browser/handler_test_runner",
FILE_PATH_LITERAL("manifest_v2.json"),
"file_browser/file_browser_handler",
FLAGS_USE_FILE_HANDLER)) << message_;
}
IN_PROC_BROWSER_TEST_F(DriveFileSystemExtensionApiTest,
FileBrowserHandlersLazy) {
EXPECT_TRUE(RunFileSystemExtensionApiTest(
"file_browser/handler_test_runner",
FILE_PATH_LITERAL("manifest_v1.json"),
"file_browser/file_browser_handler_lazy",
FLAGS_USE_FILE_HANDLER | FLAGS_LAZY_FILE_HANDLER)) << message_;
}
IN_PROC_BROWSER_TEST_F(DriveFileSystemExtensionApiTest, Search) {
// Configure the drive service to return only one search result at a time
// to simulate paginated searches.
fake_drive_service_->set_default_max_results(1);
EXPECT_TRUE(RunFileSystemExtensionApiTest(
"file_browser/drive_search_test",
FILE_PATH_LITERAL("manifest.json"),
"",
FLAGS_NONE)) << message_;
}
IN_PROC_BROWSER_TEST_F(DriveFileSystemExtensionApiTest, AppFileHandler) {
fake_drive_service_->set_default_max_results(1);
EXPECT_TRUE(RunFileSystemExtensionApiTest(
"file_browser/handler_test_runner",
FILE_PATH_LITERAL("manifest_v2.json"),
"file_browser/app_file_handler",
FLAGS_USE_FILE_HANDLER)) << message_;
}
} // namespace
| {
"content_hash": "e7b085f0ae469a89ce4772e11596739d",
"timestamp": "",
"source": "github",
"line_count": 518,
"max_line_length": 80,
"avg_line_length": 35.16216216216216,
"alnum_prop": 0.6934775447457999,
"repo_name": "codenote/chromium-test",
"id": "1fc474b0e9db8b8e91a098c8468c8998a6c29073",
"size": "21314",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "chrome/browser/chromeos/extensions/external_filesystem_apitest.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
// snippet-sourcedescription:[CancelJob.java demonstrates how to cancel a job by setting the job status to Cancelled.]
// snippet-service:[s3]
// snippet-keyword:[Java]
// snippet-sourcesyntax:[java]
// snippet-keyword:[Amazon S3]
// snippet-keyword:[Code Sample]
// snippet-sourcetype:[full-example]
// snippet-sourcedate:[2019-04-30]
// snippet-sourceauthor:[jschwarzwalder (AWS)]
// snippet-start:[s3.java.cancel_job.complete]
package aws.example.s3control;
// snippet-start:[s3.java.cancel_job.import]
import com.amazonaws.AmazonServiceException;
import com.amazonaws.SdkClientException;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.services.s3control.AWSS3Control;
import com.amazonaws.services.s3control.AWSS3ControlClient;
import com.amazonaws.services.s3control.model.UpdateJobStatusRequest;
import static com.amazonaws.regions.Regions.US_WEST_2;
// snippet-end:[s3.java.cancel_job.import]
public class CancelJob {
public static void main(String[] args) {
// snippet-start:[s3.java.cancel_job.main]
String accountId = "Account ID";
String jobId = "00e123a4-c0d8-41f4-a0eb-b46f9ba5b07c";
try {
AWSS3Control s3ControlClient = AWSS3ControlClient.builder()
.withCredentials(new ProfileCredentialsProvider())
.withRegion(US_WEST_2)
.build();
s3ControlClient.updateJobStatus(new UpdateJobStatusRequest()
.withAccountId(accountId)
.withJobId(jobId)
.withStatusUpdateReason("No longer needed")
.withRequestedJobStatus("Cancelled"));
// snippet-end:[s3.java.cancel_job.main]
} catch (AmazonServiceException e) {
// The call was transmitted successfully, but Amazon S3 couldn't process
// it and returned an error response.
e.printStackTrace();
} catch (SdkClientException e) {
// Amazon S3 couldn't be contacted for a response, or the client
// couldn't parse the response from Amazon S3.
e.printStackTrace();
}
}
}
// snippet-end:[s3.java.cancel_job.complete]
| {
"content_hash": "60e6a71f7e1a8edd542d188cc51fa72e",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 118,
"avg_line_length": 35.87096774193548,
"alnum_prop": 0.6717625899280576,
"repo_name": "awsdocs/aws-doc-sdk-examples",
"id": "4930917d574c4f041d2c957b9ca9d899e0198493",
"size": "2782",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "java/example_code/s3control/src/main/java/aws/example/s3control/CancelJob.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ABAP",
"bytes": "476653"
},
{
"name": "Batchfile",
"bytes": "900"
},
{
"name": "C",
"bytes": "3852"
},
{
"name": "C#",
"bytes": "2051923"
},
{
"name": "C++",
"bytes": "943634"
},
{
"name": "CMake",
"bytes": "82068"
},
{
"name": "CSS",
"bytes": "33378"
},
{
"name": "Dockerfile",
"bytes": "2243"
},
{
"name": "Go",
"bytes": "1764292"
},
{
"name": "HTML",
"bytes": "319090"
},
{
"name": "Java",
"bytes": "4966853"
},
{
"name": "JavaScript",
"bytes": "1655476"
},
{
"name": "Jupyter Notebook",
"bytes": "9749"
},
{
"name": "Kotlin",
"bytes": "1099902"
},
{
"name": "Makefile",
"bytes": "4922"
},
{
"name": "PHP",
"bytes": "1220594"
},
{
"name": "Python",
"bytes": "2507509"
},
{
"name": "Ruby",
"bytes": "500331"
},
{
"name": "Rust",
"bytes": "558811"
},
{
"name": "Shell",
"bytes": "63776"
},
{
"name": "Swift",
"bytes": "267325"
},
{
"name": "TypeScript",
"bytes": "119632"
}
],
"symlink_target": ""
} |
<?php
/**
* A class that provides shorthand functions to access/load files on the server.
*
* @author Leng Sheng Hong <[email protected]>
* @version $Id: DooController.php 1000 2009-07-7 18:27:22
* @package doo.uri
* @since 1.0
*/
class DooLoader
{
public $app;
/**
* Reads a file and send a header to force download it.
* @param string $file_str File name with absolute path to it
* @param bool $isLarge If True, the large file will be read chunk by chunk into the memory.
* @param string $rename Name to replace the file name that would be downloaded
*/
public function download($file, $isLarge = false, $rename = null)
{
if ($rename == null) {
if (strpos($file, '/') === false && strpos($file, '\\') === false) {
$filename = $file;
} else {
$filename = basename($file);
}
} else {
$filename = $rename;
}
$this->app->setHeader('Content-Description: File Transfer');
$this->app->setHeader('Content-Type: application/octet-stream');
$this->app->setHeader("Content-Disposition: attachment; filename=\"$filename\"");
$this->app->setHeader('Expires: 0');
$this->app->setHeader('Cache-Control: must-revalidate, post-check=0, pre-check=0');
$this->app->setHeader('Pragma: public');
$this->app->setHeader('Content-Length: ' . filesize($file));
ob_clean();
flush();
if ($isLarge) {
$this->readfile_chunked($file);
} else {
readfile($file);
}
}
/**
* Read a file and display its content chunk by chunk
* @param string $filename
* @param bool $retbytes
* @return mixed
*/
private function readfile_chunked($filename, $retbytes = true, $chunk_size = 1024)
{
$buffer = '';
$cnt = 0;
// $handle = fopen($filename, 'rb');
$handle = fopen($filename, 'rb');
if ($handle === false) {
return false;
}
while (!feof($handle)) {
$buffer = fread($handle, $chunk_size);
echo $buffer;
ob_flush();
flush();
if ($retbytes) {
$cnt += strlen($buffer);
}
}
$status = fclose($handle);
if ($retbytes && $status) {
return $cnt; // return num. bytes delivered like readfile() does.
}
return $status;
}
}
| {
"content_hash": "61e1c73466bedb14dfe165fb6b279eae",
"timestamp": "",
"source": "github",
"line_count": 82,
"max_line_length": 96,
"avg_line_length": 30.548780487804876,
"alnum_prop": 0.5305389221556887,
"repo_name": "darkredz/DooJ",
"id": "733e9acdd1f741ef9982abe4a016c010b4e98884",
"size": "2722",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mods/com.darkredz~dooj~1.0/dooframework/uri/DooLoader.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "186158"
},
{
"name": "HTML",
"bytes": "3567"
},
{
"name": "Java",
"bytes": "83386"
},
{
"name": "JavaScript",
"bytes": "1034969"
},
{
"name": "PHP",
"bytes": "1096275"
},
{
"name": "Shell",
"bytes": "107"
}
],
"symlink_target": ""
} |
export class SetterObserver {
constructor(taskQueue, obj, propertyName){
this.taskQueue = taskQueue;
this.obj = obj;
this.propertyName = propertyName;
this.callbacks = [];
this.queued = false;
this.observing = false;
this.isSVG = obj instanceof SVGElement;
}
getValue(){
return this.obj[this.propertyName];
}
setValue(newValue){
if(this.isSVG){
this.obj.setAttributeNS(null, this.propertyName, newValue);
}else{
this.obj[this.propertyName] = newValue;
}
}
getterValue(){
return this.currentValue;
}
setterValue(newValue){
var oldValue = this.currentValue;
if(oldValue != newValue){
if(!this.queued){
this.oldValue = oldValue;
this.queued = true;
this.taskQueue.queueMicroTask(this);
}
this.currentValue = newValue;
}
}
call(){
var callbacks = this.callbacks,
i = callbacks.length,
oldValue = this.oldValue,
newValue = this.currentValue;
this.queued = false;
while(i--) {
callbacks[i](newValue, oldValue);
}
}
subscribe(callback){
var callbacks = this.callbacks;
callbacks.push(callback);
if(!this.observing){
this.convertProperty();
}
return function(){
callbacks.splice(callbacks.indexOf(callback), 1);
};
}
convertProperty(){
this.observing = true;
this.currentValue = this.obj[this.propertyName];
this.setValue = this.setterValue;
this.getValue = this.getterValue;
Object.defineProperty(this.obj, this.propertyName, {
configurable: true,
enumerable: true,
get: this.getValue.bind(this),
set: this.setValue.bind(this)
});
}
}
export class OoObjectObserver {
constructor(obj){
this.obj = obj;
this.observers = {};
}
subscribe(propertyObserver, callback){
var callbacks = propertyObserver.callbacks;
callbacks.push(callback);
if(!this.observing){
this.observing = true;
Object.observe(this.obj, changes => this.handleChanges(changes), ['update', 'add']);
}
return function(){
callbacks.splice(callbacks.indexOf(callback), 1);
};
}
getObserver(propertyName){
var propertyObserver = this.observers[propertyName]
|| (this.observers[propertyName] = new OoPropertyObserver(this, this.obj, propertyName));
return propertyObserver;
}
handleChanges(changeRecords){
var updates = {},
observers = this.observers,
i = changeRecords.length;
while(i--) {
var change = changeRecords[i],
name = change.name;
if(!(name in updates)){
var observer = observers[name];
updates[name] = true;
if(observer){
observer.trigger(change.object[name], change.oldValue);
}
}
}
}
}
export class OoPropertyObserver {
constructor(owner, obj, propertyName){
this.owner = owner;
this.obj = obj;
this.propertyName = propertyName;
this.callbacks = [];
this.isSVG = obj instanceof SVGElement;
}
getValue(){
return this.obj[this.propertyName];
}
setValue(newValue){
if(this.isSVG){
this.obj.setAttributeNS(null, this.propertyName, newValue);
}else{
this.obj[this.propertyName] = newValue;
}
}
trigger(newValue, oldValue){
var callbacks = this.callbacks,
i = callbacks.length;
while(i--) {
callbacks[i](newValue, oldValue);
}
}
subscribe(callback){
return this.owner.subscribe(this, callback);
}
}
export class ElementObserver {
constructor(handler, element, propertyName){
this.element = element;
this.propertyName = propertyName;
this.callbacks = [];
this.oldValue = element[propertyName];
this.handler = handler;
}
getValue(){
return this.element[this.propertyName];
}
setValue(newValue){
this.element[this.propertyName] = newValue
this.call();
}
call(){
var callbacks = this.callbacks,
i = callbacks.length,
oldValue = this.oldValue,
newValue = this.getValue();
while(i--) {
callbacks[i](newValue, oldValue);
}
this.oldValue = newValue;
}
subscribe(callback){
var that = this;
if(!this.disposeHandler){
this.disposeHandler = this.handler
.subscribe(this.element, this.propertyName, this.call.bind(this));
}
var callbacks = this.callbacks;
callbacks.push(callback);
return function(){
callbacks.splice(callbacks.indexOf(callback), 1);
if(callback.length === 0){
that.disposeHandler();
that.disposeHandler = null;
}
};
}
} | {
"content_hash": "ac84f18a84224e2acdc898ae80475c18",
"timestamp": "",
"source": "github",
"line_count": 216,
"max_line_length": 95,
"avg_line_length": 21.60185185185185,
"alnum_prop": 0.6240891555936562,
"repo_name": "behzad88/binding",
"id": "413d377d43dff2cd14c4458c7428c6c3b1d02308",
"size": "4666",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dist/es6/property-observation.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "572034"
}
],
"symlink_target": ""
} |
package jp.co.yahoo.dataplatform.mds.spread.analyzer;
import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.Arguments;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.params.provider.Arguments.arguments;
import jp.co.yahoo.dataplatform.schema.objects.*;
import jp.co.yahoo.dataplatform.mds.spread.Spread;
import jp.co.yahoo.dataplatform.mds.spread.column.NullColumn;
import jp.co.yahoo.dataplatform.mds.spread.column.ColumnType;
public class TestBooleanColumnAnalizeResult {
@Test
public void T_getAnalizer_1() throws IOException{
BooleanColumnAnalizeResult result = new BooleanColumnAnalizeResult( "name" , 100 , true , 10 , 90 , 2 , 40 , 50 );
assertEquals( "name" , result.getColumnName() );
assertEquals( ColumnType.BOOLEAN , result.getColumnType() );
assertEquals( 100 , result.getColumnSize() );
assertEquals( true , result.maybeSorted() );
assertEquals( 10 , result.getNullCount() );
assertEquals( 90 , result.getRowCount() );
assertEquals( 2 , result.getUniqCount() );
assertEquals( 90 , result.getLogicalDataSize() );
assertEquals( 40 , result.getTrueCount() );
assertEquals( 50 , result.getFalseCount() );
}
}
| {
"content_hash": "a688f53bc3149afe8546351a4418211c",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 118,
"avg_line_length": 34.976190476190474,
"alnum_prop": 0.7542545949625595,
"repo_name": "yahoojapan/multiple-dimension-spread",
"id": "33180fb307d147a2ad2320133bffc72b357ff580",
"size": "2281",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/common/src/test/java/jp/co/yahoo/dataplatform/mds/spread/analyzer/TestBooleanColumnAnalizeResult.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "2658225"
},
{
"name": "Shell",
"bytes": "15132"
}
],
"symlink_target": ""
} |
@protocol GWCollapsibleTableDataSource <NSObject>
- (BOOL)tableView:(UITableView *)tableView canCollapseSection:(NSInteger)section;
- (UITableViewCell *)tableView:(UITableView *)tableView headerCellForCollapsibleSection:(NSInteger)section;
- (UITableViewCell *)tableView:(UITableView *)tableView bodyCellForRowAtIndexPath:(NSIndexPath *)indexPath;
- (NSInteger)tableView:(UITableView *)tableView numberOfBodyRowsInSection:(NSInteger)section;
// TODO: Support Editing & Reordering Methods
@end
@protocol GWCollapsibleTableDelegate <NSObject>
- (void)tableView:(UITableView *)tableView didSelectBodyRowAtIndexPath:(NSIndexPath *)indexPath;
@optional
- (void)tableView:(UITableView *)tableView willExpandSection:(NSInteger)section;
- (void)tableView:(UITableView *)tableView willCollapseSection:(NSInteger)section;
// TODO: Support Extra Selection Management Methods
// TODO: Support Editing & Reordering Methods
@end
| {
"content_hash": "a89b6f58db26ffb59ae374f1e9f46a16",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 107,
"avg_line_length": 38.5,
"alnum_prop": 0.8138528138528138,
"repo_name": "gregwym/GWCollapsibleTable",
"id": "04eeb35dbb8e1088d8938a9f4e46dcff7b813d23",
"size": "1158",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "CollapsibleTable/GWCollapsibleTable/GWCollapsibleTable.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "19177"
},
{
"name": "Ruby",
"bytes": "732"
}
],
"symlink_target": ""
} |
import time
import pytest
from Util import timing
def test_near_full_load_fps_timer():
# example preliminary test
start = time.time()
time_total = 2
fps = 10
num_iterations = time_total*fps
sleep = timing.create_fps_timer(fps)
sleep() # to initialize it
for _ in range(num_iterations-1): # -1 because of the first sleep
time.sleep(1/(fps+0.05)) # simulate load very close to full load
sleep()
end_time = time.time()-start
assert end_time == pytest.approx(time_total, 0.1)
def test_no_load_fps_timer():
# example preliminary test
start = time.time()
time_total = 2
fps = 10
num_iterations = time_total*fps
sleep = timing.create_fps_timer(fps)
sleep() # to initialize it
for _ in range(num_iterations-1): # -1 because of the first sleep
sleep()
end_time = time.time()-start
assert end_time == pytest.approx(time_total, 0.1)
def test_callback_called_fps_timer():
fps = 10
callback_called = False
def mock_callback(time_var): # pylint: disable=unused-argument
nonlocal callback_called
callback_called = True
sleep = timing.create_fps_timer(fps, on_miss_callback=mock_callback)
sleep()
time.sleep(0.2)
sleep()
assert callback_called is True
def test_callback_delay_fps_timer():
fps = 10
callback_time = None
def mock_callback(time_var):
nonlocal callback_time
callback_time = time_var
sleep = timing.create_fps_timer(fps, on_miss_callback=mock_callback)
sleep()
time.sleep(0.2)
sleep()
assert callback_time >= 0
| {
"content_hash": "4e1be0b6073cfb0ad1eb0e77a339e996",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 73,
"avg_line_length": 27.948275862068964,
"alnum_prop": 0.6440468846391116,
"repo_name": "RoboCupULaval/StrategyIA",
"id": "9714728429456fc79cb78d1ee93a16bd875c63c3",
"size": "1621",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev",
"path": "tests/Util/test_timing.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "528666"
},
{
"name": "Shell",
"bytes": "2438"
}
],
"symlink_target": ""
} |
//===--- ImportDecl.cpp - Import Clang Declarations -----------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements support for importing Clang declarations into Swift.
//
//===----------------------------------------------------------------------===//
#include "ImporterImpl.h"
#include "swift/Strings.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Attr.h"
#include "swift/AST/Builtins.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Expr.h"
#include "swift/AST/Module.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/Stmt.h"
#include "swift/AST/Types.h"
#include "swift/Basic/Fallthrough.h"
#include "swift/ClangImporter/ClangModule.h"
#include "swift/Parse/Lexer.h"
#include "swift/Config.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Attr.h"
#include "clang/AST/DeclVisitor.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/Lookup.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/Path.h"
#include <algorithm>
#define DEBUG_TYPE "Clang module importer"
STATISTIC(NumTotalImportedEntities, "# of imported clang entities");
STATISTIC(NumFactoryMethodsAsInitializers,
"# of factory methods mapped to initializers");
using namespace swift;
using namespace importer;
namespace swift {
namespace inferred_attributes {
enum {
requires_stored_property_inits = 0x01
};
}
}
static bool isInSystemModule(DeclContext *D) {
if (cast<ClangModuleUnit>(D->getModuleScopeContext())->isSystemModule())
return true;
return false;
}
/// Create a typedpattern(namedpattern(decl))
static Pattern *createTypedNamedPattern(VarDecl *decl) {
ASTContext &Ctx = decl->getASTContext();
Type ty = decl->getType();
Pattern *P = new (Ctx) NamedPattern(decl);
P->setType(ty);
P->setImplicit();
P = new (Ctx) TypedPattern(P, TypeLoc::withoutLoc(ty));
P->setType(ty);
P->setImplicit();
return P;
}
#ifndef NDEBUG
static bool verifyNameMapping(MappedTypeNameKind NameMapping,
StringRef left, StringRef right) {
return NameMapping == MappedTypeNameKind::DoNothing || left != right;
}
#endif
/// \brief Map a well-known C type to a swift type from the standard library.
///
/// \param IsError set to true when we know the corresponding swift type name,
/// but we could not find it. (For example, the type was not defined in the
/// standard library or the required standard library module was not imported.)
/// This should be a hard error, we don't want to map the type only sometimes.
///
/// \returns A pair of a swift type and its name that corresponds to a given
/// C type.
static std::pair<Type, StringRef>
getSwiftStdlibType(const clang::TypedefNameDecl *D,
Identifier Name,
ClangImporter::Implementation &Impl,
bool *IsError, MappedTypeNameKind &NameMapping) {
*IsError = false;
MappedCTypeKind CTypeKind;
unsigned Bitwidth;
StringRef SwiftModuleName;
bool IsSwiftModule; // True if SwiftModuleName == STDLIB_NAME.
StringRef SwiftTypeName;
bool CanBeMissing;
do {
#define MAP_TYPE(C_TYPE_NAME, C_TYPE_KIND, C_TYPE_BITWIDTH, \
SWIFT_MODULE_NAME, SWIFT_TYPE_NAME, \
CAN_BE_MISSING, C_NAME_MAPPING) \
if (Name.str() == C_TYPE_NAME) { \
CTypeKind = MappedCTypeKind::C_TYPE_KIND; \
Bitwidth = C_TYPE_BITWIDTH; \
if (StringRef(SWIFT_MODULE_NAME) == StringRef(STDLIB_NAME)) \
IsSwiftModule = true; \
else { \
IsSwiftModule = false; \
SwiftModuleName = SWIFT_MODULE_NAME; \
} \
SwiftTypeName = SWIFT_TYPE_NAME; \
CanBeMissing = CAN_BE_MISSING; \
NameMapping = MappedTypeNameKind::C_NAME_MAPPING; \
assert(verifyNameMapping(MappedTypeNameKind::C_NAME_MAPPING, \
C_TYPE_NAME, SWIFT_TYPE_NAME) && \
"MappedTypes.def: Identical names must use DoNothing"); \
break; \
}
#include "MappedTypes.def"
// We did not find this type, thus it is not mapped.
return std::make_pair(Type(), "");
} while(0);
clang::ASTContext &ClangCtx = Impl.getClangASTContext();
auto ClangType = D->getUnderlyingType();
// If the C type does not have the expected size, don't import it as a stdlib
// type.
unsigned ClangTypeSize = ClangCtx.getTypeSize(ClangType);
if (Bitwidth != 0 && Bitwidth != ClangTypeSize)
return std::make_pair(Type(), "");
// Check other expected properties of the C type.
switch(CTypeKind) {
case MappedCTypeKind::UnsignedInt:
if (!ClangType->isUnsignedIntegerType())
return std::make_pair(Type(), "");
break;
case MappedCTypeKind::SignedInt:
if (!ClangType->isSignedIntegerType())
return std::make_pair(Type(), "");
break;
case MappedCTypeKind::UnsignedWord:
if (ClangTypeSize != 64 && ClangTypeSize != 32)
return std::make_pair(Type(), "");
if (!ClangType->isUnsignedIntegerType())
return std::make_pair(Type(), "");
break;
case MappedCTypeKind::SignedWord:
if (ClangTypeSize != 64 && ClangTypeSize != 32)
return std::make_pair(Type(), "");
if (!ClangType->isSignedIntegerType())
return std::make_pair(Type(), "");
break;
case MappedCTypeKind::FloatIEEEsingle:
case MappedCTypeKind::FloatIEEEdouble:
case MappedCTypeKind::FloatX87DoubleExtended: {
if (!ClangType->isFloatingType())
return std::make_pair(Type(), "");
const llvm::fltSemantics &Sem = ClangCtx.getFloatTypeSemantics(ClangType);
switch(CTypeKind) {
case MappedCTypeKind::FloatIEEEsingle:
assert(Bitwidth == 32 && "FloatIEEEsingle should be 32 bits wide");
if (&Sem != &APFloat::IEEEsingle)
return std::make_pair(Type(), "");
break;
case MappedCTypeKind::FloatIEEEdouble:
assert(Bitwidth == 64 && "FloatIEEEdouble should be 64 bits wide");
if (&Sem != &APFloat::IEEEdouble)
return std::make_pair(Type(), "");
break;
case MappedCTypeKind::FloatX87DoubleExtended:
assert(Bitwidth == 80 && "FloatX87DoubleExtended should be 80 bits wide");
if (&Sem != &APFloat::x87DoubleExtended)
return std::make_pair(Type(), "");
break;
default:
llvm_unreachable("should see only floating point types here");
}
}
break;
case MappedCTypeKind::VaList:
if (ClangTypeSize != ClangCtx.getTypeSize(ClangCtx.VoidPtrTy))
return std::make_pair(Type(), "");
break;
case MappedCTypeKind::ObjCBool:
if (!ClangCtx.hasSameType(ClangType, ClangCtx.ObjCBuiltinBoolTy) &&
!(ClangCtx.getBOOLDecl() &&
ClangCtx.hasSameType(ClangType, ClangCtx.getBOOLType())))
return std::make_pair(Type(), "");
break;
case MappedCTypeKind::ObjCSel:
if (!ClangCtx.hasSameType(ClangType, ClangCtx.getObjCSelType()) &&
!ClangCtx.hasSameType(ClangType,
ClangCtx.getObjCSelRedefinitionType()))
return std::make_pair(Type(), "");
break;
case MappedCTypeKind::ObjCId:
if (!ClangCtx.hasSameType(ClangType, ClangCtx.getObjCIdType()) &&
!ClangCtx.hasSameType(ClangType,
ClangCtx.getObjCIdRedefinitionType()))
return std::make_pair(Type(), "");
break;
case MappedCTypeKind::ObjCClass:
if (!ClangCtx.hasSameType(ClangType, ClangCtx.getObjCClassType()) &&
!ClangCtx.hasSameType(ClangType,
ClangCtx.getObjCClassRedefinitionType()))
return std::make_pair(Type(), "");
break;
case MappedCTypeKind::CGFloat:
if (!ClangType->isFloatingType())
return std::make_pair(Type(), "");
break;
case MappedCTypeKind::Block:
if (!ClangType->isBlockPointerType())
return std::make_pair(Type(), "");
break;
}
Module *M;
if (IsSwiftModule)
M = Impl.getStdlibModule();
else
M = Impl.getNamedModule(SwiftModuleName);
if (!M) {
// User did not import the library module that contains the type we want to
// substitute.
*IsError = true;
return std::make_pair(Type(), "");
}
Type SwiftType = Impl.getNamedSwiftType(M, SwiftTypeName);
if (!SwiftType && !CanBeMissing) {
// The required type is not defined in the standard library.
*IsError = true;
return std::make_pair(Type(), "");
}
return std::make_pair(SwiftType, SwiftTypeName);
}
static bool isNSDictionaryMethod(const clang::ObjCMethodDecl *MD,
clang::Selector cmd) {
if (MD->getSelector() != cmd)
return false;
if (isa<clang::ObjCProtocolDecl>(MD->getDeclContext()))
return false;
if (MD->getClassInterface()->getName() != "NSDictionary")
return false;
return true;
}
/// Build the \c rawValue property trivial getter for an option set or
/// unknown enum.
///
/// \code
/// struct NSSomeOptionSet : OptionSetType {
/// let rawValue: Raw
/// }
/// \endcode
static FuncDecl *makeRawValueTrivialGetter(ClangImporter::Implementation &Impl,
StructDecl *optionSetDecl,
ValueDecl *rawDecl) {
ASTContext &C = Impl.SwiftContext;
auto rawType = rawDecl->getType();
auto *selfDecl = ParamDecl::createSelf(SourceLoc(), optionSetDecl);
ParameterList *params[] = {
ParameterList::createWithoutLoc(selfDecl),
ParameterList::createEmpty(C)
};
Type toRawType = ParameterList::getFullType(rawType, params);
FuncDecl *getterDecl = FuncDecl::create(
C, SourceLoc(), StaticSpellingKind::None, SourceLoc(),
DeclName(), SourceLoc(), SourceLoc(), SourceLoc(), nullptr, toRawType,
params,
TypeLoc::withoutLoc(rawType), optionSetDecl);
getterDecl->setImplicit();
getterDecl->setBodyResultType(rawType);
getterDecl->setInterfaceType(toRawType);
getterDecl->setAccessibility(Accessibility::Public);
// Don't bother synthesizing the body if we've already finished type-checking.
if (Impl.hasFinishedTypeChecking())
return getterDecl;
auto selfRef = new (C) DeclRefExpr(selfDecl, DeclNameLoc(), /*implicit*/ true);
auto valueRef = new (C) MemberRefExpr(selfRef, SourceLoc(),
rawDecl, DeclNameLoc(),
/*implicit*/ true);
auto valueRet = new (C) ReturnStmt(SourceLoc(), valueRef);
auto body = BraceStmt::create(C, SourceLoc(), ASTNode(valueRet),
SourceLoc(),
/*implicit*/ true);
getterDecl->setBody(body);
C.addExternalDecl(getterDecl);
return getterDecl;
}
/// Build the \c rawValue property trivial setter for an unknown enum.
///
/// \code
/// struct SomeRandomCEnum {
/// var rawValue: Raw
/// }
/// \endcode
static FuncDecl *makeRawValueTrivialSetter(ClangImporter::Implementation &Impl,
StructDecl *importedDecl,
ValueDecl *rawDecl) {
// FIXME: Largely duplicated from the type checker.
ASTContext &C = Impl.SwiftContext;
auto rawType = rawDecl->getType();
auto *selfDecl = ParamDecl::createSelf(SourceLoc(), importedDecl,
/*static*/false, /*inout*/true);
auto *newValueDecl = new (C) ParamDecl(/*IsLet*/true, SourceLoc(),SourceLoc(),
Identifier(), SourceLoc(),
C.Id_value, rawType, importedDecl);
newValueDecl->setImplicit();
ParameterList *params[] = {
ParameterList::createWithoutLoc(selfDecl),
ParameterList::createWithoutLoc(newValueDecl)
};
Type voidTy = TupleType::getEmpty(C);
FuncDecl *setterDecl = FuncDecl::create(
C, SourceLoc(), StaticSpellingKind::None, SourceLoc(),
DeclName(), SourceLoc(), SourceLoc(), SourceLoc(), nullptr, Type(), params,
TypeLoc::withoutLoc(voidTy), importedDecl);
setterDecl->setImplicit();
setterDecl->setMutating();
setterDecl->setType(ParameterList::getFullType(voidTy, params));
setterDecl->setInterfaceType(ParameterList::getFullType(voidTy, params));
setterDecl->setBodyResultType(voidTy);
setterDecl->setAccessibility(Accessibility::Public);
// Don't bother synthesizing the body if we've already finished type-checking.
if (Impl.hasFinishedTypeChecking())
return setterDecl;
auto selfRef = new (C) DeclRefExpr(selfDecl, DeclNameLoc(), /*implicit*/ true);
auto dest = new (C) MemberRefExpr(selfRef, SourceLoc(), rawDecl, DeclNameLoc(),
/*implicit*/ true);
auto paramRef = new (C) DeclRefExpr(newValueDecl, DeclNameLoc(),
/*implicit*/true);
auto assign = new (C) AssignExpr(dest, SourceLoc(), paramRef,
/*implicit*/true);
auto body = BraceStmt::create(C, SourceLoc(), { assign }, SourceLoc(),
/*implicit*/ true);
setterDecl->setBody(body);
C.addExternalDecl(setterDecl);
return setterDecl;
}
// Build the init(rawValue:) initializer for an imported NS_ENUM.
// enum NSSomeEnum: RawType {
// init?(rawValue: RawType) {
// self = Builtin.reinterpretCast(rawValue)
// }
// }
// Unlike a standard init(rawValue:) enum initializer, this does a reinterpret
// cast in order to preserve unknown or future cases from C.
static ConstructorDecl *
makeEnumRawValueConstructor(ClangImporter::Implementation &Impl,
EnumDecl *enumDecl) {
ASTContext &C = Impl.SwiftContext;
auto enumTy = enumDecl->getDeclaredTypeInContext();
auto metaTy = MetatypeType::get(enumTy);
auto selfDecl = ParamDecl::createSelf(SourceLoc(), enumDecl,
/*static*/false, /*inout*/true);
auto param = new (C) ParamDecl(/*let*/ true, SourceLoc(),
SourceLoc(), C.Id_rawValue,
SourceLoc(), C.Id_rawValue,
enumDecl->getRawType(),
enumDecl);
auto paramPL = ParameterList::createWithoutLoc(param);
DeclName name(C, C.Id_init, paramPL);
auto *ctorDecl = new (C) ConstructorDecl(name, enumDecl->getLoc(),
OTK_Optional, SourceLoc(),
selfDecl, paramPL,
nullptr, SourceLoc(), enumDecl);
ctorDecl->setImplicit();
ctorDecl->setAccessibility(Accessibility::Public);
auto optEnumTy = OptionalType::get(enumTy);
auto fnTy = FunctionType::get(paramPL->getType(C), optEnumTy);
auto allocFnTy = FunctionType::get(metaTy, fnTy);
auto initFnTy = FunctionType::get(enumTy, fnTy);
ctorDecl->setType(allocFnTy);
ctorDecl->setInterfaceType(allocFnTy);
ctorDecl->setInitializerType(initFnTy);
// Don't bother synthesizing the body if we've already finished type-checking.
if (Impl.hasFinishedTypeChecking())
return ctorDecl;
auto selfRef = new (C) DeclRefExpr(selfDecl, DeclNameLoc(), /*implicit*/true);
auto paramRef = new (C) DeclRefExpr(param, DeclNameLoc(),
/*implicit*/ true);
auto reinterpretCast
= cast<FuncDecl>(getBuiltinValueDecl(C,C.getIdentifier("reinterpretCast")));
auto reinterpretCastRef
= new (C) DeclRefExpr(reinterpretCast, DeclNameLoc(), /*implicit*/ true);
auto reinterpreted = new (C) CallExpr(reinterpretCastRef, paramRef,
/*implicit*/ true);
auto assign = new (C) AssignExpr(selfRef, SourceLoc(), reinterpreted,
/*implicit*/ true);
auto body = BraceStmt::create(C, SourceLoc(), ASTNode(assign), SourceLoc(),
/*implicit*/ true);
ctorDecl->setBody(body);
C.addExternalDecl(ctorDecl);
return ctorDecl;
}
// Build the rawValue getter for an imported NS_ENUM.
// enum NSSomeEnum: RawType {
// var rawValue: RawType {
// return Builtin.reinterpretCast(self)
// }
// }
// Unlike a standard init(rawValue:) enum initializer, this does a reinterpret
// cast in order to preserve unknown or future cases from C.
static FuncDecl *makeEnumRawValueGetter(ClangImporter::Implementation &Impl,
EnumDecl *enumDecl,
VarDecl *rawValueDecl) {
ASTContext &C = Impl.SwiftContext;
auto selfDecl = ParamDecl::createSelf(SourceLoc(), enumDecl);
ParameterList *params[] = {
ParameterList::createWithoutLoc(selfDecl),
ParameterList::createEmpty(C)
};
auto getterDecl =
FuncDecl::create(C, SourceLoc(), StaticSpellingKind::None, SourceLoc(),
DeclName(), SourceLoc(), SourceLoc(), SourceLoc(), nullptr,
Type(), params,
TypeLoc::withoutLoc(enumDecl->getRawType()), enumDecl);
getterDecl->setImplicit();
getterDecl->setType(ParameterList::getFullType(enumDecl->getRawType(),
params));
getterDecl->setInterfaceType(ParameterList::getFullType(enumDecl->getRawType(),
params));
getterDecl->setBodyResultType(enumDecl->getRawType());
getterDecl->setAccessibility(Accessibility::Public);
rawValueDecl->makeComputed(SourceLoc(), getterDecl, nullptr, nullptr,
SourceLoc());
// Don't bother synthesizing the body if we've already finished type-checking.
if (Impl.hasFinishedTypeChecking())
return getterDecl;
auto selfRef = new (C) DeclRefExpr(selfDecl, DeclNameLoc(), /*implicit*/true);
auto reinterpretCast
= cast<FuncDecl>(getBuiltinValueDecl(C, C.getIdentifier("reinterpretCast")));
auto reinterpretCastRef
= new (C) DeclRefExpr(reinterpretCast, DeclNameLoc(), /*implicit*/ true);
auto reinterpreted = new (C) CallExpr(reinterpretCastRef, selfRef,
/*implicit*/ true);
auto ret = new (C) ReturnStmt(SourceLoc(), reinterpreted);
auto body = BraceStmt::create(C, SourceLoc(), ASTNode(ret), SourceLoc(),
/*implicit*/ true);
getterDecl->setBody(body);
C.addExternalDecl(getterDecl);
return getterDecl;
}
static FuncDecl *makeFieldGetterDecl(ClangImporter::Implementation &Impl,
StructDecl *importedDecl,
VarDecl *importedFieldDecl,
ClangNode clangNode = ClangNode()) {
auto &C = Impl.SwiftContext;
auto selfDecl = ParamDecl::createSelf(SourceLoc(), importedDecl);
ParameterList *params[] = {
ParameterList::createWithoutLoc(selfDecl),
ParameterList::createEmpty(C)
};
auto getterType = importedFieldDecl->getType();
auto getterDecl = FuncDecl::create(C, importedFieldDecl->getLoc(),
StaticSpellingKind::None,
SourceLoc(), DeclName(), SourceLoc(),
SourceLoc(), SourceLoc(), nullptr, Type(),
params, TypeLoc::withoutLoc(getterType),
importedDecl, clangNode);
getterDecl->setAccessibility(Accessibility::Public);
getterDecl->setType(ParameterList::getFullType(getterType, params));
getterDecl->setInterfaceType(ParameterList::getFullType(getterType, params));
getterDecl->setBodyResultType(getterType);
return getterDecl;
}
static FuncDecl *makeFieldSetterDecl(ClangImporter::Implementation &Impl,
StructDecl *importedDecl,
VarDecl *importedFieldDecl,
ClangNode clangNode = ClangNode()) {
auto &C = Impl.SwiftContext;
auto selfDecl = ParamDecl::createSelf(SourceLoc(), importedDecl,
/*isStatic*/false, /*isInOut*/true);
auto newValueDecl = new (C) ParamDecl(/*isLet */ true,SourceLoc(),SourceLoc(),
Identifier(), SourceLoc(), C.Id_value,
importedFieldDecl->getType(),
importedDecl);
ParameterList *params[] = {
ParameterList::createWithoutLoc(selfDecl),
ParameterList::createWithoutLoc(newValueDecl),
};
auto voidTy = TupleType::getEmpty(C);
auto setterDecl = FuncDecl::create(C, SourceLoc(), StaticSpellingKind::None,
SourceLoc(), DeclName(), SourceLoc(),
SourceLoc(), SourceLoc(), nullptr, Type(),
params, TypeLoc::withoutLoc(voidTy),
importedDecl, clangNode);
setterDecl->setType(ParameterList::getFullType(voidTy, params));
setterDecl->setInterfaceType(ParameterList::getFullType(voidTy, params));
setterDecl->setBodyResultType(voidTy);
setterDecl->setAccessibility(Accessibility::Public);
setterDecl->setMutating();
return setterDecl;
}
/// Build the union field getter and setter.
///
/// \code
/// struct SomeImportedUnion {
/// var myField: Int {
/// get {
/// return Builtin.reinterpretCast(self)
/// }
/// set(newValue) {
/// Builtin.initialize(Builtin.addressof(self), newValue))
/// }
/// }
/// }
/// \endcode
///
/// \returns a pair of the getter and setter function decls.
static std::pair<FuncDecl *, FuncDecl *>
makeUnionFieldAccessors(ClangImporter::Implementation &Impl,
StructDecl *importedUnionDecl,
VarDecl *importedFieldDecl) {
auto &C = Impl.SwiftContext;
auto getterDecl = makeFieldGetterDecl(Impl,
importedUnionDecl,
importedFieldDecl);
auto setterDecl = makeFieldSetterDecl(Impl,
importedUnionDecl,
importedFieldDecl);
importedFieldDecl->makeComputed(SourceLoc(), getterDecl, setterDecl, nullptr,
SourceLoc());
// Don't bother synthesizing the body if we've already finished type-checking.
if (Impl.hasFinishedTypeChecking())
return { getterDecl, setterDecl };
// Synthesize the getter body
{
auto selfDecl = getterDecl->getImplicitSelfDecl();
auto selfRef = new (C) DeclRefExpr(selfDecl, DeclNameLoc(),
/*implicit*/ true);
auto reinterpretCast = cast<FuncDecl>(getBuiltinValueDecl(
C, C.getIdentifier("reinterpretCast")));
auto reinterpretCastRef
= new (C) DeclRefExpr(reinterpretCast, DeclNameLoc(), /*implicit*/ true);
auto reinterpreted = new (C) CallExpr(reinterpretCastRef, selfRef,
/*implicit*/ true);
auto ret = new (C) ReturnStmt(SourceLoc(), reinterpreted);
auto body = BraceStmt::create(C, SourceLoc(), ASTNode(ret), SourceLoc(),
/*implicit*/ true);
getterDecl->setBody(body);
C.addExternalDecl(getterDecl);
}
// Synthesize the setter body
{
auto inoutSelfDecl = setterDecl->getImplicitSelfDecl();
auto inoutSelfRef = new (C) DeclRefExpr(inoutSelfDecl, DeclNameLoc(),
/*implicit*/ true);
auto inoutSelf = new (C) InOutExpr(SourceLoc(), inoutSelfRef,
InOutType::get(importedUnionDecl->getType()), /*implicit*/ true);
auto newValueDecl = setterDecl->getParameterList(1)->get(0);
auto newValueRef = new (C) DeclRefExpr(newValueDecl, DeclNameLoc(),
/*implicit*/ true);
auto addressofFn = cast<FuncDecl>(getBuiltinValueDecl(
C, C.getIdentifier("addressof")));
auto addressofFnRef
= new (C) DeclRefExpr(addressofFn, DeclNameLoc(), /*implicit*/ true);
auto selfPointer = new (C) CallExpr(addressofFnRef, inoutSelf,
/*implicit*/ true);
auto initializeFn = cast<FuncDecl>(getBuiltinValueDecl(
C, C.getIdentifier("initialize")));
auto initializeFnRef
= new (C) DeclRefExpr(initializeFn, DeclNameLoc(), /*implicit*/ true);
auto initializeArgs = TupleExpr::createImplicit(C,
{ newValueRef, selfPointer },
{});
auto initialize = new (C) CallExpr(initializeFnRef, initializeArgs,
/*implicit*/ true);
auto body = BraceStmt::create(C, SourceLoc(), { initialize }, SourceLoc(),
/*implicit*/ true);
setterDecl->setBody(body);
C.addExternalDecl(setterDecl);
}
return { getterDecl, setterDecl };
}
static clang::DeclarationName
getAccessorDeclarationName(clang::ASTContext &Ctx,
StructDecl *structDecl,
VarDecl *fieldDecl,
const char *suffix) {
std::string id;
llvm::raw_string_ostream IdStream(id);
IdStream << "$" << structDecl->getName()
<< "$" << fieldDecl->getName()
<< "$" << suffix;
return clang::DeclarationName(&Ctx.Idents.get(IdStream.str()));
}
/// Build the bitfield getter and setter using Clang.
///
/// \code
/// static inline int get(RecordType self) {
/// return self.field;
/// }
/// static inline void set(int newValue, RecordType *self) {
/// self->field = newValue;
/// }
/// \endcode
///
/// \returns a pair of the getter and setter function decls.
static std::pair<FuncDecl *, FuncDecl *>
makeBitFieldAccessors(ClangImporter::Implementation &Impl,
clang::RecordDecl *structDecl,
StructDecl *importedStructDecl,
clang::FieldDecl *fieldDecl,
VarDecl *importedFieldDecl) {
clang::ASTContext &Ctx = Impl.getClangASTContext();
// Getter: static inline FieldType get(RecordType self);
auto recordType = Ctx.getRecordType(structDecl);
auto recordPointerType = Ctx.getPointerType(recordType);
auto fieldType = fieldDecl->getType();
auto fieldNameInfo = clang::DeclarationNameInfo(fieldDecl->getDeclName(),
clang::SourceLocation());
auto cGetterName = getAccessorDeclarationName(Ctx, importedStructDecl,
importedFieldDecl, "getter");
auto cGetterType = Ctx.getFunctionType(fieldDecl->getType(),
recordType,
clang::FunctionProtoType::ExtProtoInfo());
auto cGetterTypeInfo = Ctx.getTrivialTypeSourceInfo(cGetterType);
auto cGetterDecl = clang::FunctionDecl::Create(Ctx,
structDecl->getDeclContext(),
clang::SourceLocation(),
clang::SourceLocation(),
cGetterName,
cGetterType,
cGetterTypeInfo,
clang::SC_Static);
cGetterDecl->setImplicitlyInline();
assert(!cGetterDecl->isExternallyVisible());
auto getterDecl = makeFieldGetterDecl(Impl,
importedStructDecl,
importedFieldDecl,
cGetterDecl);
// Setter: static inline void set(FieldType newValue, RecordType *self);
SmallVector<clang::QualType, 8> cSetterParamTypes;
cSetterParamTypes.push_back(fieldType);
cSetterParamTypes.push_back(recordPointerType);
auto cSetterName = getAccessorDeclarationName(Ctx, importedStructDecl,
importedFieldDecl, "setter");
auto cSetterType = Ctx.getFunctionType(Ctx.VoidTy,
cSetterParamTypes,
clang::FunctionProtoType::ExtProtoInfo());
auto cSetterTypeInfo = Ctx.getTrivialTypeSourceInfo(cSetterType);
auto cSetterDecl = clang::FunctionDecl::Create(Ctx,
structDecl->getDeclContext(),
clang::SourceLocation(),
clang::SourceLocation(),
cSetterName,
cSetterType,
cSetterTypeInfo,
clang::SC_Static);
cSetterDecl->setImplicitlyInline();
assert(!cSetterDecl->isExternallyVisible());
auto setterDecl = makeFieldSetterDecl(Impl,
importedStructDecl,
importedFieldDecl,
cSetterDecl);
importedFieldDecl->makeComputed(SourceLoc(),
getterDecl,
setterDecl,
nullptr,
SourceLoc());
// Don't bother synthesizing the body if we've already finished type-checking.
if (Impl.hasFinishedTypeChecking())
return { getterDecl, setterDecl };
// Synthesize the getter body
{
auto cGetterSelfId = nullptr;
auto recordTypeInfo = Ctx.getTrivialTypeSourceInfo(recordType);
auto cGetterSelf = clang::ParmVarDecl::Create(Ctx, cGetterDecl,
clang::SourceLocation(),
clang::SourceLocation(),
cGetterSelfId,
recordType,
recordTypeInfo,
clang::SC_None,
nullptr);
cGetterDecl->setParams(cGetterSelf);
auto cGetterSelfExpr = new (Ctx) clang::DeclRefExpr(cGetterSelf, false,
recordType,
clang::VK_RValue,
clang::SourceLocation());
auto cGetterExpr = new (Ctx) clang::MemberExpr(cGetterSelfExpr,
/*isarrow=*/ false,
clang::SourceLocation(),
fieldDecl,
fieldNameInfo,
fieldType,
clang::VK_RValue,
clang::OK_BitField);
auto cGetterBody = new (Ctx) clang::ReturnStmt(clang::SourceLocation(),
cGetterExpr,
nullptr);
cGetterDecl->setBody(cGetterBody);
Impl.registerExternalDecl(getterDecl);
}
// Synthesize the setter body
{
SmallVector<clang::ParmVarDecl *, 2> cSetterParams;
auto fieldTypeInfo = Ctx.getTrivialTypeSourceInfo(fieldType);
auto cSetterValue = clang::ParmVarDecl::Create(Ctx, cSetterDecl,
clang::SourceLocation(),
clang::SourceLocation(),
/* nameID? */ nullptr,
fieldType,
fieldTypeInfo,
clang::SC_None,
nullptr);
cSetterParams.push_back(cSetterValue);
auto recordPointerTypeInfo = Ctx.getTrivialTypeSourceInfo(recordPointerType);
auto cSetterSelf = clang::ParmVarDecl::Create(Ctx, cSetterDecl,
clang::SourceLocation(),
clang::SourceLocation(),
/* nameID? */ nullptr,
recordPointerType,
recordPointerTypeInfo,
clang::SC_None,
nullptr);
cSetterParams.push_back(cSetterSelf);
cSetterDecl->setParams(cSetterParams);
auto cSetterSelfExpr = new (Ctx) clang::DeclRefExpr(cSetterSelf, false,
recordPointerType,
clang::VK_RValue,
clang::SourceLocation());
auto cSetterMemberExpr = new (Ctx) clang::MemberExpr(cSetterSelfExpr,
/*isarrow=*/ true,
clang::SourceLocation(),
fieldDecl,
fieldNameInfo,
fieldType,
clang::VK_LValue,
clang::OK_BitField);
auto cSetterValueExpr = new (Ctx) clang::DeclRefExpr(cSetterValue, false,
fieldType,
clang::VK_RValue,
clang::SourceLocation());
auto cSetterExpr = new (Ctx) clang::BinaryOperator(cSetterMemberExpr,
cSetterValueExpr,
clang::BO_Assign,
fieldType,
clang::VK_RValue,
clang::OK_Ordinary,
clang::SourceLocation(),
/*fpContractable=*/ false);
cSetterDecl->setBody(cSetterExpr);
Impl.registerExternalDecl(setterDecl);
}
return { getterDecl, setterDecl };
}
/// \brief Create a declaration name for anonymous enums, unions and structs.
///
/// Since Swift does not natively support these features, we fake them by
/// importing them as declarations with generated names. The generated name
/// is derived from the name of the field in the outer type. Since the
/// anonymous type is imported as a nested type of the outer type, this
/// generated name will most likely be unique.
static Identifier getClangDeclName(ClangImporter::Implementation &Impl,
const clang::TagDecl *decl) {
// Import the name of this declaration.
Identifier name = Impl.importFullName(decl).Imported.getBaseName();
if (!name.empty()) return name;
// If that didn't succeed, check whether this is an anonymous tag declaration
// with a corresponding typedef-name declaration.
if (decl->getDeclName().isEmpty()) {
if (auto *typedefForAnon = decl->getTypedefNameForAnonDecl())
return Impl.importFullName(typedefForAnon).Imported.getBaseName();
}
if (!decl->isRecord())
return name;
// If the type has no name and no structure name, but is not anonymous,
// generate a name for it. Specifically this is for cases like:
// struct a {
// struct {} z;
// }
// Where the member z is an unnamed struct, but does have a member-name
// and is accessible as a member of struct a.
if (auto recordDecl = dyn_cast<clang::RecordDecl>(decl->getLexicalDeclContext())) {
for (auto field : recordDecl->fields()) {
if (field->getType()->getAsTagDecl() == decl) {
// We found the field. The field should not be anonymous, since we are
// using its name to derive the generated declaration name.
assert(!field->isAnonymousStructOrUnion());
// Create a name for the declaration from the field name.
std::string Id;
llvm::raw_string_ostream IdStream(Id);
const char *kind;
if (decl->isStruct())
kind = "struct";
else if (decl->isUnion())
kind = "union";
else
llvm_unreachable("unknown decl kind");
IdStream << "__Unnamed_" << kind
<< "_" << field->getName();
return Impl.SwiftContext.getIdentifier(IdStream.str());
}
}
}
return name;
}
namespace {
class CFPointeeInfo {
bool IsValid;
bool IsConst;
PointerUnion<const clang::RecordDecl*, const clang::TypedefNameDecl*> Decl;
CFPointeeInfo() = default;
static CFPointeeInfo forRecord(bool isConst,
const clang::RecordDecl *decl) {
assert(decl);
CFPointeeInfo info;
info.IsValid = true;
info.IsConst = isConst;
info.Decl = decl;
return info;
}
static CFPointeeInfo forTypedef(const clang::TypedefNameDecl *decl) {
assert(decl);
CFPointeeInfo info;
info.IsValid = true;
info.IsConst = false;
info.Decl = decl;
return info;
}
static CFPointeeInfo forConstVoid() {
CFPointeeInfo info;
info.IsValid = true;
info.IsConst = true;
info.Decl = nullptr;
return info;
}
static CFPointeeInfo forInvalid() {
CFPointeeInfo info;
info.IsValid = false;
return info;
}
public:
static CFPointeeInfo classifyTypedef(const clang::TypedefNameDecl *decl);
bool isValid() const { return IsValid; }
explicit operator bool() const { return isValid(); }
bool isConst() const { return IsConst; }
bool isConstVoid() const {
assert(isValid());
return Decl.isNull();
}
bool isRecord() const {
assert(isValid());
return !Decl.isNull() && Decl.is<const clang::RecordDecl *>();
}
const clang::RecordDecl *getRecord() const {
assert(isRecord());
return Decl.get<const clang::RecordDecl *>();
}
bool isTypedef() const {
assert(isValid());
return !Decl.isNull() && Decl.is<const clang::TypedefNameDecl *>();
}
const clang::TypedefNameDecl *getTypedef() const {
assert(isTypedef());
return Decl.get<const clang::TypedefNameDecl *>();
}
};
}
/// The maximum length of any particular string in the whitelist.
const size_t MaxCFWhitelistStringLength = 38;
namespace {
struct CFWhitelistEntry {
unsigned char Length;
char Data[MaxCFWhitelistStringLength + 1];
operator StringRef() const { return StringRef(Data, Length); }
};
// Quasi-lexicographic order: string length first, then string data.
// Since we don't care about the actual length, we can use this, which
// lets us ignore the string data a larger proportion of the time.
struct CFWhitelistComparator {
bool operator()(StringRef lhs, StringRef rhs) const {
return (lhs.size() < rhs.size() ||
(lhs.size() == rhs.size() && lhs < rhs));
}
};
}
template <size_t Len>
static constexpr size_t string_lengthof(const char (&data)[Len]) {
return Len - 1;
}
/// The CF whitelist. We use 'constexpr' to verify that this is
/// emitted as a constant. Note that this is expected to be sorted in
/// quasi-lexicographic order.
static constexpr const CFWhitelistEntry CFWhitelist[] = {
#define CF_TYPE(NAME) { string_lengthof(#NAME), #NAME },
#define NON_CF_TYPE(NAME)
#include "SortedCFDatabase.def"
};
const size_t NumCFWhitelistEntries = sizeof(CFWhitelist) / sizeof(*CFWhitelist);
/// Maintain a set of whitelisted CF types.
static bool isWhitelistedCFTypeName(StringRef name) {
return std::binary_search(CFWhitelist, CFWhitelist + NumCFWhitelistEntries,
name, CFWhitelistComparator());
}
/// Classify a potential CF typedef.
CFPointeeInfo
CFPointeeInfo::classifyTypedef(const clang::TypedefNameDecl *typedefDecl) {
clang::QualType type = typedefDecl->getUnderlyingType();
if (auto subTypedef = type->getAs<clang::TypedefType>()) {
if (classifyTypedef(subTypedef->getDecl()))
return forTypedef(subTypedef->getDecl());
return forInvalid();
}
if (auto ptr = type->getAs<clang::PointerType>()) {
auto pointee = ptr->getPointeeType();
// Must be 'const' or nothing.
clang::Qualifiers quals = pointee.getQualifiers();
bool isConst = quals.hasConst();
quals.removeConst();
if (quals.empty()) {
if (auto record = pointee->getAs<clang::RecordType>()) {
auto recordDecl = record->getDecl();
if (recordDecl->hasAttr<clang::ObjCBridgeAttr>() ||
recordDecl->hasAttr<clang::ObjCBridgeMutableAttr>() ||
recordDecl->hasAttr<clang::ObjCBridgeRelatedAttr>() ||
isWhitelistedCFTypeName(typedefDecl->getName())) {
return forRecord(isConst, record->getDecl());
}
} else if (isConst && pointee->isVoidType()) {
if (typedefDecl->hasAttr<clang::ObjCBridgeAttr>() ||
isWhitelistedCFTypeName(typedefDecl->getName())) {
return forConstVoid();
}
}
}
}
return forInvalid();
}
/// Return the name to import a CF typedef as.
static StringRef getImportedCFTypeName(StringRef name) {
// If the name ends in the CF typedef suffix ("Ref"), drop that.
if (name.endswith(SWIFT_CFTYPE_SUFFIX))
return name.drop_back(strlen(SWIFT_CFTYPE_SUFFIX));
return name;
}
bool ClangImporter::Implementation::isCFTypeDecl(
const clang::TypedefNameDecl *Decl) {
if (CFPointeeInfo::classifyTypedef(Decl))
return true;
return false;
}
StringRef ClangImporter::Implementation::getCFTypeName(
const clang::TypedefNameDecl *decl,
StringRef *secondaryName) {
if (secondaryName) *secondaryName = "";
if (auto pointee = CFPointeeInfo::classifyTypedef(decl)) {
auto name = decl->getName();
if (pointee.isRecord() || pointee.isTypedef()) {
auto resultName = getImportedCFTypeName(name);
if (secondaryName && name != resultName)
*secondaryName = name;
return resultName;
}
return name;
}
return "";
}
/// Add an AvailableAttr to the declaration for the given
/// version range.
static void applyAvailableAttribute(Decl *decl, AvailabilityContext &info,
ASTContext &C) {
// If the range is "all", this is the same as not having an available
// attribute.
if (info.isAlwaysAvailable())
return;
clang::VersionTuple noVersion;
auto AvAttr = new (C) AvailableAttr(SourceLoc(), SourceRange(),
targetPlatform(C.LangOpts),
/*message=*/StringRef(),
/*rename=*/StringRef(),
info.getOSVersion().getLowerEndpoint(),
/*deprecated=*/noVersion,
/*obsoleted=*/noVersion,
UnconditionalAvailabilityKind::None,
/*implicit=*/false);
decl->getAttrs().add(AvAttr);
}
/// Synthesize availability attributes for protocol requirements
/// based on availability of the types mentioned in the requirements.
static void inferProtocolMemberAvailability(ClangImporter::Implementation &impl,
DeclContext *dc, Decl *member) {
// Don't synthesize attributes if there is already an
// availability annotation.
if (member->getAttrs().hasAttribute<AvailableAttr>())
return;
auto *valueDecl = dyn_cast<ValueDecl>(member);
if (!valueDecl)
return;
AvailabilityContext requiredRange =
AvailabilityInference::inferForType(valueDecl->getInterfaceType());
ASTContext &C = impl.SwiftContext;
const Decl *innermostDecl = dc->getInnermostDeclarationDeclContext();
AvailabilityContext containingDeclRange =
AvailabilityInference::availableRange(innermostDecl, C);
requiredRange.intersectWith(containingDeclRange);
applyAvailableAttribute(valueDecl, requiredRange, C);
}
/// Add a domain error member, as required by conformance to _BridgedNSError
/// Returns true on success, false on failure
static bool addErrorDomain(NominalTypeDecl *swiftDecl,
clang::NamedDecl *errorDomainDecl,
ClangImporter::Implementation &importer) {
auto &swiftCtx = importer.SwiftContext;
auto swiftValueDecl =
dyn_cast_or_null<ValueDecl>(importer.importDecl(errorDomainDecl));
auto stringTy = swiftCtx.getStringDecl()->getDeclaredType();
assert(stringTy && "no string type available");
if (!swiftValueDecl || !swiftValueDecl->getType()->isEqual(stringTy)) {
// Couldn't actually import it as an error enum, fall back to enum
return false;
}
SourceLoc noLoc = SourceLoc();
bool isStatic = true;
bool isImplicit = true;
DeclRefExpr *domainDeclRef = new (swiftCtx)
DeclRefExpr(ConcreteDeclRef(swiftValueDecl), {}, isImplicit);
ParameterList *params[] = {
ParameterList::createWithoutLoc(
ParamDecl::createSelf(noLoc, swiftDecl, isStatic)),
ParameterList::createEmpty(swiftCtx)};
auto toStringTy = ParameterList::getFullType(stringTy, params);
FuncDecl *getterDecl = FuncDecl::create(
swiftCtx, noLoc, StaticSpellingKind::None, noLoc, {}, noLoc, noLoc, noLoc,
nullptr, toStringTy, params, TypeLoc::withoutLoc(stringTy), swiftDecl);
// Make the property decl
auto errorDomainPropertyDecl = new (swiftCtx) VarDecl(
isStatic,
/*isLet=*/false, noLoc, swiftCtx.Id_NSErrorDomain, stringTy, swiftDecl);
errorDomainPropertyDecl->setAccessibility(Accessibility::Public);
swiftDecl->addMember(errorDomainPropertyDecl);
swiftDecl->addMember(getterDecl);
errorDomainPropertyDecl->makeComputed(noLoc, getterDecl, /*Set=*/nullptr,
/*MaterializeForSet=*/nullptr, noLoc);
getterDecl->setImplicit();
getterDecl->setStatic(isStatic);
getterDecl->setBodyResultType(stringTy);
getterDecl->setInterfaceType(toStringTy);
getterDecl->setAccessibility(Accessibility::Public);
auto ret = new (swiftCtx) ReturnStmt(noLoc, domainDeclRef);
getterDecl->setBody(
BraceStmt::create(swiftCtx, noLoc, {ret}, noLoc, isImplicit));
importer.registerExternalDecl(getterDecl);
return true;
}
/// As addErrorDomain above, but performs a lookup
static bool addErrorDomain(NominalTypeDecl *swiftDecl,
clang::IdentifierInfo *errorDomainDeclName,
ClangImporter::Implementation &importer) {
auto &clangSema = importer.getClangSema();
clang::LookupResult lookupResult(
clangSema, clang::DeclarationName(errorDomainDeclName),
clang::SourceLocation(), clang::Sema::LookupNameKind::LookupOrdinaryName);
if (!clangSema.LookupName(lookupResult, clangSema.TUScope)) {
// Couldn't actually import it as an error enum, fall back to enum
return false;
}
auto clangNamedDecl = lookupResult.getAsSingle<clang::NamedDecl>();
if (!clangNamedDecl) {
// Couldn't actually import it as an error enum, fall back to enum
return false;
}
return addErrorDomain(swiftDecl, clangNamedDecl, importer);
}
namespace {
/// \brief Convert Clang declarations into the corresponding Swift
/// declarations.
class SwiftDeclConverter
: public clang::ConstDeclVisitor<SwiftDeclConverter, Decl *>
{
ClangImporter::Implementation &Impl;
bool forwardDeclaration = false;
public:
explicit SwiftDeclConverter(ClangImporter::Implementation &impl)
: Impl(impl) { }
bool hadForwardDeclaration() const {
return forwardDeclaration;
}
Decl *VisitDecl(const clang::Decl *decl) {
return nullptr;
}
Decl *VisitTranslationUnitDecl(const clang::TranslationUnitDecl *decl) {
// Note: translation units are handled specially by importDeclContext.
return nullptr;
}
Decl *VisitNamespaceDecl(const clang::NamespaceDecl *decl) {
// FIXME: Implement once Swift has namespaces.
return nullptr;
}
Decl *VisitUsingDirectiveDecl(const clang::UsingDirectiveDecl *decl) {
// Never imported.
return nullptr;
}
Decl *VisitNamespaceAliasDecl(const clang::NamespaceAliasDecl *decl) {
// FIXME: Implement once Swift has namespaces.
return nullptr;
}
Decl *VisitLabelDecl(const clang::LabelDecl *decl) {
// Labels are function-local, and therefore never imported.
return nullptr;
}
/// Try to strip "Mutable" out of a type name.
clang::IdentifierInfo *
getImmutableCFSuperclassName(const clang::TypedefNameDecl *decl) {
StringRef name = decl->getName();
// Split at the first occurrence of "Mutable".
StringRef _mutable = "Mutable";
auto mutableIndex = camel_case::findWord(name, _mutable);
if (mutableIndex == StringRef::npos)
return nullptr;
StringRef namePrefix = name.substr(0, mutableIndex);
StringRef nameSuffix = name.substr(mutableIndex + _mutable.size());
// Abort if "Mutable" appears twice.
if (camel_case::findWord(nameSuffix, _mutable) != StringRef::npos)
return nullptr;
llvm::SmallString<128> buffer;
buffer += namePrefix;
buffer += nameSuffix;
return &Impl.getClangASTContext().Idents.get(buffer.str());
}
/// Check whether this CF typedef is a Mutable type, and if so,
/// look for a non-Mutable typedef.
///
/// If the "subclass" is:
/// typedef struct __foo *XXXMutableYYY;
/// then we look for a "superclass" that matches:
/// typedef const struct __foo *XXXYYY;
Type findImmutableCFSuperclass(const clang::TypedefNameDecl *decl,
CFPointeeInfo subclassInfo) {
// If this type is already immutable, it has no immutable
// superclass.
if (subclassInfo.isConst()) return Type();
// If this typedef name does not contain "Mutable", it has no
// immutable superclass.
auto superclassName = getImmutableCFSuperclassName(decl);
if (!superclassName) return Type();
// Look for a typedef that successfully classifies as a CF
// typedef with the same underlying record.
auto superclassTypedef = Impl.lookupTypedef(superclassName);
if (!superclassTypedef) return Type();
auto superclassInfo = CFPointeeInfo::classifyTypedef(superclassTypedef);
if (!superclassInfo || !superclassInfo.isRecord() ||
!declaresSameEntity(superclassInfo.getRecord(),
subclassInfo.getRecord()))
return Type();
// Try to import the superclass.
Decl *importedSuperclassDecl = Impl.importDeclReal(superclassTypedef);
if (!importedSuperclassDecl) return Type();
auto importedSuperclass =
cast<TypeDecl>(importedSuperclassDecl)->getDeclaredType();
assert(importedSuperclass->is<ClassType>() && "must have class type");
return importedSuperclass;
}
/// Attempt to find a superclass for the given CF typedef.
Type findCFSuperclass(const clang::TypedefNameDecl *decl,
CFPointeeInfo info) {
if (Type immutable = findImmutableCFSuperclass(decl, info))
return immutable;
// TODO: use NSObject if it exists?
return Type();
}
ClassDecl *importCFClassType(const clang::TypedefNameDecl *decl,
Identifier className, CFPointeeInfo info) {
auto dc = Impl.importDeclContextOf(decl);
if (!dc) return nullptr;
Type superclass = findCFSuperclass(decl, info);
// TODO: maybe use NSObject as the superclass if we can find it?
// TODO: try to find a non-mutable type to use as the superclass.
auto theClass =
Impl.createDeclWithClangNode<ClassDecl>(decl, SourceLoc(), className,
SourceLoc(), None,
nullptr, dc);
theClass->computeType();
theClass->setCircularityCheck(CircularityCheck::Checked);
theClass->setSuperclass(superclass);
theClass->setCheckedInheritanceClause();
theClass->setAddedImplicitInitializers(); // suppress all initializers
theClass->setForeign(true);
addObjCAttribute(theClass, None);
Impl.registerExternalDecl(theClass);
SmallVector<ProtocolDecl *, 4> protocols;
theClass->getImplicitProtocols(protocols);
addObjCProtocolConformances(theClass, protocols);
// Look for bridging attributes on the clang record. We can
// just check the most recent redeclaration, which will inherit
// any attributes from earlier declarations.
auto record = info.getRecord()->getMostRecentDecl();
if (info.isConst()) {
if (auto attr = record->getAttr<clang::ObjCBridgeAttr>()) {
// Record the Objective-C class to which this CF type is toll-free
// bridged.
if (ClassDecl *objcClass = dyn_cast_or_null<ClassDecl>(
Impl.importDeclByName(
attr->getBridgedType()->getName()))) {
theClass->getAttrs().add(
new (Impl.SwiftContext) ObjCBridgedAttr(objcClass));
}
}
} else {
if (auto attr = record->getAttr<clang::ObjCBridgeMutableAttr>()) {
// Record the Objective-C class to which this CF type is toll-free
// bridged.
if (ClassDecl *objcClass = dyn_cast_or_null<ClassDecl>(
Impl.importDeclByName(
attr->getBridgedType()->getName()))) {
theClass->getAttrs().add(
new (Impl.SwiftContext) ObjCBridgedAttr(objcClass));
}
}
}
return theClass;
}
Decl *VisitTypedefNameDecl(const clang::TypedefNameDecl *Decl) {
auto importedName = Impl.importFullName(Decl);
auto Name = importedName.Imported.getBaseName();
if (Name.empty())
return nullptr;
Type SwiftType;
if (Decl->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
bool IsError;
StringRef StdlibTypeName;
MappedTypeNameKind NameMapping;
std::tie(SwiftType, StdlibTypeName) =
getSwiftStdlibType(Decl, Name, Impl, &IsError, NameMapping);
if (IsError)
return nullptr;
// Import 'typedef struct __Blah *BlahRef;' and
// 'typedef const void *FooRef;' as CF types if they have the
// right attributes or match our name whitelist.
if (!SwiftType) {
auto DC = Impl.importDeclContextOf(Decl);
if (!DC)
return nullptr;
// Local function to create the alias, if needed.
auto createAlias = [&](TypeDecl *primary) {
if (!importedName.Alias) return;
auto aliasRef = Impl.createDeclWithClangNode<TypeAliasDecl>(
Decl,
Impl.importSourceLoc(Decl->getLocStart()),
importedName.Alias.getBaseName(),
Impl.importSourceLoc(Decl->getLocation()),
TypeLoc::withoutLoc(
primary->getDeclaredInterfaceType()),
DC);
aliasRef->computeType();
// Record this as the alternate declaration.
Impl.AlternateDecls[primary] = aliasRef;
// The "Ref" variants are deprecated and will be
// removed. Stage their removal via
// -enable-omit-needless-words.
auto attr = AvailableAttr::createUnconditional(
Impl.SwiftContext,
"",
primary->getName().str(),
Impl.OmitNeedlessWords
? UnconditionalAvailabilityKind::UnavailableInSwift
: UnconditionalAvailabilityKind::Deprecated);
aliasRef->getAttrs().add(attr);
};
if (auto pointee = CFPointeeInfo::classifyTypedef(Decl)) {
// If the pointee is a record, consider creating a class type.
if (pointee.isRecord()) {
auto swiftClass = importCFClassType(Decl, Name, pointee);
if (!swiftClass) return nullptr;
Impl.SpecialTypedefNames[Decl->getCanonicalDecl()] =
MappedTypeNameKind::DefineAndUse;
createAlias(swiftClass);
return swiftClass;
}
// If the pointee is another CF typedef, create an extra typealias
// for the name without "Ref", but not a separate type.
if (pointee.isTypedef()) {
auto underlying =
cast_or_null<TypeDecl>(Impl.importDecl(pointee.getTypedef()));
if (!underlying)
return nullptr;
// Create a typealias for this CF typedef.
TypeAliasDecl *typealias = nullptr;
typealias = Impl.createDeclWithClangNode<TypeAliasDecl>(
Decl,
Impl.importSourceLoc(Decl->getLocStart()),
Name,
Impl.importSourceLoc(Decl->getLocation()),
TypeLoc::withoutLoc(
underlying->getDeclaredInterfaceType()),
DC);
typealias->computeType();
Impl.SpecialTypedefNames[Decl->getCanonicalDecl()] =
MappedTypeNameKind::DefineAndUse;
createAlias(typealias);
return typealias;
}
// If the pointee is 'const void', 'CFTypeRef', bring it
// in specifically as AnyObject.
if (pointee.isConstVoid()) {
auto proto = Impl.SwiftContext.getProtocol(
KnownProtocolKind::AnyObject);
if (!proto)
return nullptr;
// Create a typealias for this CF typedef.
TypeAliasDecl *typealias = nullptr;
typealias = Impl.createDeclWithClangNode<TypeAliasDecl>(
Decl,
Impl.importSourceLoc(Decl->getLocStart()),
Name,
Impl.importSourceLoc(Decl->getLocation()),
TypeLoc::withoutLoc(
proto->getDeclaredInterfaceType()),
DC);
typealias->computeType();
Impl.SpecialTypedefNames[Decl->getCanonicalDecl()] =
MappedTypeNameKind::DefineAndUse;
createAlias(typealias);
return typealias;
}
}
}
if (SwiftType) {
// Note that this typedef-name is special.
Impl.SpecialTypedefNames[Decl->getCanonicalDecl()] = NameMapping;
if (NameMapping == MappedTypeNameKind::DoNothing) {
// Record the remapping using the name of the Clang declaration.
// This will be useful for type checker diagnostics when
// a user tries to use the Objective-C/C type instead of the
// Swift type.
Impl.SwiftContext.RemappedTypes[Decl->getNameAsString()]
= SwiftType;
// Don't create an extra typealias in the imported module because
// doing so will cause confusion (or even lookup ambiguity) between
// the name in the imported module and the same name in the
// standard library.
if (auto *NAT = dyn_cast<NameAliasType>(SwiftType.getPointer()))
return NAT->getDecl();
auto *NTD = SwiftType->getAnyNominal();
assert(NTD);
return NTD;
}
}
}
auto DC = Impl.importDeclContextOf(Decl);
if (!DC)
return nullptr;
if (!SwiftType) {
// Import typedefs of blocks as their fully-bridged equivalent Swift
// type. That matches how we want to use them in most cases. All other
// types should be imported in a non-bridged way.
clang::QualType ClangType = Decl->getUnderlyingType();
SwiftType = Impl.importType(ClangType,
ImportTypeKind::Typedef,
isInSystemModule(DC),
ClangType->isBlockPointerType());
}
if (!SwiftType)
return nullptr;
auto Loc = Impl.importSourceLoc(Decl->getLocation());
auto Result = Impl.createDeclWithClangNode<TypeAliasDecl>(Decl,
Impl.importSourceLoc(Decl->getLocStart()),
Name,
Loc,
TypeLoc::withoutLoc(SwiftType),
DC);
Result->computeType();
return Result;
}
Decl *
VisitUnresolvedUsingTypenameDecl(const
clang::UnresolvedUsingTypenameDecl *decl) {
// Note: only occurs in templates.
return nullptr;
}
/// \brief Create a default constructor that initializes a struct to zero.
ConstructorDecl *createDefaultConstructor(StructDecl *structDecl) {
auto &context = Impl.SwiftContext;
// Create the 'self' declaration.
auto selfDecl = ParamDecl::createSelf(SourceLoc(), structDecl,
/*static*/false, /*inout*/true);
// self & param.
auto emptyPL = ParameterList::createEmpty(context);
// Create the constructor.
DeclName name(context, context.Id_init, emptyPL);
auto constructor =
new (context) ConstructorDecl(name, structDecl->getLoc(),
OTK_None, SourceLoc(), selfDecl, emptyPL,
nullptr, SourceLoc(), structDecl);
// Set the constructor's type.
auto selfType = structDecl->getDeclaredTypeInContext();
auto selfMetatype = MetatypeType::get(selfType);
auto emptyTy = TupleType::getEmpty(context);
auto fnTy = FunctionType::get(emptyTy, selfType);
auto allocFnTy = FunctionType::get(selfMetatype, fnTy);
auto initFnTy = FunctionType::get(selfType, fnTy);
constructor->setType(allocFnTy);
constructor->setInterfaceType(allocFnTy);
constructor->setInitializerType(initFnTy);
constructor->setAccessibility(Accessibility::Public);
// Mark the constructor transparent so that we inline it away completely.
constructor->getAttrs().add(
new (context) TransparentAttr(/*implicit*/ true));
// Use a builtin to produce a zero initializer, and assign it to self.
constructor->setBodySynthesizer([](AbstractFunctionDecl *constructor) {
ASTContext &context = constructor->getASTContext();
// Construct the left-hand reference to self.
Expr *lhs =
new (context) DeclRefExpr(constructor->getImplicitSelfDecl(),
DeclNameLoc(), /*implicit=*/true);
// Construct the right-hand call to Builtin.zeroInitializer.
Identifier zeroInitID = context.getIdentifier("zeroInitializer");
auto zeroInitializerFunc =
cast<FuncDecl>(getBuiltinValueDecl(context, zeroInitID));
auto zeroInitializerRef = new (context) DeclRefExpr(zeroInitializerFunc,
DeclNameLoc(),
/*implicit*/ true);
auto emptyTuple = TupleExpr::createEmpty(context, SourceLoc(),
SourceLoc(),
/*implicit*/ true);
auto call = new (context) CallExpr(zeroInitializerRef, emptyTuple,
/*implicit*/ true);
auto assign = new (context) AssignExpr(lhs, SourceLoc(), call,
/*implicit*/ true);
// Create the function body.
auto body = BraceStmt::create(context, SourceLoc(), { assign },
SourceLoc());
constructor->setBody(body);
});
// Add this as an external definition.
Impl.registerExternalDecl(constructor);
// We're done.
return constructor;
}
/// \brief Create a constructor that initializes a struct from its members.
ConstructorDecl *createValueConstructor(StructDecl *structDecl,
ArrayRef<VarDecl *> members,
bool wantCtorParamNames,
bool wantBody) {
auto &context = Impl.SwiftContext;
// Create the 'self' declaration.
auto selfDecl = ParamDecl::createSelf(SourceLoc(), structDecl,
/*static*/false, /*inout*/true);
// Construct the set of parameters from the list of members.
SmallVector<ParamDecl*, 8> valueParameters;
for (auto var : members) {
Identifier argName = wantCtorParamNames ? var->getName()
: Identifier();
auto param = new (context) ParamDecl(/*IsLet*/ true, SourceLoc(),
SourceLoc(), argName,
SourceLoc(), var->getName(),
var->getType(), structDecl);
valueParameters.push_back(param);
}
// self & param.
ParameterList *paramLists[] = {
ParameterList::createWithoutLoc(selfDecl),
ParameterList::create(context, valueParameters)
};
// Create the constructor
DeclName name(context, context.Id_init, paramLists[1]);
auto constructor =
new (context) ConstructorDecl(name, structDecl->getLoc(),
OTK_None, SourceLoc(),
selfDecl, paramLists[1],
nullptr, SourceLoc(), structDecl);
// Set the constructor's type.
auto paramTy = paramLists[1]->getType(context);
auto selfType = structDecl->getDeclaredTypeInContext();
auto selfMetatype = MetatypeType::get(selfType);
auto fnTy = FunctionType::get(paramTy, selfType);
auto allocFnTy = FunctionType::get(selfMetatype, fnTy);
auto initFnTy = FunctionType::get(selfType, fnTy);
constructor->setType(allocFnTy);
constructor->setInterfaceType(allocFnTy);
constructor->setInitializerType(initFnTy);
constructor->setAccessibility(Accessibility::Public);
// Make the constructor transparent so we inline it away completely.
constructor->getAttrs().add(
new (context) TransparentAttr(/*implicit*/ true));
if (wantBody) {
// Assign all of the member variables appropriately.
SmallVector<ASTNode, 4> stmts;
// To keep DI happy, initialize stored properties before computed.
for (unsigned pass = 0; pass < 2; pass++) {
for (unsigned i = 0, e = members.size(); i < e; i++) {
auto var = members[i];
if (var->hasStorage() == (pass != 0))
continue;
// Construct left-hand side.
Expr *lhs = new (context) DeclRefExpr(selfDecl, DeclNameLoc(),
/*Implicit=*/true);
lhs = new (context) MemberRefExpr(lhs, SourceLoc(), var,
DeclNameLoc(), /*Implicit=*/true);
// Construct right-hand side.
auto rhs = new (context) DeclRefExpr(valueParameters[i],
DeclNameLoc(),
/*Implicit=*/true);
// Add assignment.
stmts.push_back(new (context) AssignExpr(lhs, SourceLoc(), rhs,
/*Implicit=*/true));
}
}
// Create the function body.
auto body = BraceStmt::create(context, SourceLoc(), stmts, SourceLoc());
constructor->setBody(body);
}
// Add this as an external definition.
Impl.registerExternalDecl(constructor);
// We're done.
return constructor;
}
/// Import an NS_ENUM constant as a case of a Swift enum.
Decl *importEnumCase(const clang::EnumConstantDecl *decl,
const clang::EnumDecl *clangEnum,
EnumDecl *theEnum) {
auto &context = Impl.SwiftContext;
auto name = Impl.importFullName(decl).Imported.getBaseName();
if (name.empty())
return nullptr;
// Use the constant's underlying value as its raw value in Swift.
bool negative = false;
llvm::APSInt rawValue = decl->getInitVal();
// Did we already import an enum constant for this enum with the
// same value? If so, import it as a standalone constant.
auto insertResult =
Impl.EnumConstantValues.insert({{clangEnum, rawValue}, nullptr});
if (!insertResult.second)
return importEnumCaseAlias(decl, insertResult.first->second,
clangEnum, theEnum);
if (clangEnum->getIntegerType()->isSignedIntegerOrEnumerationType()
&& rawValue.slt(0)) {
rawValue = -rawValue;
negative = true;
}
llvm::SmallString<12> rawValueText;
rawValue.toString(rawValueText, 10, /*signed*/ false);
StringRef rawValueTextC
= context.AllocateCopy(StringRef(rawValueText));
auto rawValueExpr = new (context) IntegerLiteralExpr(rawValueTextC,
SourceLoc(),
/*implicit*/ false);
if (negative)
rawValueExpr->setNegative(SourceLoc());
auto element
= Impl.createDeclWithClangNode<EnumElementDecl>(decl, SourceLoc(),
name, TypeLoc(),
SourceLoc(), rawValueExpr,
theEnum);
insertResult.first->second = element;
// Give the enum element the appropriate type.
element->computeType();
Impl.importAttributes(decl, element);
return element;
}
/// Import an NS_OPTIONS constant as a static property of a Swift struct.
///
/// This is also used to import enum case aliases.
Decl *importOptionConstant(const clang::EnumConstantDecl *decl,
const clang::EnumDecl *clangEnum,
NominalTypeDecl *theStruct) {
auto name = Impl.importFullName(decl).Imported.getBaseName();
if (name.empty())
return nullptr;
// Create the constant.
auto convertKind = ConstantConvertKind::Construction;
if (isa<EnumDecl>(theStruct))
convertKind = ConstantConvertKind::ConstructionWithUnwrap;
Decl *CD = Impl.createConstant(name, theStruct,
theStruct->getDeclaredTypeInContext(),
clang::APValue(decl->getInitVal()),
convertKind, /*isStatic*/ true, decl);
Impl.importAttributes(decl, CD);
return CD;
}
/// Import \p alias as an alias for the imported constant \p original.
///
/// This builds the getter in a way that's compatible with switch
/// statements. Changing the body here may require changing
/// TypeCheckPattern.cpp as well.
Decl *importEnumCaseAlias(const clang::EnumConstantDecl *alias,
EnumElementDecl *original,
const clang::EnumDecl *clangEnum,
NominalTypeDecl *importedEnum) {
auto name = Impl.importFullName(alias).Imported.getBaseName();
if (name.empty())
return nullptr;
// Construct the original constant. Enum constants without payloads look
// like simple values, but actually have type 'MyEnum.Type -> MyEnum'.
auto constantRef = new (Impl.SwiftContext) DeclRefExpr(original,
DeclNameLoc(),
/*implicit*/true);
Type importedEnumTy = importedEnum->getDeclaredTypeInContext();
auto typeRef = TypeExpr::createImplicit(importedEnumTy,
Impl.SwiftContext);
auto instantiate = new (Impl.SwiftContext) DotSyntaxCallExpr(constantRef,
SourceLoc(),
typeRef);
instantiate->setType(importedEnumTy);
Decl *CD = Impl.createConstant(name, importedEnum, importedEnumTy,
instantiate, ConstantConvertKind::None,
/*isStatic*/ true, alias);
Impl.importAttributes(alias, CD);
return CD;
}
template<unsigned N>
void populateInheritedTypes(NominalTypeDecl *nominal,
ProtocolDecl * const (&protocols)[N]) {
TypeLoc inheritedTypes[N];
for_each(MutableArrayRef<TypeLoc>(inheritedTypes),
ArrayRef<ProtocolDecl *>(protocols),
[](TypeLoc &tl, ProtocolDecl *proto) {
tl = TypeLoc::withoutLoc(proto->getDeclaredType());
});
nominal->setInherited(Impl.SwiftContext.AllocateCopy(inheritedTypes));
nominal->setCheckedInheritanceClause();
}
NominalTypeDecl *importAsOptionSetType(DeclContext *dc,
Identifier name,
const clang::EnumDecl *decl) {
ASTContext &cxt = Impl.SwiftContext;
// Compute the underlying type.
auto underlyingType = Impl.importType(decl->getIntegerType(),
ImportTypeKind::Enum,
isInSystemModule(dc),
/*isFullyBridgeable*/false);
if (!underlyingType)
return nullptr;
auto Loc = Impl.importSourceLoc(decl->getLocation());
// Create a struct with the underlying type as a field.
auto structDecl = Impl.createDeclWithClangNode<StructDecl>(decl,
Loc, name, Loc, None, nullptr, dc);
structDecl->computeType();
// Note that this is a raw option set type.
structDecl->getAttrs().add(
new (Impl.SwiftContext) SynthesizedProtocolAttr(
KnownProtocolKind::OptionSetType));
// Create a field to store the underlying value.
auto varName = Impl.SwiftContext.Id_rawValue;
auto var = new (Impl.SwiftContext) VarDecl(/*static*/ false,
/*IsLet*/ true,
SourceLoc(), varName,
underlyingType,
structDecl);
var->setImplicit();
var->setAccessibility(Accessibility::Public);
var->setSetterAccessibility(Accessibility::Private);
// Create a pattern binding to describe the variable.
Pattern *varPattern = createTypedNamedPattern(var);
auto patternBinding =
PatternBindingDecl::create(Impl.SwiftContext, SourceLoc(),
StaticSpellingKind::None, SourceLoc(),
varPattern, nullptr, structDecl);
// Create the init(rawValue:) constructor.
auto labeledValueConstructor = createValueConstructor(
structDecl, var,
/*wantCtorParamNames=*/true,
/*wantBody=*/!Impl.hasFinishedTypeChecking());
// Build an OptionSetType conformance for the type.
ProtocolDecl *protocols[]
= {cxt.getProtocol(KnownProtocolKind::OptionSetType)};
populateInheritedTypes(structDecl, protocols);
structDecl->addMember(labeledValueConstructor);
structDecl->addMember(patternBinding);
structDecl->addMember(var);
return structDecl;
}
Decl *VisitEnumDecl(const clang::EnumDecl *decl) {
decl = decl->getDefinition();
if (!decl) {
forwardDeclaration = true;
return nullptr;
}
auto name = getClangDeclName(Impl, decl);
if (name.empty())
return nullptr;
auto dc = Impl.importDeclContextOf(decl);
if (!dc)
return nullptr;
ASTContext &cxt = Impl.SwiftContext;
// Create the enum declaration and record it.
NominalTypeDecl *result;
auto enumInfo = Impl.getEnumInfo(decl);
auto enumKind = enumInfo.getKind();
switch (enumKind) {
case EnumKind::Constants: {
// There is no declaration. Rather, the type is mapped to the
// underlying type.
return nullptr;
}
case EnumKind::Unknown: {
// Compute the underlying type of the enumeration.
auto underlyingType = Impl.importType(decl->getIntegerType(),
ImportTypeKind::Enum,
isInSystemModule(dc),
/*isFullyBridgeable*/false);
if (!underlyingType)
return nullptr;
auto Loc = Impl.importSourceLoc(decl->getLocation());
auto structDecl = Impl.createDeclWithClangNode<StructDecl>(decl,
Loc, name, Loc, None, nullptr, dc);
structDecl->computeType();
ProtocolDecl *protocols[]
= {cxt.getProtocol(KnownProtocolKind::RawRepresentable),
cxt.getProtocol(KnownProtocolKind::Equatable)};
populateInheritedTypes(structDecl, protocols);
// Note that this is a raw representable type.
structDecl->getAttrs().add(
new (Impl.SwiftContext) SynthesizedProtocolAttr(
KnownProtocolKind::RawRepresentable));
// Create a variable to store the underlying value.
auto varName = Impl.SwiftContext.Id_rawValue;
auto var = new (Impl.SwiftContext) VarDecl(/*static*/ false,
/*IsLet*/ false,
SourceLoc(), varName,
underlyingType,
structDecl);
var->setAccessibility(Accessibility::Public);
var->setSetterAccessibility(Accessibility::Public);
// Create a pattern binding to describe the variable.
Pattern *varPattern = createTypedNamedPattern(var);
auto patternBinding =
PatternBindingDecl::create(Impl.SwiftContext, SourceLoc(),
StaticSpellingKind::None, SourceLoc(),
varPattern, nullptr, structDecl);
// Create a constructor to initialize that value from a value of the
// underlying type.
auto valueConstructor =
createValueConstructor(structDecl, var,
/*wantCtorParamNames=*/false,
/*wantBody=*/!Impl.hasFinishedTypeChecking());
auto labeledValueConstructor =
createValueConstructor(structDecl, var,
/*wantCtorParamNames=*/true,
/*wantBody=*/!Impl.hasFinishedTypeChecking());
// Add delayed implicit members to the type.
auto &Impl = this->Impl;
structDecl->setDelayedMemberDecls(
[=, &Impl](SmallVectorImpl<Decl *> &NewDecls) {
auto rawGetter = makeRawValueTrivialGetter(Impl, structDecl, var);
NewDecls.push_back(rawGetter);
auto rawSetter = makeRawValueTrivialSetter(Impl, structDecl, var);
NewDecls.push_back(rawSetter);
// FIXME: MaterializeForSet?
var->addTrivialAccessors(rawGetter, rawSetter, nullptr);
});
// Set the members of the struct.
structDecl->addMember(valueConstructor);
structDecl->addMember(labeledValueConstructor);
structDecl->addMember(patternBinding);
structDecl->addMember(var);
result = structDecl;
break;
}
case EnumKind::Enum: {
auto &swiftCtx = Impl.SwiftContext;
EnumDecl *nativeDecl;
bool declaredNative = hasNativeSwiftDecl(decl, name, dc, nativeDecl);
if (declaredNative && nativeDecl)
return nativeDecl;
// Compute the underlying type.
auto underlyingType = Impl.importType(
decl->getIntegerType(), ImportTypeKind::Enum, isInSystemModule(dc),
/*isFullyBridgeable*/ false);
if (!underlyingType)
return nullptr;
auto enumDecl = Impl.createDeclWithClangNode<EnumDecl>(
decl, Impl.importSourceLoc(decl->getLocStart()), name,
Impl.importSourceLoc(decl->getLocation()), None, nullptr, dc);
enumDecl->computeType();
// Set up the C underlying type as its Swift raw type.
enumDecl->setRawType(underlyingType);
// Add protocol declarations to the enum declaration.
SmallVector<TypeLoc, 2> inheritedTypes;
inheritedTypes.push_back(TypeLoc::withoutLoc(underlyingType));
if (enumInfo.isErrorEnum())
inheritedTypes.push_back(TypeLoc::withoutLoc(
swiftCtx.getProtocol(KnownProtocolKind::BridgedNSError)
->getDeclaredType()));
enumDecl->setInherited(swiftCtx.AllocateCopy(inheritedTypes));
enumDecl->setCheckedInheritanceClause();
// Set up error conformance to be lazily expanded
if (enumInfo.isErrorEnum())
enumDecl->getAttrs().add(new (swiftCtx) SynthesizedProtocolAttr(
KnownProtocolKind::BridgedNSError));
// Provide custom implementations of the init(rawValue:) and rawValue
// conversions that just do a bitcast. We can't reliably filter a
// C enum without additional knowledge that the type has no
// undeclared values, and won't ever add cases.
auto rawValueConstructor = makeEnumRawValueConstructor(Impl, enumDecl);
auto varName = swiftCtx.Id_rawValue;
auto rawValue = new (swiftCtx) VarDecl(/*static*/ false,
/*IsLet*/ false,
SourceLoc(), varName,
underlyingType, enumDecl);
rawValue->setImplicit();
rawValue->setAccessibility(Accessibility::Public);
rawValue->setSetterAccessibility(Accessibility::Private);
// Create a pattern binding to describe the variable.
Pattern *varPattern = createTypedNamedPattern(rawValue);
auto rawValueBinding = PatternBindingDecl::create(
swiftCtx, SourceLoc(), StaticSpellingKind::None, SourceLoc(),
varPattern, nullptr, enumDecl);
auto rawValueGetter = makeEnumRawValueGetter(Impl, enumDecl, rawValue);
enumDecl->addMember(rawValueConstructor);
enumDecl->addMember(rawValueGetter);
enumDecl->addMember(rawValue);
enumDecl->addMember(rawValueBinding);
result = enumDecl;
// Add the domain error member
if (enumInfo.isErrorEnum())
addErrorDomain(enumDecl, enumInfo.getErrorDomain(), Impl);
break;
}
case EnumKind::Options: {
result = importAsOptionSetType(dc, name, decl);
if (!result)
return nullptr;
break;
}
}
Impl.ImportedDecls[decl->getCanonicalDecl()] = result;
// Import each of the enumerators.
bool addEnumeratorsAsMembers;
switch (enumKind) {
case EnumKind::Constants:
case EnumKind::Unknown:
addEnumeratorsAsMembers = false;
break;
case EnumKind::Options:
case EnumKind::Enum:
addEnumeratorsAsMembers = true;
break;
}
for (auto ec = decl->enumerator_begin(), ecEnd = decl->enumerator_end();
ec != ecEnd; ++ec) {
Decl *enumeratorDecl;
switch (enumKind) {
case EnumKind::Constants:
case EnumKind::Unknown:
enumeratorDecl = Impl.importDecl(*ec);
break;
case EnumKind::Options:
enumeratorDecl = importOptionConstant(*ec, decl, result);
break;
case EnumKind::Enum:
enumeratorDecl = importEnumCase(*ec, decl, cast<EnumDecl>(result));
break;
}
if (!enumeratorDecl)
continue;
if (addEnumeratorsAsMembers) {
result->addMember(enumeratorDecl);
if (auto *var = dyn_cast<VarDecl>(enumeratorDecl))
result->addMember(var->getGetter());
}
}
// Add the type decl to ExternalDefinitions so that we can type-check
// raw values and SILGen can emit witness tables for derived conformances.
// FIXME: There might be better ways to do this.
Impl.registerExternalDecl(result);
return result;
}
Decl *VisitRecordDecl(const clang::RecordDecl *decl) {
// Track whether this record contains fields we can't reference in Swift
// as stored properties.
bool hasUnreferenceableStorage = false;
// Track whether this record contains fields that can't be zero-
// initialized.
bool hasZeroInitializableStorage = true;
// Track whether all fields in this record can be referenced in Swift,
// either as stored or computed properties, in which case the record type
// gets a memberwise initializer.
bool hasMemberwiseInitializer = true;
if (decl->isUnion()) {
hasUnreferenceableStorage = true;
// We generate initializers specially for unions below.
hasMemberwiseInitializer = false;
}
// FIXME: Skip Microsoft __interfaces.
if (decl->isInterface())
return nullptr;
// The types of anonymous structs or unions are never imported; their
// fields are dumped directly into the enclosing class.
if (decl->isAnonymousStructOrUnion())
return nullptr;
// FIXME: Figure out how to deal with incomplete types, since that
// notion doesn't exist in Swift.
decl = decl->getDefinition();
if (!decl) {
forwardDeclaration = true;
return nullptr;
}
auto name = getClangDeclName(Impl, decl);
if (name.empty())
return nullptr;
auto dc = Impl.importDeclContextOf(decl);
if (!dc)
return nullptr;
// Create the struct declaration and record it.
auto result = Impl.createDeclWithClangNode<StructDecl>(decl,
Impl.importSourceLoc(decl->getLocStart()),
name,
Impl.importSourceLoc(decl->getLocation()),
None, nullptr, dc);
result->computeType();
Impl.ImportedDecls[decl->getCanonicalDecl()] = result;
// FIXME: Figure out what to do with superclasses in C++. One possible
// solution would be to turn them into members and add conversion
// functions.
// Import each of the members.
SmallVector<VarDecl *, 4> members;
SmallVector<ConstructorDecl *, 4> ctors;
// FIXME: Import anonymous union fields and support field access when
// it is nested in a struct.
for (auto m : decl->decls()) {
auto nd = dyn_cast<clang::NamedDecl>(m);
if (!nd) {
// We couldn't import the member, so we can't reference it in Swift.
hasUnreferenceableStorage = true;
hasMemberwiseInitializer = false;
continue;
}
if (auto field = dyn_cast<clang::FieldDecl>(nd)) {
// Skip anonymous structs or unions; they'll be dealt with via the
// IndirectFieldDecls.
if (field->isAnonymousStructOrUnion())
continue;
// Non-nullable pointers can't be zero-initialized.
if (auto nullability = field->getType()
->getNullability(Impl.getClangASTContext())) {
if (*nullability == clang::NullabilityKind::NonNull)
hasZeroInitializableStorage = false;
}
// TODO: If we had the notion of a closed enum with no private
// cases or resilience concerns, then complete NS_ENUMs with
// no case corresponding to zero would also not be zero-
// initializable.
// Unnamed bitfields are just for padding and should not
// inhibit creation of a memberwise initializer.
if (field->isUnnamedBitfield()) {
hasUnreferenceableStorage = true;
continue;
}
}
auto member = Impl.importDecl(nd);
if (!member) {
// We don't know what this field is. Assume it may be important in C.
hasUnreferenceableStorage = true;
hasMemberwiseInitializer = false;
continue;
}
if (isa<TypeDecl>(member)) {
// A struct nested inside another struct will either be logically
// a sibling of the outer struct, or contained inside of it, depending
// on if it has a declaration name or not.
//
// struct foo { struct bar { ... } baz; } // sibling
// struct foo { struct { ... } baz; } // child
//
// In the latter case, we add the imported type as a nested type
// of the parent.
//
// TODO: C++ types have different rules.
if (auto nominalDecl = dyn_cast<NominalTypeDecl>(member->getDeclContext())) {
assert(nominalDecl == result && "interesting nesting of C types?");
nominalDecl->addMember(member);
}
continue;
}
auto VD = cast<VarDecl>(member);
// Bitfields are imported as computed properties with Clang-generated
// accessors.
if (auto field = dyn_cast<clang::FieldDecl>(nd)) {
if (field->isBitField()) {
// We can't represent this struct completely in SIL anymore,
// but we're still able to define a memberwise initializer.
hasUnreferenceableStorage = true;
makeBitFieldAccessors(Impl,
const_cast<clang::RecordDecl *>(decl),
result,
const_cast<clang::FieldDecl *>(field),
VD);
}
}
if (decl->isUnion()) {
// Union fields should only be available indirectly via a computed
// property. Since the union is made of all of the fields at once,
// this is a trivial accessor that casts self to the correct
// field type.
// FIXME: Allow indirect field access of anonymous structs.
if (isa<clang::IndirectFieldDecl>(nd))
continue;
Decl *getter, *setter;
std::tie(getter, setter) = makeUnionFieldAccessors(Impl, result, VD);
members.push_back(VD);
// Create labeled initializers for unions that take one of the
// fields, which only initializes the data for that field.
auto valueCtor =
createValueConstructor(result, VD,
/*want param names*/true,
/*wantBody=*/!Impl.hasFinishedTypeChecking());
ctors.push_back(valueCtor);
} else {
members.push_back(VD);
}
}
bool hasReferenceableFields = !members.empty();
if (hasZeroInitializableStorage) {
// Add constructors for the struct.
ctors.push_back(createDefaultConstructor(result));
if (hasReferenceableFields && hasMemberwiseInitializer) {
// The default zero initializer suppresses the implicit value
// constructor that would normally be formed, so we have to add that
// explicitly as well.
//
// If we can completely represent the struct in SIL, leave the body
// implicit, otherwise synthesize one to call property setters.
bool wantBody = (hasUnreferenceableStorage &&
!Impl.hasFinishedTypeChecking());
auto valueCtor = createValueConstructor(result, members,
/*want param names*/true,
/*want body*/wantBody);
if (!hasUnreferenceableStorage)
valueCtor->setIsMemberwiseInitializer();
ctors.push_back(valueCtor);
}
}
for (auto member : members) {
result->addMember(member);
}
for (auto ctor : ctors) {
result->addMember(ctor);
}
result->setHasUnreferenceableStorage(hasUnreferenceableStorage);
// Add the struct decl to ExternalDefinitions so that IRGen can emit
// metadata for it.
// FIXME: There might be better ways to do this.
Impl.registerExternalDecl(result);
return result;
}
Decl *VisitClassTemplateSpecializationDecl(
const clang::ClassTemplateSpecializationDecl *decl) {
// FIXME: We could import specializations, but perhaps only as unnamed
// structural types.
return nullptr;
}
Decl *VisitClassTemplatePartialSpecializationDecl(
const clang::ClassTemplatePartialSpecializationDecl *decl) {
// Note: templates are not imported.
return nullptr;
}
Decl *VisitTemplateTypeParmDecl(const clang::TemplateTypeParmDecl *decl) {
// Note: templates are not imported.
return nullptr;
}
Decl *VisitEnumConstantDecl(const clang::EnumConstantDecl *decl) {
auto clangEnum = cast<clang::EnumDecl>(decl->getDeclContext());
auto name = Impl.importFullName(decl).Imported.getBaseName();
if (name.empty())
return nullptr;
switch (Impl.getEnumKind(clangEnum)) {
case EnumKind::Constants: {
// The enumeration was simply mapped to an integral type. Create a
// constant with that integral type.
// The context where the constant will be introduced.
auto dc = Impl.importDeclContextOf(clangEnum);
if (!dc)
return nullptr;
// Enumeration type.
auto &clangContext = Impl.getClangASTContext();
auto type = Impl.importType(clangContext.getTagDeclType(clangEnum),
ImportTypeKind::Value,
isInSystemModule(dc),
/*isFullyBridgeable*/false);
if (!type)
return nullptr;
// FIXME: Importing the type will recursively revisit this same
// EnumConstantDecl. Short-circuit out if we already emitted the import
// for this decl.
if (auto Known = Impl.importDeclCached(decl))
return Known;
// Create the global constant.
auto result = Impl.createConstant(name, dc, type,
clang::APValue(decl->getInitVal()),
ConstantConvertKind::Coerce,
/*static*/ false, decl);
Impl.ImportedDecls[decl->getCanonicalDecl()] = result;
return result;
}
case EnumKind::Unknown: {
// The enumeration was mapped to a struct containing the integral
// type. Create a constant with that struct type.
auto dc = Impl.importDeclContextOf(clangEnum);
if (!dc)
return nullptr;
// Import the enumeration type.
auto enumType = Impl.importType(
Impl.getClangASTContext().getTagDeclType(clangEnum),
ImportTypeKind::Value,
isInSystemModule(dc),
/*isFullyBridgeable*/false);
if (!enumType)
return nullptr;
// FIXME: Importing the type will can recursively revisit this same
// EnumConstantDecl. Short-circuit out if we already emitted the import
// for this decl.
if (auto Known = Impl.importDeclCached(decl))
return Known;
// Create the global constant.
auto result = Impl.createConstant(name, dc, enumType,
clang::APValue(decl->getInitVal()),
ConstantConvertKind::Construction,
/*static*/ false, decl);
Impl.ImportedDecls[decl->getCanonicalDecl()] = result;
return result;
}
case EnumKind::Enum:
case EnumKind::Options: {
// The enumeration was mapped to a high-level Swift type, and its
// elements were created as children of that enum. They aren't available
// independently.
return nullptr;
}
}
}
Decl *
VisitUnresolvedUsingValueDecl(const clang::UnresolvedUsingValueDecl *decl) {
// Note: templates are not imported.
return nullptr;
}
Decl *VisitIndirectFieldDecl(const clang::IndirectFieldDecl *decl) {
// Check whether the context of any of the fields in the chain is a
// union. If so, don't import this field.
for (auto f = decl->chain_begin(), fEnd = decl->chain_end(); f != fEnd;
++f) {
if (auto record = dyn_cast<clang::RecordDecl>((*f)->getDeclContext())) {
if (record->isUnion())
return nullptr;
}
}
auto name = Impl.importFullName(decl).Imported.getBaseName();
if (name.empty())
return nullptr;
auto dc = Impl.importDeclContextOf(decl);
if (!dc)
return nullptr;
auto type = Impl.importType(decl->getType(),
ImportTypeKind::Variable,
isInSystemModule(dc),
/*isFullyBridgeable*/false);
if (!type)
return nullptr;
// Map this indirect field to a Swift variable.
auto result = Impl.createDeclWithClangNode<VarDecl>(decl,
/*static*/ false, /*IsLet*/ false,
Impl.importSourceLoc(decl->getLocStart()),
name, type, dc);
return result;
}
Decl *VisitFunctionDecl(const clang::FunctionDecl *decl) {
auto dc = Impl.importDeclContextOf(decl);
if (!dc)
return nullptr;
// Determine the name of the function.
auto importedName = Impl.importFullName(decl);
if (!importedName)
return nullptr;
DeclName name = importedName.Imported;
bool hasCustomName = importedName.HasCustomName;
// Import the function type. If we have parameters, make sure their names
// get into the resulting function type.
ParameterList *bodyParams = nullptr;
Type type = Impl.importFunctionType(decl,
decl->getReturnType(),
{ decl->param_begin(),
decl->param_size() },
decl->isVariadic(),
decl->isNoReturn(),
isInSystemModule(dc),
hasCustomName, bodyParams, name);
if (!type)
return nullptr;
auto resultTy = type->castTo<FunctionType>()->getResult();
auto loc = Impl.importSourceLoc(decl->getLocation());
// If we had no argument labels to start with, add empty labels now.
assert(!name.isSimpleName() && "Cannot have a simple name here");
// FIXME: Poor location info.
auto nameLoc = Impl.importSourceLoc(decl->getLocation());
auto result = FuncDecl::create(
Impl.SwiftContext, SourceLoc(), StaticSpellingKind::None, loc,
name, nameLoc, SourceLoc(), SourceLoc(),
/*GenericParams=*/nullptr, type, bodyParams,
TypeLoc::withoutLoc(resultTy), dc, decl);
result->setBodyResultType(resultTy);
result->setInterfaceType(type);
result->setAccessibility(Accessibility::Public);
if (decl->isNoReturn())
result->getAttrs().add(
new (Impl.SwiftContext) NoReturnAttr(/*IsImplicit=*/false));
// Keep track of inline function bodies so that we can generate
// IR from them using Clang's IR generator.
if ((decl->isInlined() || decl->hasAttr<clang::AlwaysInlineAttr>() ||
!decl->isExternallyVisible())
&& decl->hasBody()) {
Impl.registerExternalDecl(result);
}
// Set availability.
auto knownFnInfo = Impl.getKnownGlobalFunction(decl);
if (knownFnInfo && knownFnInfo->Unavailable) {
Impl.markUnavailable(result, knownFnInfo->UnavailableMsg);
}
if (decl->isVariadic()) {
Impl.markUnavailable(result, "Variadic function is unavailable");
}
return result;
}
Decl *VisitCXXMethodDecl(const clang::CXXMethodDecl *decl) {
// FIXME: Import C++ member functions as methods.
return nullptr;
}
Decl *VisitFieldDecl(const clang::FieldDecl *decl) {
// Fields are imported as variables.
auto name = Impl.importFullName(decl).Imported.getBaseName();
if (name.empty())
return nullptr;
auto dc = Impl.importDeclContextOf(decl);
if (!dc)
return nullptr;
auto type = Impl.importType(decl->getType(),
ImportTypeKind::RecordField,
isInSystemModule(dc),
/*isFullyBridgeable*/false);
if (!type)
return nullptr;
auto result =
Impl.createDeclWithClangNode<VarDecl>(decl,
/*static*/ false, /*IsLet*/ false,
Impl.importSourceLoc(decl->getLocation()),
name, type, dc);
// Handle attributes.
if (decl->hasAttr<clang::IBOutletAttr>())
result->getAttrs().add(
new (Impl.SwiftContext) IBOutletAttr(/*IsImplicit=*/false));
// FIXME: Handle IBOutletCollection.
return result;
}
Decl *VisitObjCIvarDecl(const clang::ObjCIvarDecl *decl) {
// Disallow direct ivar access (and avoid conflicts with property names).
return nullptr;
}
Decl *VisitObjCAtDefsFieldDecl(const clang::ObjCAtDefsFieldDecl *decl) {
// @defs is an anachronism; ignore it.
return nullptr;
}
Decl *VisitVarDecl(const clang::VarDecl *decl) {
// FIXME: Swift does not have static variables in structs/classes yet.
if (decl->getDeclContext()->isRecord())
return nullptr;
// Variables are imported as... variables.
auto name = Impl.importFullName(decl).Imported.getBaseName();
if (name.empty())
return nullptr;
auto dc = Impl.importDeclContextOf(decl);
if (!dc)
return nullptr;
auto knownVarInfo = Impl.getKnownGlobalVariable(decl);
// Lookup nullability info.
OptionalTypeKind optionality = OTK_ImplicitlyUnwrappedOptional;
if (knownVarInfo) {
if (auto nullability = knownVarInfo->getNullability())
optionality = Impl.translateNullability(*nullability);
}
// If the declaration is const, consider it audited.
// We can assume that loading a const global variable doesn't
// involve an ownership transfer.
bool isAudited = decl->getType().isConstQualified();
Type type = Impl.importType(decl->getType(),
(isAudited ? ImportTypeKind::AuditedVariable
: ImportTypeKind::Variable),
isInSystemModule(dc),
/*isFullyBridgeable*/false);
if (!type)
return nullptr;
auto result = Impl.createDeclWithClangNode<VarDecl>(decl,
/*static*/ false,
Impl.shouldImportGlobalAsLet(decl->getType()),
Impl.importSourceLoc(decl->getLocation()),
name, type, dc);
// Check availability.
if (knownVarInfo && knownVarInfo->Unavailable) {
Impl.markUnavailable(result, knownVarInfo->UnavailableMsg);
}
if (!decl->hasExternalStorage())
Impl.registerExternalDecl(result);
return result;
}
Decl *VisitImplicitParamDecl(const clang::ImplicitParamDecl *decl) {
// Parameters are never directly imported.
return nullptr;
}
Decl *VisitParmVarDecl(const clang::ParmVarDecl *decl) {
// Parameters are never directly imported.
return nullptr;
}
Decl *
VisitNonTypeTemplateParmDecl(const clang::NonTypeTemplateParmDecl *decl) {
// Note: templates are not imported.
return nullptr;
}
Decl *VisitTemplateDecl(const clang::TemplateDecl *decl) {
// Note: templates are not imported.
return nullptr;
}
Decl *VisitUsingDecl(const clang::UsingDecl *decl) {
// Using declarations are not imported.
return nullptr;
}
Decl *VisitUsingShadowDecl(const clang::UsingShadowDecl *decl) {
// Using shadow declarations are not imported; rather, name lookup just
// looks through them.
return nullptr;
}
/// Add an @objc(name) attribute with the given, optional name expressed as
/// selector.
///
/// The importer should use this rather than adding the attribute directly.
void addObjCAttribute(ValueDecl *decl, Optional<ObjCSelector> name) {
auto &ctx = Impl.SwiftContext;
decl->getAttrs().add(ObjCAttr::create(ctx, name, /*implicit=*/true));
// If the declaration we attached the 'objc' attribute to is within a
// class, record it in the class.
if (auto contextTy = decl->getDeclContext()->getDeclaredInterfaceType()) {
if (auto classDecl = contextTy->getClassOrBoundGenericClass()) {
if (auto method = dyn_cast<AbstractFunctionDecl>(decl)) {
classDecl->recordObjCMethod(method);
}
}
}
}
/// Add an @objc(name) attribute with the given, optional name expressed as
/// selector.
///
/// The importer should use this rather than adding the attribute directly.
void addObjCAttribute(ValueDecl *decl, Identifier name) {
addObjCAttribute(decl, ObjCSelector(Impl.SwiftContext, 0, name));
}
Decl *VisitObjCMethodDecl(const clang::ObjCMethodDecl *decl) {
auto dc = Impl.importDeclContextOf(decl);
if (!dc)
return nullptr;
// While importing the DeclContext, we might have imported the decl
// itself.
if (auto Known = Impl.importDeclCached(decl))
return Known;
return VisitObjCMethodDecl(decl, dc);
}
/// Check whether we have already imported a method with the given
/// selector in the given context.
bool methodAlreadyImported(ObjCSelector selector, bool isInstance,
DeclContext *dc) {
// We only need to perform this check for classes.
auto classDecl
= dc->getDeclaredInterfaceType()->getClassOrBoundGenericClass();
if (!classDecl)
return false;
// Make sure we don't search in Clang modules for this method.
++Impl.ActiveSelectors[{selector, isInstance}];
// Look for a matching imported or deserialized member.
bool result = false;
for (auto decl : classDecl->lookupDirect(selector, isInstance)) {
if (decl->getClangDecl()
|| !decl->getDeclContext()->getParentSourceFile()) {
result = true;
break;
}
}
// Restore the previous active count in the active-selector mapping.
auto activeCount = Impl.ActiveSelectors.find({selector, isInstance});
--activeCount->second;
if (activeCount->second == 0)
Impl.ActiveSelectors.erase(activeCount);
return result;
}
/// If the given method is a factory method, import it as a constructor
Optional<ConstructorDecl *>
importFactoryMethodAsConstructor(Decl *member,
const clang::ObjCMethodDecl *decl,
ObjCSelector selector,
DeclContext *dc) {
// Import the full name of the method.
auto importedName = Impl.importFullName(decl);
// Check that we imported an initializer name.
DeclName initName = importedName;
if (initName.getBaseName() != Impl.SwiftContext.Id_init) return None;
// ... that came from a factory method.
if (importedName.InitKind != CtorInitializerKind::Factory &&
importedName.InitKind != CtorInitializerKind::ConvenienceFactory)
return None;
bool redundant = false;
auto result = importConstructor(decl, dc, false, importedName.InitKind,
/*required=*/false, selector,
importedName,
{decl->param_begin(), decl->param_size()},
decl->isVariadic(), redundant);
if ((result || redundant) && member) {
++NumFactoryMethodsAsInitializers;
// Mark the imported class method "unavailable", with a useful error
// message.
// TODO: Could add a replacement string?
llvm::SmallString<64> message;
llvm::raw_svector_ostream os(message);
os << "use object construction '"
<< decl->getClassInterface()->getName() << "(";
for (auto arg : initName.getArgumentNames()) {
os << arg << ":";
}
os << ")'";
member->getAttrs().add(
AvailableAttr::createUnconditional(
Impl.SwiftContext,
Impl.SwiftContext.AllocateCopy(os.str())));
}
/// Record the initializer as an alternative declaration for the
/// member.
if (result)
Impl.AlternateDecls[member] = result;
return result;
}
/// Determine if the given Objective-C instance method should also
/// be imported as a class method.
///
/// Objective-C root class instance methods are also reflected as
/// class methods.
bool shouldAlsoImportAsClassMethod(FuncDecl *method) {
// Only instance methods.
if (!method->isInstanceMember()) return false;
// Must be a method within a class or extension thereof.
auto classDecl =
method->getDeclContext()->isClassOrClassExtensionContext();
if (!classDecl) return false;
// The class must not have a superclass.
if (classDecl->getSuperclass()) return false;
// There must not already be a class method with the same
// selector.
auto objcClass =
cast_or_null<clang::ObjCInterfaceDecl>(classDecl->getClangDecl());
if (!objcClass) return false;
auto objcMethod =
cast_or_null<clang::ObjCMethodDecl>(method->getClangDecl());
if (!objcMethod) return false;
return !objcClass->getClassMethod(objcMethod->getSelector(),
/*AllowHidden=*/true);
}
Decl *VisitObjCMethodDecl(const clang::ObjCMethodDecl *decl,
DeclContext *dc) {
return VisitObjCMethodDecl(decl, dc, false);
}
private:
Decl *VisitObjCMethodDecl(const clang::ObjCMethodDecl *decl,
DeclContext *dc,
bool forceClassMethod) {
// If we have an init method, import it as an initializer.
if (Impl.isInitMethod(decl)) {
// Cannot force initializers into class methods.
if (forceClassMethod)
return nullptr;
return importConstructor(decl, dc, /*isImplicit=*/false, None,
/*required=*/false);
}
// Check whether we already imported this method.
if (!forceClassMethod && dc == Impl.importDeclContextOf(decl)) {
// FIXME: Should also be able to do this for forced class
// methods.
auto known = Impl.ImportedDecls.find(decl->getCanonicalDecl());
if (known != Impl.ImportedDecls.end())
return known->second;
}
// Check whether another method with the same selector has already been
// imported into this context.
ObjCSelector selector = Impl.importSelector(decl->getSelector());
bool isInstance = decl->isInstanceMethod() && !forceClassMethod;
if (methodAlreadyImported(selector, isInstance, dc))
return nullptr;
auto importedName
= Impl.importFullName(decl,
ClangImporter::Implementation::ImportNameFlags
::SuppressFactoryMethodAsInit);
if (!importedName)
return nullptr;
assert(dc->getDeclaredTypeOfContext() && "Method in non-type context?");
assert(isa<ClangModuleUnit>(dc->getModuleScopeContext()) &&
"Clang method in Swift context?");
// FIXME: We should support returning "Self.Type" for a root class
// instance method mirrored as a class method, but it currently causes
// problems for the type checker.
if (forceClassMethod && decl->hasRelatedResultType())
return nullptr;
// Add the implicit 'self' parameter patterns.
SmallVector<ParameterList *, 4> bodyParams;
auto selfVar =
ParamDecl::createSelf(SourceLoc(), dc,
/*isStatic*/
decl->isClassMethod() || forceClassMethod);
bodyParams.push_back(ParameterList::createWithoutLoc(selfVar));
SpecialMethodKind kind = SpecialMethodKind::Regular;
// FIXME: This doesn't handle implicit properties.
if (decl->isPropertyAccessor())
kind = SpecialMethodKind::PropertyAccessor;
else if (isNSDictionaryMethod(decl, Impl.objectForKeyedSubscript))
kind = SpecialMethodKind::NSDictionarySubscriptGetter;
// Import the type that this method will have.
DeclName name = importedName.Imported;
Optional<ForeignErrorConvention> errorConvention;
bodyParams.push_back(nullptr);
auto type = Impl.importMethodType(decl,
decl->getReturnType(),
{ decl->param_begin(),
decl->param_size() },
decl->isVariadic(),
decl->hasAttr<clang::NoReturnAttr>(),
isInSystemModule(dc),
&bodyParams.back(),
importedName,
name,
errorConvention,
kind);
if (!type)
return nullptr;
// Check whether we recursively imported this method
if (!forceClassMethod && dc == Impl.importDeclContextOf(decl)) {
// FIXME: Should also be able to do this for forced class
// methods.
auto known = Impl.ImportedDecls.find(decl->getCanonicalDecl());
if (known != Impl.ImportedDecls.end())
return known->second;
}
auto result = FuncDecl::create(
Impl.SwiftContext, SourceLoc(), StaticSpellingKind::None,
SourceLoc(), name, SourceLoc(), SourceLoc(), SourceLoc(),
/*GenericParams=*/nullptr, Type(),
bodyParams, TypeLoc(), dc, decl);
result->setAccessibility(Accessibility::Public);
auto resultTy = type->castTo<FunctionType>()->getResult();
Type interfaceType;
// If the method has a related result type that is representable
// in Swift as DynamicSelf, do so.
if (decl->hasRelatedResultType()) {
result->setDynamicSelf(true);
resultTy = result->getDynamicSelf();
assert(resultTy && "failed to get dynamic self");
Type interfaceSelfTy = result->getDynamicSelfInterface();
OptionalTypeKind nullability = OTK_ImplicitlyUnwrappedOptional;
if (auto typeNullability = decl->getReturnType()->getNullability(
Impl.getClangASTContext())) {
// If the return type has nullability, use it.
nullability = Impl.translateNullability(*typeNullability);
} else if (auto known = Impl.getKnownObjCMethod(decl)) {
// If the method is known to have nullability information for
// its return type, use that.
if (known->NullabilityAudited) {
nullability = Impl.translateNullability(known->getReturnTypeInfo());
}
}
if (nullability != OTK_None && !errorConvention.hasValue()) {
resultTy = OptionalType::get(nullability, resultTy);
interfaceSelfTy = OptionalType::get(nullability, interfaceSelfTy);
}
// Update the method type with the new result type.
auto methodTy = type->castTo<FunctionType>();
type = FunctionType::get(methodTy->getInput(), resultTy,
methodTy->getExtInfo());
// Create the interface type of the method.
interfaceType = FunctionType::get(methodTy->getInput(), interfaceSelfTy,
methodTy->getExtInfo());
interfaceType = FunctionType::get(selfVar->getType(), interfaceType);
}
// Add the 'self' parameter to the function type.
type = FunctionType::get(selfVar->getType(), type);
if (!interfaceType)
interfaceType = type;
if (auto proto = dyn_cast<ProtocolDecl>(dc)) {
std::tie(type, interfaceType)
= getProtocolMethodType(proto, type->castTo<AnyFunctionType>());
}
result->setBodyResultType(resultTy);
result->setType(type);
result->setInterfaceType(interfaceType);
// Optional methods in protocols.
if (decl->getImplementationControl() == clang::ObjCMethodDecl::Optional &&
isa<ProtocolDecl>(dc))
result->getAttrs().add(new (Impl.SwiftContext)
OptionalAttr(/*implicit*/false));
// Mark class methods as static.
if (decl->isClassMethod() || forceClassMethod)
result->setStatic();
if (forceClassMethod)
result->setImplicit();
// Mark this method @objc.
addObjCAttribute(result, selector);
// If this method overrides another method, mark it as such.
recordObjCOverride(result);
// Record the error convention.
if (errorConvention) {
result->setForeignErrorConvention(*errorConvention);
}
// Handle attributes.
if (decl->hasAttr<clang::IBActionAttr>())
result->getAttrs().add(
new (Impl.SwiftContext) IBActionAttr(/*IsImplicit=*/false));
// Check whether there's some special method to import.
if (!forceClassMethod) {
if (dc == Impl.importDeclContextOf(decl) &&
!Impl.ImportedDecls[decl->getCanonicalDecl()])
Impl.ImportedDecls[decl->getCanonicalDecl()] = result;
if (importedName.IsSubscriptAccessor) {
// If this was a subscript accessor, try to create a
// corresponding subscript declaration.
(void)importSubscript(result, decl);
} else if (shouldAlsoImportAsClassMethod(result)) {
// If we should import this instance method also as a class
// method, do so and mark the result as an alternate
// declaration.
if (auto imported = VisitObjCMethodDecl(decl, dc,
/*forceClassMethod=*/true))
Impl.AlternateDecls[result] = cast<ValueDecl>(imported);
} else if (auto factory = importFactoryMethodAsConstructor(
result, decl, selector, dc)) {
// We imported the factory method as an initializer, so
// record it as an alternate declaration.
if (*factory)
Impl.AlternateDecls[result] = *factory;
}
}
return result;
}
public:
/// Record the function or initializer overridden by the given Swift method.
void recordObjCOverride(AbstractFunctionDecl *decl) {
// Figure out the class in which this method occurs.
auto classTy = decl->getExtensionType()->getAs<ClassType>();
if (!classTy)
return;
auto superTy = classTy->getSuperclass(nullptr);
if (!superTy)
return;
// Dig out the Objective-C superclass.
auto superDecl = superTy->getAnyNominal();
SmallVector<ValueDecl *, 4> results;
superDecl->lookupQualified(superTy, decl->getFullName(),
NL_QualifiedDefault | NL_KnownNoDependency,
Impl.getTypeResolver(),
results);
for (auto member : results) {
if (member->getKind() != decl->getKind() ||
member->isInstanceMember() != decl->isInstanceMember())
continue;
// Set function override.
if (auto func = dyn_cast<FuncDecl>(decl)) {
auto foundFunc = cast<FuncDecl>(member);
// Require a selector match.
if (func->getObjCSelector() != foundFunc->getObjCSelector())
continue;
func->setOverriddenDecl(foundFunc);
return;
}
// Set constructor override.
auto ctor = cast<ConstructorDecl>(decl);
auto memberCtor = cast<ConstructorDecl>(member);
// Require a selector match.
if (ctor->getObjCSelector() != memberCtor->getObjCSelector())
continue;
ctor->setOverriddenDecl(memberCtor);
// Propagate 'required' to subclass initializers.
if (memberCtor->isRequired() &&
!ctor->getAttrs().hasAttribute<RequiredAttr>()) {
ctor->getAttrs().add(
new (Impl.SwiftContext) RequiredAttr(/*implicit=*/true));
}
}
}
/// \brief Given an imported method, try to import it as a constructor.
///
/// Objective-C methods in the 'init' family are imported as
/// constructors in Swift, enabling object construction syntax, e.g.,
///
/// \code
/// // in objc: [[NSArray alloc] initWithCapacity:1024]
/// NSArray(capacity: 1024)
/// \endcode
ConstructorDecl *importConstructor(const clang::ObjCMethodDecl *objcMethod,
DeclContext *dc,
bool implicit,
Optional<CtorInitializerKind> kind,
bool required) {
// Only methods in the 'init' family can become constructors.
assert(Impl.isInitMethod(objcMethod) && "Not a real init method");
// Check whether we've already created the constructor.
auto known = Impl.Constructors.find({objcMethod, dc});
if (known != Impl.Constructors.end())
return known->second;
// Check whether there is already a method with this selector.
auto selector = Impl.importSelector(objcMethod->getSelector());
if (methodAlreadyImported(selector, /*isInstance=*/true, dc))
return nullptr;
// Map the name and complete the import.
ArrayRef<const clang::ParmVarDecl *> params{
objcMethod->param_begin(),
objcMethod->param_end()
};
bool variadic = objcMethod->isVariadic();
auto importedName = Impl.importFullName(objcMethod);
if (!importedName) return nullptr;
// If we dropped the variadic, handle it now.
if (importedName.DroppedVariadic) {
selector = ObjCSelector(Impl.SwiftContext, selector.getNumArgs()-1,
selector.getSelectorPieces().drop_back());
params = params.drop_back(1);
variadic = false;
}
bool redundant;
return importConstructor(objcMethod, dc, implicit, kind, required,
selector, importedName, params,
variadic, redundant);
}
/// Returns the latest "introduced" version on the current platform for
/// \p D.
clang::VersionTuple findLatestIntroduction(const clang::Decl *D) {
clang::VersionTuple result;
for (auto *attr : D->specific_attrs<clang::AvailabilityAttr>()) {
if (attr->getPlatform()->getName() == "swift") {
clang::VersionTuple maxVersion{~0U, ~0U, ~0U};
return maxVersion;
}
// Does this availability attribute map to the platform we are
// currently targeting?
if (!Impl.PlatformAvailabilityFilter ||
!Impl.PlatformAvailabilityFilter(attr->getPlatform()->getName()))
continue;
// Take advantage of the empty version being 0.0.0.0.
result = std::max(result, attr->getIntroduced());
}
return result;
}
/// Returns true if importing \p objcMethod will produce a "better"
/// initializer than \p existingCtor.
bool
existingConstructorIsWorse(const ConstructorDecl *existingCtor,
const clang::ObjCMethodDecl *objcMethod,
CtorInitializerKind kind) {
CtorInitializerKind existingKind = existingCtor->getInitKind();
// If the new kind is the same as the existing kind, stick with
// the existing constructor.
if (existingKind == kind)
return false;
// Check for cases that are obviously better or obviously worse.
if (kind == CtorInitializerKind::Designated ||
existingKind == CtorInitializerKind::Factory)
return true;
if (kind == CtorInitializerKind::Factory ||
existingKind == CtorInitializerKind::Designated)
return false;
assert(kind == CtorInitializerKind::Convenience ||
kind == CtorInitializerKind::ConvenienceFactory);
assert(existingKind == CtorInitializerKind::Convenience ||
existingKind == CtorInitializerKind::ConvenienceFactory);
// Between different kinds of convenience initializers, keep the one that
// was introduced first.
// FIXME: But if one of them is now deprecated, should we prefer the
// other?
clang::VersionTuple introduced = findLatestIntroduction(objcMethod);
AvailabilityContext existingAvailability =
AvailabilityInference::availableRange(existingCtor,
Impl.SwiftContext);
assert(!existingAvailability.isKnownUnreachable());
if (existingAvailability.isAlwaysAvailable()) {
if (!introduced.empty())
return false;
} else {
VersionRange existingIntroduced = existingAvailability.getOSVersion();
if (introduced != existingIntroduced.getLowerEndpoint()) {
return introduced < existingIntroduced.getLowerEndpoint();
}
}
// The "introduced" versions are the same. Prefer Convenience over
// ConvenienceFactory, but otherwise prefer leaving things as they are.
if (kind == CtorInitializerKind::Convenience &&
existingKind == CtorInitializerKind::ConvenienceFactory)
return true;
return false;
}
using ImportedName = ClangImporter::Implementation::ImportedName;
/// \brief Given an imported method, try to import it as a constructor.
///
/// Objective-C methods in the 'init' family are imported as
/// constructors in Swift, enabling object construction syntax, e.g.,
///
/// \code
/// // in objc: [[NSArray alloc] initWithCapacity:1024]
/// NSArray(capacity: 1024)
/// \endcode
///
/// This variant of the function is responsible for actually binding the
/// constructor declaration appropriately.
ConstructorDecl *importConstructor(const clang::ObjCMethodDecl *objcMethod,
DeclContext *dc,
bool implicit,
Optional<CtorInitializerKind> kindIn,
bool required,
ObjCSelector selector,
ImportedName importedName,
ArrayRef<const clang::ParmVarDecl*> args,
bool variadic,
bool &redundant) {
redundant = false;
// Figure out the type of the container.
auto containerTy = dc->getDeclaredTypeOfContext();
assert(containerTy && "Method in non-type context?");
auto nominalOwner = containerTy->getAnyNominal();
// Find the interface, if we can.
const clang::ObjCInterfaceDecl *interface = nullptr;
if (auto classDecl = containerTy->getClassOrBoundGenericClass()) {
interface = dyn_cast_or_null<clang::ObjCInterfaceDecl>(
classDecl->getClangDecl());
}
// If we weren't told what kind of initializer this should be,
// figure it out now.
CtorInitializerKind kind;
if (kindIn) {
kind = *kindIn;
// If we know this is a designated initializer, mark it as such.
if (interface && Impl.hasDesignatedInitializers(interface) &&
Impl.isDesignatedInitializer(interface, objcMethod))
kind = CtorInitializerKind::Designated;
} else {
// If the owning Objective-C class has designated initializers and this
// is not one of them, treat it as a convenience initializer.
if (interface && Impl.hasDesignatedInitializers(interface) &&
!Impl.isDesignatedInitializer(interface, objcMethod)) {
kind = CtorInitializerKind::Convenience;
} else {
kind = CtorInitializerKind::Designated;
}
}
// Add the implicit 'self' parameter patterns.
SmallVector<ParameterList*, 4> bodyParams;
auto selfMetaVar = ParamDecl::createSelf(SourceLoc(), dc, /*static*/true);
auto selfTy = selfMetaVar->getType()->castTo<MetatypeType>()->getInstanceType();
bodyParams.push_back(ParameterList::createWithoutLoc(selfMetaVar));
// Import the type that this method will have.
Optional<ForeignErrorConvention> errorConvention;
DeclName name = importedName.Imported;
bodyParams.push_back(nullptr);
auto type = Impl.importMethodType(objcMethod,
objcMethod->getReturnType(),
args,
variadic,
objcMethod->hasAttr<clang::NoReturnAttr>(),
isInSystemModule(dc),
&bodyParams.back(),
importedName,
name,
errorConvention,
SpecialMethodKind::Constructor);
if (!type)
return nullptr;
// Determine the failability of this initializer.
auto oldFnType = type->castTo<AnyFunctionType>();
OptionalTypeKind failability;
(void)oldFnType->getResult()->getAnyOptionalObjectType(failability);
// Rebuild the function type with the appropriate result type;
Type resultTy = selfTy;
if (failability)
resultTy = OptionalType::get(failability, resultTy);
type = FunctionType::get(oldFnType->getInput(), resultTy,
oldFnType->getExtInfo());
// Add the 'self' parameter to the function types.
Type allocType = FunctionType::get(selfMetaVar->getType(), type);
Type initType = FunctionType::get(selfTy, type);
// Look for other imported constructors that occur in this context with
// the same name.
Type allocParamType = allocType->castTo<AnyFunctionType>()->getResult()
->castTo<AnyFunctionType>()->getInput();
for (auto other : nominalOwner->lookupDirect(name)) {
auto ctor = dyn_cast<ConstructorDecl>(other);
if (!ctor || ctor->isInvalid() ||
ctor->getAttrs().isUnavailable(Impl.SwiftContext) ||
!ctor->getClangDecl())
continue;
// Resolve the type of the constructor.
if (!ctor->hasType())
Impl.getTypeResolver()->resolveDeclSignature(ctor);
// If the types don't match, this is a different constructor with
// the same selector. This can happen when an overlay overloads an
// existing selector with a Swift-only signature.
Type ctorParamType = ctor->getType()->castTo<AnyFunctionType>()
->getResult()->castTo<AnyFunctionType>()
->getInput();
if (!ctorParamType->isEqual(allocParamType)) {
continue;
}
// If the existing constructor has a less-desirable kind, mark
// the existing constructor unavailable.
if (existingConstructorIsWorse(ctor, objcMethod, kind)) {
// Show exactly where this constructor came from.
llvm::SmallString<32> errorStr;
errorStr += "superseded by import of ";
if (objcMethod->isClassMethod())
errorStr += "+[";
else
errorStr += "-[";
auto objcDC = objcMethod->getDeclContext();
if (auto objcClass = dyn_cast<clang::ObjCInterfaceDecl>(objcDC)) {
errorStr += objcClass->getName();
errorStr += ' ';
} else if (auto objcCat = dyn_cast<clang::ObjCCategoryDecl>(objcDC)) {
errorStr += objcCat->getClassInterface()->getName();
auto catName = objcCat->getName();
if (!catName.empty()) {
errorStr += '(';
errorStr += catName;
errorStr += ')';
}
errorStr += ' ';
} else if (auto objcProto=dyn_cast<clang::ObjCProtocolDecl>(objcDC)) {
errorStr += objcProto->getName();
errorStr += ' ';
}
errorStr += objcMethod->getSelector().getAsString();
errorStr += ']';
auto attr
= AvailableAttr::createUnconditional(
Impl.SwiftContext,
Impl.SwiftContext.AllocateCopy(errorStr.str()));
ctor->getAttrs().add(attr);
continue;
}
// Otherwise, we shouldn't create a new constructor, because
// it will be no better than the existing one.
redundant = true;
return nullptr;
}
// Check whether we've already created the constructor.
auto known = Impl.Constructors.find({objcMethod, dc});
if (known != Impl.Constructors.end())
return known->second;
auto *selfVar = ParamDecl::createSelf(SourceLoc(), dc);
// Create the actual constructor.
auto result = Impl.createDeclWithClangNode<ConstructorDecl>(objcMethod,
name, SourceLoc(), failability, SourceLoc(), selfVar,
bodyParams.back(), /*GenericParams=*/nullptr,
SourceLoc(), dc);
// Make the constructor declaration immediately visible in its
// class or protocol type.
nominalOwner->makeMemberVisible(result);
addObjCAttribute(result, selector);
// Fix the types when we've imported into a protocol.
if (auto proto = dyn_cast<ProtocolDecl>(dc)) {
Type interfaceAllocType;
Type interfaceInitType;
std::tie(allocType, interfaceAllocType)
= getProtocolMethodType(proto, allocType->castTo<AnyFunctionType>());
std::tie(initType, interfaceInitType)
= getProtocolMethodType(proto, initType->castTo<AnyFunctionType>());
result->setInitializerInterfaceType(interfaceInitType);
result->setInterfaceType(interfaceAllocType);
} else {
result->setInterfaceType(allocType);
}
result->setType(allocType);
result->setInitializerType(initType);
if (implicit)
result->setImplicit();
// Set the kind of initializer.
result->setInitKind(kind);
// Consult API notes to determine whether this initializer is required.
if (!required && Impl.isRequiredInitializer(objcMethod))
required = true;
// Check whether this initializer satisfies a requirement in a protocol.
if (!required && !isa<ProtocolDecl>(dc) &&
objcMethod->isInstanceMethod()) {
auto objcParent = cast<clang::ObjCContainerDecl>(
objcMethod->getDeclContext());
if (isa<clang::ObjCProtocolDecl>(objcParent)) {
// An initializer declared in a protocol is required.
required = true;
} else {
// If the class in which this initializer was declared conforms to a
// protocol that requires this initializer, then this initializer is
// required.
SmallPtrSet<clang::ObjCProtocolDecl *, 8> objcProtocols;
objcParent->getASTContext().CollectInheritedProtocols(objcParent,
objcProtocols);
for (auto objcProto : objcProtocols) {
for (auto decl : objcProto->lookup(objcMethod->getSelector())) {
if (cast<clang::ObjCMethodDecl>(decl)->isInstanceMethod()) {
required = true;
break;
}
}
if (required)
break;
}
}
}
// If this initializer is required, add the appropriate attribute.
if (required) {
result->getAttrs().add(
new (Impl.SwiftContext) RequiredAttr(/*implicit=*/true));
}
// Record the error convention.
if (errorConvention) {
result->setForeignErrorConvention(*errorConvention);
}
// Record the constructor for future re-use.
Impl.Constructors[{objcMethod, dc}] = result;
// If this constructor overrides another constructor, mark it as such.
recordObjCOverride(result);
// Inform the context that we have external definitions.
Impl.registerExternalDecl(result);
return result;
}
/// \brief Retrieve the single variable described in the given pattern.
///
/// This routine assumes that the pattern is something very simple
/// like (x : type) or (x).
VarDecl *getSingleVar(Pattern *pattern) {
pattern = pattern->getSemanticsProvidingPattern();
if (auto tuple = dyn_cast<TuplePattern>(pattern)) {
pattern = tuple->getElement(0).getPattern()
->getSemanticsProvidingPattern();
}
return cast<NamedPattern>(pattern)->getDecl();
}
/// Retrieves the type and interface type for a protocol or
/// protocol extension method given the computed type of that
/// method.
std::pair<Type, Type> getProtocolMethodType(DeclContext *dc,
AnyFunctionType *fnType) {
Type type = PolymorphicFunctionType::get(fnType->getInput(),
fnType->getResult(),
dc->getGenericParamsOfContext());
// Figure out the curried 'self' type for the interface type. It's always
// either the generic parameter type 'Self' or a metatype thereof.
auto selfDecl = dc->getProtocolSelf();
auto selfTy = selfDecl->getDeclaredType();
auto interfaceInputTy = selfTy;
auto inputTy = fnType->getInput();
if (auto tupleTy = inputTy->getAs<TupleType>()) {
if (tupleTy->getNumElements() == 1)
inputTy = tupleTy->getElementType(0);
}
if (inputTy->is<MetatypeType>())
interfaceInputTy = MetatypeType::get(interfaceInputTy);
auto selfArchetype = selfDecl->getArchetype();
auto interfaceResultTy = fnType->getResult().transform(
[&](Type type) -> Type {
if (type->is<DynamicSelfType>() || type->isEqual(selfArchetype)) {
return DynamicSelfType::get(selfTy, Impl.SwiftContext);
}
return type;
});
Type interfaceType = GenericFunctionType::get(
dc->getGenericSignatureOfContext(),
interfaceInputTy,
interfaceResultTy,
AnyFunctionType::ExtInfo());
return { type, interfaceType };
}
/// Build a declaration for an Objective-C subscript getter.
FuncDecl *buildSubscriptGetterDecl(const FuncDecl *getter, Type elementTy,
DeclContext *dc, ParamDecl *index) {
auto &context = Impl.SwiftContext;
auto loc = getter->getLoc();
// self & index.
ParameterList *getterArgs[] = {
ParameterList::createSelf(SourceLoc(), dc),
ParameterList::create(context, index)
};
// Form the type of the getter.
auto getterType = ParameterList::getFullType(elementTy, getterArgs);
// If we're in a protocol, the getter thunk will be polymorphic.
Type interfaceType;
if (dc->isProtocolOrProtocolExtensionContext()) {
std::tie(getterType, interfaceType)
= getProtocolMethodType(dc, getterType->castTo<AnyFunctionType>());
} else {
interfaceType = getterType;
}
// Create the getter thunk.
FuncDecl *thunk = FuncDecl::create(
context, SourceLoc(), StaticSpellingKind::None, loc,
Identifier(), SourceLoc(), SourceLoc(), SourceLoc(), nullptr, getterType,
getterArgs, TypeLoc::withoutLoc(elementTy), dc,
getter->getClangNode());
thunk->setBodyResultType(elementTy);
thunk->setInterfaceType(interfaceType);
thunk->setAccessibility(Accessibility::Public);
auto objcAttr = getter->getAttrs().getAttribute<ObjCAttr>();
assert(objcAttr);
thunk->getAttrs().add(objcAttr->clone(context));
// FIXME: Should we record thunks?
return thunk;
}
/// Build a declaration for an Objective-C subscript setter.
FuncDecl *buildSubscriptSetterDecl(const FuncDecl *setter, Type elementTy,
DeclContext *dc, ParamDecl *index) {
auto &context = Impl.SwiftContext;
auto loc = setter->getLoc();
// Objective-C subscript setters are imported with a function type
// such as:
//
// (self) -> (value, index) -> ()
//
// Build a setter thunk with the latter signature that maps to the
// former.
auto valueIndex = setter->getParameterList(1);
// 'self'
auto selfDecl = ParamDecl::createSelf(SourceLoc(), dc);
auto paramVarDecl = new (context) ParamDecl(/*isLet=*/false, SourceLoc(),
SourceLoc(), Identifier(),loc,
valueIndex->get(0)->getName(),
elementTy, dc);
auto valueIndicesPL = ParameterList::create(context, {
paramVarDecl,
index
});
// Form the argument lists.
ParameterList *setterArgs[] = {
ParameterList::createWithoutLoc(selfDecl),
valueIndicesPL
};
// Form the type of the setter.
Type setterType = ParameterList::getFullType(TupleType::getEmpty(context),
setterArgs);
// If we're in a protocol or extension thereof, the setter thunk
// will be polymorphic.
Type interfaceType;
if (dc->isProtocolOrProtocolExtensionContext()) {
std::tie(setterType, interfaceType)
= getProtocolMethodType(dc, setterType->castTo<AnyFunctionType>());
} else {
interfaceType = setterType;
}
// Create the setter thunk.
FuncDecl *thunk = FuncDecl::create(
context, SourceLoc(), StaticSpellingKind::None, setter->getLoc(),
Identifier(), SourceLoc(), SourceLoc(), SourceLoc(), nullptr,
setterType,
setterArgs, TypeLoc::withoutLoc(TupleType::getEmpty(context)), dc,
setter->getClangNode());
thunk->setBodyResultType(TupleType::getEmpty(context));
thunk->setInterfaceType(interfaceType);
thunk->setAccessibility(Accessibility::Public);
auto objcAttr = setter->getAttrs().getAttribute<ObjCAttr>();
assert(objcAttr);
thunk->getAttrs().add(objcAttr->clone(context));
return thunk;
}
/// Retrieve the element type and of a subscript setter.
std::pair<Type, ParamDecl *>
decomposeSubscriptSetter(FuncDecl *setter) {
auto *PL = setter->getParameterList(1);
if (PL->size() != 2)
return { nullptr, nullptr };
return { PL->get(0)->getType(), PL->get(1) };
}
/// Rectify the (possibly different) types determined by the
/// getter and setter for a subscript.
///
/// \param canUpdateType whether the type of subscript can be
/// changed from the getter type to something compatible with both
/// the getter and the setter.
///
/// \returns the type to be used for the subscript, or a null type
/// if the types cannot be rectified.
Type rectifySubscriptTypes(Type getterType, Type setterType,
bool canUpdateType) {
// If the caller couldn't provide a setter type, there is
// nothing to rectify.
if (!setterType) return nullptr;
// Trivial case: same type in both cases.
if (getterType->isEqual(setterType)) return getterType;
// The getter/setter types are different. If we cannot update
// the type, we have to fail.
if (!canUpdateType) return nullptr;
// Unwrap one level of optionality from each.
if (Type getterObjectType = getterType->getAnyOptionalObjectType())
getterType = getterObjectType;
if (Type setterObjectType = setterType->getAnyOptionalObjectType())
setterType = setterObjectType;
// If they are still different, fail.
// FIXME: We could produce the greatest common supertype of the
// two types.
if (!getterType->isEqual(setterType)) return nullptr;
// Create an implicitly-unwrapped optional of the object type,
// which subsumes both behaviors.
return ImplicitlyUnwrappedOptionalType::get(setterType);
}
void recordObjCOverride(SubscriptDecl *subscript) {
// Figure out the class in which this subscript occurs.
auto classTy =
subscript->getDeclContext()->isClassOrClassExtensionContext();
if (!classTy)
return;
auto superTy = classTy->getSuperclass();
if (!superTy)
return;
// Determine whether this subscript operation overrides another subscript
// operation.
SmallVector<ValueDecl *, 2> lookup;
subscript->getModuleContext()
->lookupQualified(superTy, subscript->getFullName(),
NL_QualifiedDefault | NL_KnownNoDependency,
Impl.getTypeResolver(), lookup);
Type unlabeledIndices;
for (auto result : lookup) {
auto parentSub = dyn_cast<SubscriptDecl>(result);
if (!parentSub)
continue;
// Compute the type of indices for our own subscript operation, lazily.
if (!unlabeledIndices) {
unlabeledIndices = subscript->getIndices()->getType(Impl.SwiftContext)
->getUnlabeledType(Impl.SwiftContext);
}
// Compute the type of indices for the subscript we found.
auto parentUnlabeledIndices =
parentSub->getIndices()->getType(Impl.SwiftContext)
->getUnlabeledType(Impl.SwiftContext);
if (!unlabeledIndices->isEqual(parentUnlabeledIndices))
continue;
// The index types match. This is an override, so mark it as such.
subscript->setOverriddenDecl(parentSub);
auto getterThunk = subscript->getGetter();
getterThunk->setOverriddenDecl(parentSub->getGetter());
if (auto parentSetter = parentSub->getSetter()) {
if (auto setterThunk = subscript->getSetter())
setterThunk->setOverriddenDecl(parentSetter);
}
// FIXME: Eventually, deal with multiple overrides.
break;
}
}
/// \brief Given either the getter or setter for a subscript operation,
/// create the Swift subscript declaration.
SubscriptDecl *importSubscript(Decl *decl,
const clang::ObjCMethodDecl *objcMethod) {
assert(objcMethod->isInstanceMethod() && "Caller must filter");
// If the method we're attempting to import has the
// swift_private attribute, don't import as a subscript.
if (objcMethod->hasAttr<clang::SwiftPrivateAttr>())
return nullptr;
// Figure out where to look for the counterpart.
const clang::ObjCInterfaceDecl *interface = nullptr;
const clang::ObjCProtocolDecl *protocol =
dyn_cast<clang::ObjCProtocolDecl>(objcMethod->getDeclContext());
if (!protocol)
interface = objcMethod->getClassInterface();
auto lookupInstanceMethod = [&](clang::Selector Sel) ->
const clang::ObjCMethodDecl * {
if (interface)
return interface->lookupInstanceMethod(Sel);
return protocol->lookupInstanceMethod(Sel);
};
auto findCounterpart = [&](clang::Selector sel) -> FuncDecl * {
// If the declaration we're starting from is in a class, first
// look for a class member with the appropriate selector.
if (auto classDecl
= decl->getDeclContext()->isClassOrClassExtensionContext()) {
auto swiftSel = Impl.importSelector(sel);
for (auto found : classDecl->lookupDirect(swiftSel, true)) {
if (auto foundFunc = dyn_cast<FuncDecl>(found))
return foundFunc;
}
}
// Find based on selector within the current type.
auto counterpart = lookupInstanceMethod(sel);
if (!counterpart) return nullptr;
return cast_or_null<FuncDecl>(Impl.importDecl(counterpart));
};
// Determine the selector of the counterpart.
FuncDecl *getter = nullptr, *setter = nullptr;
clang::Selector counterpartSelector;
if (objcMethod->getSelector() == Impl.objectAtIndexedSubscript) {
getter = cast<FuncDecl>(decl);
counterpartSelector = Impl.setObjectAtIndexedSubscript;
} else if (objcMethod->getSelector() == Impl.setObjectAtIndexedSubscript){
setter = cast<FuncDecl>(decl);
counterpartSelector = Impl.objectAtIndexedSubscript;
} else if (objcMethod->getSelector() == Impl.objectForKeyedSubscript) {
getter = cast<FuncDecl>(decl);
counterpartSelector = Impl.setObjectForKeyedSubscript;
} else if (objcMethod->getSelector() == Impl.setObjectForKeyedSubscript) {
setter = cast<FuncDecl>(decl);
counterpartSelector = Impl.objectForKeyedSubscript;
} else {
llvm_unreachable("Unknown getter/setter selector");
}
// Find the counterpart.
bool optionalMethods = (objcMethod->getImplementationControl() ==
clang::ObjCMethodDecl::Optional);
if (auto *counterpart = findCounterpart(counterpartSelector)) {
// If the counterpart to the method we're attempting to import has the
// swift_private attribute, don't import as a subscript.
if (auto importedFrom = counterpart->getClangDecl()) {
if (importedFrom->hasAttr<clang::SwiftPrivateAttr>())
return nullptr;
auto counterpartMethod
= dyn_cast<clang::ObjCMethodDecl>(importedFrom);
if (optionalMethods)
optionalMethods = (counterpartMethod->getImplementationControl() ==
clang::ObjCMethodDecl::Optional);
}
assert(!counterpart || !counterpart->isStatic());
if (getter)
setter = counterpart;
else
getter = counterpart;
}
// Swift doesn't have write-only subscripting.
if (!getter)
return nullptr;
// Check whether we've already created a subscript operation for
// this getter/setter pair.
if (auto subscript = Impl.Subscripts[{getter, setter}]) {
return subscript->getDeclContext() == decl->getDeclContext()
? subscript
: nullptr;
}
// Find the getter indices and make sure they match.
ParamDecl *getterIndex;
{
auto params = getter->getParameterList(1);
if (params->size() != 1)
return nullptr;
getterIndex = params->get(0);
}
// Compute the element type based on the getter, looking through
// the implicit 'self' parameter and the normal function
// parameters.
auto elementTy
= getter->getType()->castTo<AnyFunctionType>()->getResult()
->castTo<AnyFunctionType>()->getResult();
// Local function to mark the setter unavailable.
auto makeSetterUnavailable = [&] {
if (setter && !setter->getAttrs().isUnavailable(Impl.SwiftContext))
Impl.markUnavailable(setter, "use subscripting");
};
// If we have a setter, rectify it with the getter.
ParamDecl *setterIndex;
bool getterAndSetterInSameType = false;
if (setter) {
// Whether there is an existing read-only subscript for which
// we have now found a setter.
SubscriptDecl *existingSubscript = Impl.Subscripts[{getter, nullptr}];
// Are the getter and the setter in the same type.
getterAndSetterInSameType =
(getter->getDeclContext()
->isNominalTypeOrNominalTypeExtensionContext()
== setter->getDeclContext()
->isNominalTypeOrNominalTypeExtensionContext());
// Whether we can update the types involved in the subscript
// operation.
bool canUpdateSubscriptType
= !existingSubscript && getterAndSetterInSameType;
// Determine the setter's element type and indices.
Type setterElementTy;
std::tie(setterElementTy, setterIndex) =
decomposeSubscriptSetter(setter);
// Rectify the setter element type with the getter's element type.
Type newElementTy = rectifySubscriptTypes(elementTy, setterElementTy,
canUpdateSubscriptType);
if (!newElementTy)
return decl == getter ? existingSubscript : nullptr;
// Update the element type.
elementTy = newElementTy;
// Make sure that the index types are equivalent.
// FIXME: Rectify these the same way we do for element types.
if (!setterIndex->getType()->isEqual(getterIndex->getType())) {
// If there is an existing subscript operation, we're done.
if (existingSubscript)
return decl == getter ? existingSubscript : nullptr;
// Otherwise, just forget we had a setter.
// FIXME: This feels very, very wrong.
setter = nullptr;
setterIndex = nullptr;
}
// If there is an existing subscript within this context, we
// cannot create a new subscript. Update it if possible.
if (setter && existingSubscript && getterAndSetterInSameType) {
// Can we update the subscript by adding the setter?
if (existingSubscript->hasClangNode() &&
!existingSubscript->isSettable()) {
// Create the setter thunk.
auto setterThunk = buildSubscriptSetterDecl(
setter, elementTy, setter->getDeclContext(),
setterIndex);
// Set the computed setter.
existingSubscript->setComputedSetter(setterThunk);
// Mark the setter as unavailable; one should use
// subscripting when it is present.
makeSetterUnavailable();
}
return decl == getter ? existingSubscript : nullptr;
}
}
// The context into which the subscript should go.
bool associateWithSetter = setter && !getterAndSetterInSameType;
DeclContext *dc = associateWithSetter ? setter->getDeclContext()
: getter->getDeclContext();
// Build the thunks.
FuncDecl *getterThunk = buildSubscriptGetterDecl(getter, elementTy, dc,
getterIndex);
FuncDecl *setterThunk = nullptr;
if (setter)
setterThunk = buildSubscriptSetterDecl(setter, elementTy, dc,
setterIndex);
// Build the subscript declaration.
auto &context = Impl.SwiftContext;
auto bodyParams = getterThunk->getParameterList(1)->clone(context);
DeclName name(context, context.Id_subscript, { Identifier() });
auto subscript
= Impl.createDeclWithClangNode<SubscriptDecl>(getter->getClangNode(),
name, decl->getLoc(), bodyParams,
decl->getLoc(),
TypeLoc::withoutLoc(elementTy), dc);
/// Record the subscript as an alternative declaration.
Impl.AlternateDecls[associateWithSetter ? setter : getter] = subscript;
subscript->makeComputed(SourceLoc(), getterThunk, setterThunk, nullptr,
SourceLoc());
auto indicesType = bodyParams->getType(context);
subscript->setType(FunctionType::get(indicesType, elementTy));
subscript->setInterfaceType(FunctionType::get(indicesType, elementTy));
addObjCAttribute(subscript, None);
// Optional subscripts in protocols.
if (optionalMethods && isa<ProtocolDecl>(dc))
subscript->getAttrs().add(new (Impl.SwiftContext) OptionalAttr(true));
// Note that we've created this subscript.
Impl.Subscripts[{getter, setter}] = subscript;
if (setter && !Impl.Subscripts[{getter, nullptr}])
Impl.Subscripts[{getter, nullptr}] = subscript;
// Make the getter/setter methods unavailable.
if (!getter->getAttrs().isUnavailable(Impl.SwiftContext))
Impl.markUnavailable(getter, "use subscripting");
makeSetterUnavailable();
// Wire up overrides.
recordObjCOverride(subscript);
return subscript;
}
/// Import the accessor and its attributes.
FuncDecl *importAccessor(clang::ObjCMethodDecl *clangAccessor,
DeclContext *dc) {
auto *accessor =
cast_or_null<FuncDecl>(VisitObjCMethodDecl(clangAccessor, dc));
if (!accessor) {
return nullptr;
}
Impl.importAttributes(clangAccessor, accessor);
return accessor;
}
public:
/// Recursively add the given protocol and its inherited protocols to the
/// given vector, guarded by the known set of protocols.
void addProtocols(ProtocolDecl *protocol,
SmallVectorImpl<ProtocolDecl *> &protocols,
llvm::SmallPtrSet<ProtocolDecl *, 4> &known) {
if (!known.insert(protocol).second)
return;
protocols.push_back(protocol);
for (auto inherited : protocol->getInheritedProtocols(
Impl.getTypeResolver()))
addProtocols(inherited, protocols, known);
}
// Import the given Objective-C protocol list, along with any
// implicitly-provided protocols, and attach them to the given
// declaration.
void importObjCProtocols(Decl *decl,
const clang::ObjCProtocolList &clangProtocols,
SmallVectorImpl<TypeLoc> &inheritedTypes) {
SmallVector<ProtocolDecl *, 4> protocols;
llvm::SmallPtrSet<ProtocolDecl *, 4> knownProtocols;
if (auto nominal = dyn_cast<NominalTypeDecl>(decl)) {
nominal->getImplicitProtocols(protocols);
knownProtocols.insert(protocols.begin(), protocols.end());
}
for (auto cp = clangProtocols.begin(), cpEnd = clangProtocols.end();
cp != cpEnd; ++cp) {
if (auto proto = cast_or_null<ProtocolDecl>(Impl.importDecl(*cp))) {
addProtocols(proto, protocols, knownProtocols);
inheritedTypes.push_back(
TypeLoc::withoutLoc(proto->getDeclaredType()));
}
}
addObjCProtocolConformances(decl, protocols);
}
/// Add conformances to the given Objective-C protocols to the
/// given declaration.
void addObjCProtocolConformances(Decl *decl,
ArrayRef<ProtocolDecl*> protocols) {
// Set the inherited protocols of a protocol.
if (auto proto = dyn_cast<ProtocolDecl>(decl)) {
// Copy the list of protocols.
MutableArrayRef<ProtocolDecl *> allProtocols
= Impl.SwiftContext.AllocateCopy(protocols);
proto->setInheritedProtocols(allProtocols);
return;
}
Impl.recordImportedProtocols(decl, protocols);
// Synthesize trivial conformances for each of the protocols.
SmallVector<ProtocolConformance *, 4> conformances;
;
auto dc = decl->getInnermostDeclContext();
auto &ctx = Impl.SwiftContext;
for (unsigned i = 0, n = protocols.size(); i != n; ++i) {
// FIXME: Build a superclass conformance if the superclass
// conforms.
auto conformance
= ctx.getConformance(dc->getDeclaredTypeOfContext(),
protocols[i], SourceLoc(),
dc,
ProtocolConformanceState::Incomplete);
Impl.scheduleFinishProtocolConformance(conformance);
conformances.push_back(conformance);
}
// Set the conformances.
// FIXME: This could be lazier.
unsigned id = Impl.allocateDelayedConformance(std::move(conformances));
if (auto nominal = dyn_cast<NominalTypeDecl>(decl)) {
nominal->setConformanceLoader(&Impl, id);
} else {
auto ext = cast<ExtensionDecl>(decl);
ext->setConformanceLoader(&Impl, id);
}
}
/// Import members of the given Objective-C container and add them to the
/// list of corresponding Swift members.
void importObjCMembers(const clang::ObjCContainerDecl *decl,
DeclContext *swiftContext,
SmallVectorImpl<Decl *> &members) {
llvm::SmallPtrSet<Decl *, 4> knownMembers;
for (auto m = decl->decls_begin(), mEnd = decl->decls_end();
m != mEnd; ++m) {
auto nd = dyn_cast<clang::NamedDecl>(*m);
if (!nd || nd != nd->getCanonicalDecl())
continue;
auto member = Impl.importDecl(nd);
if (!member) continue;
if (auto objcMethod = dyn_cast<clang::ObjCMethodDecl>(nd)) {
// If there is an alternate declaration for this member, add it.
if (auto alternate = Impl.getAlternateDecl(member)) {
if (alternate->getDeclContext() == member->getDeclContext() &&
knownMembers.insert(alternate).second)
members.push_back(alternate);
}
// If this declaration shouldn't be visible, don't add it to
// the list.
if (Impl.shouldSuppressDeclImport(objcMethod)) continue;
}
members.push_back(member);
}
}
static bool
classImplementsProtocol(const clang::ObjCInterfaceDecl *constInterface,
const clang::ObjCProtocolDecl *constProto,
bool checkCategories) {
auto interface = const_cast<clang::ObjCInterfaceDecl *>(constInterface);
auto proto = const_cast<clang::ObjCProtocolDecl *>(constProto);
return interface->ClassImplementsProtocol(proto, checkCategories);
}
/// \brief Import the members of all of the protocols to which the given
/// Objective-C class, category, or extension explicitly conforms into
/// the given list of members, so long as the method was not already
/// declared in the class.
///
/// FIXME: This whole thing is a hack, because name lookup should really
/// just find these members when it looks in the protocol. Unfortunately,
/// that's not something the name lookup code can handle right now, and
/// it may still be necessary when the protocol's instance methods become
/// class methods on a root class (e.g. NSObject-the-protocol's instance
/// methods become class methods on NSObject).
void importMirroredProtocolMembers(const clang::ObjCContainerDecl *decl,
DeclContext *dc,
ArrayRef<ProtocolDecl *> protocols,
SmallVectorImpl<Decl *> &members,
ASTContext &Ctx) {
assert(dc);
const clang::ObjCInterfaceDecl *interfaceDecl = nullptr;
const ClangModuleUnit *declModule;
const ClangModuleUnit *interfaceModule;
for (auto proto : protocols) {
auto clangProto =
cast_or_null<clang::ObjCProtocolDecl>(proto->getClangDecl());
if (!clangProto)
continue;
if (!interfaceDecl) {
declModule = Impl.getClangModuleForDecl(decl);
if ((interfaceDecl = dyn_cast<clang::ObjCInterfaceDecl>(decl))) {
interfaceModule = declModule;
} else {
auto category = cast<clang::ObjCCategoryDecl>(decl);
interfaceDecl = category->getClassInterface();
interfaceModule = Impl.getClangModuleForDecl(interfaceDecl);
}
}
// Don't import a protocol's members if the superclass already adopts
// the protocol, or (for categories) if the class itself adopts it
// in its main @interface.
if (decl != interfaceDecl)
if (classImplementsProtocol(interfaceDecl, clangProto, false))
continue;
if (auto superInterface = interfaceDecl->getSuperClass())
if (classImplementsProtocol(superInterface, clangProto, true))
continue;
for (auto member : proto->getMembers()) {
if (auto prop = dyn_cast<VarDecl>(member)) {
auto objcProp =
dyn_cast_or_null<clang::ObjCPropertyDecl>(prop->getClangDecl());
if (!objcProp)
continue;
// We can't import a property if there's already a method with this
// name. (This also covers other properties with that same name.)
// FIXME: We should still mirror the setter as a method if it's
// not already there.
clang::Selector sel = objcProp->getGetterName();
if (interfaceDecl->getInstanceMethod(sel))
continue;
bool inNearbyCategory =
std::any_of(interfaceDecl->visible_categories_begin(),
interfaceDecl->visible_categories_end(),
[=](const clang::ObjCCategoryDecl *category)->bool {
if (category != decl) {
auto *categoryModule = Impl.getClangModuleForDecl(category);
if (categoryModule != declModule &&
categoryModule != interfaceModule) {
return false;
}
}
return category->getInstanceMethod(sel);
});
if (inNearbyCategory)
continue;
if (auto imported = Impl.importMirroredDecl(objcProp, dc, proto)) {
members.push_back(imported);
// FIXME: We should mirror properties of the root class onto the
// metatype.
}
continue;
}
auto afd = dyn_cast<AbstractFunctionDecl>(member);
if (!afd)
continue;
if (auto func = dyn_cast<FuncDecl>(afd))
if (func->isAccessor())
continue;
auto objcMethod =
dyn_cast_or_null<clang::ObjCMethodDecl>(member->getClangDecl());
if (!objcMethod)
continue;
// When mirroring an initializer, make it designated and required.
if (Impl.isInitMethod(objcMethod)) {
// Import the constructor.
if (auto imported = importConstructor(
objcMethod, dc, /*implicit=*/true,
CtorInitializerKind::Designated,
/*required=*/true)){
members.push_back(imported);
}
continue;
}
// Import the method.
if (auto imported = Impl.importMirroredDecl(objcMethod, dc, proto)) {
members.push_back(imported);
if (auto alternate = Impl.getAlternateDecl(imported))
if (imported->getDeclContext() == alternate->getDeclContext())
members.push_back(alternate);
}
}
}
}
/// \brief Import constructors from our superclasses (and their
/// categories/extensions), effectively "inheriting" constructors.
void importInheritedConstructors(ClassDecl *classDecl,
SmallVectorImpl<Decl *> &newMembers) {
if (!classDecl->hasSuperclass())
return;
auto curObjCClass
= cast<clang::ObjCInterfaceDecl>(classDecl->getClangDecl());
auto inheritConstructors = [&](DeclRange members,
Optional<CtorInitializerKind> kind) {
for (auto member : members) {
auto ctor = dyn_cast<ConstructorDecl>(member);
if (!ctor)
continue;
// Don't inherit (non-convenience) factory initializers.
// Note that convenience factories return instancetype and can be
// inherited.
switch (ctor->getInitKind()) {
case CtorInitializerKind::Factory:
continue;
case CtorInitializerKind::ConvenienceFactory:
case CtorInitializerKind::Convenience:
case CtorInitializerKind::Designated:
break;
}
auto objcMethod
= dyn_cast_or_null<clang::ObjCMethodDecl>(ctor->getClangDecl());
if (!objcMethod)
continue;
auto &clangSourceMgr = Impl.getClangASTContext().getSourceManager();
clang::PrettyStackTraceDecl trace(objcMethod, clang::SourceLocation(),
clangSourceMgr,
"importing (inherited)");
// If this initializer came from a factory method, inherit
// it as an initializer.
if (objcMethod->isClassMethod()) {
assert(ctor->getInitKind() ==
CtorInitializerKind::ConvenienceFactory);
ImportedName importedName = Impl.importFullName(objcMethod);
importedName.HasCustomName = true;
bool redundant;
if (auto newCtor = importConstructor(objcMethod, classDecl,
/*implicit=*/true,
ctor->getInitKind(),
/*required=*/false,
ctor->getObjCSelector(),
importedName,
objcMethod->parameters(),
objcMethod->isVariadic(),
redundant)) {
Impl.importAttributes(objcMethod, newCtor, curObjCClass);
newMembers.push_back(newCtor);
}
continue;
}
// Figure out what kind of constructor this will be.
CtorInitializerKind myKind;
bool isRequired = false;
if (ctor->isRequired()) {
// Required initializers are always considered designated.
isRequired = true;
myKind = CtorInitializerKind::Designated;
} else if (kind) {
myKind = *kind;
} else {
myKind = ctor->getInitKind();
}
// Import the constructor into this context.
if (auto newCtor = importConstructor(objcMethod, classDecl,
/*implicit=*/true,
myKind,
isRequired)) {
Impl.importAttributes(objcMethod, newCtor, curObjCClass);
newMembers.push_back(newCtor);
}
}
};
// The kind of initializer to import. If this class has designated
// initializers, everything it imports is a convenience initializer.
Optional<CtorInitializerKind> kind;
if (Impl.hasDesignatedInitializers(curObjCClass))
kind = CtorInitializerKind::Convenience;
auto superclass
= cast<ClassDecl>(classDecl->getSuperclass()->getAnyNominal());
// If we have a superclass, import from it.
if (auto superclassClangDecl = superclass->getClangDecl()) {
if (isa<clang::ObjCInterfaceDecl>(superclassClangDecl)) {
inheritConstructors(superclass->getMembers(), kind);
for (auto ext : superclass->getExtensions())
inheritConstructors(ext->getMembers(), kind);
}
}
}
Decl *VisitObjCCategoryDecl(const clang::ObjCCategoryDecl *decl) {
// Objective-C categories and extensions map to Swift extensions.
clang::SourceLocation categoryNameLoc = decl->getCategoryNameLoc();
if (categoryNameLoc.isMacroID()) {
// Climb up to the top-most macro invocation.
clang::Preprocessor &PP = Impl.getClangPreprocessor();
clang::SourceManager &SM = PP.getSourceManager();
clang::SourceLocation macroCaller =
SM.getImmediateMacroCallerLoc(categoryNameLoc);
while (macroCaller.isMacroID()) {
categoryNameLoc = macroCaller;
macroCaller = SM.getImmediateMacroCallerLoc(categoryNameLoc);
}
if (PP.getImmediateMacroName(categoryNameLoc) == "SWIFT_EXTENSION")
return nullptr;
}
// Find the Swift class being extended.
auto objcClass
= cast_or_null<ClassDecl>(Impl.importDecl(decl->getClassInterface()));
if (!objcClass)
return nullptr;
auto dc = Impl.importDeclContextOf(decl);
if (!dc)
return nullptr;
// Create the extension declaration and record it.
auto loc = Impl.importSourceLoc(decl->getLocStart());
auto result = ExtensionDecl::create(
Impl.SwiftContext, loc,
TypeLoc::withoutLoc(objcClass->getDeclaredType()),
{ }, dc, nullptr, decl);
objcClass->addExtension(result);
Impl.ImportedDecls[decl->getCanonicalDecl()] = result;
SmallVector<TypeLoc, 4> inheritedTypes;
importObjCProtocols(result, decl->getReferencedProtocols(),
inheritedTypes);
result->setValidated();
result->setInherited(Impl.SwiftContext.AllocateCopy(inheritedTypes));
result->setCheckedInheritanceClause();
result->setMemberLoader(&Impl, 0);
return result;
}
template <typename T, typename U>
T *resolveSwiftDeclImpl(const U *decl, Identifier name, Module *adapter) {
SmallVector<ValueDecl *, 4> results;
adapter->lookupValue({}, name, NLKind::QualifiedLookup, results);
if (results.size() == 1) {
if (auto singleResult = dyn_cast<T>(results.front())) {
if (auto typeResolver = Impl.getTypeResolver())
typeResolver->resolveDeclSignature(singleResult);
Impl.ImportedDecls[decl->getCanonicalDecl()] = singleResult;
return singleResult;
}
}
return nullptr;
}
template <typename T, typename U>
T *resolveSwiftDecl(const U *decl, Identifier name,
ClangModuleUnit *clangModule) {
if (auto adapter = clangModule->getAdapterModule())
return resolveSwiftDeclImpl<T>(decl, name, adapter);
if (clangModule == Impl.ImportedHeaderUnit) {
// Use an index-based loop because new owners can come in as we're
// iterating.
for (size_t i = 0; i < Impl.ImportedHeaderOwners.size(); ++i) {
Module *owner = Impl.ImportedHeaderOwners[i];
if (T *result = resolveSwiftDeclImpl<T>(decl, name, owner))
return result;
}
}
return nullptr;
}
template <typename U>
bool hasNativeSwiftDecl(const U *decl) {
using clang::AnnotateAttr;
for (auto annotation : decl->template specific_attrs<AnnotateAttr>()) {
if (annotation->getAnnotation() == SWIFT_NATIVE_ANNOTATION_STRING) {
return true;
}
}
return false;
}
template <typename T, typename U>
bool hasNativeSwiftDecl(const U *decl, Identifier name,
const DeclContext *dc, T *&swiftDecl) {
if (!hasNativeSwiftDecl(decl))
return false;
if (auto *nameAttr = decl->template getAttr<clang::SwiftNameAttr>()) {
StringRef customName = nameAttr->getName();
if (Lexer::isIdentifier(customName))
name = Impl.SwiftContext.getIdentifier(customName);
}
auto wrapperUnit = cast<ClangModuleUnit>(dc->getModuleScopeContext());
swiftDecl = resolveSwiftDecl<T>(decl, name, wrapperUnit);
return true;
}
void markMissingSwiftDecl(ValueDecl *VD) {
const char *message;
if (isa<ClassDecl>(VD))
message = "cannot find Swift declaration for this class";
else if (isa<ProtocolDecl>(VD))
message = "cannot find Swift declaration for this protocol";
else
llvm_unreachable("unknown bridged decl kind");
auto attr = AvailableAttr::createUnconditional(Impl.SwiftContext,
message);
VD->getAttrs().add(attr);
}
Decl *VisitObjCProtocolDecl(const clang::ObjCProtocolDecl *decl) {
Identifier name = Impl.importFullName(decl).Imported.getBaseName();
if (name.empty())
return nullptr;
// FIXME: Figure out how to deal with incomplete protocols, since that
// notion doesn't exist in Swift.
if (!decl->hasDefinition()) {
// Check if this protocol is implemented in its adapter.
if (auto clangModule = Impl.getClangModuleForDecl(decl, true))
if (auto native = resolveSwiftDecl<ProtocolDecl>(decl, name,
clangModule))
return native;
forwardDeclaration = true;
return nullptr;
}
decl = decl->getDefinition();
auto dc = Impl.importDeclContextOf(decl);
if (!dc)
return nullptr;
ProtocolDecl *nativeDecl;
bool declaredNative = hasNativeSwiftDecl(decl, name, dc, nativeDecl);
if (declaredNative && nativeDecl)
return nativeDecl;
// Create the protocol declaration and record it.
auto result = Impl.createDeclWithClangNode<ProtocolDecl>(decl,
dc,
Impl.importSourceLoc(decl->getLocStart()),
Impl.importSourceLoc(decl->getLocation()),
name,
None);
result->computeType();
addObjCAttribute(result, Impl.importIdentifier(decl->getIdentifier()));
if (declaredNative)
markMissingSwiftDecl(result);
Impl.ImportedDecls[decl->getCanonicalDecl()] = result;
// Create the archetype for the implicit 'Self'.
auto selfId = Impl.SwiftContext.Id_Self;
auto selfDecl = result->getProtocolSelf();
ArchetypeType *selfArchetype =
ArchetypeType::getNew(Impl.SwiftContext, nullptr,
result, selfId,
Type(result->getDeclaredType()),
Type(), false);
selfDecl->setArchetype(selfArchetype);
// Set AllArchetypes of the protocol. ObjC protocols don't have associated
// types so only the Self archetype is present.
result->getGenericParams()->setAllArchetypes(
Impl.SwiftContext.AllocateCopy(llvm::makeArrayRef(selfArchetype)));
// Set the generic parameters and requirements.
auto genericParam = selfDecl->getDeclaredType()
->castTo<GenericTypeParamType>();
Requirement genericRequirements[2] = {
Requirement(RequirementKind::WitnessMarker, genericParam, Type()),
Requirement(RequirementKind::Conformance, genericParam,
result->getDeclaredType())
};
auto sig = GenericSignature::get(genericParam, genericRequirements);
result->setGenericSignature(sig);
result->setCircularityCheck(CircularityCheck::Checked);
// Import protocols this protocol conforms to.
SmallVector<TypeLoc, 4> inheritedTypes;
importObjCProtocols(result, decl->getReferencedProtocols(),
inheritedTypes);
result->setInherited(Impl.SwiftContext.AllocateCopy(inheritedTypes));
result->setCheckedInheritanceClause();
result->setMemberLoader(&Impl, 0);
// Add the protocol decl to ExternalDefinitions so that IRGen can emit
// metadata for it.
// FIXME: There might be better ways to do this.
Impl.registerExternalDecl(result);
return result;
}
// Add inferred attributes.
void addInferredAttributes(Decl *decl, unsigned attributes) {
using namespace inferred_attributes;
if (attributes & requires_stored_property_inits) {
auto a = new (Impl.SwiftContext)
RequiresStoredPropertyInitsAttr(/*IsImplicit=*/true);
decl->getAttrs().add(a);
cast<ClassDecl>(decl)->setRequiresStoredPropertyInits(true);
}
}
Decl *VisitObjCInterfaceDecl(const clang::ObjCInterfaceDecl *decl) {
auto name = Impl.importFullName(decl).Imported.getBaseName();
if (name.empty())
return nullptr;
auto createRootClass = [=](DeclContext *dc = nullptr) -> ClassDecl * {
if (!dc) {
dc = Impl.getClangModuleForDecl(decl->getCanonicalDecl(),
/*forwardDeclaration=*/true);
}
auto result = Impl.createDeclWithClangNode<ClassDecl>(decl,
SourceLoc(), name,
SourceLoc(), None,
nullptr, dc);
result->computeType();
Impl.ImportedDecls[decl->getCanonicalDecl()] = result;
result->setCircularityCheck(CircularityCheck::Checked);
result->setSuperclass(Type());
result->setCheckedInheritanceClause();
result->setAddedImplicitInitializers(); // suppress all initializers
addObjCAttribute(result, Impl.importIdentifier(decl->getIdentifier()));
Impl.registerExternalDecl(result);
return result;
};
// Special case for Protocol, which gets forward-declared as an ObjC
// class which is hidden in modern Objective-C runtimes.
// We treat it as a foreign class (like a CF type) because it doesn't
// have a real public class object.
clang::ASTContext &clangCtx = Impl.getClangASTContext();
if (decl->getCanonicalDecl() ==
clangCtx.getObjCProtocolDecl()->getCanonicalDecl()) {
Type nsObjectTy = Impl.getNSObjectType();
if (!nsObjectTy)
return nullptr;
const ClassDecl *nsObjectDecl =
nsObjectTy->getClassOrBoundGenericClass();
auto result = createRootClass(nsObjectDecl->getDeclContext());
result->setForeign(true);
return result;
}
if (!decl->hasDefinition()) {
// Check if this class is implemented in its adapter.
if (auto clangModule = Impl.getClangModuleForDecl(decl, true)) {
if (auto native = resolveSwiftDecl<ClassDecl>(decl, name,
clangModule)) {
return native;
}
}
if (Impl.ImportForwardDeclarations) {
// Fake it by making an unavailable opaque @objc root class.
auto result = createRootClass();
result->setImplicit();
auto attr = AvailableAttr::createUnconditional(Impl.SwiftContext,
"This Objective-C class has only been forward-declared; "
"import its owning module to use it");
result->getAttrs().add(attr);
return result;
}
forwardDeclaration = true;
return nullptr;
}
decl = decl->getDefinition();
assert(decl);
auto dc = Impl.importDeclContextOf(decl);
if (!dc)
return nullptr;
ClassDecl *nativeDecl;
bool declaredNative = hasNativeSwiftDecl(decl, name, dc, nativeDecl);
if (declaredNative && nativeDecl)
return nativeDecl;
// Create the class declaration and record it.
auto result = Impl.createDeclWithClangNode<ClassDecl>(decl,
Impl.importSourceLoc(decl->getLocStart()),
name,
Impl.importSourceLoc(decl->getLocation()),
None, nullptr, dc);
result->computeType();
Impl.ImportedDecls[decl->getCanonicalDecl()] = result;
result->setCircularityCheck(CircularityCheck::Checked);
result->setAddedImplicitInitializers();
addObjCAttribute(result, Impl.importIdentifier(decl->getIdentifier()));
if (declaredNative)
markMissingSwiftDecl(result);
// If this Objective-C class has a supertype, import it.
SmallVector<TypeLoc, 4> inheritedTypes;
Type superclassType;
if (auto objcSuper = decl->getSuperClass()) {
auto super = cast_or_null<ClassDecl>(Impl.importDecl(objcSuper));
if (!super)
return nullptr;
superclassType = super->getDeclaredType();
inheritedTypes.push_back(TypeLoc::withoutLoc(superclassType));
}
result->setSuperclass(superclassType);
// Import protocols this class conforms to.
importObjCProtocols(result, decl->getReferencedProtocols(),
inheritedTypes);
result->setInherited(Impl.SwiftContext.AllocateCopy(inheritedTypes));
result->setCheckedInheritanceClause();
// Add inferred attributes.
#define INFERRED_ATTRIBUTES(ModuleName, ClassName, AttributeSet) \
if (name.str().equals(#ClassName) && \
result->getParentModule()->getName().str().equals(#ModuleName)) { \
using namespace inferred_attributes; \
addInferredAttributes(result, AttributeSet); \
}
#include "InferredAttributes.def"
result->setMemberLoader(&Impl, 0);
// Pass the class to the type checker to create an implicit destructor.
Impl.registerExternalDecl(result);
return result;
}
Decl *VisitObjCImplDecl(const clang::ObjCImplDecl *decl) {
// Implementations of Objective-C classes and categories are not
// reflected into Swift.
return nullptr;
}
Decl *VisitObjCPropertyDecl(const clang::ObjCPropertyDecl *decl) {
auto dc = Impl.importDeclContextOf(decl);
if (!dc)
return nullptr;
// While importing the DeclContext, we might have imported the decl
// itself.
if (auto Known = Impl.importDeclCached(decl))
return Known;
return VisitObjCPropertyDecl(decl, dc);
}
void applyPropertyOwnership(
VarDecl *prop, clang::ObjCPropertyDecl::PropertyAttributeKind attrs) {
Type ty = prop->getType();
if (auto innerTy = ty->getAnyOptionalObjectType())
ty = innerTy;
if (!ty->isAnyClassReferenceType())
return;
ASTContext &ctx = prop->getASTContext();
if (attrs & clang::ObjCPropertyDecl::OBJC_PR_copy) {
prop->getAttrs().add(new (ctx) NSCopyingAttr(false));
return;
}
if (attrs & clang::ObjCPropertyDecl::OBJC_PR_weak) {
prop->getAttrs().add(new (ctx) OwnershipAttr(Ownership::Weak));
prop->overwriteType(WeakStorageType::get(prop->getType(), ctx));
return;
}
if ((attrs & clang::ObjCPropertyDecl::OBJC_PR_assign) ||
(attrs & clang::ObjCPropertyDecl::OBJC_PR_unsafe_unretained)) {
prop->getAttrs().add(new (ctx) OwnershipAttr(Ownership::Unmanaged));
prop->overwriteType(UnmanagedStorageType::get(prop->getType(), ctx));
return;
}
}
/// Hack: Handle the case where a property is declared \c readonly in the
/// main class interface (either explicitly or because of an adopted
/// protocol) and then \c readwrite in a category/extension.
///
/// \see VisitObjCPropertyDecl
void handlePropertyRedeclaration(VarDecl *original,
const clang::ObjCPropertyDecl *redecl) {
// If the property isn't from Clang, we can't safely update it.
if (!original->hasClangNode())
return;
// If the original declaration was implicit, we may want to change that.
if (original->isImplicit() && !redecl->isImplicit() &&
!isa<clang::ObjCProtocolDecl>(redecl->getDeclContext()))
original->setImplicit(false);
if (!original->getAttrs().hasAttribute<OwnershipAttr>() &&
!original->getAttrs().hasAttribute<NSCopyingAttr>()) {
applyPropertyOwnership(original,
redecl->getPropertyAttributesAsWritten());
}
auto clangSetter = redecl->getSetterMethodDecl();
if (!clangSetter)
return;
// The only other transformation we know how to do safely is add a
// setter. If the property is already settable, we're done.
if (original->isSettable(nullptr))
return;
FuncDecl *setter = importAccessor(clangSetter,
original->getDeclContext());
if (!setter)
return;
original->setComputedSetter(setter);
}
Decl *VisitObjCPropertyDecl(const clang::ObjCPropertyDecl *decl,
DeclContext *dc) {
assert(dc);
auto name = Impl.importFullName(decl).Imported.getBaseName();
if (name.empty())
return nullptr;
if (Impl.isAccessibilityDecl(decl))
return nullptr;
// Check whether there is a function with the same name as this
// property. If so, suppress the property; the user will have to use
// the methods directly, to avoid ambiguities.
auto containerTy = dc->getDeclaredTypeInContext();
VarDecl *overridden = nullptr;
SmallVector<ValueDecl *, 2> lookup;
dc->lookupQualified(containerTy, name,
NL_QualifiedDefault | NL_KnownNoDependency,
Impl.getTypeResolver(), lookup);
for (auto result : lookup) {
if (isa<FuncDecl>(result) && result->isInstanceMember() &&
result->getFullName().getArgumentNames().empty())
return nullptr;
if (auto var = dyn_cast<VarDecl>(result)) {
// If the selectors of the getter match in Objective-C, we have an
// override.
if (var->getObjCGetterSelector() ==
Impl.importSelector(decl->getGetterName()))
overridden = var;
}
}
if (overridden) {
const DeclContext *overrideContext = overridden->getDeclContext();
if (overrideContext != dc &&
overrideContext->getDeclaredTypeInContext()->isEqual(containerTy)) {
// We've encountered a redeclaration of the property.
// HACK: Just update the original declaration instead of importing a
// second property.
handlePropertyRedeclaration(overridden, decl);
return nullptr;
}
}
Type type = Impl.importPropertyType(decl, isInSystemModule(dc));
if (!type)
return nullptr;
// Import the getter.
FuncDecl *getter = nullptr;
if (auto clangGetter = decl->getGetterMethodDecl()) {
getter = importAccessor(clangGetter, dc);
if (!getter)
return nullptr;
}
// Import the setter, if there is one.
FuncDecl *setter = nullptr;
if (auto clangSetter = decl->getSetterMethodDecl()) {
setter = importAccessor(clangSetter, dc);
if (!setter)
return nullptr;
}
// Check whether the property already got imported.
if (dc == Impl.importDeclContextOf(decl)) {
auto known = Impl.ImportedDecls.find(decl->getCanonicalDecl());
if (known != Impl.ImportedDecls.end())
return known->second;
}
auto result = Impl.createDeclWithClangNode<VarDecl>(decl,
/*static*/ false, /*IsLet*/ false,
Impl.importSourceLoc(decl->getLocation()),
name, type, dc);
// Turn this into a computed property.
// FIXME: Fake locations for '{' and '}'?
result->makeComputed(SourceLoc(), getter, setter, nullptr, SourceLoc());
addObjCAttribute(result, None);
applyPropertyOwnership(result, decl->getPropertyAttributesAsWritten());
// Handle attributes.
if (decl->hasAttr<clang::IBOutletAttr>())
result->getAttrs().add(
new (Impl.SwiftContext) IBOutletAttr(/*IsImplicit=*/false));
if (decl->getPropertyImplementation() == clang::ObjCPropertyDecl::Optional
&& isa<ProtocolDecl>(dc) &&
!result->getAttrs().hasAttribute<OptionalAttr>())
result->getAttrs().add(new (Impl.SwiftContext)
OptionalAttr(/*implicit*/false));
// FIXME: Handle IBOutletCollection.
if (overridden)
result->setOverriddenDecl(overridden);
return result;
}
Decl *
VisitObjCCompatibleAliasDecl(const clang::ObjCCompatibleAliasDecl *decl) {
// Like C++ using declarations, name lookup simply looks through
// Objective-C compatibility aliases. They are not imported directly.
return nullptr;
}
Decl *VisitLinkageSpecDecl(const clang::LinkageSpecDecl *decl) {
// Linkage specifications are not imported.
return nullptr;
}
Decl *VisitObjCPropertyImplDecl(const clang::ObjCPropertyImplDecl *decl) {
// @synthesize and @dynamic are not imported, since they are not part
// of the interface to a class.
return nullptr;
}
Decl *VisitFileScopeAsmDecl(const clang::FileScopeAsmDecl *decl) {
return nullptr;
}
Decl *VisitAccessSpecDecl(const clang::AccessSpecDecl *decl) {
return nullptr;
}
Decl *VisitFriendDecl(const clang::FriendDecl *decl) {
// Friends are not imported; Swift has a different access control
// mechanism.
return nullptr;
}
Decl *VisitFriendTemplateDecl(const clang::FriendTemplateDecl *decl) {
// Friends are not imported; Swift has a different access control
// mechanism.
return nullptr;
}
Decl *VisitStaticAssertDecl(const clang::StaticAssertDecl *decl) {
// Static assertions are an implementation detail.
return nullptr;
}
Decl *VisitBlockDecl(const clang::BlockDecl *decl) {
// Blocks are not imported (although block types can be imported).
return nullptr;
}
Decl *VisitClassScopeFunctionSpecializationDecl(
const clang::ClassScopeFunctionSpecializationDecl *decl) {
// Note: templates are not imported.
return nullptr;
}
Decl *VisitImportDecl(const clang::ImportDecl *decl) {
// Transitive module imports are not handled at the declaration level.
// Rather, they are understood from the module itself.
return nullptr;
}
};
}
Decl *ClangImporter::Implementation::importDeclCached(
const clang::NamedDecl *ClangDecl) {
auto Known = ImportedDecls.find(ClangDecl->getCanonicalDecl());
if (Known != ImportedDecls.end())
return Known->second;
return nullptr;
}
/// Checks if we don't need to import the typedef itself. If the typedef
/// should be skipped, returns the underlying declaration that the typedef
/// refers to -- this declaration should be imported instead.
static const clang::TagDecl *
canSkipOverTypedef(ClangImporter::Implementation &Impl,
const clang::NamedDecl *D,
bool &TypedefIsSuperfluous) {
// If we have a typedef that refers to a tag type of the same name,
// skip the typedef and import the tag type directly.
TypedefIsSuperfluous = false;
auto *ClangTypedef = dyn_cast<clang::TypedefNameDecl>(D);
if (!ClangTypedef)
return nullptr;
const clang::DeclContext *RedeclContext =
ClangTypedef->getDeclContext()->getRedeclContext();
if (!RedeclContext->isTranslationUnit())
return nullptr;
clang::QualType UnderlyingType = ClangTypedef->getUnderlyingType();
// A typedef to a typedef should get imported as a typealias.
auto *TypedefT = UnderlyingType->getAs<clang::TypedefType>();
if (TypedefT)
return nullptr;
auto *TT = UnderlyingType->getAs<clang::TagType>();
if (!TT)
return nullptr;
clang::TagDecl *UnderlyingDecl = TT->getDecl();
if (UnderlyingDecl->getDeclContext()->getRedeclContext() != RedeclContext)
return nullptr;
if (UnderlyingDecl->getDeclName().isEmpty())
return UnderlyingDecl;
auto TypedefName = ClangTypedef->getDeclName();
auto TagDeclName = UnderlyingDecl->getDeclName();
if (TypedefName != TagDeclName)
return nullptr;
TypedefIsSuperfluous = true;
return UnderlyingDecl;
}
/// Import Clang attributes as Swift attributes.
void ClangImporter::Implementation::importAttributes(
const clang::NamedDecl *ClangDecl,
Decl *MappedDecl,
const clang::ObjCContainerDecl *NewContext)
{
ASTContext &C = SwiftContext;
if (auto maybeDefinition = getDefinitionForClangTypeDecl(ClangDecl))
if (maybeDefinition.getValue())
ClangDecl = cast<clang::NamedDecl>(maybeDefinition.getValue());
// Scan through Clang attributes and map them onto Swift
// equivalents.
bool AnyUnavailable = false;
for (clang::NamedDecl::attr_iterator AI = ClangDecl->attr_begin(),
AE = ClangDecl->attr_end(); AI != AE; ++AI) {
//
// __attribute__((unavailable)
//
// Mapping: @available(*,unavailable)
//
if (auto unavailable = dyn_cast<clang::UnavailableAttr>(*AI)) {
auto Message = unavailable->getMessage();
auto attr = AvailableAttr::createUnconditional(C, Message);
MappedDecl->getAttrs().add(attr);
AnyUnavailable = true;
continue;
}
//
// __attribute__((annotate(swift1_unavailable)))
//
// Mapping: @available(*, unavailable)
//
if (auto unavailable_annot = dyn_cast<clang::AnnotateAttr>(*AI))
if (unavailable_annot->getAnnotation() == "swift1_unavailable") {
auto attr = AvailableAttr::createUnconditional(
C, "", "", UnconditionalAvailabilityKind::UnavailableInSwift);
MappedDecl->getAttrs().add(attr);
AnyUnavailable = true;
continue;
}
//
// __attribute__((deprecated))
//
// Mapping: @available(*,deprecated)
//
if (auto deprecated = dyn_cast<clang::DeprecatedAttr>(*AI)) {
auto Message = deprecated->getMessage();
auto attr = AvailableAttr::createUnconditional(C, Message, "",
UnconditionalAvailabilityKind::Deprecated);
MappedDecl->getAttrs().add(attr);
continue;
}
// __attribute__((availability))
//
if (auto avail = dyn_cast<clang::AvailabilityAttr>(*AI)) {
StringRef Platform = avail->getPlatform()->getName();
// Is this our special "availability(swift, unavailable)" attribute?
if (Platform == "swift") {
auto attr = AvailableAttr::createUnconditional(
C, avail->getMessage(), /*renamed*/"",
UnconditionalAvailabilityKind::UnavailableInSwift);
MappedDecl->getAttrs().add(attr);
AnyUnavailable = true;
continue;
}
// Does this availability attribute map to the platform we are
// currently targeting?
if (!PlatformAvailabilityFilter ||
!PlatformAvailabilityFilter(Platform))
continue;
auto platformK =
llvm::StringSwitch<Optional<PlatformKind>>(Platform)
.Case("ios", PlatformKind::iOS)
.Case("macosx", PlatformKind::OSX)
.Case("tvos", PlatformKind::tvOS)
.Case("watchos", PlatformKind::watchOS)
.Case("ios_app_extension", PlatformKind::iOSApplicationExtension)
.Case("macosx_app_extension",
PlatformKind::OSXApplicationExtension)
.Case("tvos_app_extension",
PlatformKind::tvOSApplicationExtension)
.Case("watchos_app_extension",
PlatformKind::watchOSApplicationExtension)
.Default(None);
if (!platformK)
continue;
// Is this declaration marked unconditionally unavailable?
auto Unconditional = UnconditionalAvailabilityKind::None;
if (avail->getUnavailable()) {
Unconditional = UnconditionalAvailabilityKind::Unavailable;
AnyUnavailable = true;
}
StringRef message = avail->getMessage();
const auto &deprecated = avail->getDeprecated();
if (!deprecated.empty()) {
if (DeprecatedAsUnavailableFilter &&
DeprecatedAsUnavailableFilter(deprecated.getMajor(),
deprecated.getMinor())) {
AnyUnavailable = true;
Unconditional = UnconditionalAvailabilityKind::Unavailable;
if (message.empty())
message = DeprecatedAsUnavailableMessage;
}
}
const auto &obsoleted = avail->getObsoleted();
const auto &introduced = avail->getIntroduced();
auto AvAttr = new (C) AvailableAttr(SourceLoc(), SourceRange(),
platformK.getValue(),
message, /*rename*/StringRef(),
introduced, deprecated, obsoleted,
Unconditional, /*implicit=*/false);
MappedDecl->getAttrs().add(AvAttr);
}
}
// If the declaration is unavailable, we're done.
if (AnyUnavailable)
return;
// Add implicit attributes.
if (auto MD = dyn_cast<clang::ObjCMethodDecl>(ClangDecl)) {
Optional<api_notes::ObjCMethodInfo> knownMethod;
if (NewContext)
knownMethod = getKnownObjCMethod(MD, NewContext);
if (!knownMethod)
knownMethod = getKnownObjCMethod(MD);
// Any knowledge of methods known due to our whitelists.
if (knownMethod) {
// Availability.
if (knownMethod->Unavailable) {
auto attr = AvailableAttr::createUnconditional(
C,
SwiftContext.AllocateCopy(knownMethod->UnavailableMsg));
MappedDecl->getAttrs().add(attr);
// If we made a protocol requirement unavailable, mark it optional:
// nobody should have to satisfy it.
if (isa<ProtocolDecl>(MappedDecl->getDeclContext())) {
if (!MappedDecl->getAttrs().hasAttribute<OptionalAttr>())
MappedDecl->getAttrs().add(new (C) OptionalAttr(/*implicit*/false));
}
}
}
} else if (auto PD = dyn_cast<clang::ObjCPropertyDecl>(ClangDecl)) {
if (auto knownProperty = getKnownObjCProperty(PD)) {
if (knownProperty->Unavailable) {
auto attr = AvailableAttr::createUnconditional(
C,
SwiftContext.AllocateCopy(knownProperty->UnavailableMsg));
MappedDecl->getAttrs().add(attr);
}
}
} else if (auto CD = dyn_cast<clang::ObjCContainerDecl>(ClangDecl)) {
if (isa<clang::ObjCInterfaceDecl>(CD) || isa<clang::ObjCProtocolDecl>(CD)) {
if (auto knownContext = getKnownObjCContext(CD)) {
if (knownContext->Unavailable) {
auto attr = AvailableAttr::createUnconditional(
C,
SwiftContext.AllocateCopy(
knownContext->UnavailableMsg));
MappedDecl->getAttrs().add(attr);
}
}
}
}
// Ban NSInvocation.
if (auto ID = dyn_cast<clang::ObjCInterfaceDecl>(ClangDecl)) {
if (ID->getName() == "NSInvocation") {
auto attr = AvailableAttr::createUnconditional(C, "");
MappedDecl->getAttrs().add(attr);
return;
}
}
// Ban CFRelease|CFRetain|CFAutorelease(CFTypeRef) as well as custom ones
// such as CGColorRelease(CGColorRef).
if (auto FD = dyn_cast<clang::FunctionDecl>(ClangDecl)) {
if (FD->getNumParams() == 1 &&
(FD->getName().endswith("Release") ||
FD->getName().endswith("Retain") ||
FD->getName().endswith("Autorelease")))
if (auto t = FD->getParamDecl(0)->getType()->getAs<clang::TypedefType>())
if (isCFTypeDecl(t->getDecl())) {
auto attr = AvailableAttr::createUnconditional(C,
"Core Foundation objects are automatically memory managed");
MappedDecl->getAttrs().add(attr);
return;
}
}
// Hack: mark any method named "print" with less than two parameters as
// warn_unqualified_access.
if (auto MD = dyn_cast<FuncDecl>(MappedDecl)) {
if (MD->getName().str() == "print" &&
MD->getDeclContext()->isTypeContext()) {
auto *formalParams = MD->getParameterList(1);
if (formalParams->size() <= 1) {
// Use a non-implicit attribute so it shows up in the generated
// interface.
MD->getAttrs().add(
new (C) WarnUnqualifiedAccessAttr(/*implicit*/false));
}
}
}
// Map __attribute__((warn_unused_result)).
if (ClangDecl->hasAttr<clang::WarnUnusedResultAttr>()) {
MappedDecl->getAttrs().add(new (C) WarnUnusedResultAttr(SourceLoc(),
SourceLoc(),
false));
}
// Map __attribute__((const)).
if (ClangDecl->hasAttr<clang::ConstAttr>()) {
MappedDecl->getAttrs().add(new (C) EffectsAttr(EffectsKind::ReadNone));
}
// Map __attribute__((pure)).
if (ClangDecl->hasAttr<clang::PureAttr>()) {
MappedDecl->getAttrs().add(new (C) EffectsAttr(EffectsKind::ReadOnly));
}
}
Decl *
ClangImporter::Implementation::importDeclImpl(const clang::NamedDecl *ClangDecl,
bool &TypedefIsSuperfluous,
bool &HadForwardDeclaration) {
assert(ClangDecl);
bool SkippedOverTypedef = false;
Decl *Result = nullptr;
if (auto *UnderlyingDecl = canSkipOverTypedef(*this, ClangDecl,
TypedefIsSuperfluous)) {
Result = importDecl(UnderlyingDecl);
SkippedOverTypedef = true;
}
if (!Result) {
SwiftDeclConverter converter(*this);
Result = converter.Visit(ClangDecl);
HadForwardDeclaration = converter.hadForwardDeclaration();
}
if (!Result) {
// If we couldn't import this Objective-C entity, determine
// whether it was a required member of a protocol.
bool hasMissingRequiredMember = false;
if (auto clangProto
= dyn_cast<clang::ObjCProtocolDecl>(ClangDecl->getDeclContext())) {
if (auto method = dyn_cast<clang::ObjCMethodDecl>(ClangDecl)) {
if (method->getImplementationControl()
== clang::ObjCMethodDecl::Required)
hasMissingRequiredMember = true;
} else if (auto prop = dyn_cast<clang::ObjCPropertyDecl>(ClangDecl)) {
if (prop->getPropertyImplementation()
== clang::ObjCPropertyDecl::Required)
hasMissingRequiredMember = true;
}
if (hasMissingRequiredMember) {
// Mark the protocol as having missing requirements.
if (auto proto = cast_or_null<ProtocolDecl>(importDecl(clangProto))) {
proto->setHasMissingRequirements(true);
}
}
}
return nullptr;
}
// Finalize the imported declaration.
auto finalizeDecl = [&](Decl *result) {
importAttributes(ClangDecl, result);
// Hack to deal with unannotated Objective-C protocols. If the protocol
// comes from clang and is not annotated and the protocol requirement
// itself is not annotated, then infer availability of the requirement
// based on its types. This makes it possible for a type to conform to an
// Objective-C protocol that is missing annotations but whose requirements
// use types that are less available than the conforming type.
auto dc = result->getDeclContext();
auto *proto = dyn_cast<ProtocolDecl>(dc);
if (!proto || proto->getAttrs().hasAttribute<AvailableAttr>())
return;
inferProtocolMemberAvailability(*this, dc, result);
};
if (Result) {
finalizeDecl(Result);
if (auto alternate = getAlternateDecl(Result))
finalizeDecl(alternate);
}
#ifndef NDEBUG
auto Canon = cast<clang::NamedDecl>(ClangDecl->getCanonicalDecl());
// Note that the decl was imported from Clang. Don't mark Swift decls as
// imported.
if (!Result->getDeclContext()->isModuleScopeContext() ||
isa<ClangModuleUnit>(Result->getDeclContext())) {
// Either the Swift declaration was from stdlib,
// or we imported the underlying decl of the typedef,
// or we imported the decl itself.
bool ImportedCorrectly =
!Result->getClangDecl() || SkippedOverTypedef ||
Result->getClangDecl()->getCanonicalDecl() == Canon;
// Or the other type is a typedef,
if (!ImportedCorrectly &&
isa<clang::TypedefNameDecl>(Result->getClangDecl())) {
// both types are ValueDecls:
if (isa<clang::ValueDecl>(Result->getClangDecl())) {
ImportedCorrectly =
getClangASTContext().hasSameType(
cast<clang::ValueDecl>(Result->getClangDecl())->getType(),
cast<clang::ValueDecl>(Canon)->getType());
} else if (isa<clang::TypeDecl>(Result->getClangDecl())) {
// both types are TypeDecls:
ImportedCorrectly =
getClangASTContext().hasSameUnqualifiedType(
getClangASTContext().getTypeDeclType(
cast<clang::TypeDecl>(Result->getClangDecl())),
getClangASTContext().getTypeDeclType(
cast<clang::TypeDecl>(Canon)));
}
assert(ImportedCorrectly);
}
assert(Result->hasClangNode());
}
#else
(void)SkippedOverTypedef;
#endif
return Result;
}
void ClangImporter::Implementation::startedImportingEntity() {
++NumCurrentImportingEntities;
++NumTotalImportedEntities;
}
void ClangImporter::Implementation::finishedImportingEntity() {
assert(NumCurrentImportingEntities &&
"finishedImportingEntity not paired with startedImportingEntity");
if (NumCurrentImportingEntities == 1) {
// We decrease NumCurrentImportingEntities only after pending actions
// are finished, to avoid recursively re-calling finishPendingActions().
finishPendingActions();
}
--NumCurrentImportingEntities;
}
void ClangImporter::Implementation::finishPendingActions() {
while (true) {
if (!RegisteredExternalDecls.empty()) {
if (hasFinishedTypeChecking()) {
RegisteredExternalDecls.clear();
} else {
Decl *D = RegisteredExternalDecls.pop_back_val();
SwiftContext.addExternalDecl(D);
if (auto typeResolver = getTypeResolver())
if (auto *nominal = dyn_cast<NominalTypeDecl>(D))
if (!nominal->hasDelayedMembers())
typeResolver->resolveExternalDeclImplicitMembers(nominal);
}
} else if (!DelayedProtocolConformances.empty()) {
NormalProtocolConformance *conformance =
DelayedProtocolConformances.pop_back_val();
finishProtocolConformance(conformance);
} else {
break;
}
}
}
/// Finish the given protocol conformance (for an imported type)
/// by filling in any missing witnesses.
void ClangImporter::Implementation::finishProtocolConformance(
NormalProtocolConformance *conformance) {
// Create witnesses for requirements not already met.
for (auto req : conformance->getProtocol()->getMembers()) {
auto valueReq = dyn_cast<ValueDecl>(req);
if (!valueReq)
continue;
if (!conformance->hasWitness(valueReq)) {
if (auto func = dyn_cast<AbstractFunctionDecl>(valueReq)){
// For an optional requirement, record an empty witness:
// we'll end up querying this at runtime.
auto Attrs = func->getAttrs();
if (Attrs.hasAttribute<OptionalAttr>()) {
conformance->setWitness(valueReq, ConcreteDeclRef());
continue;
}
}
conformance->setWitness(valueReq, valueReq);
} else {
// An initializer that conforms to a requirement is required.
auto witness = conformance->getWitness(valueReq, nullptr).getDecl();
if (auto ctor = dyn_cast_or_null<ConstructorDecl>(witness)) {
if (!ctor->getAttrs().hasAttribute<RequiredAttr>()) {
ctor->getAttrs().add(
new (SwiftContext) RequiredAttr(/*implicit=*/true));
}
}
}
}
conformance->setState(ProtocolConformanceState::Complete);
}
Decl *ClangImporter::Implementation::importDeclAndCacheImpl(
const clang::NamedDecl *ClangDecl,
bool SuperfluousTypedefsAreTransparent) {
if (!ClangDecl)
return nullptr;
clang::PrettyStackTraceDecl trace(ClangDecl, clang::SourceLocation(),
Instance->getSourceManager(), "importing");
auto Canon = cast<clang::NamedDecl>(ClangDecl->getCanonicalDecl());
if (auto Known = importDeclCached(Canon)) {
if (!SuperfluousTypedefsAreTransparent &&
SuperfluousTypedefs.count(Canon))
return nullptr;
return Known;
}
bool TypedefIsSuperfluous = false;
bool HadForwardDeclaration = false;
ImportingEntityRAII ImportingEntity(*this);
Decl *Result = importDeclImpl(ClangDecl, TypedefIsSuperfluous,
HadForwardDeclaration);
if (!Result)
return nullptr;
if (TypedefIsSuperfluous) {
SuperfluousTypedefs.insert(Canon);
if (auto tagDecl = dyn_cast_or_null<clang::TagDecl>(Result->getClangDecl()))
DeclsWithSuperfluousTypedefs.insert(tagDecl);
}
if (!HadForwardDeclaration)
ImportedDecls[Canon] = Result;
if (!SuperfluousTypedefsAreTransparent && TypedefIsSuperfluous)
return nullptr;
return Result;
}
Decl *
ClangImporter::Implementation::importMirroredDecl(const clang::NamedDecl *decl,
DeclContext *dc,
ProtocolDecl *proto) {
assert(dc);
if (!decl)
return nullptr;
clang::PrettyStackTraceDecl trace(decl, clang::SourceLocation(),
Instance->getSourceManager(),
"importing (mirrored)");
auto canon = decl->getCanonicalDecl();
auto known = ImportedProtocolDecls.find({canon, dc });
if (known != ImportedProtocolDecls.end())
return known->second;
SwiftDeclConverter converter(*this);
Decl *result;
if (auto method = dyn_cast<clang::ObjCMethodDecl>(decl)) {
result = converter.VisitObjCMethodDecl(method, dc);
} else if (auto prop = dyn_cast<clang::ObjCPropertyDecl>(decl)) {
result = converter.VisitObjCPropertyDecl(prop, dc);
} else {
llvm_unreachable("unexpected mirrored decl");
}
if (result) {
assert(result->getClangDecl() && result->getClangDecl() == canon);
auto updateMirroredDecl = [&](Decl *result) {
result->setImplicit();
// Map the Clang attributes onto Swift attributes.
importAttributes(decl, result);
if (proto->getAttrs().hasAttribute<AvailableAttr>()) {
if (!result->getAttrs().hasAttribute<AvailableAttr>()) {
AvailabilityContext protoRange =
AvailabilityInference::availableRange(proto, SwiftContext);
applyAvailableAttribute(result, protoRange, SwiftContext);
}
} else {
// Infer the same availability for the mirrored declaration as
// we would for the protocol member it is mirroring.
inferProtocolMemberAvailability(*this, dc, result);
}
};
updateMirroredDecl(result);
// Update the alternate declaration as well.
if (auto alternate = getAlternateDecl(result))
updateMirroredDecl(alternate);
}
if (result || !converter.hadForwardDeclaration())
ImportedProtocolDecls[{canon, dc}] = result;
return result;
}
DeclContext *ClangImporter::Implementation::importDeclContextImpl(
const clang::DeclContext *dc) {
// Every declaration should come from a module, so we should not see the
// TranslationUnit DeclContext here.
assert(!dc->isTranslationUnit());
auto decl = dyn_cast<clang::NamedDecl>(dc);
if (!decl)
return nullptr;
auto swiftDecl = importDecl(decl);
if (!swiftDecl)
return nullptr;
if (auto nominal = dyn_cast<NominalTypeDecl>(swiftDecl))
return nominal;
if (auto extension = dyn_cast<ExtensionDecl>(swiftDecl))
return extension;
if (auto constructor = dyn_cast<ConstructorDecl>(swiftDecl))
return constructor;
if (auto destructor = dyn_cast<DestructorDecl>(swiftDecl))
return destructor;
return nullptr;
}
DeclContext *
ClangImporter::Implementation::importDeclContextOf(const clang::Decl *D) {
const clang::DeclContext *DC = D->getDeclContext();
if (DC->isTranslationUnit()) {
if (auto *M = getClangModuleForDecl(D))
return M;
else
return nullptr;
}
return importDeclContextImpl(DC);
}
ValueDecl *
ClangImporter::Implementation::createConstant(Identifier name, DeclContext *dc,
Type type,
const clang::APValue &value,
ConstantConvertKind convertKind,
bool isStatic,
ClangNode ClangN) {
auto &context = SwiftContext;
// Create the integer literal value.
Expr *expr = nullptr;
switch (value.getKind()) {
case clang::APValue::AddrLabelDiff:
case clang::APValue::Array:
case clang::APValue::ComplexFloat:
case clang::APValue::ComplexInt:
case clang::APValue::LValue:
case clang::APValue::MemberPointer:
case clang::APValue::Struct:
case clang::APValue::Uninitialized:
case clang::APValue::Union:
case clang::APValue::Vector:
llvm_unreachable("Unhandled APValue kind");
case clang::APValue::Float:
case clang::APValue::Int: {
// Print the value.
llvm::SmallString<16> printedValueBuf;
if (value.getKind() == clang::APValue::Int) {
value.getInt().toString(printedValueBuf);
} else {
assert(value.getFloat().isFinite() && "can't handle infinities or NaNs");
value.getFloat().toString(printedValueBuf);
}
StringRef printedValue = printedValueBuf.str();
// If this was a negative number, record that and strip off the '-'.
bool isNegative = printedValue.front() == '-';
if (isNegative)
printedValue = printedValue.drop_front();
// Create the expression node.
StringRef printedValueCopy(context.AllocateCopy(printedValue));
if (value.getKind() == clang::APValue::Int) {
expr = new (context) IntegerLiteralExpr(printedValueCopy, SourceLoc(),
/*Implicit=*/true);
} else {
expr = new (context) FloatLiteralExpr(printedValueCopy, SourceLoc(),
/*Implicit=*/true);
}
if (isNegative)
cast<NumberLiteralExpr>(expr)->setNegative(SourceLoc());
break;
}
}
assert(expr);
return createConstant(name, dc, type, expr, convertKind, isStatic, ClangN);
}
ValueDecl *
ClangImporter::Implementation::createConstant(Identifier name, DeclContext *dc,
Type type, StringRef value,
ConstantConvertKind convertKind,
bool isStatic,
ClangNode ClangN) {
auto expr = new (SwiftContext) StringLiteralExpr(value, SourceRange());
return createConstant(name, dc, type, expr, convertKind, isStatic, ClangN);
}
ValueDecl *
ClangImporter::Implementation::createConstant(Identifier name, DeclContext *dc,
Type type, Expr *valueExpr,
ConstantConvertKind convertKind,
bool isStatic,
ClangNode ClangN) {
auto &context = SwiftContext;
auto var = createDeclWithClangNode<VarDecl>(ClangN,
isStatic, /*IsLet*/ false,
SourceLoc(), name, type, dc);
// Form the argument patterns.
SmallVector<ParameterList*, 3> getterArgs;
// 'self'
if (dc->isTypeContext()) {
auto *selfDecl = ParamDecl::createSelf(SourceLoc(), dc, isStatic);
getterArgs.push_back(ParameterList::createWithoutLoc(selfDecl));
}
// empty tuple
getterArgs.push_back(ParameterList::createEmpty(context));
// Form the type of the getter.
auto getterType = ParameterList::getFullType(type, getterArgs);
// Create the getter function declaration.
auto func = FuncDecl::create(context, SourceLoc(), StaticSpellingKind::None,
SourceLoc(), Identifier(),
SourceLoc(), SourceLoc(), SourceLoc(),
nullptr, getterType,
getterArgs, TypeLoc::withoutLoc(type), dc);
func->setStatic(isStatic);
func->setBodyResultType(type);
func->setInterfaceType(getterType);
func->setAccessibility(Accessibility::Public);
// If we're not done type checking, build the getter body.
if (!hasFinishedTypeChecking()) {
auto expr = valueExpr;
// If we need a conversion, add one now.
switch (convertKind) {
case ConstantConvertKind::None:
break;
case ConstantConvertKind::Construction:
case ConstantConvertKind::ConstructionWithUnwrap: {
auto typeRef = TypeExpr::createImplicit(type, context);
// make a "(rawValue: <subexpr>)" tuple.
expr = TupleExpr::create(context, SourceLoc(), expr,
context.Id_rawValue, SourceLoc(),
SourceLoc(), /*trailingClosure*/false,
/*implicit*/true);
expr = new (context) CallExpr(typeRef, expr, /*Implicit=*/true);
if (convertKind == ConstantConvertKind::ConstructionWithUnwrap)
expr = new (context) ForceValueExpr(expr, SourceLoc());
break;
}
case ConstantConvertKind::Coerce:
break;
case ConstantConvertKind::Downcast: {
expr = new (context) ForcedCheckedCastExpr(expr, SourceLoc(), SourceLoc(),
TypeLoc::withoutLoc(type));
expr->setImplicit();
break;
}
}
// Create the return statement.
auto ret = new (context) ReturnStmt(SourceLoc(), expr);
// Finally, set the body.
func->setBody(BraceStmt::create(context, SourceLoc(),
ASTNode(ret),
SourceLoc()));
}
// Mark the function transparent so that we inline it away completely.
func->getAttrs().add(new (context) TransparentAttr(/*implicit*/ true));
// Set the function up as the getter.
var->makeComputed(SourceLoc(), func, nullptr, nullptr, SourceLoc());
// Register this thunk as an external definition.
registerExternalDecl(func);
return var;
}
/// \brief Create a decl with error type and an "unavailable" attribute on it
/// with the specified message.
void ClangImporter::Implementation::
markUnavailable(ValueDecl *decl, StringRef unavailabilityMsgRef) {
unavailabilityMsgRef = SwiftContext.AllocateCopy(unavailabilityMsgRef);
auto ua = AvailableAttr::createUnconditional(SwiftContext,
unavailabilityMsgRef);
decl->getAttrs().add(ua);
}
/// \brief Create a decl with error type and an "unavailable" attribute on it
/// with the specified message.
ValueDecl *ClangImporter::Implementation::
createUnavailableDecl(Identifier name, DeclContext *dc, Type type,
StringRef UnavailableMessage, bool isStatic,
ClangNode ClangN) {
// Create a new VarDecl with dummy type.
auto var = createDeclWithClangNode<VarDecl>(ClangN,
isStatic, /*IsLet*/ false,
SourceLoc(), name, type, dc);
markUnavailable(var, UnavailableMessage);
return var;
}
void
ClangImporter::Implementation::loadAllMembers(Decl *D, uint64_t unused) {
assert(D);
assert(D->hasClangNode());
auto clangDecl = cast<clang::ObjCContainerDecl>(D->getClangDecl());
clang::PrettyStackTraceDecl trace(clangDecl, clang::SourceLocation(),
Instance->getSourceManager(),
"loading members for");
SwiftDeclConverter converter(*this);
DeclContext *DC;
IterableDeclContext *IDC;
SmallVector<ProtocolDecl *, 4> protos;
// Figure out the declaration context we're importing into.
if (auto nominal = dyn_cast<NominalTypeDecl>(D)) {
DC = nominal;
IDC = nominal;
} else {
auto ext = cast<ExtensionDecl>(D);
DC = ext;
IDC = ext;
}
ImportingEntityRAII Importing(*this);
SmallVector<Decl *, 16> members;
converter.importObjCMembers(clangDecl, DC, members);
protos = takeImportedProtocols(D);
if (auto clangClass = dyn_cast<clang::ObjCInterfaceDecl>(clangDecl)) {
auto swiftClass = cast<ClassDecl>(D);
clangDecl = clangClass = clangClass->getDefinition();
// Imported inherited initializers.
if (clangClass->getName() != "Protocol") {
converter.importInheritedConstructors(const_cast<ClassDecl *>(swiftClass),
members);
}
} else if (auto clangProto = dyn_cast<clang::ObjCProtocolDecl>(clangDecl)) {
clangDecl = clangProto->getDefinition();
}
// Import mirrored declarations for protocols to which this category
// or extension conforms.
// FIXME: This is supposed to be a short-term hack.
converter.importMirroredProtocolMembers(clangDecl, DC,
protos, members, SwiftContext);
// Add the members now, before ~ImportingEntityRAII does work that might
// involve them.
for (auto member : members) {
IDC->addMember(member);
}
}
void ClangImporter::Implementation::loadAllConformances(
const Decl *D, uint64_t contextData,
SmallVectorImpl<ProtocolConformance *> &Conformances) {
Conformances = takeDelayedConformance(contextData);
}
Optional<MappedTypeNameKind>
ClangImporter::Implementation::getSpecialTypedefKind(clang::TypedefNameDecl *decl) {
auto iter = SpecialTypedefNames.find(decl->getCanonicalDecl());
if (iter == SpecialTypedefNames.end())
return None;
return iter->second;
}
Identifier
ClangImporter::getEnumConstantName(const clang::EnumConstantDecl *enumConstant){
return Impl.importFullName(enumConstant).Imported.getBaseName();
}
| {
"content_hash": "c776b431831f9dec7649ef7ce7a24490",
"timestamp": "",
"source": "github",
"line_count": 5960,
"max_line_length": 87,
"avg_line_length": 38.93842281879195,
"alnum_prop": 0.592244681630349,
"repo_name": "slavapestov/swift",
"id": "bcd678a3acbaecf003462f02b8c1c5b01480bedf",
"size": "232073",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/ClangImporter/ImportDecl.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "34605"
},
{
"name": "C++",
"bytes": "17863411"
},
{
"name": "CMake",
"bytes": "203474"
},
{
"name": "DTrace",
"bytes": "1427"
},
{
"name": "Emacs Lisp",
"bytes": "33811"
},
{
"name": "LLVM",
"bytes": "45324"
},
{
"name": "Makefile",
"bytes": "1841"
},
{
"name": "Objective-C",
"bytes": "166522"
},
{
"name": "Objective-C++",
"bytes": "152692"
},
{
"name": "Perl",
"bytes": "2219"
},
{
"name": "Python",
"bytes": "282261"
},
{
"name": "Ruby",
"bytes": "2087"
},
{
"name": "Shell",
"bytes": "111391"
},
{
"name": "Swift",
"bytes": "10972835"
},
{
"name": "Vim Script",
"bytes": "10933"
}
],
"symlink_target": ""
} |
package com.jfixby.red.triplane.resources.fsbased;
import com.jfixby.rana.api.pkg.io.BankHeaderInfo;
import com.jfixby.scarabei.api.debug.Debug;
import com.jfixby.scarabei.api.file.File;
public class BankHeader {
private final File bank_folder;
private final String bank_name;
public BankHeader (final BankHeaderInfo headerInfo, final File bank_folder) {
this.bank_folder = bank_folder;
this.bank_name = headerInfo.bank_name;
Debug.checkNull("bank_name", this.bank_name);
Debug.checkEmpty("bank_name", this.bank_name);
}
public File getRoot () {
return this.bank_folder;
}
@Override
public String toString () {
return "Bank[" + this.bank_folder + "]";
}
public String getName () {
return this.bank_name;
}
}
| {
"content_hash": "b07a216484b61b931231c5370ee9a6ac",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 78,
"avg_line_length": 23.484848484848484,
"alnum_prop": 0.6967741935483871,
"repo_name": "JFixby/Rana",
"id": "0ca1849b3b557cabb50f9e8627ff09b156146562",
"size": "775",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "rana-package-red/src/com/jfixby/red/triplane/resources/fsbased/BankHeader.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "111608"
}
],
"symlink_target": ""
} |
import { visit, visitArray, compile, Opcodes } from '../../utils/compiler'
import { objectToSortedKVArray } from '../../utils/array-utils'
import { Type } from '../../models/types'
import Post from '../../models/post'
import MarkupSection from '../../models/markup-section'
import ListSection from '../../models/list-section'
import ListItem from '../../models/list-item'
import Image from '../../models/image'
import Card from '../../models/card'
import Marker from '../../models/marker'
import Markup from '../../models/markup'
import Atom from '../../models/atom'
import { Dict } from '../../utils/types'
import { MobiledocSectionKind, MobiledocMarkerKind } from './constants'
export const MOBILEDOC_VERSION = '0.3.0'
const visitor = {
[Type.POST](node: Post, opcodes: Opcodes) {
opcodes.push(['openPost'])
visitArray(visitor, node.sections, opcodes)
},
[Type.MARKUP_SECTION](node: MarkupSection, opcodes: Opcodes) {
opcodes.push(['openMarkupSection', node.tagName])
visitArray(visitor, node.markers, opcodes)
},
[Type.LIST_SECTION](node: ListSection, opcodes: Opcodes) {
opcodes.push(['openListSection', node.tagName])
visitArray(visitor, node.items, opcodes)
},
[Type.LIST_ITEM](node: ListItem, opcodes: Opcodes) {
opcodes.push(['openListItem'])
visitArray(visitor, node.markers, opcodes)
},
[Type.IMAGE_SECTION](node: Image, opcodes: Opcodes) {
opcodes.push(['openImageSection', node.src])
},
[Type.CARD](node: Card, opcodes: Opcodes) {
opcodes.push(['openCardSection', node.name, node.payload])
},
[Type.MARKER](node: Marker, opcodes: Opcodes) {
opcodes.push(['openMarker', node.closedMarkups.length, node.value])
visitArray(visitor, node.openedMarkups, opcodes)
},
[Type.MARKUP](node: Markup, opcodes: Opcodes) {
opcodes.push(['openMarkup', node.tagName, objectToSortedKVArray(node.attributes)])
},
[Type.ATOM](node: Atom, opcodes: Opcodes) {
opcodes.push(['openAtom', node.closedMarkups.length, node.name, node.value, node.payload])
visitArray(visitor, node.openedMarkups, opcodes)
},
}
export type MobiledocMarkupMarker = [MobiledocMarkerKind.MARKUP, number[], number, string]
export type MobiledocAtomMarker = [MobiledocMarkerKind.ATOM, number[], number, number]
export type MobiledocMarker = MobiledocMarkupMarker | MobiledocAtomMarker
export type MobiledocMarkupSection = [MobiledocSectionKind.MARKUP, string, MobiledocMarker[]]
export type MobiledocListSection = [MobiledocSectionKind.LIST, string, MobiledocMarker[][]]
export type MobiledocImageSection = [MobiledocSectionKind.IMAGE, string]
export type MobiledocCardSection = [MobiledocSectionKind.CARD, number]
export type MobiledocSection =
| MobiledocMarkupSection
| MobiledocListSection
| MobiledocImageSection
| MobiledocCardSection
export type MobiledocAtom = [string, string, {}]
export type MobiledocCard = [string, {}]
export type MobiledocMarkerType = [string, string[]?]
class PostOpcodeCompiler {
markupMarkerIds!: number[]
markers!: MobiledocMarker[]
sections!: MobiledocSection[]
items!: MobiledocMarker[][]
markerTypes!: MobiledocMarkerType[]
atomTypes!: MobiledocAtom[]
cardTypes!: MobiledocCard[]
result!: MobiledocV0_3
_markerTypeCache!: Dict<number>
openMarker(closeCount: number, value: string) {
this.markupMarkerIds = []
this.markers.push([MobiledocMarkerKind.MARKUP, this.markupMarkerIds, closeCount, value || ''])
}
openAtom(closeCount: number, name: string, value: string, payload: {}) {
const index = this._addAtomTypeIndex(name, value, payload)
this.markupMarkerIds = []
this.markers.push([MobiledocMarkerKind.ATOM, this.markupMarkerIds, closeCount, index])
}
openMarkupSection(tagName: string) {
this.markers = []
this.sections.push([MobiledocSectionKind.MARKUP, tagName, this.markers])
}
openListSection(tagName: string) {
this.items = []
this.sections.push([MobiledocSectionKind.LIST, tagName, this.items])
}
openListItem() {
this.markers = []
this.items.push(this.markers)
}
openImageSection(url: string) {
this.sections.push([MobiledocSectionKind.IMAGE, url])
}
openCardSection(name: string, payload: {}) {
const index = this._addCardTypeIndex(name, payload)
this.sections.push([MobiledocSectionKind.CARD, index])
}
openPost() {
this.atomTypes = []
this.cardTypes = []
this.markerTypes = []
this.sections = []
this.result = {
version: MOBILEDOC_VERSION,
atoms: this.atomTypes,
cards: this.cardTypes,
markups: this.markerTypes,
sections: this.sections,
}
}
openMarkup(tagName: string, attributes: string[]) {
const index = this._findOrAddMarkerTypeIndex(tagName, attributes)
this.markupMarkerIds.push(index)
}
_addCardTypeIndex(cardName: string, payload: {}) {
let cardType: MobiledocCard = [cardName, payload]
this.cardTypes.push(cardType)
return this.cardTypes.length - 1
}
_addAtomTypeIndex(atomName: string, atomValue: string, payload: {}) {
let atomType: MobiledocAtom = [atomName, atomValue, payload]
this.atomTypes.push(atomType)
return this.atomTypes.length - 1
}
_findOrAddMarkerTypeIndex(tagName: string, attributesArray: string[]) {
if (!this._markerTypeCache) {
this._markerTypeCache = {}
}
const key = `${tagName}-${attributesArray.join('-')}`
let index = this._markerTypeCache[key]
if (index === undefined) {
let markerType: MobiledocMarkerType = [tagName]
if (attributesArray.length) {
markerType.push(attributesArray)
}
this.markerTypes.push(markerType)
index = this.markerTypes.length - 1
this._markerTypeCache[key] = index
}
return index
}
}
export interface MobiledocV0_3 {
version: typeof MOBILEDOC_VERSION
atoms: MobiledocAtom[]
cards: MobiledocCard[]
markups: MobiledocMarkerType[]
sections: MobiledocSection[]
}
/**
* Render from post -> mobiledoc
*/
const MobiledocRenderer = {
/**
* @param {Post}
* @return {Mobiledoc}
*/
render(post: Post): MobiledocV0_3 {
let opcodes: Opcodes = []
visit(visitor, post, opcodes)
let compiler = new PostOpcodeCompiler()
compile(compiler, opcodes)
return compiler.result
},
}
export default MobiledocRenderer
| {
"content_hash": "5aed5275106b38ff5b6ef37a438161e5",
"timestamp": "",
"source": "github",
"line_count": 199,
"max_line_length": 98,
"avg_line_length": 31.798994974874372,
"alnum_prop": 0.7011694058154235,
"repo_name": "bustle/mobiledoc-kit",
"id": "f02132dcacef4a40f2d56513ebcce85d32628479",
"size": "6328",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/js/renderers/mobiledoc/0-3.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2736"
},
{
"name": "HTML",
"bytes": "541"
},
{
"name": "JavaScript",
"bytes": "568555"
},
{
"name": "Shell",
"bytes": "331"
},
{
"name": "TypeScript",
"bytes": "459570"
}
],
"symlink_target": ""
} |
import os
import copy
import pprint
from kivy.uix.image import Image
from kivy.uix.widget import Widget
# TODO: Handle this creation somewhere in app init
IMAGES_DICTIONARY = {'okapi': '/Assets/Sprites/okapi.png',
'normal_ground': '/Assets/Sprites/normal_ground.png',
'wall': '/Assets/Sprites/wall.png'
}
ACTORS = {"x": 'block',
"c": "",
"d": "",
"o": ""}
STATICS = {"#": "wall",
" ": "normal_ground"
}
class SpriteMap(object):
def __init__(self):
pass
class LevelFileReader(object):
"""Level loader, reads a level file, returns a level object
"""
def __init__(self, path):
# TODO: Get this from app init
self.levels = self.parse_file(path)
def parse_file(self, level_file):
"""Turns a levels file into a Levels object
"""
# TODO: Add in the ability to have sensible whitespace
levels = []
current_level = []
lines = self.open_and_read_file(level_file)
for line in lines:
# Ignore comment lines
if self.is_comment(line):
continue
# Split up the string into a proper list
line = [l for l in line]
# If the line is real, we want it
if line:
current_level.append(line)
# At blank line, finalize the current level and add
# it to ``this.levels``
else:
if current_level:
self.add_to_levels(levels, current_level)
current_level = []
# Don't forget trailing content if the file didn't end
# with an empty newline
if current_level:
self.add_to_levels(levels, current_level)
return levels
def is_comment(self, line):
"""Helper function to check the line for commentage
@param line: string returned from .readlines()
@return: If the line is a comment
(Any line that contains a ; is considered a comment)
"""
if line.startswith(";"):
return True
def add_to_levels(self, levels, current_level):
"""Puts the current level content into the larger levels file
"""
levels.append(copy.copy(current_level))
def open_and_read_file(self, level_file):
"""I/O Handler for level files
@param level_file: The target file to read
@return lines: array of strings, representing level rows
"""
lines = []
try:
with open(level_file, 'r') as my_file:
for line in my_file.readlines():
lines.append(line.rstrip(os.linesep))
return lines
except IOError:
raise IOError("Level File Not Found!")
# class Sprite(Image):
# def __init__(self, **kwargs):
# super(Sprite, self).__init__(**kwargs)
# self.size = self.texture_size
# class Ground(Widget):
# def __init__(self):
# self.sprite_path = None
# self.actor = None
# def get_sprite_path(self):
# if self.sprite_path:
# pass
# def render(self):
# self.add_widget(Sprite(source=self.get_sprite_path())
# if self.actor:
# self.add_widget(Sprite(source=self.actor_path))
# class Actor(Ground):
# def __init__(self):
# super(Ground, self).__init__()
# # self.actor = actor
# class Generic(object):
# def __init__(self):
# self.name = 'Generic'
# class Child(Generic):
# def __init__(self):
# super(Generic, self).__init__()
# self.name = 'Child'
# class GameStateInitializer(object):
# def __init__(self, level_number):
# self.raw_levels = LevelFileReader().levels
# self.level_number = level_number
# self.spritemap = SpriteMap()
# def create_objects(self):
# game_objects = []
# raw_level = copy.copy(self.raw_levels[self.level_number])
# for row in raw_level:
# game_objects.append([self.objectify(element) for element in row])
# return game_objects
# def objectify(self, raw_object):
# """Objectify level raw text into objects
# """
# spritemap = SpriteMap()
# if raw_object in spritemap.actors.keys():
# return Actor(raw_object)
# else:
# return Ground(raw_object)
if __name__ == '__main__':
gs = GameStateInitializer(1)
gs.create_objects()
| {
"content_hash": "5b655bc1a4b18faf3057b2800a9acdae",
"timestamp": "",
"source": "github",
"line_count": 162,
"max_line_length": 79,
"avg_line_length": 28.506172839506174,
"alnum_prop": 0.5426591598094413,
"repo_name": "kostyll/kivy-okapi",
"id": "6e6493712839713ae8d872723218dd54aeb4e9cc",
"size": "4618",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "okapi/engine/level_file_reader.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "38775"
}
],
"symlink_target": ""
} |
package org.wildfly.camel.test.slack;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.component.slack.SlackComponent;
import org.apache.camel.impl.DefaultCamelContext;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.extension.camel.CamelAware;
@CamelAware
@RunWith(Arquillian.class)
public class SlackIntegrationTest {
@Deployment
public static WebArchive deployment() {
return ShrinkWrap.create(WebArchive.class, "camel-slack-tests.war");
}
@Test
public void testSlackMessage() throws Exception {
CamelContext camelctx = new DefaultCamelContext();
camelctx.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:test").to("slack:#general?iconEmoji=:camel:&username=CamelTest").to("mock:result");
from("undertow:http://localhost/slack/webhook").setBody(constant("{\"ok\": true}"));
}
});
SlackComponent comp = camelctx.getComponent("slack", SlackComponent.class);
comp.setWebhookUrl("http://localhost:8080/slack/webhook");
MockEndpoint mockEndpoint = camelctx.getEndpoint("mock:result", MockEndpoint.class);
mockEndpoint.expectedMessageCount(1);
camelctx.start();
try {
ProducerTemplate producer = camelctx.createProducerTemplate();
producer.sendBody("direct:test", "Hello from Camel!");
mockEndpoint.assertIsSatisfied();
} finally {
camelctx.stop();
}
}
}
| {
"content_hash": "401af7d58495c39c41b14cf5992f6201",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 112,
"avg_line_length": 35.629629629629626,
"alnum_prop": 0.6990644490644491,
"repo_name": "jamesnetherton/wildfly-camel",
"id": "2f82d8271641b10901e9250a2bfd50e373a19231",
"size": "2727",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "itests/standalone/basic/src/test/java/org/wildfly/camel/test/slack/SlackIntegrationTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "391"
},
{
"name": "Dockerfile",
"bytes": "602"
},
{
"name": "FreeMarker",
"bytes": "675"
},
{
"name": "Groovy",
"bytes": "15942"
},
{
"name": "HTML",
"bytes": "633"
},
{
"name": "Java",
"bytes": "2966813"
},
{
"name": "JavaScript",
"bytes": "1447"
},
{
"name": "Python",
"bytes": "60"
},
{
"name": "Ruby",
"bytes": "61"
},
{
"name": "Shell",
"bytes": "4829"
},
{
"name": "TSQL",
"bytes": "89"
},
{
"name": "Tcl",
"bytes": "34"
},
{
"name": "XSLT",
"bytes": "4383"
}
],
"symlink_target": ""
} |
var foo = {};
var bar = {};
// A function that uses `this`
function func(val) {
this.val = val;
}
// Force this in func to be foo
func.call(foo, 123);
// Force this in func to be bar
func.call(bar, 456);
// Verify:
console.log(foo.val); // 123
console.log(bar.val); // 456 | {
"content_hash": "9afd7174f09ac9b5079e12f130c3bebd",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 31,
"avg_line_length": 16.529411764705884,
"alnum_prop": 0.6192170818505338,
"repo_name": "decentcamper/MeanStackDevelopment",
"id": "7d55e2345d9e4250b72d7cf7790c08738df641d7",
"size": "281",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Express/1_Connect/oo/2call.js",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "172521"
},
{
"name": "JavaScript",
"bytes": "411664"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<solid android:color="@color/auto_color_3b4d63_90" />
<corners
android:radius="@dimen/auto_dimen2_4"
android:topLeftRadius="0.0dip"
android:topRightRadius="0.0dip"
android:bottomLeftRadius="@dimen/auto_dimen2_4"
android:bottomRightRadius="@dimen/auto_dimen2_4" />
</shape>
</item>
</layer-list> | {
"content_hash": "5d6efc00f9b828198f556b8eca1e1fdd",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 71,
"avg_line_length": 39.142857142857146,
"alnum_prop": 0.5675182481751825,
"repo_name": "eagle-S/Test",
"id": "e062e05dcab55a8cd9eaf3c536cc2ee3e2194f8a",
"size": "548",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SkyAutoNavi/app/src/main/res/drawable/auto_bg_navi_eta_threed_day.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "14215"
}
],
"symlink_target": ""
} |
package org.synyx.urlaubsverwaltung.core.settings;
import org.junit.Assert;
import org.junit.Test;
/**
* Unit test for {@link MailSettings}.
*
* @author Aljona Murygina - [email protected]
*/
public class MailSettingsTest {
@Test
public void ensureHasSomeDefaultValues() {
MailSettings mailSettings = new MailSettings();
// Fields without default values
Assert.assertNull("Username should not be set", mailSettings.getUsername());
Assert.assertNull("Password should not be set", mailSettings.getPassword());
// Fields with default values
Assert.assertNotNull("Host should be set", mailSettings.getHost());
Assert.assertNotNull("Port should be set", mailSettings.getPort());
Assert.assertNotNull("Admin mail address should be set", mailSettings.getAdministrator());
Assert.assertNotNull("From mail address should be set", mailSettings.getFrom());
Assert.assertNotNull("Base link URL should be set", mailSettings.getBaseLinkURL());
Assert.assertFalse("Should be inactive", mailSettings.isActive());
Assert.assertEquals("Wrong host", "localhost", mailSettings.getHost());
Assert.assertEquals("Wrong port", (Integer) 25, mailSettings.getPort());
Assert.assertEquals("Wrong admin mail address", "[email protected]", mailSettings.getAdministrator());
Assert.assertEquals("Wrong from mail address", "[email protected]", mailSettings.getFrom());
Assert.assertEquals("Wrong base link URL", "http://localhost:8080/", mailSettings.getBaseLinkURL());
}
}
| {
"content_hash": "50168ac69d91f81853eb8cfddaa6fdb3",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 108,
"avg_line_length": 42.891891891891895,
"alnum_prop": 0.7038437303087587,
"repo_name": "pongo710/urlaubsverwaltung",
"id": "44b3653eb50b7a9f6356ab5d56127544cee30cc7",
"size": "1587",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/org/synyx/urlaubsverwaltung/core/settings/MailSettingsTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "70345"
},
{
"name": "HTML",
"bytes": "3615"
},
{
"name": "Java",
"bytes": "1432465"
},
{
"name": "JavaScript",
"bytes": "401327"
}
],
"symlink_target": ""
} |
__revision__ = "test/site_scons/basic.py rel_2.5.1:3735:9dc6cee5c168 2016/11/03 14:02:02 bdbaddog"
import TestSCons
"""
Verify basic functionality of the site_scons dir and
site_scons/site_init.py file:
Make sure the site_scons/site_init.py file gets loaded,
and make sure a tool can be loaded from the site_scons/site_tools subdir,
even when executing out of a subdirectory.
"""
test = TestSCons.TestSCons()
test.subdir('site_scons', ['site_scons', 'site_tools'])
test.write(['site_scons', 'site_init.py'], """
from SCons.Script import *
print "Hi there, I am in site_scons/site_init.py!"
""")
test.write(['site_scons', 'site_tools', 'mytool.py'], """
import SCons.Tool
def generate(env):
env['MYTOOL']='mytool'
def exists(env):
return 1
""")
test.write('SConstruct', """
e=Environment(tools=['default', 'mytool'])
print e.subst('My site tool is $MYTOOL')
""")
test.run(arguments = '-Q .',
stdout = """Hi there, I am in site_scons/site_init.py!
My site tool is mytool
scons: `.' is up to date.\n""")
test.pass_test()
# end of file
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
| {
"content_hash": "25251d88354ba3908cef4a6776ed3b08",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 98,
"avg_line_length": 22.96078431372549,
"alnum_prop": 0.6806148590947908,
"repo_name": "EmanueleCannizzaro/scons",
"id": "2868e0787b0b779831967ba7dc89db4f4c7c4cb2",
"size": "2306",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/site_scons/basic.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "2491"
},
{
"name": "C",
"bytes": "659"
},
{
"name": "C++",
"bytes": "598"
},
{
"name": "CSS",
"bytes": "18502"
},
{
"name": "D",
"bytes": "1997"
},
{
"name": "HTML",
"bytes": "817651"
},
{
"name": "Java",
"bytes": "6860"
},
{
"name": "JavaScript",
"bytes": "215495"
},
{
"name": "Makefile",
"bytes": "3795"
},
{
"name": "Perl",
"bytes": "29978"
},
{
"name": "Python",
"bytes": "7510453"
},
{
"name": "Roff",
"bytes": "556545"
},
{
"name": "Ruby",
"bytes": "11074"
},
{
"name": "Shell",
"bytes": "52682"
},
{
"name": "XSLT",
"bytes": "7567242"
}
],
"symlink_target": ""
} |
const options = {
manager: require('../../../../src/managers/master/design-tracking-reason-manager'),
model: require('bateeq-models').master.DesignTrackingReason,
util: require('../../../data-util/master/design-tracking-reason-data-util'),
validator: require('bateeq-models').validator.master.designTrackingReason,
createDuplicate: false,
keys: []
};
const basicTest = require('../../../basic-test-factory');
basicTest(options);
| {
"content_hash": "daa41fc4eac1388e30bf0bdd3538f608",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 87,
"avg_line_length": 41.27272727272727,
"alnum_prop": 0.6894273127753304,
"repo_name": "danliris/bateeq-module",
"id": "080afbd81b2e0385d349ef3be2505f1d77ecdef7",
"size": "454",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/managers/master/design-tracking-reason/basic.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "2440314"
}
],
"symlink_target": ""
} |
"""Example Script: How to configure a Spark Datasource
This example script is intended for use in documentation on how to configure a Spark Datasource.
Assert statements are included to ensure that if the behaviour shown in this script breaks it will not pass
tests and will be updated. These statements can be ignored by users.
Comments with the tags `<snippet>` and `</snippet>` are used to ensure that if this script is updated
the snippets that are specified for use in documentation are maintained. These comments can be ignored by users.
--documentation--
https://docs.greatexpectations.io/docs/guides/connecting_to_your_data/datasource_configuration/how_to_configure_a_spark_datasource
To run this code as a local test, use the following console command:
```
pytest -v --docs-tests -m integration -k "how_to_configure_a_spark_datasource" tests/integration/test_script_runner.py
```
To validate the snippets in this file, use the following console command:
```
yarn snippet-check ./tests/integration/docusaurus/connecting_to_your_data/datasource_configuration/how_to_configure_a_spark_datasource.py
```
"""
# The following imports are used as part of verifying that all example snippets are consistent.
# Users may disregard them.
from ruamel import yaml
import great_expectations as gx
from tests.integration.docusaurus.connecting_to_your_data.datasource_configuration.datasource_configuration_test_utilities import (
is_subset,
)
from tests.integration.docusaurus.connecting_to_your_data.datasource_configuration.full_datasource_configurations import (
get_full_config_spark_configured_datasource_multi_batch,
get_full_config_spark_configured_datasource_single_batch,
get_full_config_spark_inferred_datasource_multi_batch,
get_full_config_spark_inferred_datasource_single_batch,
get_full_config_spark_runtime_datasource,
get_partial_config_universal_datasource_config_elements,
)
data_context: gx.DataContext = gx.get_context()
def validate_universal_config_elements():
"""Validates that the 'universal' configuration keys and values are in fact identical to the keys and values
in all the full Spark configurations.
"""
universal_elements = get_partial_config_universal_datasource_config_elements()
is_subset(
universal_elements, get_full_config_spark_configured_datasource_single_batch()
)
is_subset(
universal_elements, get_full_config_spark_configured_datasource_multi_batch()
)
is_subset(
universal_elements, get_full_config_spark_inferred_datasource_single_batch()
)
is_subset(
universal_elements, get_full_config_spark_inferred_datasource_multi_batch()
)
is_subset(universal_elements, get_full_config_spark_runtime_datasource())
# The following methods correspond to the section headings in the how-to guide linked in the module docstring.
def section_5_add_the_spark_execution_engine_to_your_datasource_configuration():
"""Provides and tests the snippets for section 5 of the Spark Datasource configuration guide."""
# <snippet name="spark datasource_config up to definition of Spark execution engine">
datasource_config: dict = {
"name": "my_datasource_name",
"class_name": "Datasource",
"module_name": "great_expectations.datasource",
"execution_engine": {
"class_name": "SparkDFExecutionEngine",
"module_name": "great_expectations.execution_engine",
},
}
# </snippet>
execution_engine_snippet: dict = {
"name": "my_datasource_name",
"class_name": "Datasource",
"module_name": "great_expectations.datasource",
# <snippet name="define spark execution engine">
"execution_engine": {
"class_name": "SparkDFExecutionEngine",
"module_name": "great_expectations.execution_engine",
}
# </snippet>
}
assert datasource_config == execution_engine_snippet
is_subset(
datasource_config, get_full_config_spark_configured_datasource_single_batch()
)
is_subset(
datasource_config, get_full_config_spark_configured_datasource_multi_batch()
)
is_subset(
datasource_config, get_full_config_spark_inferred_datasource_single_batch()
)
is_subset(
datasource_config, get_full_config_spark_inferred_datasource_multi_batch()
)
is_subset(datasource_config, get_full_config_spark_runtime_datasource())
def section_6_add_a_dictionary_as_the_value_of_the_data_connectors_key():
"""Provides and tests the snippets for section 6 of the Spark Datasource configuration guide."""
# <snippet name="spark datasource_config up to adding an empty data_connectors dictionary">
datasource_config: dict = {
"name": "my_datasource_name",
"class_name": "Datasource",
"module_name": "great_expectations.datasource",
"execution_engine": {
"class_name": "SparkDFExecutionEngine",
"module_name": "great_expectations.execution_engine",
},
"data_connectors": {},
}
# </snippet>
is_subset(
datasource_config, get_full_config_spark_configured_datasource_single_batch()
)
is_subset(
datasource_config, get_full_config_spark_configured_datasource_multi_batch()
)
is_subset(
datasource_config, get_full_config_spark_inferred_datasource_single_batch()
)
is_subset(
datasource_config, get_full_config_spark_inferred_datasource_multi_batch()
)
is_subset(datasource_config, get_full_config_spark_runtime_datasource())
def section_7_configure_your_individual_data_connectors__inferred():
"""Provides and tests the InferredAssetFilesystemDataConnector snippets for section 7 of the
Spark Datasource configuration guide.
"""
# <snippet name="spark Datasource configuration up to adding an empty inferred data connector">
datasource_config: dict = {
"name": "my_datasource_name",
"class_name": "Datasource",
"module_name": "great_expectations.datasource",
"execution_engine": {
"class_name": "SparkDFExecutionEngine",
"module_name": "great_expectations.execution_engine",
},
"data_connectors": {"name_of_my_inferred_data_connector": {}},
}
# </snippet>
is_subset(
datasource_config, get_full_config_spark_inferred_datasource_single_batch()
)
is_subset(
datasource_config, get_full_config_spark_inferred_datasource_multi_batch()
)
# <snippet name="inferred spark datasource_config up to adding empty default_regex and batch_spec_passthrough dictionaries">
datasource_config: dict = {
"name": "my_datasource_name",
"class_name": "Datasource",
"module_name": "great_expectations.datasource",
"execution_engine": {
"class_name": "SparkDFExecutionEngine",
"module_name": "great_expectations.execution_engine",
},
"data_connectors": {
"name_of_my_inferred_data_connector": {
# <snippet name="inferred data connector define class_name as InferredAssetFilesystemDataConnector">
"class_name": "InferredAssetFilesystemDataConnector",
# </snippet>
"base_directory": "../data",
"default_regex": {},
"batch_spec_passthrough": {},
}
},
}
# </snippet>
is_subset(
datasource_config, get_full_config_spark_inferred_datasource_single_batch()
)
is_subset(
datasource_config, get_full_config_spark_inferred_datasource_multi_batch()
)
glob_directive: dict = {
"name": "my_datasource_name",
"class_name": "Datasource",
"module_name": "great_expectations.datasource",
"execution_engine": {
"class_name": "SparkDFExecutionEngine",
"module_name": "great_expectations.execution_engine",
},
"data_connectors": {
"name_of_my_inferred_data_connector": {
"class_name": "InferredAssetFilesystemDataConnector",
"base_directory": "../data",
# <snippet name="define glob_directive">
"glob_directive": "*/*",
# </snippet>
"default_regex": {},
"batch_spec_passthrough": {},
}
},
}
is_subset(datasource_config, glob_directive)
# <snippet name="spark inferred datasource_config post glob_directive definition">
datasource_config: dict = {
"name": "my_datasource_name",
"class_name": "Datasource",
"module_name": "great_expectations.datasource",
"execution_engine": {
"class_name": "SparkDFExecutionEngine",
"module_name": "great_expectations.execution_engine",
},
"data_connectors": {
"name_of_my_inferred_data_connector": {
"class_name": "InferredAssetFilesystemDataConnector",
"base_directory": "../data",
"glob_directive": "*/*",
"default_regex": {},
"batch_spec_passthrough": {},
}
},
}
# </snippet>
assert datasource_config == glob_directive
def section_7_configure_your_individual_data_connectors__configured():
"""Provides and tests the ConfiguredAssetFilesystemDataConnector snippets for section 7 of the
Spark Datasource configuration guide.
"""
# <snippet name="spark Datasource configuration up to adding an empty configured data connector">
datasource_config: dict = {
"name": "my_datasource_name",
"class_name": "Datasource",
"module_name": "great_expectations.datasource",
"execution_engine": {
"class_name": "SparkDFExecutionEngine",
"module_name": "great_expectations.execution_engine",
},
"data_connectors": {"name_of_my_configured_data_connector": {}},
}
# </snippet>
is_subset(
datasource_config, get_full_config_spark_configured_datasource_single_batch()
)
is_subset(
datasource_config, get_full_config_spark_configured_datasource_multi_batch()
)
# <snippet name="configured spark datasource_config up to adding empty assets and batch_spec_passthrough dictionaries">
datasource_config: dict = {
"name": "my_datasource_name",
"class_name": "Datasource",
"module_name": "great_expectations.datasource",
"execution_engine": {
"class_name": "SparkDFExecutionEngine",
"module_name": "great_expectations.execution_engine",
},
"data_connectors": {
"name_of_my_configured_data_connector": {
# <snippet name="configured data connector define class_name as ConfiguredAssetFilesystemDataConnector">
"class_name": "ConfiguredAssetFilesystemDataConnector",
# </snippet>
"base_directory": "../data",
"assets": {},
"batch_spec_passthrough": {},
}
},
}
# </snippet>
is_subset(
datasource_config, get_full_config_spark_configured_datasource_single_batch()
)
is_subset(
datasource_config, get_full_config_spark_configured_datasource_multi_batch()
)
def section_7_configure_your_individual_data_connectors__runtime():
"""Provides and tests the RuntimeDataConnector snippets for section 7 of the
Spark Datasource configuration guide.
"""
# <snippet name="spark Datasource configuration up to adding an empty runtime data connector">
datasource_config: dict = {
"name": "my_datasource_name",
"class_name": "Datasource",
"module_name": "great_expectations.datasource",
"execution_engine": {
"class_name": "SparkDFExecutionEngine",
"module_name": "great_expectations.execution_engine",
},
"data_connectors": {"name_of_my_runtime_data_connector": {}},
}
# </snippet>
is_subset(datasource_config, get_full_config_spark_runtime_datasource())
# <snippet name="runtime spark datasource_config up to adding empty batch_identifiers and batch_spec_passthrough dictionaries">
datasource_config: dict = {
"name": "my_datasource_name",
"class_name": "Datasource",
"module_name": "great_expectations.datasource",
"execution_engine": {
"class_name": "SparkDFExecutionEngine",
"module_name": "great_expectations.execution_engine",
},
"data_connectors": {
"name_of_my_runtime_data_connector": {
# <snippet name="runtime data connector define class_name as RuntimeDataConnector">
"class_name": "RuntimeDataConnector",
# </snippet>
"batch_spec_passthrough": {},
"batch_identifiers": [],
}
},
}
# </snippet>
is_subset(datasource_config, get_full_config_spark_runtime_datasource())
def section_8_configure_the_values_for_batch_spec_passthrough__universal():
"""Provides and tests the RuntimeDataConnector snippets for section 7 of the
Spark Datasource configuration guide.
"""
empty_batch_spec_passthrough: dict = {
# <snippet name="populate batch_spec_passthrough with empty reader_method and reader_options">
"batch_spec_passthrough": {"reader_method": "", "reader_options": {}}
# </snippet>
}
smaller_snippets: dict = {
"batch_spec_passthrough": {
# <snippet name="populate reader_method with csv">
"reader_method": "csv",
# </snippet>
# <snippet name = "populate reader_options with empty header and inferSchema keys">
"reader_options": {"header": "", "inferSchema": ""}
# </snippet>
}
}
even_smaller_snippets: dict = {
"batch_spec_passthrough": {
"reader_method": "csv",
"reader_options": {
# <snippet name="define header as True for reader_options">
"header": True,
# </snippet>
# <snippet name="define inferSchema as True for reader_options">
"inferSchema": True
# </snippet>
},
}
}
is_subset(empty_batch_spec_passthrough, even_smaller_snippets)
is_subset(smaller_snippets, even_smaller_snippets)
is_subset(
even_smaller_snippets,
get_full_config_spark_configured_datasource_single_batch()["data_connectors"][
"name_of_my_configured_data_connector"
],
)
is_subset(
even_smaller_snippets,
get_full_config_spark_configured_datasource_multi_batch()["data_connectors"][
"name_of_my_configured_data_connector"
],
)
is_subset(
even_smaller_snippets,
get_full_config_spark_inferred_datasource_single_batch()["data_connectors"][
"name_of_my_inferred_data_connector"
],
)
is_subset(
even_smaller_snippets,
get_full_config_spark_inferred_datasource_multi_batch()["data_connectors"][
"name_of_my_inferred_data_connector"
],
)
is_subset(
even_smaller_snippets,
get_full_config_spark_runtime_datasource()["data_connectors"][
"name_of_my_runtime_data_connector"
],
)
assert (
even_smaller_snippets["batch_spec_passthrough"]
== get_full_config_spark_configured_datasource_single_batch()[
"data_connectors"
]["name_of_my_configured_data_connector"]["batch_spec_passthrough"]
)
assert (
even_smaller_snippets["batch_spec_passthrough"]
== get_full_config_spark_configured_datasource_multi_batch()["data_connectors"][
"name_of_my_configured_data_connector"
]["batch_spec_passthrough"]
)
assert (
even_smaller_snippets["batch_spec_passthrough"]
== get_full_config_spark_inferred_datasource_single_batch()["data_connectors"][
"name_of_my_inferred_data_connector"
]["batch_spec_passthrough"]
)
assert (
even_smaller_snippets["batch_spec_passthrough"]
== get_full_config_spark_inferred_datasource_multi_batch()["data_connectors"][
"name_of_my_inferred_data_connector"
]["batch_spec_passthrough"]
)
assert (
even_smaller_snippets["batch_spec_passthrough"]
== get_full_config_spark_runtime_datasource()["data_connectors"][
"name_of_my_runtime_data_connector"
]["batch_spec_passthrough"]
)
def section_8_configure_the_values_for_batch_spec_passthrough__inferred():
# <snippet name="inferred spark datasource_config post batch_spec_passthrough definition">
datasource_config: dict = {
"name": "my_datasource_name", # Preferably name it something relevant
"class_name": "Datasource",
"module_name": "great_expectations.datasource",
"execution_engine": {
"class_name": "SparkDFExecutionEngine",
"module_name": "great_expectations.execution_engine",
},
"data_connectors": {
"name_of_my_inferred_data_connector": {
"class_name": "InferredAssetFilesystemDataConnector",
"base_directory": "../data",
"default_regex": {},
"batch_spec_passthrough": {
"reader_method": "csv",
"reader_options": {
"header": True,
"inferSchema": True,
},
},
}
},
}
# </snippet>
is_subset(
datasource_config, get_full_config_spark_inferred_datasource_single_batch()
)
is_subset(
datasource_config, get_full_config_spark_inferred_datasource_multi_batch()
)
def section_8_configure_the_values_for_batch_spec_passthrough__configured():
# <snippet name="configured spark datasource_config post batch_spec_passthrough definition">
datasource_config: dict = {
"name": "my_datasource_name", # Preferably name it something relevant
"class_name": "Datasource",
"module_name": "great_expectations.datasource",
"execution_engine": {
"class_name": "SparkDFExecutionEngine",
"module_name": "great_expectations.execution_engine",
},
"data_connectors": {
"name_of_my_configured_data_connector": {
"class_name": "ConfiguredAssetFilesystemDataConnector",
"base_directory": "../data",
"assets": {},
"batch_spec_passthrough": {
"reader_method": "csv",
"reader_options": {
"header": True,
"inferSchema": True,
},
},
}
},
}
# </snippet>
is_subset(
datasource_config, get_full_config_spark_configured_datasource_single_batch()
)
is_subset(
datasource_config, get_full_config_spark_configured_datasource_multi_batch()
)
def section_8_configure_the_values_for_batch_spec_passthrough__runtime():
# <snippet name="runtime spark datasource_config post batch_spec_passthrough definition">
datasource_config: dict = {
"name": "my_datasource_name", # Preferably name it something relevant
"class_name": "Datasource",
"module_name": "great_expectations.datasource",
"execution_engine": {
"class_name": "SparkDFExecutionEngine",
"module_name": "great_expectations.execution_engine",
},
"data_connectors": {
"name_of_my_runtime_data_connector": {
"class_name": "RuntimeDataConnector",
"batch_spec_passthrough": {
"reader_method": "csv",
"reader_options": {
"header": True,
"inferSchema": True,
},
},
"batch_identifiers": [],
}
},
}
# </snippet>
is_subset(datasource_config, get_full_config_spark_runtime_datasource())
def section_9_configure_your_data_connectors_data_assets__inferred__single_batch():
single_line_snippets: dict = {
"data_connectors": {
"name_of_my_inferred_data_connector": {
"default_regex": {
# <snippet name="inferred spark single batch pattern">
"pattern": "(.*)\\.csv",
# </snippet>
# <snippet name="inferred spark single batch group_names">
"group_names": ["data_asset_name"]
# </snippet>
},
},
},
}
is_subset(
single_line_snippets, get_full_config_spark_inferred_datasource_single_batch()
)
data_connector_snippet: dict = {
"data_connectors": {
# <snippet name="inferred spark single batch data connector config">
"name_of_my_inferred_data_connector": {
"class_name": "InferredAssetFilesystemDataConnector",
"base_directory": "../data",
"default_regex": {
"pattern": "(.*)\\.csv",
"group_names": ["data_asset_name"],
},
},
# </snippet>
},
# </snippet>
}
is_subset(
data_connector_snippet, get_full_config_spark_inferred_datasource_single_batch()
)
# <snippet name="full datasource_config for inferred spark single batch datasource">
datasource_config: dict = {
"name": "my_datasource_name", # Preferably name it something relevant
"class_name": "Datasource",
"module_name": "great_expectations.datasource",
"execution_engine": {
"class_name": "SparkDFExecutionEngine",
"module_name": "great_expectations.execution_engine",
},
"data_connectors": {
"name_of_my_inferred_data_connector": {
"class_name": "InferredAssetFilesystemDataConnector",
"base_directory": "../data",
"default_regex": {
"pattern": "(.*)\\.csv",
"group_names": ["data_asset_name"],
},
"batch_spec_passthrough": {
"reader_method": "csv",
"reader_options": {
"header": True,
"inferSchema": True,
},
},
}
},
}
# </snippet>
is_subset(
datasource_config, get_full_config_spark_inferred_datasource_single_batch()
)
def section_9_configure_your_data_connectors_data_assets__inferred__multi_batch():
# <snippet name="full datasource_config for inferred spark multi batch datasource">
datasource_config: dict = {
"name": "my_datasource_name", # Preferably name it something relevant
"class_name": "Datasource",
"module_name": "great_expectations.datasource",
"execution_engine": {
"class_name": "SparkDFExecutionEngine",
"module_name": "great_expectations.execution_engine",
},
"data_connectors": {
# <snippet name="inferred spark multi batch data connector config">
"name_of_my_inferred_data_connector": {
"class_name": "InferredAssetFilesystemDataConnector",
"base_directory": "../data",
"default_regex": {
"pattern": "(yellow_tripdata_sample_2020)-(\\d.*)\\.csv",
"group_names": ["data_asset_name", "month"],
},
"batch_spec_passthrough": {
"reader_method": "csv",
"reader_options": {
"header": True,
"inferSchema": True,
},
},
}
# </snippet>
},
}
# </snippet>
is_subset(
datasource_config, get_full_config_spark_inferred_datasource_multi_batch()
)
def section_9_configure_your_data_connectors_data_assets__configured__single_batch():
datasource_config: dict = {
"data_connectors": {
"name_of_my_configured_data_connector": {
"assets": {
# <snippet name="empty asset for configured spark single batch datasource">
"yellow_tripdata_jan": {}
# </snippet>
}
}
}
}
is_subset(
datasource_config, get_full_config_spark_configured_datasource_single_batch()
)
# <snippet name="full datasource_config for configured spark single batch datasource">
datasource_config: dict = {
"name": "my_datasource_name", # Preferably name it something relevant
"class_name": "Datasource",
"module_name": "great_expectations.datasource",
"execution_engine": {
"class_name": "SparkDFExecutionEngine",
"module_name": "great_expectations.execution_engine",
},
"data_connectors": {
# <snippet name="configured spark single batch data connector config">
"name_of_my_configured_data_connector": {
"class_name": "ConfiguredAssetFilesystemDataConnector",
"base_directory": "../data",
"assets": {
# <snippet name="configured spark single batch asset">
"yellow_tripdata_jan": {
# <snippet name="configured spark single batch pattern">
"pattern": "yellow_tripdata_sample_2020-(01)\\.csv",
# </snippet>
# <snippet name="configured spark single batch group_names">
"group_names": ["month"],
# </snippet>
},
# </snippet>
},
"batch_spec_passthrough": {
"reader_method": "csv",
"reader_options": {
"header": True,
"inferSchema": True,
},
},
}
# </snippet>
},
}
# </snippet>
is_subset(
datasource_config, get_full_config_spark_configured_datasource_single_batch()
)
def section_9_configure_your_data_connectors_data_assets__configured__multi_batch():
datasource_config: dict = {
"data_connectors": {
"name_of_my_configured_data_connector": {
"assets": {
# <snippet name="empty asset for configured spark multi batch datasource">
"yellow_tripdata_2020": {}
# </snippet>
}
}
}
}
is_subset(
datasource_config, get_full_config_spark_configured_datasource_multi_batch()
)
# <snippet name="full datasource_config for configured spark multi batch datasource">
datasource_config: dict = {
"name": "my_datasource_name", # Preferably name it something relevant
"class_name": "Datasource",
"module_name": "great_expectations.datasource",
"execution_engine": {
"class_name": "SparkDFExecutionEngine",
"module_name": "great_expectations.execution_engine",
},
"data_connectors": {
# <snippet name="configured spark multi batch data connector config">
"name_of_my_configured_data_connector": {
"class_name": "ConfiguredAssetFilesystemDataConnector",
"base_directory": "../data",
"assets": {
# <snippet name="configured spark multi batch asset">
"yellow_tripdata_2020": {
# <snippet name="configured spark multi batch pattern">
"pattern": "yellow_tripdata_sample_2020-(.*)\\.csv",
# </snippet>
# <snippet name="configured spark multi batch group_names">
"group_names": ["month"],
# </snippet>
},
# </snippet>
},
"batch_spec_passthrough": {
"reader_method": "csv",
"reader_options": {
"header": True,
"inferSchema": True,
},
},
}
# </snippet>
},
}
# </snippet>
is_subset(
datasource_config, get_full_config_spark_configured_datasource_multi_batch()
)
def section_9_configure_your_data_connectors_data_assets__runtime():
# <snippet name="full datasource_config for runtime spark datasource">
datasource_config: dict = {
"name": "my_datasource_name", # Preferably name it something relevant
"class_name": "Datasource",
"module_name": "great_expectations.datasource",
"execution_engine": {
"class_name": "SparkDFExecutionEngine",
"module_name": "great_expectations.execution_engine",
},
"data_connectors": {
"name_of_my_runtime_data_connector": {
"class_name": "RuntimeDataConnector",
"batch_spec_passthrough": {
"reader_method": "csv",
"reader_options": {
"header": True,
"inferSchema": True,
},
},
# <snippet name="runtime spark batch_identifiers">
"batch_identifiers": ["batch_timestamp"],
# </snippet>
}
},
}
# </snippet>
is_subset(datasource_config, get_full_config_spark_runtime_datasource())
def section_10_test_your_configuration_with_test_yaml_config():
for datasource_config, connector_name, asset_count in (
(
get_full_config_spark_runtime_datasource(),
"name_of_my_runtime_data_connector",
0,
),
(
get_full_config_spark_inferred_datasource_single_batch(),
"name_of_my_inferred_data_connector",
12,
),
(
get_full_config_spark_inferred_datasource_multi_batch(),
"name_of_my_inferred_data_connector",
1,
),
(
get_full_config_spark_configured_datasource_single_batch(),
"name_of_my_configured_data_connector",
1,
),
(
get_full_config_spark_configured_datasource_multi_batch(),
"name_of_my_configured_data_connector",
1,
),
):
test_result = data_context.test_yaml_config(yaml.dump(datasource_config))
datasource_check = test_result.self_check(max_examples=12)
# NOTE: The following code is only for testing and can be ignored by users.
# Assert that there are no data sets -- those get defined in a Batch Request.
assert (
datasource_check["data_connectors"][connector_name]["data_asset_count"]
== asset_count
), f"{connector_name} {asset_count} != {datasource_check['data_connectors'][connector_name]['data_asset_count']}"
def section_12_add_your_new_datasource_to_your_datacontext():
for datasource_config, datasource_name in (
(
get_full_config_spark_runtime_datasource(),
"name_of_my_runtime_data_connector",
),
(
get_full_config_spark_inferred_datasource_single_batch(),
"name_of_my_inferred_data_connector",
),
(
get_full_config_spark_inferred_datasource_multi_batch(),
"name_of_my_inferred_data_connector",
),
(
get_full_config_spark_configured_datasource_single_batch(),
"name_of_my_configured_data_connector",
),
(
get_full_config_spark_configured_datasource_multi_batch(),
"name_of_my_configured_data_connector",
),
):
# <snippet name="test your spark datasource config with test_yaml_config">
data_context.test_yaml_config(yaml.dump(datasource_config))
# </snippet>
# <snippet name="add your spark datasource to your data_context">
data_context.add_datasource(**datasource_config)
# </snippet>
# <snippet name="add your spark datasource to your data_context only if it does not already exit">
# add_datasource only if it doesn't already exist in your Data Context
try:
data_context.get_datasource(datasource_config["name"])
except ValueError:
data_context.add_datasource(**datasource_config)
else:
print(
f"The datasource {datasource_config['name']} already exists in your Data Context!"
)
# </snippet>
assert (
datasource_name
in data_context.list_datasources()[0]["data_connectors"].keys()
), f"{datasource_name} not in {data_context.list_datasources()}"
data_context.delete_datasource(name="my_datasource_name")
validate_universal_config_elements()
section_5_add_the_spark_execution_engine_to_your_datasource_configuration()
section_6_add_a_dictionary_as_the_value_of_the_data_connectors_key()
section_7_configure_your_individual_data_connectors__inferred()
section_7_configure_your_individual_data_connectors__configured()
section_7_configure_your_individual_data_connectors__runtime()
section_8_configure_the_values_for_batch_spec_passthrough__universal()
section_8_configure_the_values_for_batch_spec_passthrough__inferred()
section_8_configure_the_values_for_batch_spec_passthrough__configured()
section_8_configure_the_values_for_batch_spec_passthrough__runtime()
section_9_configure_your_data_connectors_data_assets__inferred__single_batch()
section_9_configure_your_data_connectors_data_assets__inferred__multi_batch()
section_9_configure_your_data_connectors_data_assets__configured__single_batch()
section_9_configure_your_data_connectors_data_assets__configured__multi_batch()
section_9_configure_your_data_connectors_data_assets__runtime()
section_10_test_your_configuration_with_test_yaml_config()
section_12_add_your_new_datasource_to_your_datacontext()
| {
"content_hash": "c0cd560f8333697209fe6fb32b988ef3",
"timestamp": "",
"source": "github",
"line_count": 897,
"max_line_length": 137,
"avg_line_length": 38.827201783723524,
"alnum_prop": 0.5862237280349144,
"repo_name": "great-expectations/great_expectations",
"id": "6861548bb21c1ab42347ad59081d0e6f8eedae09",
"size": "34828",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "tests/integration/docusaurus/connecting_to_your_data/datasource_configuration/how_to_configure_a_spark_datasource.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "23771"
},
{
"name": "Dockerfile",
"bytes": "2388"
},
{
"name": "HTML",
"bytes": "27311"
},
{
"name": "JavaScript",
"bytes": "45960"
},
{
"name": "Jinja",
"bytes": "66650"
},
{
"name": "Jupyter Notebook",
"bytes": "816323"
},
{
"name": "Lua",
"bytes": "3489"
},
{
"name": "Makefile",
"bytes": "657"
},
{
"name": "Python",
"bytes": "15728777"
},
{
"name": "Shell",
"bytes": "2930"
}
],
"symlink_target": ""
} |
<p align="center">
<img src="https://pigjian.com/images/v-distpicker.png" alt="Powered By Jiajian Chan" width="160">
</p>
<p align="center">A flexible, highly available district selector for picking provinces, cities and districts of China. </p>
# V - Distpicker
  
[Documents and Demo ](https://jcc.github.io/v-distpicker/)
[English] | [简体中文](./README.zh_CN.md)
[CHANGELOG](./CHANGELOG.zh-CN.md)
## Installation
Vue 2
```shell
npm install v-distpicker@^1.3.3 --save
```
Vue 3
```shell
npm install v-distpicker@^2.1.0 --save
```
CDN
```html
<script src="https://cdn.jsdelivr.net/npm/v-distpicker@version/dist/v-distpicker.js"></script>
<!-- or -->
<script src="https://unpkg.com/v-distpicker@version/dist/v-distpicker.js"></script>
```
## Usage
**Register component**
Registe global component:
```javascript
import VDistpicker from 'v-distpicker'
const app = createApp(App)
app.component('v-distpicker', VDistpicker)
```
Use setup-api:
```javascript
<script setup>import VDistpicker from 'v-distpicker'</script>
```
Registe component:
```javascript
import { defineComponent } from 'vue'
import VDistpicker from 'v-distpicker'
export default defineComponent({
components: { VDistpicker },
})
```
**How to use**
Basic:
```javascript
<v-distpicker></v-distpicker>
```
Default Value:
```javascript
<v-distpicker province="广东省" city="广州市" area="海珠区"></v-distpicker>
```
Mobile:
```javascript
<v-distpicker type="mobile"></v-distpicker>
```
Demo:
```vue
<template>
<v-distpicker
:province="select.province"
:city="select.city"
:area="select.area"
@selected="onSelect"
@change="onChange"
@province="selectProvince"
@city="selectCity"
@area="selectArea"
></v-distpicker>
</template>
<script setup>
import VDistpicker from 'v-distpicker'
let select = reactive({ province: '', city: '', area: '' })
function onSelect(data) {
console.log(data)
}
function onChange(data) {
console.log(data)
}
function selectProvince({ code, value }) {
select.province = value
console.log({ code, value })
}
function selectCity({ code, value }) {
select.city = value
console.log({ code, value })
}
function selectArea({ code, value }) {
select.area = value
console.log({ code, value })
}
</script>
```
## Props
| Name | Type | Description | Default | Sample |
| ----------------- | ------------- | ------------------------- | ---------------------------- | ----------------------------------- |
| province | String/Number | 省级编码或名称 | | '广东省'/440000/'440000' |
| city | String/Number | 市级编码或名称 | | '广州市'/440100/'440100' |
| area | String/Number | 区级编码或名称 | | '海珠区'/440105/'440105' |
| placeholder | Object | 默认显示的值 | | {province:'省',city:'市',area:'区'} |
| type | String | 区分 pc 和 mobile,默认 pc | | |
| only-province | Boolean | 只显示省级选择器 | false | |
| hide-area | Boolean | 隐藏区级 | false | |
| disabled | Boolean | 禁用 | false | |
| province-disabled | Boolean | 禁用省 | false | |
| city-disabled | Boolean | 禁用市 | false | |
| area-disabled | Boolean | 禁用区 | false | |
| province-source | Object | 省数据源 | | examples/components/data |
| city-source | Object | 市级数据源 | | |
| address-source | Object | 区级数据源 | | |
| wrapper | String | className | 'distpicker-address-wrapper' | |
| address-header | String | className(mobile) | 'address-header' | |
| address-container | String | className(mobile) | 'address-container' | |
## Event
| Name | Type | Description | Return |
| --------------- | -------- | ------------------ | ------------------------------------------------------------ |
| province | Function | 选择省时触发 | {code,value} |
| city | Function | 选择市时触发 | {code,value} |
| area | Function | 选择区时触发 | {code,value} |
| selected | Function | 选择最后一项时触发 | {province:{code,value},city:{code,value},area:{code,value} } |
| change-province | Function | 省级改变时触发 | {code,value} |
| change-city | Function | 市级改变时触发 | {code,value} |
| change-area | Function | 区级改变时触发 | {code,value} |
| change | Function | 省市区改变时触发 | {province:{code,value},city:{code,value},area:{code,value} } |
## Contributors
<a href="https://github.com/jcc/v-distpicker/graphs/contributors">
<img src="https://contrib.rocks/image?repo=jcc/v-distpicker" />
</a>
## Thanks
- [Distpicker](https://github.com/fengyuanchen/distpicker)
## License
The plugin is open-sourced software licensed under the [MIT license](http://opensource.org/licenses/MIT).
| {
"content_hash": "2071a74955e04bc5456d021135df1612",
"timestamp": "",
"source": "github",
"line_count": 175,
"max_line_length": 237,
"avg_line_length": 36.8,
"alnum_prop": 0.45729813664596275,
"repo_name": "jcc/v-distpicker",
"id": "55efa76398395b9a28e4977a77aa66f9c4c80519",
"size": "6740",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "316"
},
{
"name": "JavaScript",
"bytes": "127723"
},
{
"name": "Vue",
"bytes": "11236"
}
],
"symlink_target": ""
} |
"""Widget for induction of regression trees"""
from Orange.modelling.tree import TreeLearner
from Orange.widgets.model.owtree import OWTreeLearner
from Orange.widgets.utils.owlearnerwidget import OWBaseLearner
class OWTreeLearner(OWTreeLearner):
name = "Regression Tree"
description = "A regression tree algorithm with forward pruning."
icon = "icons/RegressionTree.svg"
priority = 30
LEARNER = TreeLearner
# Disable the special classification layout to be used when widgets are
# fully merged
add_classification_layout = OWBaseLearner.add_classification_layout
def _test():
import sys
from AnyQt.QtWidgets import QApplication
from Orange.data import Table
a = QApplication(sys.argv)
ow = OWRegressionTree()
d = Table('housing')
ow.set_data(d)
ow.show()
a.exec_()
ow.saveSettings()
if __name__ == "__main__":
_test()
| {
"content_hash": "b6fe50bc697139fb021e694872e5cab6",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 75,
"avg_line_length": 25.771428571428572,
"alnum_prop": 0.7095343680709535,
"repo_name": "cheral/orange3",
"id": "deb309c105435a747b6c860e4bf53c10bccfe87c",
"size": "902",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Orange/widgets/regression/owregressiontree.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C",
"bytes": "20412"
},
{
"name": "C++",
"bytes": "1992"
},
{
"name": "GLSL",
"bytes": "75"
},
{
"name": "HTML",
"bytes": "3503"
},
{
"name": "JavaScript",
"bytes": "12023"
},
{
"name": "Jupyter Notebook",
"bytes": "6662"
},
{
"name": "NSIS",
"bytes": "20217"
},
{
"name": "Python",
"bytes": "4139574"
},
{
"name": "Shell",
"bytes": "47441"
}
],
"symlink_target": ""
} |
<HTML><HEAD>
<TITLE>Review for Bone Collector, The (1999)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1 ALIGN="CENTER" CLASS="title"><A HREF="/Title?0145681">Bone Collector, The (1999)</A></H1><H3 ALIGN=CENTER>reviewed by<BR><A HREF="/ReviewsBy?Ross+Anthony">Ross Anthony</A></H3><HR WIDTH="40%" SIZE="4">
<PRE>More than a few Bones to Pick
The Bone Collector</PRE>
<PRE>By Ross Anthony</PRE>
<P>Yes, it's thrilling, suspenseful and at times even bone-chilling. One
woman's scream becomes a crying siren of emergency vehicles rushing to save
her from being boiled alive. That's an effective scene change. In fact, "The
Bone Collector" is a pretty good movie right up to the end where it makes a
clean break into not being a very good movie -- fractured, as it were, in
several places.</P>
<P>The on and off Denzel, is more on in this movie than off while Jolie is
simply radiant. Denzel plays a paralyzed homicide investigator for whom the
rookie cop Jolie becomes the eyes, ears and body. There's a killer loose,
he's leaving all kinds of TV movie clues for Denzel to decode. The
production, direction and acting work as a team to keep this film alive and
kicking; unfortunately the poorly scripted climax overwhelms them all with
stale anti-drama and ultimately leaves the picture itself somewhat hog-tied
and whimpering.</P>
<P>The Bone Collector. Copyright © 1999. Rated R.
Starring Denzel Washington and Angelina Jolie, Queen Latifah.
Directed by Phillip Noyce.
Screenplay by Jeremy Iacone.
Produced by Martin Bregman, Louis A. Stroller, Michael Bregman at
Universal/Columbia</P>
<P>Grade..........................B
--
Copyright © 1999 Ross Anthony, currently based in Los Angeles, has scripted
and shot documentaries, music videos, and shorts in 35 countries across
North America, Europe, Africa and Asia. For more reviews visit:
<A HREF="http://RossAnthony.com">http://RossAnthony.com</A></P>
<HR><P CLASS=flush><SMALL>The review above was posted to the
<A HREF="news:rec.arts.movies.reviews">rec.arts.movies.reviews</A> newsgroup (<A HREF="news:de.rec.film.kritiken">de.rec.film.kritiken</A> for German reviews).<BR>
The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.<BR>
Please direct comments/criticisms of the review to relevant newsgroups.<BR>
Broken URLs inthe reviews are the responsibility of the author.<BR>
The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.
</SMALL></P>
<P ALIGN=CENTER>Related links: <A HREF="/Reviews/">index of all rec.arts.movies.reviews reviews</A></P>
</P></BODY></HTML>
| {
"content_hash": "713297ae91c3f39545116cf8750fcc1f",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 205,
"avg_line_length": 56.2,
"alnum_prop": 0.7437722419928826,
"repo_name": "xianjunzhengbackup/code",
"id": "6ca3ead1764f1d8518fd0d2b7d36f8b7d043f18c",
"size": "2810",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "data science/machine_learning_for_the_web/chapter_4/movie/21622.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "BitBake",
"bytes": "113"
},
{
"name": "BlitzBasic",
"bytes": "256"
},
{
"name": "CSS",
"bytes": "49827"
},
{
"name": "HTML",
"bytes": "157006325"
},
{
"name": "JavaScript",
"bytes": "14029"
},
{
"name": "Jupyter Notebook",
"bytes": "4875399"
},
{
"name": "Mako",
"bytes": "2060"
},
{
"name": "Perl",
"bytes": "716"
},
{
"name": "Python",
"bytes": "874414"
},
{
"name": "R",
"bytes": "454"
},
{
"name": "Shell",
"bytes": "3984"
}
],
"symlink_target": ""
} |
using System.Collections.Generic;
using CollectionsOnline.Core.Models;
using CollectionsOnline.WebSite.Models;
namespace CollectionsOnline.WebSite.Transformers
{
public class SpecimenViewTransformerResult
{
public Specimen Specimen { get; set; }
public IList<EmuAggregateRootViewModel> RelatedItems { get; set; }
public IList<EmuAggregateRootViewModel> RelatedSpecimens { get; set; }
public IList<EmuAggregateRootViewModel> RelatedSpecies { get; set; }
public IList<EmuAggregateRootViewModel> RelatedArticles { get; set; }
public int RelatedSpeciesSpecimenItemCount { get; set; }
public IList<KeyValuePair<string, string>> GeoSpatial { get; set; }
public SpecimenViewTransformerResult()
{
RelatedItems = new List<EmuAggregateRootViewModel>();
RelatedSpecimens = new List<EmuAggregateRootViewModel>();
RelatedSpecies = new List<EmuAggregateRootViewModel>();
RelatedArticles = new List<EmuAggregateRootViewModel>();
GeoSpatial = new List<KeyValuePair<string, string>>();
}
}
} | {
"content_hash": "b86ed19650ec702cfd055e7aeddddb93",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 78,
"avg_line_length": 35.46875,
"alnum_prop": 0.6977973568281939,
"repo_name": "museumsvictoria/collections-online",
"id": "b098e262e6f90fd0d45070c794bdbf4618ec0b38",
"size": "1137",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/CollectionsOnline.WebSite/Transformers/SpecimenViewTransformerResult.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP.NET",
"bytes": "108"
},
{
"name": "C#",
"bytes": "749523"
},
{
"name": "HTML",
"bytes": "270378"
},
{
"name": "JavaScript",
"bytes": "41996"
},
{
"name": "SCSS",
"bytes": "204679"
}
],
"symlink_target": ""
} |
import { expect } from "chai";
import { Formatter } from "@export/formatter";
import { MathRun } from "../math-run";
import { MathDegree } from "./math-degree";
describe("MathDegree", () => {
describe("#constructor()", () => {
it("should create a MathDegree with correct root key", () => {
const mathDegree = new MathDegree();
const tree = new Formatter().format(mathDegree);
expect(tree).to.deep.equal({
"m:deg": {},
});
});
it("should create a MathDegree with correct root key with child", () => {
const mathDegree = new MathDegree([new MathRun("2")]);
const tree = new Formatter().format(mathDegree);
expect(tree).to.deep.equal({
"m:deg": [
{
"m:r": [
{
"m:t": ["2"],
},
],
},
],
});
});
});
});
| {
"content_hash": "ebf867224420b6bd13901befca69758a",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 81,
"avg_line_length": 29.583333333333332,
"alnum_prop": 0.40938967136150234,
"repo_name": "dolanmiu/docx",
"id": "656d8d8ac9eb837a11788641cb4efc032bcaf7ca",
"size": "1065",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/file/paragraph/math/radical/math-degree.spec.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "9707"
},
{
"name": "Shell",
"bytes": "50"
},
{
"name": "TypeScript",
"bytes": "1210572"
}
],
"symlink_target": ""
} |
Subsets and Splits