text
stringlengths 2
1.04M
| meta
dict |
---|---|
exports.config = {
framework:'jasmine',
jasmineNodeOpts: {
defaultTimeoutInterval: 30000
},
seleniumAddress: 'http://localhost:4444/wd/hub',
// seleniumServerJar: './node_modules/protractor/selenium/selenium-server-standalone-2.51.0.jar',
specs: ['test/protractor/**/*Spec.js'],
capabilities: {
browserName: 'chrome'
}
};
| {
"content_hash": "47ff9ae70d63ba62b1dcb531c42d43e3",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 101,
"avg_line_length": 28.53846153846154,
"alnum_prop": 0.6442048517520216,
"repo_name": "mweltin/d3demo",
"id": "2f2de2db72b1cacb0dfadc87ba0479ee2cddc32d",
"size": "371",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "protractor.conf.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "34"
},
{
"name": "HTML",
"bytes": "1095"
},
{
"name": "JavaScript",
"bytes": "12552"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.coolweather.android">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name="org.litepal.LitePalApplication"
android:allowBackup="true"
android:icon="@mipmap/logo"
android:label="@string/app_name"
android:roundIcon="@mipmap/logo"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".WeatherActivity" />
<service
android:name=".service.AutoUpdateService"
android:enabled="true"
android:exported="true" />
</application>
</manifest> | {
"content_hash": "498af00e3155d91d8ac03431df737275",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 76,
"avg_line_length": 33.93333333333333,
"alnum_prop": 0.618860510805501,
"repo_name": "YouLe2016/coolweather",
"id": "3738ab354fcf9448b4c8e2d15a6ed13ec473bef9",
"size": "1018",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/AndroidManifest.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "36122"
}
],
"symlink_target": ""
} |
package de.undercouch.citeproc;
import de.undercouch.citeproc.csl.CSLCitation;
import de.undercouch.citeproc.csl.CSLCitationItem;
import de.undercouch.citeproc.csl.CSLCitationItemBuilder;
import de.undercouch.citeproc.csl.CSLItemData;
import de.undercouch.citeproc.csl.CSLItemDataBuilder;
import de.undercouch.citeproc.csl.internal.GeneratedCitation;
import de.undercouch.citeproc.csl.internal.RenderContext;
import de.undercouch.citeproc.csl.internal.SSort;
import de.undercouch.citeproc.csl.internal.SStyle;
import de.undercouch.citeproc.csl.internal.format.AsciiDocFormat;
import de.undercouch.citeproc.csl.internal.format.FoFormat;
import de.undercouch.citeproc.csl.internal.format.Format;
import de.undercouch.citeproc.csl.internal.format.HtmlFormat;
import de.undercouch.citeproc.csl.internal.format.TextFormat;
import de.undercouch.citeproc.csl.internal.locale.LLocale;
import de.undercouch.citeproc.helper.CSLUtils;
import de.undercouch.citeproc.output.Bibliography;
import de.undercouch.citeproc.output.Citation;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.IntStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* <p>The citation processor.</p>
*
* <p>In order to use the processor in your application you first have to
* create an {@link ItemDataProvider} that provides citation item data. For
* example, the following dummy provider returns always the same data:</p>
*
* <blockquote><pre>
* public class MyItemProvider implements ItemDataProvider {
* @Override
* public CSLItemData retrieveItem(String id) {
* return new CSLItemDataBuilder()
* .id(id)
* .type(CSLType.ARTICLE_JOURNAL)
* .title("A dummy journal article")
* .author("John", "Smith")
* .issued(2013, 9, 6)
* .containerTitle("Dummy journal")
* .build();
* }
*
* @Override
* public String[] getIds() {
* String ids[] = {"ID-0", "ID-1", "ID-2"};
* return ids;
* }
* }</pre></blockquote>
*
* Now you can instantiate the CSL processor.
*
* <blockquote><pre>
* CSL citeproc = new CSL(new MyItemProvider(), "ieee");
* citeproc.setOutputFormat("html");</pre></blockquote>
*
* <h3>Ad-hoc usage</h3>
*
* <p>You may also use {@link #makeAdhocBibliography(String, CSLItemData...)} or
* {@link #makeAdhocBibliography(String, String, CSLItemData...)} to create
* ad-hoc bibliographies from CSL items.</p>
*
* <blockquote><pre>
* CSLItemData item = new CSLItemDataBuilder()
* .type(CSLType.WEBPAGE)
* .title("citeproc-java: A Citation Style Language (CSL) processor for Java")
* .author("Michel", "Kraemer")
* .issued(2014, 7, 13)
* .URL("http://michel-kraemer.github.io/citeproc-java/")
* .accessed(2014, 7, 13)
* .build();
*
* String bibl = CSL.makeAdhocBibliography("ieee", item).makeString();</pre></blockquote>
*
* @author Michel Kraemer
*/
public class CSL {
/**
* The output format
*/
private Format outputFormat = new HtmlFormat();
/**
* {@code true} if the processor should convert URLs and DOIs in the output
* to links.
* @see #setConvertLinks(boolean)
*/
private boolean convertLinks = false;
/**
* The CSL style used to render citations and bibliographies
*/
private final SStyle style;
/**
* The localization data used to render citations and bibliographies
*/
private final LLocale locale;
/**
* An object that provides citation item data
*/
private final ItemDataProvider itemDataProvider;
/**
* An object that provides abbreviations (may be {@code null})
*/
private final AbbreviationProvider abbreviationProvider;
/**
* Citation items registered through {@link #registerCitationItems(String...)}
*/
private final Map<String, CSLItemData> registeredItems = new LinkedHashMap<>();
/**
* Contains the same items as {@link #registeredItems} but sorted
*/
private final List<CSLItemData> sortedItems = new ArrayList<>();
/**
* A list of generated citations sorted by their index
*/
private List<GeneratedCitation> generatedCitations = new ArrayList<>();
/**
* Constructs a new citation processor
* @param itemDataProvider an object that provides citation item data
* @param style the citation style to use. May either be a serialized
* XML representation of the style or a style's name such as <code>ieee</code>.
* In the latter case, the processor loads the style from the classpath (e.g.
* <code>/ieee.csl</code>)
* @throws IOException if the CSL style could not be loaded
*/
public CSL(ItemDataProvider itemDataProvider, String style) throws IOException {
this(itemDataProvider, new DefaultLocaleProvider(), null, style, null);
}
/**
* Constructs a new citation processor
* @param itemDataProvider an object that provides citation item data
* @param style the citation style to use. May either be a serialized
* XML representation of the style or a style's name such as <code>ieee</code>.
* In the latter case, the processor loads the style from the classpath (e.g.
* <code>/ieee.csl</code>)
* @param lang an RFC 4646 identifier for the citation locale (e.g. <code>en-US</code>)
* @throws IOException if the CSL style could not be loaded
*/
public CSL(ItemDataProvider itemDataProvider, String style, String lang) throws IOException {
this(itemDataProvider, new DefaultLocaleProvider(), null, style, lang);
}
/**
* Constructs a new citation processor
* @param itemDataProvider an object that provides citation item data
* @param localeProvider an object that provides CSL locales
* @param abbreviationProvider an object that provides abbreviations
* (may be {@code null})
* @param style the citation style to use. May either be a serialized
* XML representation of the style or a style name such as <code>ieee</code>.
* In the latter case, the processor loads the style from the classpath (e.g.
* <code>/ieee.csl</code>)
* @param lang an RFC 4646 identifier for the citation locale (e.g.
* {@code en-US}). If this argument is {@code null}, the default locale of
* the citation style will be used. If the citation style does not define
* a default locale, the method falls back to {@code en-US}.
* @throws IOException if the CSL style could not be loaded
*/
public CSL(ItemDataProvider itemDataProvider, LocaleProvider localeProvider,
AbbreviationProvider abbreviationProvider, String style,
String lang) throws IOException {
// load style if needed
if (!isStyle(style)) {
style = retrieveStyle(style);
}
this.itemDataProvider = itemDataProvider;
this.abbreviationProvider = abbreviationProvider;
// TODO parse style and locale directly from URL if possible
// TODO instead of loading them into strings first
this.style = loadStyle(style);
if (lang == null) {
lang = this.style.getDefaultLocale();
if (lang == null) {
lang = "en-US";
}
}
// load locale
String strLocale = localeProvider.retrieveLocale(lang);
LLocale locale = loadLocale(strLocale);
for (LLocale l : this.style.getLocales()) {
if (l.getLang() == null ||
(l.getLang().getLanguage().equals(locale.getLang().getLanguage()) &&
(l.getLang().getCountry().isEmpty() ||
l.getLang().getCountry().equals(locale.getLang().getCountry())))) {
// additional localization data in the style file overrides or
// augments the data from the locale file
locale = locale.merge(l);
}
}
this.locale = locale;
}
/**
* Get a list of supported output formats
* @return the formats
*/
public static List<String> getSupportedOutputFormats() {
return Arrays.asList("asciidoc", "fo", "html", "text");
}
private static Set<String> getAvailableFiles(String prefix,
String knownName, String extension) throws IOException {
Set<String> result = new LinkedHashSet<>();
// first load a file that is known to exist
String name = prefix + knownName + "." + extension;
URL knownUrl = CSL.class.getResource("/" + name);
if (knownUrl != null) {
String path = knownUrl.getPath();
// get the jar file containing the file
if (path.endsWith(".jar!/" + name)) {
String jarPath = path.substring(0, path.length() - name.length() - 2);
URI jarUri;
try {
jarUri = new URI(jarPath);
} catch (URISyntaxException e) {
// ignore
return result;
}
try (ZipFile zip = new ZipFile(new File(jarUri))) {
Enumeration<? extends ZipEntry> entries = zip.entries();
while (entries.hasMoreElements()) {
ZipEntry e = entries.nextElement();
if (e.getName().endsWith("." + extension) &&
(prefix.isEmpty() || e.getName().startsWith(prefix))) {
result.add(e.getName().substring(
prefix.length(), e.getName().length() - 4));
}
}
}
}
}
return result;
}
/**
* Calculates a list of available citation styles
* @return the list
* @throws IOException if the citation styles could not be loaded
*/
public static Set<String> getSupportedStyles() throws IOException {
return getAvailableFiles("", "ieee", "csl");
}
/**
* Checks if a given citation style is supported
* @param style the citation style's name
* @return true if the style is supported, false otherwise
*/
public static boolean supportsStyle(String style) {
String styleFileName = style;
if (!styleFileName.endsWith(".csl")) {
styleFileName = styleFileName + ".csl";
}
if (!styleFileName.startsWith("/")) {
styleFileName = "/" + styleFileName;
}
URL url = CSL.class.getResource(styleFileName);
return (url != null);
}
/**
* Calculates a list of available citation locales
* @return the list
* @throws IOException if the citation locales could not be loaded
*/
public static Set<String> getSupportedLocales() throws IOException {
return getAvailableFiles("locales-", "en-US", "xml");
}
/**
* Checks if the given String contains the serialized XML representation
* of a style
* @param style the string to examine
* @return true if the String is XML, false otherwise
*/
private static boolean isStyle(String style) {
for (int i = 0; i < style.length(); ++i) {
char c = style.charAt(i);
if (!Character.isWhitespace(c)) {
return (c == '<');
}
}
return false;
}
/**
* Determines whether the given citation style contains instructions to
* format bibliographies.
* @param style the style
* @return {@code true} if the style can be used to format bibliographies
*/
private static boolean canFormatBibliographies(SStyle style) {
return style.getBibliography() != null;
}
/**
* Determines whether the given citation style contains instructions to
* format bibliographies
* @param style the citation style. May either be a serialized XML
* representation of the style or a style name such as <code>ieee</code>.
* In the latter case, the style is loaded from the classpath (e.g.
* <code>/ieee.csl</code>)
* @return {@code true} if the style can be used to format bibliographies
* @throws IOException if the style could not be loaded or parsed
*/
public static boolean canFormatBibliographies(String style) throws IOException {
if (!isStyle(style)) {
style = retrieveStyle(style);
}
SStyle ss = loadStyle(style);
return canFormatBibliographies(ss);
}
private static SStyle loadStyle(String style) throws IOException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
throw new IOException("Could not create document builder", e);
}
// load style
Document styleDocument;
try {
styleDocument = builder.parse(new InputSource(
new StringReader(style)));
} catch (SAXException e) {
throw new IOException("Could not parse style", e);
}
return new SStyle(styleDocument);
}
/**
* Retrieves a CSL style from the classpath. For example, if the given name
* is <code>ieee</code> this method will load the file <code>/ieee.csl</code>
* @param styleName the style's name
* @return the serialized XML representation of the style
* @throws IOException if the style could not be loaded
*/
private static String retrieveStyle(String styleName) throws IOException {
URL url;
if (styleName.startsWith("http://") || styleName.startsWith("https://")) {
try {
// try to load matching style from classpath
return retrieveStyle(styleName.substring(styleName.lastIndexOf('/') + 1));
} catch (FileNotFoundException e) {
// there is no matching style in classpath
url = new URL(styleName);
}
} else {
// normalize file name
if (!styleName.endsWith(".csl")) {
styleName = styleName + ".csl";
}
if (!styleName.startsWith("/")) {
styleName = "/" + styleName;
}
// try to find style in classpath
url = CSL.class.getResource(styleName);
if (url == null) {
throw new FileNotFoundException("Could not find style in "
+ "classpath: " + styleName);
}
}
// load style
String result = CSLUtils.readURLToString(url, "UTF-8");
// handle dependent styles
if (isDependent(result)) {
String independentParentLink;
try {
independentParentLink = getIndependentParentLink(result);
} catch (ParserConfigurationException | IOException | SAXException e) {
throw new IOException("Could not load independent parent style", e);
}
if (independentParentLink == null) {
throw new IOException("Dependent style does not have an "
+ "independent parent");
}
return retrieveStyle(independentParentLink);
}
return result;
}
/**
* Test if the given string represents a dependent style
* @param style the style
* @return true if the string is a dependent style, false otherwise
*/
private static boolean isDependent(String style) {
if (!style.trim().startsWith("<")) {
return false;
}
Pattern p = Pattern.compile("rel\\s*=\\s*\"\\s*independent-parent\\s*\"");
Matcher m = p.matcher(style);
return m.find();
}
/**
* Parse a string representing a dependent parent style and
* get link to its independent parent style
* @param style the dependent style
* @return the link to the parent style or <code>null</code> if the link
* could not be found
* @throws ParserConfigurationException if the XML parser could not be created
* @throws IOException if the string could not be read
* @throws SAXException if the string could not be parsed
*/
public static String getIndependentParentLink(String style)
throws ParserConfigurationException, IOException, SAXException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource src = new InputSource(new StringReader(style));
Document doc = builder.parse(src);
NodeList links = doc.getElementsByTagName("link");
for (int i = 0; i < links.getLength(); ++i) {
Node n = links.item(i);
Node relAttr = n.getAttributes().getNamedItem("rel");
if (relAttr != null) {
if ("independent-parent".equals(relAttr.getTextContent())) {
Node hrefAttr = n.getAttributes().getNamedItem("href");
if (hrefAttr != null) {
return hrefAttr.getTextContent();
}
}
}
}
return null;
}
private static LLocale loadLocale(String strLocale) throws IOException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
throw new IOException("Could not create document builder", e);
}
Document localeDocument;
try {
localeDocument = builder.parse(new InputSource(
new StringReader(strLocale)));
} catch (SAXException e) {
throw new IOException("Could not parse locale", e);
}
return new LLocale(localeDocument);
}
/**
* Sets the processor's output format
* @param format the format (one of {@code "asciidoc"}, {@code "fo"},
* {@code "html"}, and {@code "text"}.
*/
public void setOutputFormat(String format) {
if ("asciidoc".equals(format)) {
setOutputFormat(new AsciiDocFormat());
} else if ("fo".equals(format)) {
setOutputFormat(new FoFormat());
} else if ("html".equals(format)) {
setOutputFormat(new HtmlFormat());
} else if ("text".equals(format)) {
setOutputFormat(new TextFormat());
} else {
throw new IllegalArgumentException("Unknown output format: `" +
format + "'. Supported formats: `asciidoc', `fo', `html', `text'.");
}
}
/**
* Sets the processor's output format
* @param outputFormat the format
*/
public void setOutputFormat(Format outputFormat) {
this.outputFormat = outputFormat;
outputFormat.setConvertLinks(convertLinks);
}
/**
* Specifies if the processor should convert URLs and DOIs in the output
* to links. How links are created depends on the output format that has
* been set with {@link #setOutputFormat(String)}
* @param convert true if URLs and DOIs should be converted to links
*/
public void setConvertLinks(boolean convert) {
convertLinks = convert;
outputFormat.setConvertLinks(convert);
}
/**
* Fetches the item data for the given citation items and adds it to
* {@link #registeredItems}. Also, sorts the items according to the sorting
* specified in the style's bibliography element and stores the result in
* {@link #sortedItems}. If the style does not have a bibliography element
* or no sorting is specified, the items will just be appended to
* {@link #sortedItems}. In addition, the method updates any items already
* stored in {@link #sortedItems} and coming after the generated ones.
* Updated items will be returned in the given {@code updatedItems} set
* (unless it is {@code null}).
* @param ids the IDs of the citation items to register
* @param updatedItems an empty set that will be filled with the citation
* items the method had to update (may be {@code null})
* @param unsorted {@code true} if any sorting specified in the style
* should be ignored
* @return a list of registered citation item data
*/
private List<CSLItemData> registerItems(Collection<String> ids,
Set<CSLItemData> updatedItems, boolean unsorted) {
List<CSLItemData> result = new ArrayList<>();
SSort.SortComparator comparator = null;
for (String id : ids) {
// check if item has already been registered
CSLItemData itemData = registeredItems.get(id);
if (itemData != null) {
result.add(itemData);
continue;
}
// fetch item data
itemData = itemDataProvider.retrieveItem(id);
if (itemData == null) {
throw new IllegalArgumentException("Missing citation " +
"item with ID: " + id);
}
// register item
if (unsorted || style.getBibliography() == null ||
style.getBibliography().getSort() == null) {
// We don't have to sort. Add item to the end of the list.
itemData = new CSLItemDataBuilder(itemData)
.citationNumber(String.valueOf(registeredItems.size() + 1))
.build();
sortedItems.add(itemData);
} else {
// We have to sort. Find insert point.
if (comparator == null) {
comparator = style.getBibliography().getSort()
.comparator(style, locale, abbreviationProvider);
}
int i = Collections.binarySearch(sortedItems, itemData, comparator);
if (i < 0) {
i = -(i + 1);
} else {
// binarySearch thinks we found the item in the list but
// this is impossible. It's more likely that the comparator
// returned 0 because no key was given or it did not yield
// sensible results. Just append the item to the list.
i = sortedItems.size();
}
// determine citation number depending on sort direction
int citationNumber;
int citationNumberDirection = comparator.getCitationNumberDirection();
if (citationNumberDirection > 0) {
citationNumber = i + 1;
} else {
citationNumber = sortedItems.size() + 1 - i;
}
// create new item data with citation data and add it to
// the list of sorted items
itemData = new CSLItemDataBuilder(itemData)
.citationNumber(String.valueOf(citationNumber))
.build();
sortedItems.add(i, itemData);
// determine if we need to update the following items or
// the preceding ones (depending on the sort direction)
IntStream idStream;
if (citationNumberDirection > 0) {
idStream = IntStream.range(i + 1, sortedItems.size());
} else {
int e = i;
idStream = IntStream.range(0, e).map(n -> e - 1 - n);
}
// update the other items if necessary
idStream.forEach(j -> {
CSLItemData item2 = sortedItems.get(j);
// determine new citation number
int citationNumber2;
if (citationNumberDirection > 0) {
citationNumber2 = j + 1;
} else {
citationNumber2 = sortedItems.size() - j;
}
// create new item data with new citation number
item2 = new CSLItemDataBuilder(item2)
.citationNumber(String.valueOf(citationNumber2))
.build();
// overwrite existing item data
sortedItems.set(j, item2);
registeredItems.put(item2.getId(), item2);
// store updated item
if (updatedItems != null) {
updatedItems.add(item2);
}
});
}
// save registered item data
registeredItems.put(itemData.getId(), itemData);
result.add(itemData);
}
return result;
}
/**
* Introduces the given citation IDs to the processor. The processor will
* call {@link ItemDataProvider#retrieveItem(String)} for each ID to get
* the respective citation item. The retrieved items will be added to the
* bibliography, so you don't have to call {@link #makeCitation(String...)}
* for each of them anymore.
* @param ids the IDs to register
* @throws IllegalArgumentException if one of the given IDs refers to
* citation item data that does not exist
*/
public void registerCitationItems(String... ids) {
registerCitationItems(ids, false);
}
/**
* Introduces the given citation IDs to the processor. The processor will
* call {@link ItemDataProvider#retrieveItem(String)} for each ID to get
* the respective citation item. The retrieved items will be added to the
* bibliography, so you don't have to call {@link #makeCitation(String...)}
* for each of them anymore.
* @param ids the IDs to register
* @param unsorted true if items should not be sorted in the bibliography
* @throws IllegalArgumentException if one of the given IDs refers to
* citation item data that does not exist
*/
public void registerCitationItems(String[] ids, boolean unsorted) {
registerCitationItems(Arrays.asList(ids), unsorted);
}
/**
* Introduces the given citation IDs to the processor. The processor will
* call {@link ItemDataProvider#retrieveItem(String)} for each ID to get
* the respective citation item. The retrieved items will be added to the
* bibliography, so you don't have to call {@link #makeCitation(String...)}
* for each of them anymore.
* @param ids the IDs to register
* @throws IllegalArgumentException if one of the given IDs refers to
* citation item data that does not exist
*/
public void registerCitationItems(Collection<String> ids) {
registerCitationItems(ids, false);
}
/**
* Introduces the given citation IDs to the processor. The processor will
* call {@link ItemDataProvider#retrieveItem(String)} for each ID to get
* the respective citation item. The retrieved items will be added to the
* bibliography, so you don't have to call {@link #makeCitation(String...)}
* for each of them anymore.
* @param ids the IDs to register
* @param unsorted true if items should not be sorted in the bibliography
* @throws IllegalArgumentException if one of the given IDs refers to
* citation item data that does not exist
*/
public void registerCitationItems(Collection<String> ids, boolean unsorted) {
registeredItems.clear();
sortedItems.clear();
registerItems(ids, null, unsorted);
}
/**
* Get an unmodifiable collection of all citation items that have been
* registered with the processor so far
* @return the registered citation items
*/
public Collection<CSLItemData> getRegisteredItems() {
return Collections.unmodifiableCollection(sortedItems);
}
/**
* Generates citation strings that can be inserted into the text. The
* method calls {@link ItemDataProvider#retrieveItem(String)} for each of the given
* IDs to request the corresponding citation item. Additionally, it saves
* the IDs, so {@link #makeBibliography()} will generate a bibliography
* that only consists of the retrieved citation items.
* @param ids IDs of citation items for which strings should be generated
* @return citations strings that can be inserted into the text
* @throws IllegalArgumentException if one of the given IDs refers to
* citation item data that does not exist
*/
public List<Citation> makeCitation(String... ids) {
return makeCitation(Arrays.asList(ids));
}
/**
* Generates citation strings that can be inserted into the text. The
* method calls {@link ItemDataProvider#retrieveItem(String)} for each of the given
* IDs to request the corresponding citation item. Additionally, it saves
* the IDs, so {@link #makeBibliography()} will generate a bibliography
* that only consists of the retrieved citation items.
* @param ids IDs of citation items for which strings should be generated
* @return citations strings that can be inserted into the text
* @throws IllegalArgumentException if one of the given IDs refers to
* citation item data that does not exist
*/
public List<Citation> makeCitation(Collection<String> ids) {
CSLCitationItem[] items = new CSLCitationItem[ids.size()];
int i = 0;
for (String id : ids) {
items[i++] = new CSLCitationItem(id);
}
return makeCitation(new CSLCitation(items));
}
/**
* Perform steps to prepare the given citation for rendering. Register
* citation items and sort them. Return a prepared citation that can be
* passed to {@link #renderCitation(CSLCitation)}
* @param citation the citation to render
* @param updatedItems an empty set that will be filled with citation
* items that had to be updated while rendering the given one (may be
* {@code null})
* @return the prepared citation
*/
private CSLCitation preRenderCitation(CSLCitation citation,
Set<CSLItemData> updatedItems) {
// get item IDs
int len = citation.getCitationItems().length;
List<String> itemIds = new ArrayList<>(len);
CSLCitationItem[] items = citation.getCitationItems();
for (int i = 0; i < len; i++) {
CSLCitationItem item = items[i];
itemIds.add(item.getId());
}
// register items
List<CSLItemData> registeredItems = registerItems(itemIds,
updatedItems, false);
// prepare items
CSLCitationItem[] preparedItems = new CSLCitationItem[len];
for (int i = 0; i < len; i++) {
CSLCitationItem item = items[i];
CSLItemData itemData = registeredItems.get(i);
// overwrite locator
if (item.getLocator() != null) {
itemData = new CSLItemDataBuilder(itemData)
.locator(item.getLocator())
.build();
}
preparedItems[i] = new CSLCitationItemBuilder(item)
.itemData(itemData)
.build();
}
// sort array of items
boolean unsorted = false;
if (citation.getProperties() != null &&
citation.getProperties().getUnsorted() != null) {
unsorted = citation.getProperties().getUnsorted();
}
if (!unsorted && style.getCitation().getSort() != null) {
Comparator<CSLItemData> itemComparator =
style.getCitation().getSort().comparator(style, locale,
abbreviationProvider);
Arrays.sort(preparedItems, (a, b) -> itemComparator.compare(
a.getItemData(), b.getItemData()));
}
return new CSLCitation(preparedItems,
citation.getCitationID(), citation.getProperties());
}
/**
* Render the given prepared citation
* @param preparedCitation the citation to render. The citation must have
* been prepared by {@link #preRenderCitation(CSLCitation, Set)}
* @return the rendered string
*/
private String renderCitation(CSLCitation preparedCitation) {
// render items
RenderContext ctx = new RenderContext(style, locale, null, abbreviationProvider,
preparedCitation, Collections.unmodifiableList(generatedCitations));
style.getCitation().render(ctx);
return outputFormat.formatCitation(ctx);
}
/**
* Generates citation strings that can be inserted into the text. The
* method calls {@link ItemDataProvider#retrieveItem(String)} for each item in the
* given set to request the corresponding citation item data. Additionally,
* it saves the requested citation IDs, so {@link #makeBibliography()} will
* generate a bibliography that only consists of the retrieved items.
* @param citation a set of citation items for which strings should be generated
* @return citations strings that can be inserted into the text
* @throws IllegalArgumentException if the given set of citation items
* refers to citation item data that does not exist
*/
public List<Citation> makeCitation(CSLCitation citation) {
Set<CSLItemData> updatedItems = new LinkedHashSet<>();
CSLCitation preparedCitation = preRenderCitation(citation, updatedItems);
String text = renderCitation(preparedCitation);
// re-render updated citations
List<Citation> result = new ArrayList<>();
if (!updatedItems.isEmpty()) {
List<GeneratedCitation> oldGeneratedCitations = generatedCitations;
generatedCitations = new ArrayList<>(oldGeneratedCitations.size());
for (int i = 0; i < oldGeneratedCitations.size(); i++) {
GeneratedCitation gc = oldGeneratedCitations.get(i);
boolean needsUpdate = false;
for (CSLItemData updatedItemData : updatedItems) {
for (CSLCitationItem item : gc.getOriginal().getCitationItems()) {
if (item.getId().equals(updatedItemData.getId())) {
needsUpdate = true;
break;
}
}
}
if (!needsUpdate) {
generatedCitations.add(gc);
continue;
}
// prepare citation again (!)
CSLCitation upc = preRenderCitation(gc.getOriginal(), null);
// render it again
String ut = renderCitation(upc);
if (!ut.equals(gc.getGenerated().getText())) {
// render result was different
Citation uc = new Citation(i, ut);
generatedCitations.add(new GeneratedCitation(
gc.getOriginal(), upc, uc));
result.add(uc);
}
}
}
// generate citation
Citation generatedCitation = new Citation(generatedCitations.size(), text);
generatedCitations.add(new GeneratedCitation(citation,
preparedCitation, generatedCitation));
result.add(generatedCitation);
return result;
}
/**
* Generates a bibliography for the registered citations
* @return the bibliography
*/
public Bibliography makeBibliography() {
return makeBibliography(null);
}
/**
* Generates a bibliography for the registered citations. Depending
* on the selection mode selects, includes, or excludes bibliography
* items whose fields and field values match the fields and field values
* from the given example item data objects.
* @param mode the selection mode
* @param selection the example item data objects that contain
* the fields and field values to match
* @return the bibliography
*/
public Bibliography makeBibliography(SelectionMode mode, CSLItemData... selection) {
return makeBibliography(mode, selection, null);
}
/**
* <p>Generates a bibliography for the registered citations. Depending
* on the selection mode selects, includes, or excludes bibliography
* items whose fields and field values match the fields and field values
* from the given example item data objects.</p>
* <p>Note: This method will be deprecated in the next release.</p>
* @param mode the selection mode
* @param selection the example item data objects that contain
* the fields and field values to match
* @param quash regardless of the item data in {@code selection}
* skip items if all fields/values from this list match
* @return the bibliography
*/
public Bibliography makeBibliography(SelectionMode mode,
CSLItemData[] selection, CSLItemData[] quash) {
return makeBibliography(item -> {
boolean include = true;
if (selection != null) {
switch (mode) {
case INCLUDE:
include = false;
for (CSLItemData s : selection) {
if (itemDataEqualsAny(item, s)) {
include = true;
break;
}
}
break;
case EXCLUDE:
for (CSLItemData s : selection) {
if (itemDataEqualsAny(item, s)) {
include = false;
break;
}
}
break;
case SELECT:
for (CSLItemData s : selection) {
if (!itemDataEqualsAny(item, s)) {
include = false;
break;
}
}
break;
}
}
if (include && quash != null) {
boolean match = true;
for (CSLItemData s : quash) {
if (!itemDataEqualsAny(item, s)) {
match = false;
break;
}
}
if (match) {
include = false;
}
}
return include;
});
}
/**
* Generates a bibliography for registered citations
* @param filter a function to apply to each registered citation item to
* determine if it should be included in the bibliography or not (may
* be {@code null} if all items should be included)
* @return the bibliography
*/
public Bibliography makeBibliography(Predicate<CSLItemData> filter) {
if (!canFormatBibliographies(style)) {
throw new IllegalStateException("The citation style does " +
"not contain instructions to format bibliographies");
}
List<CSLItemData> filteredItems;
if (filter == null) {
filteredItems = sortedItems;
} else {
filteredItems = new ArrayList<>();
for (CSLItemData item : sortedItems) {
if (filter.test(item)) {
filteredItems.add(item);
}
}
}
List<String> entries = new ArrayList<>();
for (int i = 0; i < filteredItems.size(); i++) {
CSLItemData item = filteredItems.get(i);
RenderContext ctx = new RenderContext(style, locale, item,
abbreviationProvider);
style.getBibliography().render(ctx);
if (!ctx.getResult().isEmpty()) {
entries.add(outputFormat.formatBibliographyEntry(ctx, i));
}
}
return outputFormat.makeBibliography(entries.toArray(new String[0]),
style.getBibliography());
}
/**
* Resets the processor's state
*/
public void reset() {
outputFormat = new HtmlFormat();
convertLinks = false;
registeredItems.clear();
sortedItems.clear();
generatedCitations.clear();
}
/**
* Creates an ad hoc bibliography from the given citation items using the
* <code>"html"</code> output format.
* @param style the citation style to use. May either be a serialized
* XML representation of the style or a style's name such as <code>ieee</code>.
* In the latter case, the processor loads the style from the classpath (e.g.
* <code>/ieee.csl</code>)
* @param items the citation items to add to the bibliography
* @return the bibliography
* @throws IOException if the underlying JavaScript files or the CSL style
* could not be loaded
* @see #makeAdhocBibliography(String, String, CSLItemData...)
*/
public static Bibliography makeAdhocBibliography(String style, CSLItemData... items)
throws IOException {
return makeAdhocBibliography(style, "html", items);
}
/**
* Creates an ad hoc bibliography from the given citation items.
* @param style the citation style to use. May either be a serialized
* XML representation of the style or a style's name such as <code>ieee</code>.
* In the latter case, the processor loads the style from the classpath (e.g.
* <code>/ieee.csl</code>)
* @param outputFormat the processor's output format (one of
* <code>"html"</code>, <code>"text"</code>, <code>"asciidoc"</code>,
* <code>"fo"</code>, or <code>"rtf"</code>)
* @param items the citation items to add to the bibliography
* @return the bibliography
* @throws IOException if the CSL style could not be loaded
*/
public static Bibliography makeAdhocBibliography(String style, String outputFormat,
CSLItemData... items) throws IOException {
ItemDataProvider provider = new ListItemDataProvider(items);
CSL csl = new CSL(provider, style);
csl.setOutputFormat(outputFormat);
String[] ids = new String[items.length];
for (int i = 0; i < items.length; ++i) {
ids[i] = items[i].getId();
}
csl.registerCitationItems(ids);
return csl.makeBibliography();
}
/**
* Creates an ad hoc citation from the given citation items using the
* <code>"html"</code> output format.
* @param style the citation style to use. May either be a serialized
* XML representation of the style or a style's name such as <code>ieee</code>.
* In the latter case, the processor loads the style from the classpath (e.g.
* <code>/ieee.csl</code>)
* @param items the citation items
* @return a list of generated citations strings that can be inserted into the text
* @see #makeCitation(String...)
* @throws IOException if the CSL style could not be loaded
*/
public static List<Citation> makeAdhocCitation(String style, CSLItemData... items)
throws IOException {
return makeAdhocCitation(style, "html", items);
}
/**
* Creates an ad hoc citation from the given citation items.
* @param style the citation style to use. May either be a serialized
* XML representation of the style or a style's name such as <code>ieee</code>.
* In the latter case, the processor loads the style from the classpath (e.g.
* <code>/ieee.csl</code>)
* @param outputFormat the processor's output format (one of
* <code>"html"</code>, <code>"text"</code>, <code>"asciidoc"</code>,
* <code>"fo"</code>, or <code>"rtf"</code>)
* @param items the citation items
* @return a list of generated citations strings that can be inserted into the text
* @see #makeCitation(String...)
* @throws IOException if the CSL style could not be loaded
*/
public static List<Citation> makeAdhocCitation(String style, String outputFormat,
CSLItemData... items) throws IOException {
ItemDataProvider provider = new ListItemDataProvider(items);
CSL csl = new CSL(provider, style);
csl.setOutputFormat(outputFormat);
String[] ids = new String[items.length];
for (int i = 0; i < items.length; ++i) {
ids[i] = items[i].getId();
}
return csl.makeCitation(ids);
}
/**
* Test if any of the attributes of {@code b} match the ones of {@code a}.
* Note: This method will be deprecated in the next release
* @param a the first object
* @param b the object to match against
* @return {@code true} if the match succeeds
*/
private static boolean itemDataEqualsAny(CSLItemData a, CSLItemData b) {
if (a == b) {
return true;
}
if (b == null) {
return false;
}
if (b.getId() != null && Objects.equals(a.getId(), b.getId())) {
return true;
}
if (b.getType() != null && Objects.equals(a.getType(), b.getType())) {
return true;
}
if (b.getCategories() != null && Arrays.equals(a.getCategories(), b.getCategories())) {
return true;
}
if (b.getLanguage() != null && Objects.equals(a.getLanguage(), b.getLanguage())) {
return true;
}
if (b.getJournalAbbreviation() != null && Objects.equals(a.getJournalAbbreviation(), b.getJournalAbbreviation())) {
return true;
}
if (b.getShortTitle() != null && Objects.equals(a.getShortTitle(), b.getShortTitle())) {
return true;
}
if (b.getAuthor() != null && Arrays.equals(a.getAuthor(), b.getAuthor())) {
return true;
}
if (b.getCollectionEditor() != null && Arrays.equals(a.getCollectionEditor(), b.getCollectionEditor())) {
return true;
}
if (b.getComposer() != null && Arrays.equals(a.getComposer(), b.getComposer())) {
return true;
}
if (b.getContainerAuthor() != null && Arrays.equals(a.getContainerAuthor(), b.getContainerAuthor())) {
return true;
}
if (b.getDirector() != null && Arrays.equals(a.getDirector(), b.getDirector())) {
return true;
}
if (b.getEditor() != null && Arrays.equals(a.getEditor(), b.getEditor())) {
return true;
}
if (b.getEditorialDirector() != null && Arrays.equals(a.getEditorialDirector(), b.getEditorialDirector())) {
return true;
}
if (b.getInterviewer() != null && Arrays.equals(a.getInterviewer(), b.getInterviewer())) {
return true;
}
if (b.getIllustrator() != null && Arrays.equals(a.getIllustrator(), b.getIllustrator())) {
return true;
}
if (b.getOriginalAuthor() != null && Arrays.equals(a.getOriginalAuthor(), b.getOriginalAuthor())) {
return true;
}
if (b.getRecipient() != null && Arrays.equals(a.getRecipient(), b.getRecipient())) {
return true;
}
if (b.getReviewedAuthor() != null && Arrays.equals(a.getReviewedAuthor(), b.getReviewedAuthor())) {
return true;
}
if (b.getTranslator() != null && Arrays.equals(a.getTranslator(), b.getTranslator())) {
return true;
}
if (b.getAccessed() != null && Objects.equals(a.getAccessed(), b.getAccessed())) {
return true;
}
if (b.getContainer() != null && Objects.equals(a.getContainer(), b.getContainer())) {
return true;
}
if (b.getEventDate() != null && Objects.equals(a.getEventDate(), b.getEventDate())) {
return true;
}
if (b.getIssued() != null && Objects.equals(a.getIssued(), b.getIssued())) {
return true;
}
if (b.getOriginalDate() != null && Objects.equals(a.getOriginalDate(), b.getOriginalDate())) {
return true;
}
if (b.getSubmitted() != null && Objects.equals(a.getSubmitted(), b.getSubmitted())) {
return true;
}
if (b.getAbstrct() != null && Objects.equals(a.getAbstrct(), b.getAbstrct())) {
return true;
}
if (b.getAnnote() != null && Objects.equals(a.getAnnote(), b.getAnnote())) {
return true;
}
if (b.getArchive() != null && Objects.equals(a.getArchive(), b.getArchive())) {
return true;
}
if (b.getArchiveLocation() != null && Objects.equals(a.getArchiveLocation(), b.getArchiveLocation())) {
return true;
}
if (b.getArchivePlace() != null && Objects.equals(a.getArchivePlace(), b.getArchivePlace())) {
return true;
}
if (b.getAuthority() != null && Objects.equals(a.getAuthority(), b.getAuthority())) {
return true;
}
if (b.getCallNumber() != null && Objects.equals(a.getCallNumber(), b.getCallNumber())) {
return true;
}
if (b.getChapterNumber() != null && Objects.equals(a.getChapterNumber(), b.getChapterNumber())) {
return true;
}
if (b.getCitationNumber() != null && Objects.equals(a.getCitationNumber(), b.getCitationNumber())) {
return true;
}
if (b.getCitationLabel() != null && Objects.equals(a.getCitationLabel(), b.getCitationLabel())) {
return true;
}
if (b.getCollectionNumber() != null && Objects.equals(a.getCollectionNumber(), b.getCollectionNumber())) {
return true;
}
if (b.getCollectionTitle() != null && Objects.equals(a.getCollectionTitle(), b.getCollectionTitle())) {
return true;
}
if (b.getContainerTitle() != null && Objects.equals(a.getContainerTitle(), b.getContainerTitle())) {
return true;
}
if (b.getContainerTitleShort() != null && Objects.equals(a.getContainerTitleShort(), b.getContainerTitleShort())) {
return true;
}
if (b.getDimensions() != null && Objects.equals(a.getDimensions(), b.getDimensions())) {
return true;
}
if (b.getDOI() != null && Objects.equals(a.getDOI(), b.getDOI())) {
return true;
}
if (b.getEdition() != null && Objects.equals(a.getEdition(), b.getEdition())) {
return true;
}
if (b.getEvent() != null && Objects.equals(a.getEvent(), b.getEvent())) {
return true;
}
if (b.getEventPlace() != null && Objects.equals(a.getEventPlace(), b.getEventPlace())) {
return true;
}
if (b.getFirstReferenceNoteNumber() != null && Objects.equals(a.getFirstReferenceNoteNumber(), b.getFirstReferenceNoteNumber())) {
return true;
}
if (b.getGenre() != null && Objects.equals(a.getGenre(), b.getGenre())) {
return true;
}
if (b.getISBN() != null && Objects.equals(a.getISBN(), b.getISBN())) {
return true;
}
if (b.getISSN() != null && Objects.equals(a.getISSN(), b.getISSN())) {
return true;
}
if (b.getIssue() != null && Objects.equals(a.getIssue(), b.getIssue())) {
return true;
}
if (b.getJurisdiction() != null && Objects.equals(a.getJurisdiction(), b.getJurisdiction())) {
return true;
}
if (b.getKeyword() != null && Objects.equals(a.getKeyword(), b.getKeyword())) {
return true;
}
if (b.getLocator() != null && Objects.equals(a.getLocator(), b.getLocator())) {
return true;
}
if (b.getMedium() != null && Objects.equals(a.getMedium(), b.getMedium())) {
return true;
}
if (b.getNote() != null && Objects.equals(a.getNote(), b.getNote())) {
return true;
}
if (b.getNumber() != null && Objects.equals(a.getNumber(), b.getNumber())) {
return true;
}
if (b.getNumberOfPages() != null && Objects.equals(a.getNumberOfPages(), b.getNumberOfPages())) {
return true;
}
if (b.getNumberOfVolumes() != null && Objects.equals(a.getNumberOfVolumes(), b.getNumberOfVolumes())) {
return true;
}
if (b.getOriginalPublisher() != null && Objects.equals(a.getOriginalPublisher(), b.getOriginalPublisher())) {
return true;
}
if (b.getOriginalPublisherPlace() != null && Objects.equals(a.getOriginalPublisherPlace(), b.getOriginalPublisherPlace())) {
return true;
}
if (b.getOriginalTitle() != null && Objects.equals(a.getOriginalTitle(), b.getOriginalTitle())) {
return true;
}
if (b.getPage() != null && Objects.equals(a.getPage(), b.getPage())) {
return true;
}
if (b.getPageFirst() != null && Objects.equals(a.getPageFirst(), b.getPageFirst())) {
return true;
}
if (b.getPMCID() != null && Objects.equals(a.getPMCID(), b.getPMCID())) {
return true;
}
if (b.getPMID() != null && Objects.equals(a.getPMID(), b.getPMID())) {
return true;
}
if (b.getPublisher() != null && Objects.equals(a.getPublisher(), b.getPublisher())) {
return true;
}
if (b.getPublisherPlace() != null && Objects.equals(a.getPublisherPlace(), b.getPublisherPlace())) {
return true;
}
if (b.getReferences() != null && Objects.equals(a.getReferences(), b.getReferences())) {
return true;
}
if (b.getReviewedTitle() != null && Objects.equals(a.getReviewedTitle(), b.getReviewedTitle())) {
return true;
}
if (b.getScale() != null && Objects.equals(a.getScale(), b.getScale())) {
return true;
}
if (b.getSection() != null && Objects.equals(a.getSection(), b.getSection())) {
return true;
}
if (b.getSource() != null && Objects.equals(a.getSource(), b.getSource())) {
return true;
}
if (b.getStatus() != null && Objects.equals(a.getStatus(), b.getStatus())) {
return true;
}
if (b.getTitle() != null && Objects.equals(a.getTitle(), b.getTitle())) {
return true;
}
if (b.getTitleShort() != null && Objects.equals(a.getTitleShort(), b.getTitleShort())) {
return true;
}
if (b.getURL() != null && Objects.equals(a.getURL(), b.getURL())) {
return true;
}
if (b.getVersion() != null && Objects.equals(a.getVersion(), b.getVersion())) {
return true;
}
if (b.getVolume() != null && Objects.equals(a.getVolume(), b.getVolume())) {
return true;
}
return b.getYearSuffix() != null && Objects.equals(a.getYearSuffix(), b.getYearSuffix());
}
}
| {
"content_hash": "4b02f45e6c3e5cdd2bbd1b4b8179b950",
"timestamp": "",
"source": "github",
"line_count": 1390,
"max_line_length": 138,
"avg_line_length": 40.69280575539568,
"alnum_prop": 0.5899085974930608,
"repo_name": "michel-kraemer/citeproc-java",
"id": "860832efccf0c64ffe32286c8002bcab378d9e7d",
"size": "56563",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "citeproc-java/src/main/java/de/undercouch/citeproc/CSL.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "9980"
},
{
"name": "Dockerfile",
"bytes": "389"
},
{
"name": "Groovy",
"bytes": "8367"
},
{
"name": "Java",
"bytes": "747008"
}
],
"symlink_target": ""
} |
import copy
import json
import os
from datetime import datetime, timedelta
from django.conf import settings
from django.core import mail
import mock
import pytest
from waffle.testutils import override_switch
from olympia import amo
from olympia.access.models import Group, GroupUser
from olympia.activity.models import (
MAX_TOKEN_USE_COUNT, ActivityLog, ActivityLogToken)
from olympia.activity.utils import (
ACTIVITY_MAIL_GROUP, ActivityEmailEncodingError, ActivityEmailParser,
ActivityEmailTokenError, ActivityEmailUUIDError, add_email_to_activity_log,
add_email_to_activity_log_wrapper, log_and_notify,
notify_about_activity_log, send_activity_mail)
from olympia.addons.models import Addon, AddonReviewerFlags
from olympia.amo.templatetags.jinja_helpers import absolutify
from olympia.amo.tests import TestCase, addon_factory, user_factory
from olympia.amo.urlresolvers import reverse
TESTS_DIR = os.path.dirname(os.path.abspath(__file__))
sample_message_file = os.path.join(TESTS_DIR, 'emails', 'message.json')
with open(sample_message_file) as file_object:
sample_message_content = json.loads(file_object.read())
class TestEmailParser(TestCase):
def test_basic_email(self):
parser = ActivityEmailParser(sample_message_content['Message'])
assert parser.get_uuid() == '5a0b8a83d501412589cc5d562334b46b'
assert parser.reply == (
'This is a developer reply to an AMO. It\'s nice.')
def test_with_invalid_msg(self):
with self.assertRaises(ActivityEmailEncodingError):
ActivityEmailParser('youtube?v=dQw4w9WgXcQ')
def test_with_empty_to(self):
message = copy.deepcopy(sample_message_content['Message'])
message['To'] = None
parser = ActivityEmailParser(message)
with self.assertRaises(ActivityEmailUUIDError):
# It should fail, but not because of a Not Iterable TypeError,
# instead we handle that gracefully and raise an exception that
# we control and catch later.
parser.get_uuid()
def test_empty_text_body(self):
"""We receive requests that either have no `TextBody` or it's None
https://github.com/mozilla/addons-server/issues/8848
"""
message = copy.deepcopy(sample_message_content['Message'])
message['TextBody'] = None
with self.assertRaises(ActivityEmailEncodingError):
ActivityEmailParser(message)
message = copy.deepcopy(sample_message_content['Message'])
message.pop('TextBody', None)
with self.assertRaises(ActivityEmailEncodingError):
ActivityEmailParser(message)
@override_switch('activity-email-bouncing', active=True)
class TestEmailBouncing(TestCase):
BOUNCE_REPLY = (
'Hello,\n\nAn email was received, apparently from you. Unfortunately '
'we couldn\'t process it because of:\n%s\n\nPlease visit %s to leave '
'a reply instead.\n--\nMozilla Add-ons\n%s')
def setUp(self):
self.bounce_reply = (
self.BOUNCE_REPLY % ('%s', settings.SITE_URL, settings.SITE_URL))
self.email_text = sample_message_content['Message']
@mock.patch('olympia.activity.utils.ActivityLog.create')
def test_no_note_logged(self, log_mock):
# First set everything up so it's working
addon = addon_factory()
version = addon.find_latest_version(channel=amo.RELEASE_CHANNEL_LISTED)
user = user_factory()
self.grant_permission(user, '*:*')
ActivityLogToken.objects.create(
user=user, version=version,
uuid='5a0b8a83d501412589cc5d562334b46b')
# Make log_mock return false for some reason.
log_mock.return_value = False
# No exceptions thrown, but no log means something went wrong.
assert not add_email_to_activity_log_wrapper(self.email_text)
assert len(mail.outbox) == 1
out = mail.outbox[0]
assert out.body == (
self.bounce_reply % 'Undefined Error.')
assert out.subject == 'Re: This is the subject of a test message.'
assert out.to == ['sender@example.com']
def test_exception_because_invalid_token(self):
# Fails because the token doesn't exist in ActivityToken.objects
assert not add_email_to_activity_log_wrapper(self.email_text)
assert len(mail.outbox) == 1
out = mail.outbox[0]
assert out.body == (
self.bounce_reply %
'UUID found in email address TO: header but is not a valid token '
'(5a0b8a83d501412589cc5d562334b46b).')
assert out.subject == 'Re: This is the subject of a test message.'
assert out.to == ['sender@example.com']
def test_exception_because_invalid_email(self):
# Fails because the token doesn't exist in ActivityToken.objects
email_text = copy.deepcopy(self.email_text)
email_text['To'] = [{
'EmailAddress': 'foobar@addons.mozilla.org',
'FriendlyName': 'not a valid activity mail reply'}]
assert not add_email_to_activity_log_wrapper(email_text)
assert len(mail.outbox) == 1
out = mail.outbox[0]
assert out.body == (
self.bounce_reply %
'TO: address does not contain activity email uuid ('
'foobar@addons.mozilla.org).')
assert out.subject == 'Re: This is the subject of a test message.'
assert out.to == ['sender@example.com']
def test_exception_parser_because_malformed_message(self):
assert not add_email_to_activity_log_wrapper("blah de blah")
# No From or Reply means no bounce, alas.
assert len(mail.outbox) == 0
def _test_exception_in_parser_but_can_send_email(self, message):
assert not add_email_to_activity_log_wrapper(message)
assert len(mail.outbox) == 1
assert mail.outbox[0].body == (
self.bounce_reply % 'Invalid or malformed json message object.')
assert mail.outbox[0].subject == 'Re: your email to us'
assert mail.outbox[0].to == ['bob@dole.org']
def test_exception_in_parser_but_from_defined(self):
"""Unlikely scenario of an email missing a body but having a From."""
self._test_exception_in_parser_but_can_send_email(
{'From': {'EmailAddress': 'bob@dole.org'}})
def test_exception_in_parser_but_reply_to_defined(self):
"""Even more unlikely scenario of an email missing a body but having a
ReplyTo."""
self._test_exception_in_parser_but_can_send_email(
{'ReplyTo': {'EmailAddress': 'bob@dole.org'}})
def test_exception_to_notifications_alias(self):
email_text = copy.deepcopy(self.email_text)
email_text['To'] = [{
'EmailAddress': 'notifications@%s' % settings.INBOUND_EMAIL_DOMAIN,
'FriendlyName': 'not a valid activity mail reply'}]
assert not add_email_to_activity_log_wrapper(email_text)
assert len(mail.outbox) == 1
out = mail.outbox[0]
assert ('This email address is not meant to receive emails '
'directly.') in out.body
assert out.subject == 'Re: This is the subject of a test message.'
assert out.to == ['sender@example.com']
@override_switch('activity-email-bouncing', active=False)
def test_exception_but_bouncing_waffle_off(self):
# Fails because the token doesn't exist in ActivityToken.objects
assert not add_email_to_activity_log_wrapper(self.email_text)
# But no bounce.
assert len(mail.outbox) == 0
class TestAddEmailToActivityLog(TestCase):
def setUp(self):
self.addon = addon_factory(name='Badger', status=amo.STATUS_NOMINATED)
version = self.addon.find_latest_version(
channel=amo.RELEASE_CHANNEL_LISTED)
self.profile = user_factory()
self.token = ActivityLogToken.objects.create(
version=version, user=self.profile)
self.token.update(uuid='5a0b8a83d501412589cc5d562334b46b')
self.parser = ActivityEmailParser(sample_message_content['Message'])
def test_developer_comment(self):
self.profile.addonuser_set.create(addon=self.addon)
note = add_email_to_activity_log(self.parser)
assert note.log == amo.LOG.DEVELOPER_REPLY_VERSION
self.token.refresh_from_db()
assert self.token.use_count == 1
def test_reviewer_comment(self):
self.grant_permission(self.profile, 'Addons:Review')
note = add_email_to_activity_log(self.parser)
assert note.log == amo.LOG.REVIEWER_REPLY_VERSION
self.token.refresh_from_db()
assert self.token.use_count == 1
def test_with_max_count_token(self):
"""Test with an invalid token."""
self.token.update(use_count=MAX_TOKEN_USE_COUNT + 1)
with self.assertRaises(ActivityEmailTokenError):
assert not add_email_to_activity_log(self.parser)
self.token.refresh_from_db()
assert self.token.use_count == MAX_TOKEN_USE_COUNT + 1
def test_with_unpermitted_token(self):
"""Test when the token user doesn't have a permission to add a note."""
with self.assertRaises(ActivityEmailTokenError):
assert not add_email_to_activity_log(self.parser)
self.token.refresh_from_db()
assert self.token.use_count == 0
def test_non_existent_token(self):
self.token.update(uuid='12345678901234567890123456789012')
with self.assertRaises(ActivityEmailUUIDError):
assert not add_email_to_activity_log(self.parser)
def test_broken_token(self):
parser = ActivityEmailParser(
copy.deepcopy(sample_message_content['Message']))
parser.email['To'][0]['EmailAddress'] = 'reviewreply+1234@foo.bar'
with self.assertRaises(ActivityEmailUUIDError):
assert not add_email_to_activity_log(parser)
class TestLogAndNotify(TestCase):
def setUp(self):
self.developer = user_factory()
self.developer2 = user_factory()
self.reviewer = user_factory()
self.grant_permission(self.reviewer, 'Addons:Review',
'Addon Reviewers')
self.addon = addon_factory()
self.version = self.addon.find_latest_version(
channel=amo.RELEASE_CHANNEL_LISTED)
self.addon.addonuser_set.create(user=self.developer)
self.addon.addonuser_set.create(user=self.developer2)
self.task_user = user_factory(id=settings.TASK_USER_ID)
def _create(self, action, author=None):
author = author or self.reviewer
details = {
'comments': u'I spy, with my líttle €ye...',
'version': self.version.version}
activity = ActivityLog.create(
action, self.addon, self.version, user=author, details=details)
activity.update(created=self.days_ago(1))
return activity
def _recipients(self, email_mock):
recipients = []
for call in email_mock.call_args_list:
recipients += call[1]['recipient_list']
[reply_to] = call[1]['reply_to']
assert reply_to.startswith('reviewreply+')
assert reply_to.endswith(settings.INBOUND_EMAIL_DOMAIN)
return recipients
def _check_email_info_request(self, call, url, reason_text, days_text):
subject = call[0][0]
body = call[0][1]
assert subject == u'Mozilla Add-ons: Action Required for %s %s' % (
self.addon.name, self.version.version)
assert ('visit %s' % url) in body
assert ('receiving this email because %s' % reason_text) in body
if days_text is not None:
assert 'If we do not hear from you within' in body
assert days_text in body
assert 'reviewing version %s of the add-on %s' % (
self.version.version, self.addon.name) in body
def _check_email(self, call, url, reason_text):
subject = call[0][0]
body = call[0][1]
assert subject == u'Mozilla Add-ons: %s %s' % (
self.addon.name, self.version.version)
assert ('visit %s' % url) in body
assert ('receiving this email because %s' % reason_text) in body
assert 'If we do not hear from you within' not in body
@mock.patch('olympia.activity.utils.send_mail')
def test_reviewer_request_for_information(self, send_mail_mock):
AddonReviewerFlags.objects.create(
addon=self.addon,
pending_info_request=datetime.now() + timedelta(days=7))
self._create(amo.LOG.REQUEST_INFORMATION, self.reviewer)
log_and_notify(
amo.LOG.REQUEST_INFORMATION, 'blah', self.reviewer, self.version)
assert send_mail_mock.call_count == 2 # Both authors.
sender = '%s <notifications@%s>' % (
self.reviewer.name, settings.INBOUND_EMAIL_DOMAIN)
assert sender == send_mail_mock.call_args_list[0][1]['from_email']
recipients = self._recipients(send_mail_mock)
assert len(recipients) == 2
assert self.developer.email in recipients
assert self.developer2.email in recipients
# The reviewer who sent it doesn't get their email back.
assert self.reviewer.email not in recipients
self._check_email_info_request(
send_mail_mock.call_args_list[0],
absolutify(self.addon.get_dev_url('versions')),
'you are listed as an author of this add-on.',
'seven (7) days of this notification')
self._check_email_info_request(
send_mail_mock.call_args_list[1],
absolutify(self.addon.get_dev_url('versions')),
'you are listed as an author of this add-on.',
'seven (7) days of this notification')
@mock.patch('olympia.activity.utils.send_mail')
def test_reviewer_request_for_information_close_date(self, send_mail_mock):
AddonReviewerFlags.objects.create(
addon=self.addon,
pending_info_request=datetime.now() + timedelta(days=1))
self._create(amo.LOG.REQUEST_INFORMATION, self.reviewer)
log_and_notify(
amo.LOG.REQUEST_INFORMATION, 'blah', self.reviewer, self.version)
assert send_mail_mock.call_count == 2 # Both authors.
sender = '%s <notifications@%s>' % (
self.reviewer.name, settings.INBOUND_EMAIL_DOMAIN)
assert sender == send_mail_mock.call_args_list[0][1]['from_email']
recipients = self._recipients(send_mail_mock)
assert len(recipients) == 2
assert self.developer.email in recipients
assert self.developer2.email in recipients
# The reviewer who sent it doesn't get their email back.
assert self.reviewer.email not in recipients
self._check_email_info_request(
send_mail_mock.call_args_list[0],
absolutify(self.addon.get_dev_url('versions')),
'you are listed as an author of this add-on.',
'one (1) day of this notification')
self._check_email_info_request(
send_mail_mock.call_args_list[1],
absolutify(self.addon.get_dev_url('versions')),
'you are listed as an author of this add-on.',
'one (1) day of this notification')
@mock.patch('olympia.activity.utils.send_mail')
def test_reviewer_request_for_information_far_date(self, send_mail_mock):
AddonReviewerFlags.objects.create(
addon=self.addon,
pending_info_request=datetime.now() + timedelta(days=21))
self._create(amo.LOG.REQUEST_INFORMATION, self.reviewer)
log_and_notify(
amo.LOG.REQUEST_INFORMATION, 'blah', self.reviewer, self.version)
assert send_mail_mock.call_count == 2 # Both authors.
sender = '%s <notifications@%s>' % (
self.reviewer.name, settings.INBOUND_EMAIL_DOMAIN)
assert sender == send_mail_mock.call_args_list[0][1]['from_email']
recipients = self._recipients(send_mail_mock)
assert len(recipients) == 2
assert self.developer.email in recipients
assert self.developer2.email in recipients
# The reviewer who sent it doesn't get their email back.
assert self.reviewer.email not in recipients
self._check_email_info_request(
send_mail_mock.call_args_list[0],
absolutify(self.addon.get_dev_url('versions')),
'you are listed as an author of this add-on.',
'21 days of this notification')
self._check_email_info_request(
send_mail_mock.call_args_list[1],
absolutify(self.addon.get_dev_url('versions')),
'you are listed as an author of this add-on.',
'21 days of this notification')
def test_post_reviewer_request_for_information(self):
GroupUser.objects.filter(user=self.reviewer).delete()
self.grant_permission(
self.reviewer, 'Addons:PostReview', 'Reviewers: Foo')
self.test_reviewer_request_for_information()
def test_content_reviewer_request_for_information(self):
GroupUser.objects.filter(user=self.reviewer).delete()
self.grant_permission(
self.reviewer, 'Addons:ContentReview', 'Reviewers: Bar')
self.test_reviewer_request_for_information()
@mock.patch('olympia.activity.utils.send_mail')
def test_developer_reply(self, send_mail_mock):
# Set pending info request flag to make sure
# it has been dropped after the reply.
AddonReviewerFlags.objects.create(
addon=self.addon,
pending_info_request=datetime.now() + timedelta(days=1))
# One from the reviewer.
self._create(amo.LOG.REJECT_VERSION, self.reviewer)
# One from the developer. So the developer is on the 'thread'
self._create(amo.LOG.DEVELOPER_REPLY_VERSION, self.developer)
action = amo.LOG.DEVELOPER_REPLY_VERSION
comments = u'Thïs is á reply'
log_and_notify(action, comments, self.developer, self.version)
logs = ActivityLog.objects.filter(action=action.id)
assert len(logs) == 2 # We added one above.
assert logs[0].details['comments'] == u'Thïs is á reply'
assert send_mail_mock.call_count == 2 # One author, one reviewer.
sender = '%s <notifications@%s>' % (
self.developer.name, settings.INBOUND_EMAIL_DOMAIN)
assert sender == send_mail_mock.call_args_list[0][1]['from_email']
recipients = self._recipients(send_mail_mock)
assert len(recipients) == 2
assert self.reviewer.email in recipients
assert self.developer2.email in recipients
# The developer who sent it doesn't get their email back.
assert self.developer.email not in recipients
self._check_email(
send_mail_mock.call_args_list[0],
absolutify(self.addon.get_dev_url('versions')),
'you are listed as an author of this add-on.')
review_url = absolutify(
reverse('reviewers.review',
kwargs={'addon_id': self.version.addon.pk,
'channel': 'listed'},
add_prefix=False))
self._check_email(
send_mail_mock.call_args_list[1],
review_url, 'you reviewed this add-on.')
self.addon = Addon.objects.get(pk=self.addon.pk)
assert not self.addon.pending_info_request
@mock.patch('olympia.activity.utils.send_mail')
def test_reviewer_reply(self, send_mail_mock):
# One from the reviewer.
self._create(amo.LOG.REJECT_VERSION, self.reviewer)
# One from the developer.
self._create(amo.LOG.DEVELOPER_REPLY_VERSION, self.developer)
action = amo.LOG.REVIEWER_REPLY_VERSION
comments = u'Thîs ïs a revïewer replyîng'
log_and_notify(action, comments, self.reviewer, self.version)
logs = ActivityLog.objects.filter(action=action.id)
assert len(logs) == 1
assert logs[0].details['comments'] == u'Thîs ïs a revïewer replyîng'
assert send_mail_mock.call_count == 2 # Both authors.
sender = '%s <notifications@%s>' % (
self.reviewer.name, settings.INBOUND_EMAIL_DOMAIN)
assert sender == send_mail_mock.call_args_list[0][1]['from_email']
recipients = self._recipients(send_mail_mock)
assert len(recipients) == 2
assert self.developer.email in recipients
assert self.developer2.email in recipients
# The reviewer who sent it doesn't get their email back.
assert self.reviewer.email not in recipients
self._check_email(
send_mail_mock.call_args_list[0],
absolutify(self.addon.get_dev_url('versions')),
'you are listed as an author of this add-on.')
self._check_email(
send_mail_mock.call_args_list[1],
absolutify(self.addon.get_dev_url('versions')),
'you are listed as an author of this add-on.')
@mock.patch('olympia.activity.utils.send_mail')
def test_log_with_no_comment(self, send_mail_mock):
# One from the reviewer.
self._create(amo.LOG.REJECT_VERSION, self.reviewer)
action = amo.LOG.APPROVAL_NOTES_CHANGED
log_and_notify(
action=action, comments=None, note_creator=self.developer,
version=self.version)
logs = ActivityLog.objects.filter(action=action.id)
assert len(logs) == 1
assert not logs[0].details # No details json because no comment.
assert send_mail_mock.call_count == 2 # One author, one reviewer.
sender = '%s <notifications@%s>' % (
self.developer.name, settings.INBOUND_EMAIL_DOMAIN)
assert sender == send_mail_mock.call_args_list[0][1]['from_email']
recipients = self._recipients(send_mail_mock)
assert len(recipients) == 2
assert self.reviewer.email in recipients
assert self.developer2.email in recipients
assert u'Approval notes changed' in (
send_mail_mock.call_args_list[0][0][1])
assert u'Approval notes changed' in (
send_mail_mock.call_args_list[1][0][1])
def test_staff_cc_group_is_empty_no_failure(self):
Group.objects.create(name=ACTIVITY_MAIL_GROUP, rules='None:None')
log_and_notify(amo.LOG.REJECT_VERSION, u'á', self.reviewer,
self.version)
@mock.patch('olympia.activity.utils.send_mail')
def test_staff_cc_group_get_mail(self, send_mail_mock):
self.grant_permission(self.reviewer, 'None:None', ACTIVITY_MAIL_GROUP)
action = amo.LOG.DEVELOPER_REPLY_VERSION
comments = u'Thïs is á reply'
log_and_notify(action, comments, self.developer, self.version)
logs = ActivityLog.objects.filter(action=action.id)
assert len(logs) == 1
recipients = self._recipients(send_mail_mock)
sender = '%s <notifications@%s>' % (
self.developer.name, settings.INBOUND_EMAIL_DOMAIN)
assert sender == send_mail_mock.call_args_list[0][1]['from_email']
assert len(recipients) == 2
# self.reviewers wasn't on the thread, but gets an email anyway.
assert self.reviewer.email in recipients
assert self.developer2.email in recipients
review_url = absolutify(
reverse('reviewers.review',
kwargs={'addon_id': self.version.addon.pk,
'channel': 'listed'},
add_prefix=False))
self._check_email(send_mail_mock.call_args_list[1],
review_url,
'you are member of the activity email cc group.')
@mock.patch('olympia.activity.utils.send_mail')
def test_mail_needinfo_correct_subject(self, send_mail_mock):
self.grant_permission(self.reviewer, 'None:None', ACTIVITY_MAIL_GROUP)
action = amo.LOG.REQUEST_INFORMATION
comments = u'Thïs is á reply'
log_and_notify(action, comments, self.developer, self.version)
logs = ActivityLog.objects.filter(action=action.id)
assert len(logs) == 1
recipients = self._recipients(send_mail_mock)
sender = '%s <notifications@%s>' % (
self.developer.name, settings.INBOUND_EMAIL_DOMAIN)
assert sender == send_mail_mock.call_args_list[0][1]['from_email']
developer_subject = send_mail_mock.call_args_list[0][0][0]
assert developer_subject == (
u'Mozilla Add-ons: Action Required for '
'%s %s' % (self.addon.name, self.version.version))
reviewer_subject = send_mail_mock.call_args_list[1][0][0]
assert reviewer_subject == u'Mozilla Add-ons: %s %s' % (
self.addon.name, self.version.version)
assert len(recipients) == 2
# self.reviewers wasn't on the thread, but gets an email anyway.
assert self.reviewer.email in recipients
assert self.developer2.email in recipients
review_url = absolutify(
reverse('reviewers.review',
kwargs={'addon_id': self.version.addon.pk,
'channel': 'listed'},
add_prefix=False))
self._check_email(send_mail_mock.call_args_list[1],
review_url,
'you are member of the activity email cc group.')
@mock.patch('olympia.activity.utils.send_mail')
def test_task_user_doesnt_get_mail(self, send_mail_mock):
"""The task user account is used to auto-sign unlisted addons, amongst
other things, but we don't want that user account to get mail."""
self._create(amo.LOG.APPROVE_VERSION, self.task_user)
action = amo.LOG.DEVELOPER_REPLY_VERSION
comments = u'Thïs is á reply'
log_and_notify(action, comments, self.developer, self.version)
logs = ActivityLog.objects.filter(action=action.id)
assert len(logs) == 1
recipients = self._recipients(send_mail_mock)
assert len(recipients) == 1
assert self.developer2.email in recipients
assert self.task_user.email not in recipients
@mock.patch('olympia.activity.utils.send_mail')
def test_ex_reviewer_doesnt_get_mail(self, send_mail_mock):
"""If a reviewer has now left the team don't email them."""
self._create(amo.LOG.REJECT_VERSION, self.reviewer)
# Take his joob!
GroupUser.objects.get(group=Group.objects.get(name='Addon Reviewers'),
user=self.reviewer).delete()
action = amo.LOG.DEVELOPER_REPLY_VERSION
comments = u'Thïs is á reply'
log_and_notify(action, comments, self.developer, self.version)
logs = ActivityLog.objects.filter(action=action.id)
assert len(logs) == 1
recipients = self._recipients(send_mail_mock)
assert len(recipients) == 1
assert self.developer2.email in recipients
assert self.reviewer.email not in recipients
@mock.patch('olympia.activity.utils.send_mail')
def test_review_url_listed(self, send_mail_mock):
# One from the reviewer.
self._create(amo.LOG.REJECT_VERSION, self.reviewer)
# One from the developer. So the developer is on the 'thread'
self._create(amo.LOG.DEVELOPER_REPLY_VERSION, self.developer)
action = amo.LOG.DEVELOPER_REPLY_VERSION
comments = u'Thïs is á reply'
log_and_notify(action, comments, self.developer, self.version)
logs = ActivityLog.objects.filter(action=action.id)
assert len(logs) == 2 # We added one above.
assert logs[0].details['comments'] == u'Thïs is á reply'
assert send_mail_mock.call_count == 2 # One author, one reviewer.
recipients = self._recipients(send_mail_mock)
assert len(recipients) == 2
assert self.reviewer.email in recipients
assert self.developer2.email in recipients
# The developer who sent it doesn't get their email back.
assert self.developer.email not in recipients
self._check_email(send_mail_mock.call_args_list[0],
absolutify(self.addon.get_dev_url('versions')),
'you are listed as an author of this add-on.')
review_url = absolutify(
reverse('reviewers.review', add_prefix=False,
kwargs={'channel': 'listed', 'addon_id': self.addon.pk}))
self._check_email(send_mail_mock.call_args_list[1],
review_url, 'you reviewed this add-on.')
@mock.patch('olympia.activity.utils.send_mail')
def test_review_url_unlisted(self, send_mail_mock):
self.version.update(channel=amo.RELEASE_CHANNEL_UNLISTED)
self.grant_permission(self.reviewer, 'Addons:ReviewUnlisted',
'Addon Reviewers')
# One from the reviewer.
self._create(amo.LOG.COMMENT_VERSION, self.reviewer)
# One from the developer. So the developer is on the 'thread'
self._create(amo.LOG.DEVELOPER_REPLY_VERSION, self.developer)
action = amo.LOG.DEVELOPER_REPLY_VERSION
comments = u'Thïs is á reply'
log_and_notify(action, comments, self.developer, self.version)
logs = ActivityLog.objects.filter(action=action.id)
assert len(logs) == 2 # We added one above.
assert logs[0].details['comments'] == u'Thïs is á reply'
assert send_mail_mock.call_count == 2 # One author, one reviewer.
recipients = self._recipients(send_mail_mock)
assert len(recipients) == 2
assert self.reviewer.email in recipients
assert self.developer2.email in recipients
# The developer who sent it doesn't get their email back.
assert self.developer.email not in recipients
self._check_email(send_mail_mock.call_args_list[0],
absolutify(self.addon.get_dev_url('versions')),
'you are listed as an author of this add-on.')
review_url = absolutify(
reverse('reviewers.review', add_prefix=False,
kwargs={'channel': 'unlisted', 'addon_id': self.addon.pk}))
self._check_email(send_mail_mock.call_args_list[1],
review_url, 'you reviewed this add-on.')
@mock.patch('olympia.activity.utils.send_mail')
def test_from_name_escape(self, send_mail_mock):
self.reviewer.update(display_name='mr "quote" escape')
# One from the reviewer.
self._create(amo.LOG.REJECT_VERSION, self.reviewer)
action = amo.LOG.REVIEWER_REPLY_VERSION
comments = u'Thîs ïs a revïewer replyîng'
log_and_notify(action, comments, self.reviewer, self.version)
sender = r'"mr \"quote\" escape" <notifications@%s>' % (
settings.INBOUND_EMAIL_DOMAIN)
assert sender == send_mail_mock.call_args_list[0][1]['from_email']
@mock.patch('olympia.activity.utils.send_mail')
def test_comment_entity_decode(self, send_mail_mock):
# One from the reviewer.
self._create(amo.LOG.REJECT_VERSION, self.reviewer)
action = amo.LOG.REVIEWER_REPLY_VERSION
comments = u'This email's entities should be decoded'
log_and_notify(action, comments, self.reviewer, self.version)
body = send_mail_mock.call_args_list[1][0][1]
assert "email's entities should be decoded" in body
assert "&" not in body
@mock.patch('olympia.activity.utils.send_mail')
def test_notify_about_previous_activity(self, send_mail_mock):
# Create an activity to use when notifying.
activity = self._create(amo.LOG.REQUEST_INFORMATION, self.reviewer)
notify_about_activity_log(self.addon, self.version, activity)
assert ActivityLog.objects.count() == 1 # No new activity created.
assert send_mail_mock.call_count == 2 # Both authors.
sender = '%s <notifications@%s>' % (
self.reviewer.name, settings.INBOUND_EMAIL_DOMAIN)
assert sender == send_mail_mock.call_args_list[0][1]['from_email']
recipients = self._recipients(send_mail_mock)
assert len(recipients) == 2
assert self.developer.email in recipients
assert self.developer2.email in recipients
# The reviewer who sent it doesn't get their email back.
assert self.reviewer.email not in recipients
self._check_email_info_request(
send_mail_mock.call_args_list[0],
absolutify(self.addon.get_dev_url('versions')),
'you are listed as an author of this add-on.',
days_text=None)
self._check_email_info_request(
send_mail_mock.call_args_list[1],
absolutify(self.addon.get_dev_url('versions')),
'you are listed as an author of this add-on.',
days_text=None)
@pytest.mark.django_db
def test_send_activity_mail():
subject = u'This ïs ã subject'
message = u'And... this ïs a messãge!'
addon = addon_factory()
latest_version = addon.find_latest_version(
channel=amo.RELEASE_CHANNEL_LISTED)
user = user_factory()
recipients = [user, ]
from_email = 'bob@bob.bob'
action = ActivityLog.create(amo.LOG.DEVELOPER_REPLY_VERSION, user=user)
send_activity_mail(
subject, message, latest_version, recipients, from_email, action.id)
assert len(mail.outbox) == 1
assert mail.outbox[0].body == message
assert mail.outbox[0].subject == subject
uuid = latest_version.token.get(user=user).uuid.hex
reference_header = '<{addon}/{version}@{site}>'.format(
addon=latest_version.addon.id, version=latest_version.id,
site=settings.INBOUND_EMAIL_DOMAIN)
message_id = '<{addon}/{version}/{action}@{site}>'.format(
addon=latest_version.addon.id, version=latest_version.id,
action=action.id, site=settings.INBOUND_EMAIL_DOMAIN)
assert mail.outbox[0].extra_headers['In-Reply-To'] == reference_header
assert mail.outbox[0].extra_headers['References'] == reference_header
assert mail.outbox[0].extra_headers['Message-ID'] == message_id
reply_email = 'reviewreply+%s@%s' % (uuid, settings.INBOUND_EMAIL_DOMAIN)
assert mail.outbox[0].reply_to == [reply_email]
| {
"content_hash": "39a6cdf315eaf72ad79c36c9a6fb7a7e",
"timestamp": "",
"source": "github",
"line_count": 761,
"max_line_length": 79,
"avg_line_length": 45.26281208935611,
"alnum_prop": 0.636144578313253,
"repo_name": "atiqueahmedziad/addons-server",
"id": "564194dd4adcf408d5e1a4066ce4e3f718d32b14",
"size": "34509",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/olympia/activity/tests/test_utils.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "810065"
},
{
"name": "Dockerfile",
"bytes": "2868"
},
{
"name": "HTML",
"bytes": "599024"
},
{
"name": "JavaScript",
"bytes": "1070220"
},
{
"name": "Makefile",
"bytes": "820"
},
{
"name": "PLSQL",
"bytes": "1074"
},
{
"name": "PLpgSQL",
"bytes": "2381"
},
{
"name": "Python",
"bytes": "5272277"
},
{
"name": "SQLPL",
"bytes": "559"
},
{
"name": "Shell",
"bytes": "11171"
},
{
"name": "Smarty",
"bytes": "1497"
}
],
"symlink_target": ""
} |
<?php
/**
* TOP API: tmall.traderate.cattags.get request
*
* @author auto create
* @since 1.0, 2014-09-13 16:51:04
*/
class TmallTraderateCattagsGetRequest
{
/**
* 类目ID
**/
private $catId;
private $apiParas = array();
public function setCatId($catId)
{
$this->catId = $catId;
$this->apiParas["cat_id"] = $catId;
}
public function getCatId()
{
return $this->catId;
}
public function getApiMethodName()
{
return "tmall.traderate.cattags.get";
}
public function getApiParas()
{
return $this->apiParas;
}
public function check()
{
RequestCheckUtil::checkNotNull($this->catId,"catId");
}
public function putOtherTextParam($key, $value) {
$this->apiParas[$key] = $value;
$this->$key = $value;
}
}
| {
"content_hash": "e1d6ce7f8324665507d720c7124c8705",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 55,
"avg_line_length": 15.6875,
"alnum_prop": 0.6427622841965471,
"repo_name": "zhangbobell/mallshop",
"id": "5fe731278a649457fae60342ce5f2bd3bf6d0a63",
"size": "757",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "plugins/onekey/taobao/top/request/TmallTraderateCattagsGetRequest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "331783"
},
{
"name": "JavaScript",
"bytes": "1035225"
},
{
"name": "PHP",
"bytes": "4876816"
},
{
"name": "XSLT",
"bytes": "9223"
}
],
"symlink_target": ""
} |
<?php
class Resource
{
private static $caching = false;
private static $extensions_mime = array(
'js' => 'application/x-javascript',
'css' => 'text/css',
'htm' => 'text/html',
'html' => 'text/html',
'xml' => 'application/xml',
'txt' => 'text/plain',
'svg' => 'image/svg+xml',
'eot' => 'application/vnd.ms-fontobject',
'woff' => 'application/font-woff',
'otf' => 'application/octet-stream',
'ttf' => 'application/x-font-ttf',
'bmp' => 'image/bmp',
'png' => 'image/png',
'gif' => 'image/gif',
'jpg' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'tif' => 'image/tiff',
'tiff' => 'image/tiff',
'wav' => 'audio/x-wav',
'avi' => 'video/x-msvideo',
'mp3' => 'audio/mpeg',
'mp4' => 'video/mp4',
'mov' => 'video/quicktime',
'mpe' => 'video/mpeg',
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'swf' => 'application/x-shockwave-flash',
'doc' => 'application/msword',
'ppt' => 'application/vnd.ms-powerpoint',
'xls' => 'application/vnd.ms-excel',
'pdf' => 'application/pdf',
'zip' => 'application/zip',
'rar' => 'application/x-rar-compressed',
'7z' => 'application/x-7z-compressed',
'tar' => 'application/x-tar',
);
public static function setCaching($caching) {
self::$caching = $caching;
}
public static function getMime($extension)
{
return self::$extensions_mime[strtolower($extension)];
}
public static function isResource($extension)
{
return array_key_exists(strtolower($extension), self::$extensions_mime);
}
public static function isImage($extension)
{
$extension = strtolower($extension);
return ($extension == 'png' || $extension == 'gif' || $extension == 'jpg' || $extension == 'jpeg'); // only types that can be resized
}
public static function getMinified($filename)
{
$min = Common::insertMinExtension($filename);
if (is_file($min) && filemtime($filename) < filemtime($min))
return $min;
// SmushIt gif -> png case
if (substr($filename, strrpos($filename, '.') + 1) == 'gif')
{
$min .= '.png';
if (is_file($min) && filemtime($filename) < filemtime($min))
$filename = $min;
}
return $filename;
}
private static function cacheFilename($filenames, $cache_formatted_filename)
{
$latest_modify_time = 0;
foreach ($filenames as $filename)
if (!is_file(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . $filename))
user_error('File "' . $filename . '" could not be found', WARNING);
else
{
$modify_time = filemtime(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . $filename);
$latest_modify_time = max($modify_time, $latest_modify_time);
}
$unique_scriptname = implode($filenames) . $latest_modify_time;
return sprintf($cache_formatted_filename, sha1($unique_scriptname));
}
public static function cacheFiles($filenames, $extension)
{
$starttime_local = explode(' ', microtime());
if ($extension == 'js' || $extension == 'css') // use minified js and css when available
foreach ($filenames as $i => $filename)
if (is_file(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . Common::insertMinExtension($filename)) &&
filemtime(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . $filename) < filemtime(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . Common::insertMinExtension($filename)))
$filenames[$i] = Common::insertMinExtension($filename);
$cache_filename = self::cacheFilename($filenames, 'cache/%s.' . $extension);
if (!is_file(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . $cache_filename) || !self::$caching)
{
$content = '';
foreach ($filenames as $filename)
if (is_file(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . $filename))
$content .= file_get_contents(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . $filename);
file_put_contents(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . $cache_filename, $content);
$endtime_local = explode(' ', microtime());
$totaltime = ($endtime_local[1] + $endtime_local[0] - $starttime_local[1] - $starttime_local[0]);
Log::caching($cache_filename . ' took ' . number_format($totaltime, 4) . 's');
}
return 'res/' . $cache_filename;
}
public static function expandUrl($url)
{
$filename = '';
if (isset($url[1]) && isset($url[2]))
if ($url[1] == 'cache')
$filename = 'cache/' . implode('/', array_splice($url, 2));
else if ($url[1] == 'assets')
$filename = 'assets/' . implode('/', array_splice($url, 2));
else if ($url[1] == 'core')
$filename = 'core/resources/' . implode('/', array_splice($url, 2));
else if ($url[1] == 'module')
$filename = 'modules/' . $url[2] . '/resources/' . implode('/', array_splice($url, 3));
else if ($url[1] == 'theme')
$filename = 'themes/' . $url[2] . '/resources/' . implode('/', array_splice($url, 3));
if (empty($filename))
user_error('Could not expand URL "' . implode('/', $url) . '" to resource', ERROR);
return $filename;
}
public static function imageSize($filename, $max_width, $max_height = 0)
{
if (!is_file(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . $filename))
{
user_error('Could not find "' . $filename . '" to determine new image size', WARNING);
return array(0, 0);
}
list($width, $height, $mime_type, $attribute) = getimagesize(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . $filename);
$new_width = $width;
$new_height = $height;
if ($width > $max_width && $max_width != 0)
{
$new_width = $max_width;
$new_height = floor($height * ($new_width / $width));
if ($new_height > $max_height && $max_height != 0)
{
$new_height = $max_height;
$new_width = floor($width * ($new_height / $height));
}
}
else if ($height > $max_height && $max_height != 0)
{
$new_height = $max_height;
$new_width = floor($width * ($new_height / $height));
if ($new_width > $max_width && $max_width != 0)
{
$new_width = $max_width;
$new_height = floor($height * ($new_width / $width));
}
}
return array($new_width, $new_height);
}
public static function imageSizeAttributes($request_url, $max_width, $max_height = 0)
{
$filename = self::expandUrl($request_url);
list($new_width, $new_height) = self::imageSize($filename, $max_width, $max_height);
return 'width="' . $new_width . '" height="' . $new_height . '"';
}
public static function imageResize($filename, $max_width, $max_height = 0)
{
$starttime_local = explode(' ', microtime());
$cache_filename = 'cache/' . sha1($filename . '_' . $max_width . '_' . $max_height . '_' . filemtime(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . $filename)) . '.png';
if (!is_file(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . $cache_filename))
{
list($width, $height, $mime_type, $attribute) = getimagesize(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . $filename);
list($new_width, $new_height) = self::imageSize($filename, $max_width, $max_height);
switch (image_type_to_mime_type($mime_type))
{
case 'image/jpeg':
$image = imagecreatefromjpeg(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . $filename);
break;
case 'image/png':
$image = imagecreatefrompng(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . $filename);
imagealphablending($image, true);
imagesavealpha($image, true);
break;
case 'image/gif':
$image = imagecreatefromgif(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . $filename);
break;
default:
user_error('Could not resize "' . $filename . '" since it is not a JPEG, PNG or GIF', WARNING);
return $filename;
}
$resizedImage = imagecreatetruecolor($new_width, $new_height);
imagealphablending($resizedImage, false);
imagesavealpha($resizedImage, true);
imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
if (function_exists('imageistruecolor') && !imageistruecolor($image) && imagecolortransparent($image) > 0)
imagetruecolortopalette($resizedImage, false, imagecolorstotal($image));
imagepng($resizedImage, $cache_filename);
imagedestroy($resizedImage);
imagedestroy($image);
$endtime_local = explode(' ', microtime());
$totaltime = ($endtime_local[1] + $endtime_local[0] - $starttime_local[1] - $starttime_local[0]);
Log::caching($cache_filename . ' resize took ' . number_format($totaltime, 4) . 's (' . $width . 'x' . $height . ' to ' . $new_width . 'x' . $new_height . ')');
}
return $cache_filename;
}
}
| {
"content_hash": "822174b01db33afbc4a8c50f69a6b746",
"timestamp": "",
"source": "github",
"line_count": 238,
"max_line_length": 169,
"avg_line_length": 35.088235294117645,
"alnum_prop": 0.6147766734522812,
"repo_name": "tdewolff/Dex",
"id": "b585ec35ef9b07461e344201ee3b7a385b5d1128",
"size": "8351",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "include/resource.class.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "162322"
},
{
"name": "JavaScript",
"bytes": "61473"
},
{
"name": "PHP",
"bytes": "145423"
}
],
"symlink_target": ""
} |
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flowable.variable.service.impl;
import java.util.List;
import java.util.Set;
import org.flowable.common.engine.api.FlowableIllegalArgumentException;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.common.engine.impl.interceptor.CommandExecutor;
import org.flowable.common.engine.impl.query.AbstractQuery;
import org.flowable.variable.api.history.HistoricVariableInstance;
import org.flowable.variable.api.history.HistoricVariableInstanceQuery;
import org.flowable.variable.service.VariableServiceConfiguration;
import org.flowable.variable.service.impl.persistence.entity.HistoricVariableInstanceEntity;
import org.flowable.variable.service.impl.types.CacheableVariable;
import org.flowable.variable.service.impl.types.JPAEntityListVariableType;
import org.flowable.variable.service.impl.types.JPAEntityVariableType;
/**
* @author Joram Barrez
* @author Tijs Rademakers
*/
public class HistoricVariableInstanceQueryImpl extends AbstractQuery<HistoricVariableInstanceQuery, HistoricVariableInstance> implements HistoricVariableInstanceQuery {
private static final long serialVersionUID = 1L;
protected VariableServiceConfiguration variableServiceConfiguration;
protected String id;
protected String taskId;
protected Set<String> taskIds;
protected String executionId;
protected Set<String> executionIds;
protected String processInstanceId;
protected String activityInstanceId;
protected String variableName;
protected String variableNameLike;
protected boolean excludeTaskRelated;
protected boolean excludeVariableInitialization;
protected String scopeId;
protected String subScopeId;
protected String scopeType;
protected QueryVariableValue queryVariableValue;
public HistoricVariableInstanceQueryImpl() {
}
public HistoricVariableInstanceQueryImpl(CommandContext commandContext, VariableServiceConfiguration variableServiceConfiguration) {
super(commandContext);
this.variableServiceConfiguration = variableServiceConfiguration;
}
public HistoricVariableInstanceQueryImpl(CommandExecutor commandExecutor, VariableServiceConfiguration variableServiceConfiguration) {
super(commandExecutor);
this.variableServiceConfiguration = variableServiceConfiguration;
}
@Override
public HistoricVariableInstanceQuery id(String id) {
this.id = id;
return this;
}
@Override
public HistoricVariableInstanceQueryImpl processInstanceId(String processInstanceId) {
if (processInstanceId == null) {
throw new FlowableIllegalArgumentException("processInstanceId is null");
}
this.processInstanceId = processInstanceId;
return this;
}
@Override
public HistoricVariableInstanceQueryImpl executionId(String executionId) {
if (executionId == null) {
throw new FlowableIllegalArgumentException("Execution id is null");
}
this.executionId = executionId;
return this;
}
@Override
public HistoricVariableInstanceQueryImpl executionIds(Set<String> executionIds) {
if (executionIds == null) {
throw new FlowableIllegalArgumentException("executionIds is null");
}
if (executionIds.isEmpty()) {
throw new FlowableIllegalArgumentException("Set of executionIds is empty");
}
this.executionIds = executionIds;
return this;
}
public HistoricVariableInstanceQuery activityInstanceId(String activityInstanceId) {
this.activityInstanceId = activityInstanceId;
return this;
}
@Override
public HistoricVariableInstanceQuery taskId(String taskId) {
if (taskId == null) {
throw new FlowableIllegalArgumentException("taskId is null");
}
if (excludeTaskRelated) {
throw new FlowableIllegalArgumentException("Cannot use taskId together with excludeTaskVariables");
}
this.taskId = taskId;
return this;
}
@Override
public HistoricVariableInstanceQueryImpl taskIds(Set<String> taskIds) {
if (taskIds == null) {
throw new FlowableIllegalArgumentException("taskIds is null");
}
if (taskIds.isEmpty()) {
throw new FlowableIllegalArgumentException("Set of taskIds is empty");
}
if (excludeTaskRelated) {
throw new FlowableIllegalArgumentException("Cannot use taskIds together with excludeTaskVariables");
}
this.taskIds = taskIds;
return this;
}
@Override
public HistoricVariableInstanceQuery excludeTaskVariables() {
if (taskId != null) {
throw new FlowableIllegalArgumentException("Cannot use taskId together with excludeTaskVariables");
}
if (taskIds != null) {
throw new FlowableIllegalArgumentException("Cannot use taskIds together with excludeTaskVariables");
}
excludeTaskRelated = true;
return this;
}
@Override
public HistoricVariableInstanceQuery excludeVariableInitialization() {
excludeVariableInitialization = true;
return this;
}
@Override
public HistoricVariableInstanceQuery variableName(String variableName) {
if (variableName == null) {
throw new FlowableIllegalArgumentException("variableName is null");
}
this.variableName = variableName;
return this;
}
@Override
public HistoricVariableInstanceQuery variableValueEquals(String variableName, Object variableValue) {
if (variableName == null) {
throw new FlowableIllegalArgumentException("variableName is null");
}
if (variableValue == null) {
throw new FlowableIllegalArgumentException("variableValue is null");
}
this.variableName = variableName;
queryVariableValue = new QueryVariableValue(variableName, variableValue, QueryOperator.EQUALS, true);
return this;
}
@Override
public HistoricVariableInstanceQuery variableValueNotEquals(String variableName, Object variableValue) {
if (variableName == null) {
throw new FlowableIllegalArgumentException("variableName is null");
}
if (variableValue == null) {
throw new FlowableIllegalArgumentException("variableValue is null");
}
this.variableName = variableName;
queryVariableValue = new QueryVariableValue(variableName, variableValue, QueryOperator.NOT_EQUALS, true);
return this;
}
@Override
public HistoricVariableInstanceQuery variableValueLike(String variableName, String variableValue) {
if (variableName == null) {
throw new FlowableIllegalArgumentException("variableName is null");
}
if (variableValue == null) {
throw new FlowableIllegalArgumentException("variableValue is null");
}
this.variableName = variableName;
queryVariableValue = new QueryVariableValue(variableName, variableValue, QueryOperator.LIKE, true);
return this;
}
@Override
public HistoricVariableInstanceQuery variableValueLikeIgnoreCase(String variableName, String variableValue) {
if (variableName == null) {
throw new FlowableIllegalArgumentException("variableName is null");
}
if (variableValue == null) {
throw new FlowableIllegalArgumentException("variableValue is null");
}
this.variableName = variableName;
queryVariableValue = new QueryVariableValue(variableName, variableValue.toLowerCase(), QueryOperator.LIKE_IGNORE_CASE, true);
return this;
}
@Override
public HistoricVariableInstanceQuery variableNameLike(String variableNameLike) {
if (variableNameLike == null) {
throw new FlowableIllegalArgumentException("variableNameLike is null");
}
this.variableNameLike = variableNameLike;
return this;
}
@Override
public HistoricVariableInstanceQuery scopeId(String scopeId) {
this.scopeId = scopeId;
return this;
}
@Override
public HistoricVariableInstanceQuery subScopeId(String subScopeId) {
this.subScopeId = subScopeId;
return this;
}
@Override
public HistoricVariableInstanceQuery scopeType(String scopeType) {
this.scopeType = scopeType;
return this;
}
protected void ensureVariablesInitialized() {
if (this.queryVariableValue != null) {
queryVariableValue.initialize(variableServiceConfiguration);
}
}
@Override
public long executeCount(CommandContext commandContext) {
ensureVariablesInitialized();
return variableServiceConfiguration.getHistoricVariableInstanceEntityManager().findHistoricVariableInstanceCountByQueryCriteria(this);
}
@Override
public List<HistoricVariableInstance> executeList(CommandContext commandContext) {
ensureVariablesInitialized();
List<HistoricVariableInstance> historicVariableInstances = variableServiceConfiguration.getHistoricVariableInstanceEntityManager().findHistoricVariableInstancesByQueryCriteria(this);
if (!excludeVariableInitialization) {
for (HistoricVariableInstance historicVariableInstance : historicVariableInstances) {
if (historicVariableInstance instanceof HistoricVariableInstanceEntity) {
HistoricVariableInstanceEntity variableEntity = (HistoricVariableInstanceEntity) historicVariableInstance;
if (variableEntity.getVariableType() != null) {
variableEntity.getValue();
// make sure JPA entities are cached for later retrieval
if (JPAEntityVariableType.TYPE_NAME.equals(variableEntity.getVariableType().getTypeName()) || JPAEntityListVariableType.TYPE_NAME.equals(variableEntity.getVariableType().getTypeName())) {
((CacheableVariable) variableEntity.getVariableType()).setForceCacheable(true);
}
}
}
}
}
return historicVariableInstances;
}
// order by
// /////////////////////////////////////////////////////////////////
@Override
public HistoricVariableInstanceQuery orderByProcessInstanceId() {
orderBy(HistoricVariableInstanceQueryProperty.PROCESS_INSTANCE_ID);
return this;
}
@Override
public HistoricVariableInstanceQuery orderByVariableName() {
orderBy(HistoricVariableInstanceQueryProperty.VARIABLE_NAME);
return this;
}
// getters and setters
// //////////////////////////////////////////////////////
public String getProcessInstanceId() {
return processInstanceId;
}
public String getTaskId() {
return taskId;
}
public String getActivityInstanceId() {
return activityInstanceId;
}
public boolean getExcludeTaskRelated() {
return excludeTaskRelated;
}
public String getVariableName() {
return variableName;
}
public String getVariableNameLike() {
return variableNameLike;
}
public String getScopeId() {
return scopeId;
}
public String getSubScopeId() {
return subScopeId;
}
public String getScopeType() {
return scopeType;
}
public QueryVariableValue getQueryVariableValue() {
return queryVariableValue;
}
}
| {
"content_hash": "74247b84eb64f26169b4d57d8b0b3071",
"timestamp": "",
"source": "github",
"line_count": 338,
"max_line_length": 211,
"avg_line_length": 36.25739644970414,
"alnum_prop": 0.6931048551611587,
"repo_name": "paulstapleton/flowable-engine",
"id": "b88c03938f9ec7a680632ec9960353b2c6eeb380",
"size": "12255",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/flowable-variable-service/src/main/java/org/flowable/variable/service/impl/HistoricVariableInstanceQueryImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "166"
},
{
"name": "CSS",
"bytes": "688913"
},
{
"name": "Dockerfile",
"bytes": "6367"
},
{
"name": "Groovy",
"bytes": "482"
},
{
"name": "HTML",
"bytes": "1100650"
},
{
"name": "Java",
"bytes": "33678803"
},
{
"name": "JavaScript",
"bytes": "12395741"
},
{
"name": "PLSQL",
"bytes": "109354"
},
{
"name": "PLpgSQL",
"bytes": "11691"
},
{
"name": "SQLPL",
"bytes": "1265"
},
{
"name": "Shell",
"bytes": "19145"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
Mycologia 89(4): 625 (1997)
#### Original name
Hygrocybe pakelo Desjardin & Hemmes
### Remarks
null | {
"content_hash": "955aac41c9aab1ef6679b511d11dfdf8",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 35,
"avg_line_length": 12.538461538461538,
"alnum_prop": 0.7055214723926381,
"repo_name": "mdoering/backbone",
"id": "69d5358874e15cebea84bb7cb84ea03666da5652",
"size": "222",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Hygrophoraceae/Hygrocybe/Hygrocybe pakelo/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
/* eslint-disable func-names, space-before-function-paren, no-var, prefer-rest-params, wrap-iife, max-len, one-var, one-var-declaration-per-line, quotes, prefer-template, newline-per-chained-call, comma-dangle, new-cap, no-else-return, consistent-return */
/* global FilesCommentButton */
(function() {
var bind = function(fn, me) { return function() { return fn.apply(me, arguments); }; };
this.FilesCommentButton = (function() {
var COMMENT_BUTTON_CLASS, COMMENT_BUTTON_TEMPLATE, DEBOUNCE_TIMEOUT_DURATION, EMPTY_CELL_CLASS, LINE_COLUMN_CLASSES, LINE_CONTENT_CLASS, LINE_HOLDER_CLASS, LINE_NUMBER_CLASS, OLD_LINE_CLASS, TEXT_FILE_SELECTOR, UNFOLDABLE_LINE_CLASS;
COMMENT_BUTTON_CLASS = '.add-diff-note';
COMMENT_BUTTON_TEMPLATE = _.template('<button name="button" type="submit" class="btn <%- COMMENT_BUTTON_CLASS %> js-add-diff-note-button" title="Add a comment to this line"><i class="fa fa-comment-o"></i></button>');
LINE_HOLDER_CLASS = '.line_holder';
LINE_NUMBER_CLASS = 'diff-line-num';
LINE_CONTENT_CLASS = 'line_content';
UNFOLDABLE_LINE_CLASS = 'js-unfold';
EMPTY_CELL_CLASS = 'empty-cell';
OLD_LINE_CLASS = 'old_line';
LINE_COLUMN_CLASSES = "." + LINE_NUMBER_CLASS + ", .line_content";
TEXT_FILE_SELECTOR = '.text-file';
DEBOUNCE_TIMEOUT_DURATION = 100;
function FilesCommentButton(filesContainerElement) {
var debounce;
this.filesContainerElement = filesContainerElement;
this.destroy = bind(this.destroy, this);
this.render = bind(this.render, this);
this.VIEW_TYPE = $('input#view[type=hidden]').val();
debounce = _.debounce(this.render, DEBOUNCE_TIMEOUT_DURATION);
$(this.filesContainerElement).off('mouseover', LINE_COLUMN_CLASSES).off('mouseleave', LINE_COLUMN_CLASSES).on('mouseover', LINE_COLUMN_CLASSES, debounce).on('mouseleave', LINE_COLUMN_CLASSES, this.destroy);
}
FilesCommentButton.prototype.render = function(e) {
var $currentTarget, buttonParentElement, lineContentElement, textFileElement;
$currentTarget = $(e.currentTarget);
buttonParentElement = this.getButtonParent($currentTarget);
if (!this.validateButtonParent(buttonParentElement)) return;
lineContentElement = this.getLineContent($currentTarget);
if (!this.validateLineContent(lineContentElement)) return;
textFileElement = this.getTextFileElement($currentTarget);
buttonParentElement.append(this.buildButton({
noteableType: textFileElement.attr('data-noteable-type'),
noteableID: textFileElement.attr('data-noteable-id'),
commitID: textFileElement.attr('data-commit-id'),
noteType: lineContentElement.attr('data-note-type'),
position: lineContentElement.attr('data-position'),
lineType: lineContentElement.attr('data-line-type'),
discussionID: lineContentElement.attr('data-discussion-id'),
lineCode: lineContentElement.attr('data-line-code')
}));
};
FilesCommentButton.prototype.destroy = function(e) {
if (this.isMovingToSameType(e)) {
return;
}
$(COMMENT_BUTTON_CLASS, this.getButtonParent($(e.currentTarget))).remove();
};
FilesCommentButton.prototype.buildButton = function(buttonAttributes) {
var initializedButtonTemplate;
initializedButtonTemplate = COMMENT_BUTTON_TEMPLATE({
COMMENT_BUTTON_CLASS: COMMENT_BUTTON_CLASS.substr(1)
});
return $(initializedButtonTemplate).attr({
'data-noteable-type': buttonAttributes.noteableType,
'data-noteable-id': buttonAttributes.noteableID,
'data-commit-id': buttonAttributes.commitID,
'data-note-type': buttonAttributes.noteType,
'data-line-code': buttonAttributes.lineCode,
'data-position': buttonAttributes.position,
'data-discussion-id': buttonAttributes.discussionID,
'data-line-type': buttonAttributes.lineType
});
};
FilesCommentButton.prototype.getTextFileElement = function(hoveredElement) {
return $(hoveredElement.closest(TEXT_FILE_SELECTOR));
};
FilesCommentButton.prototype.getLineContent = function(hoveredElement) {
if (hoveredElement.hasClass(LINE_CONTENT_CLASS)) {
return hoveredElement;
}
if (this.VIEW_TYPE === 'inline') {
return $(hoveredElement).closest(LINE_HOLDER_CLASS).find("." + LINE_CONTENT_CLASS);
} else {
return $(hoveredElement).next("." + LINE_CONTENT_CLASS);
}
};
FilesCommentButton.prototype.getButtonParent = function(hoveredElement) {
if (this.VIEW_TYPE === 'inline') {
if (hoveredElement.hasClass(OLD_LINE_CLASS)) {
return hoveredElement;
}
return hoveredElement.parent().find("." + OLD_LINE_CLASS);
} else {
if (hoveredElement.hasClass(LINE_NUMBER_CLASS)) {
return hoveredElement;
}
return $(hoveredElement).prev("." + LINE_NUMBER_CLASS);
}
};
FilesCommentButton.prototype.isMovingToSameType = function(e) {
var newButtonParent;
newButtonParent = this.getButtonParent($(e.toElement));
if (!newButtonParent) {
return false;
}
return newButtonParent.is(this.getButtonParent($(e.currentTarget)));
};
FilesCommentButton.prototype.validateButtonParent = function(buttonParentElement) {
return !buttonParentElement.hasClass(EMPTY_CELL_CLASS) && !buttonParentElement.hasClass(UNFOLDABLE_LINE_CLASS) && $(COMMENT_BUTTON_CLASS, buttonParentElement).length === 0;
};
FilesCommentButton.prototype.validateLineContent = function(lineContentElement) {
return lineContentElement.attr('data-discussion-id') && lineContentElement.attr('data-discussion-id') !== '';
};
return FilesCommentButton;
})();
$.fn.filesCommentButton = function() {
if (!(this && (this.parent().data('can-create-note') != null))) {
return;
}
return this.each(function() {
if (!$.data(this, 'filesCommentButton')) {
return $.data(this, 'filesCommentButton', new FilesCommentButton($(this)));
}
});
};
}).call(this);
| {
"content_hash": "3fd991f275268d7c1dbca5c295e0e37f",
"timestamp": "",
"source": "github",
"line_count": 147,
"max_line_length": 256,
"avg_line_length": 41.78231292517007,
"alnum_prop": 0.6797460110713123,
"repo_name": "openwide-java/gitlabhq",
"id": "895a872568dff78e99e2b1a3dd466031608a3c6e",
"size": "6142",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/assets/javascripts/files_comment_button.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "453942"
},
{
"name": "Gherkin",
"bytes": "144175"
},
{
"name": "HTML",
"bytes": "937606"
},
{
"name": "JavaScript",
"bytes": "1166895"
},
{
"name": "Ruby",
"bytes": "8486818"
},
{
"name": "Shell",
"bytes": "24191"
}
],
"symlink_target": ""
} |
package com.melay.sync.data;
import android.util.Log;
import com.melay.sync.local.LocalDatabase;
import com.raizlabs.android.dbflow.annotation.Column;
import com.raizlabs.android.dbflow.annotation.ColumnIgnore;
import com.raizlabs.android.dbflow.annotation.PrimaryKey;
import com.raizlabs.android.dbflow.annotation.Table;
import java.util.Arrays;
import java.util.Date;
/**
* Created by matth on 1/28/2018.
*
* The base class for a message that is stored locally
*/
@Table(database = LocalDatabase.class)
public class MelayMessage extends Encryptable implements Syncable {
@PrimaryKey
int id; //the message ID
@Column
int threadId; //the thread that it's a part of
@Column
String from; //where the message is to- if we sent this, it is blank
@Column(typeConverter=StringArrayConverter.class)
String[] to; //if it's to anyone else (numerical order) our phone number is never in this
@Column
String body; //the actual message
@Column
Date sent; //when it was sent
//not encrypted
@Column
boolean unsent = false;
@Column
boolean read = false; //if the user has read it
@Column
boolean incoming = false; //if the user sent it
@Column
DataStatus status = DataStatus.ON_DEVICE; //this should not be encrypted
//----------------------
@Override
public void Encrypt(String key) {
//if we are already encrypted, don't mess with it
if (encrypted) return;
//encrypt the various methods on the data
from = this.EncryptString(from, key);
body = this.EncryptString(body, key);
to = this.EncryptString(to, key);
encrypted = true;
}
@Override
public String toString() {
return "MelayMessage{" +
"id=" + id +
", threadId=" + threadId +
", from='" + from + '\'' +
", to=" + Arrays.toString(to) +
", encrypted=" + encrypted +
", body='" + body + '\'' +
", sent=" + sent +
", read=" + read +
", incoming=" + incoming +
", status=" + status +
", IV="+iv+
'}';
}
@Override
public boolean Decrypt(String key) {
encrypted = false;
return false;
}
static String TAG = MelayMessage.class.getCanonicalName();
//Default constructor, do not use
public MelayMessage(){
//set everything to zero
this(0,0,"NONE","NONE",new Date(),false,false);
}
public MelayMessage(int anInt, int deviceID, String from, String body, Date date, int seenInt, boolean incoming) {
this(anInt, deviceID, from, body, date, true, incoming);
read = (seenInt == 1);
}
//creates a new message
public MelayMessage(int anInt, int deviceID, String from, String body, Date date, boolean incoming) {
this(anInt, deviceID, from, body, date, true, incoming);
}
//creates a new message
public MelayMessage(int anInt, int deviceID, String from, String body, Date date, boolean read, boolean incoming) {
id = deviceID;
this.from = from;
this.body = body;
Log.i(TAG, "Created a new message from" + from + " at index " + deviceID + " string1: " + body + " : " + anInt);
sent = date;
this.incoming = incoming;
}
public void MarkRead(boolean read) {
this.read = read;
}
@Override
public void UpdateState(DataStatus newState) {
status = newState;
}
@Override
public DataStatus GetState() {
return status;
}
@Override
public boolean isDataEqual(Object o) {
MelayMessage other = (MelayMessage) o;
if (other == null) return false;
if (other.getId() != id) return false;
if (other.isRead() != read) return false;
if (other.sent != sent) return false;
//don't compare body since that's possibly encrypted
return true;
}
//GETTERS AND SETTERS
public boolean isRead() {
return read;
}
public int getId() {
return id;
}
}
| {
"content_hash": "3ab697d08edd7a90f11f3c61399aadc5",
"timestamp": "",
"source": "github",
"line_count": 150,
"max_line_length": 120,
"avg_line_length": 27.773333333333333,
"alnum_prop": 0.5940950552088334,
"repo_name": "matthewfcarlson/Melay",
"id": "36a341d743f3472b1744c82e3fbbf1e7b2e8b3b7",
"size": "4166",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/android/app/src/main/java/com/melay/sync/data/MelayMessage.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1186"
},
{
"name": "HTML",
"bytes": "4423"
},
{
"name": "Java",
"bytes": "1427890"
},
{
"name": "JavaScript",
"bytes": "522938"
},
{
"name": "Objective-C",
"bytes": "9256"
},
{
"name": "Python",
"bytes": "3440"
}
],
"symlink_target": ""
} |
package org.openspaces.admin.internal.pu.events;
import org.openspaces.admin.internal.admin.InternalAdmin;
import org.openspaces.admin.internal.pu.InternalProcessingUnits;
import org.openspaces.admin.internal.support.GroovyHelper;
import org.openspaces.admin.pu.ProcessingUnit;
import org.openspaces.admin.pu.events.ProcessingUnitRemovedEventListener;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* @author kimchy
*/
public class DefaultProcessingUnitRemovedEventManager implements InternalProcessingUnitRemovedEventManager {
private final InternalProcessingUnits processingUnits;
private final InternalAdmin admin;
private final List<ProcessingUnitRemovedEventListener> listeners = new CopyOnWriteArrayList<ProcessingUnitRemovedEventListener>();
public DefaultProcessingUnitRemovedEventManager(InternalProcessingUnits processingUnits) {
this.processingUnits = processingUnits;
this.admin = (InternalAdmin) processingUnits.getAdmin();
}
public void processingUnitRemoved(final ProcessingUnit processingUnit) {
for (final ProcessingUnitRemovedEventListener listener : listeners) {
admin.pushScheduleMonitorCorrelatedEvent(listener, new Runnable() {
public void run() {
listener.processingUnitRemoved(processingUnit);
}
});
}
}
public void add(ProcessingUnitRemovedEventListener eventListener) {
listeners.add(eventListener);
}
public void remove(ProcessingUnitRemovedEventListener eventListener) {
listeners.remove(eventListener);
}
public void plus(Object eventListener) {
if (GroovyHelper.isClosure(eventListener)) {
add(new ClosureProcessingUnitRemovedEventListener(eventListener));
} else {
add((ProcessingUnitRemovedEventListener) eventListener);
}
}
public void leftShift(Object eventListener) {
plus(eventListener);
}
public void minus(Object eventListener) {
if (GroovyHelper.isClosure(eventListener)) {
remove(new ClosureProcessingUnitRemovedEventListener(eventListener));
} else {
remove((ProcessingUnitRemovedEventListener) eventListener);
}
}
public void rightShift(Object eventListener) {
minus(eventListener);
}
}
| {
"content_hash": "9a7de1b3691fa2f38fb924c81a570885",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 134,
"avg_line_length": 34.114285714285714,
"alnum_prop": 0.7278056951423786,
"repo_name": "Gigaspaces/xap-openspaces",
"id": "00f58ba6847fc6d294561b78679db46edc088a1f",
"size": "3192",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/openspaces/admin/internal/pu/events/DefaultProcessingUnitRemovedEventManager.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1107"
},
{
"name": "Groovy",
"bytes": "5372"
},
{
"name": "HTML",
"bytes": "13501"
},
{
"name": "Java",
"bytes": "8666667"
},
{
"name": "Shell",
"bytes": "917"
}
],
"symlink_target": ""
} |
module.exports = function() {
return {
basePath: '../',
frameworks: ['mocha', 'chai', 'sinon', 'chai-sinon'],
reporters: ['progress', 'html'],
browsers: ['PhantomJS'],
autoWatch: true,
port: 8080,
// these are default values anyway
singleRun: false,
colors: true,
files : [
//3rd Party Code
'app/bower_components/angular/angular.js',
'app/bower_components/angular-mocks/angular-mocks.js',
//App-specific Code
'app/scripts/app.js',
'app/scripts/services/**/*.js',
//Test-Specific Code
'node_modules/bardjs/dist/bard.js',
'node_modules/chai/chai.js',
'test/lib/chai-should.js',
'test/lib/chai-expect.js',
'test/lib/chai-assert.js'
]
}
};
| {
"content_hash": "506073e5775088dbd7a8da01feb29db7",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 60,
"avg_line_length": 23.78125,
"alnum_prop": 0.5834428383705651,
"repo_name": "sensebox/OpenSenseMap",
"id": "3cada82452ff49cccea5942d93f6fde17e47218c",
"size": "761",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "test/karma-shared.conf.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "24139"
},
{
"name": "CSS",
"bytes": "16995"
},
{
"name": "HTML",
"bytes": "47839"
},
{
"name": "JavaScript",
"bytes": "111553"
}
],
"symlink_target": ""
} |
IsaPlanner is a proof planner for [Isabele](http://isabelle.in.tum.de/). It
facilitates the encoding of reasoning techniques and their application to prove
theorems in Isabelle. In particular, it provides an inductive prover based on
Rippling, as well as automatic theory formation tools (IsaCoSy and IsaScheme)
IsaPlanner is written in Isabelle/StandardML (based on
[PolyML](http://www.polyml.org/)
The old IsaPlanner homepage is here: http://dream.inf.ed.ac.uk/projects/isaplanner
See the INSTALL file for more information on how to install
IsaPlanner. (briefly, run the command "isabelle make" and you are
done)
You want to be familiar with [Isabele](http://isabelle.in.tum.de/) before trying
to use IsaPlanner. :)
This version of IsaPlanner is intended to work with Isabelle 2015 and requires that you have a clone/download of the [Isabelle-2015 branch of isaplib](https://github.com/iislucas/isaplib/tree/Isabelle-2015) in your Isabelle contrib directory.
## Quickly playing with IsaPlanner
Simply open the file `quicktest.thy` in Isabelle 2015.
## Setup IsaPlanner Heap
Change into the IsaPlanner directory.
```
cd IsaPlanner
export ISAPLANNER_DIRECTORY=$(pwd)
```
To use IsaPlanner, you should build the heap from IsaPlanner dir by running the command:
```
isabelle build -d $ISAPLANNER_DIRECTORY -b HOL-IsaPlannerSession
```
where `ISAPLANNER_DIRECTORY` is dierctory containing IsaPlanner
(optionally relative to the current directory), that was set above.
This will build and ML heap (also sometimes referred to as an Isabelle Session)
called "HOL-IsaPlannerSession" containing Isabelle/HOL with IsaPlanner tools
loaded in a theory "IsaP". Now you can make a new theory that imports "IsaP"
and in that theory you can use IsaPlanner and IsaCoSy.
For example, start Isabelle with the Isabelle session 'HOL-IsaPlannerSession'
using this command:
```
isabelle jedit -l HOL-IsaPlannerSession -d $ISAPLANNER_DIRECTORY
```
## Running tests
```
isabelle build -d $ISAPLANNER_DIRECTORY -b IsaPlanner-Test
```
## Developing new techniques
You'll be doing ML programming in Isabelle, so make sure to have the
[Isabelle CookBook](http://www.dcs.kcl.ac.uk/staff/urbanc/Cookbook/) handy.
TODO: complete this section. :)
## Using the Docker environment
Build the IsaPlanner docker image:
```
docker build -t theorymine/isaplanner:2015.0.2 .
```
Start a new docker container from the image running a bash shell:
```
docker run -i -t theorymine/isaplanner:2015.0.2 /bin/bash
```
| {
"content_hash": "e9dba82b8e757bd855ac5819252a0671",
"timestamp": "",
"source": "github",
"line_count": 86,
"max_line_length": 242,
"avg_line_length": 29.11627906976744,
"alnum_prop": 0.7723642172523961,
"repo_name": "TheoryMine/IsaPlanner",
"id": "d0e1b3b7cad3bbdc63accfd1bd9cbc0c0285bd40",
"size": "2549",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Isabelle",
"bytes": "398870"
},
{
"name": "OCaml",
"bytes": "62411"
},
{
"name": "Perl",
"bytes": "188"
},
{
"name": "Shell",
"bytes": "1026"
},
{
"name": "Standard ML",
"bytes": "2166678"
},
{
"name": "TeX",
"bytes": "85677"
}
],
"symlink_target": ""
} |
// Module: base64-js@1.1.2
// License: MIT
//
// Module: bluebird@3.4.7
// License: MIT
//
// Module: buffer-shims@1.0.0
// License: MIT
//
// Module: buffer@4.6.0
// License: MIT
//
// Module: core-util-is@1.0.2
// License: MIT
//
// Module: events@1.1.0
// License: MIT
//
// Module: ieee754@1.1.6
// License: MIT
//
// Module: inherits@2.0.1
// License: ISC
//
// Module: isarray@1.0.0
// License: MIT
//
// Module: isarray@1.0.0
// License: MIT
//
// Module: jszip@2.5.0
// License: MIT or GPLv3
//
// Module: lodash@3.10.1
// License: MIT
//
// Module: lop@0.4.0
// License: BSD
//
// Module: mammoth@1.4.3
// License: BSD-2-Clause
//
// Module: option@0.2.3
// License: BSD
//
// Module: pako@0.2.7
// License: MIT
//
// Module: path-browserify@0.0.0
// License: MIT
//
// Module: process-nextick-args@1.0.7
// License: MIT
//
// Module: process@0.11.5
// License: MIT
//
// Module: readable-stream@2.1.4
// License: MIT
//
// Module: sax@1.1.6
// License: ISC
//
// Module: stream-browserify@2.0.1
// License: MIT
//
// Module: string_decoder@0.10.31
// License: MIT
//
// Module: underscore@1.4.4
// License: MIT
//
// Module: underscore@1.8.3
// License: MIT
//
// Module: util-deprecate@1.0.2
// License: MIT
//
// Module: util@0.10.3
// License: MIT
//
// Module: xmlbuilder@2.6.5
// License: MIT
//
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.mammoth = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var promises = require("../../lib/promises");
exports.Files = Files;
function Files() {
function read(uri) {
return promises.reject(new Error("could not open external image: '" + uri + "'\ncannot open linked files from a web browser"));
}
return {
read: read
};
}
},{"../../lib/promises":23}],2:[function(require,module,exports){
var promises = require("../lib/promises");
var zipfile = require("../lib/zipfile");
exports.openZip = openZip;
function openZip(options) {
if (options.arrayBuffer) {
return promises.resolve(zipfile.openArrayBuffer(options.arrayBuffer));
} else {
return promises.reject(new Error("Could not find file in options"));
}
}
},{"../lib/promises":23,"../lib/zipfile":38}],3:[function(require,module,exports){
var _ = require("underscore");
var promises = require("./promises");
var documents = require("./documents");
var htmlPaths = require("./styles/html-paths");
var results = require("./results");
var images = require("./images");
var Html = require("./html");
var writers = require("./writers");
exports.DocumentConverter = DocumentConverter;
function DocumentConverter(options) {
return {
convertToHtml: function(element) {
var comments = _.indexBy(
element.type === documents.types.document ? element.comments : [],
"commentId"
);
var conversion = new DocumentConversion(options, comments);
return conversion.convertToHtml(element);
}
};
}
function DocumentConversion(options, comments) {
var noteNumber = 1;
var noteReferences = [];
var referencedComments = [];
options = _.extend({ignoreEmptyParagraphs: true}, options);
var idPrefix = options.idPrefix === undefined ? "" : options.idPrefix;
var ignoreEmptyParagraphs = options.ignoreEmptyParagraphs;
var defaultParagraphStyle = htmlPaths.topLevelElement("p");
var styleMap = options.styleMap || [];
function convertToHtml(document) {
var messages = [];
var html = elementToHtml(document, messages, {});
var deferredNodes = [];
walkHtml(html, function(node) {
if (node.type === "deferred") {
deferredNodes.push(node);
}
});
var deferredValues = {};
return promises.mapSeries(deferredNodes, function(deferred) {
return deferred.value().then(function(value) {
deferredValues[deferred.id] = value;
});
}).then(function() {
function replaceDeferred(nodes) {
return flatMap(nodes, function(node) {
if (node.type === "deferred") {
return deferredValues[node.id];
} else if (node.children) {
return [
_.extend({}, node, {
children: replaceDeferred(node.children)
})
];
} else {
return [node];
}
});
}
var writer = writers.writer({
prettyPrint: options.prettyPrint,
outputFormat: options.outputFormat
});
Html.write(writer, Html.simplify(replaceDeferred(html)));
return new results.Result(writer.asString(), messages);
});
}
function convertElements(elements, messages, options) {
return flatMap(elements, function(element) {
return elementToHtml(element, messages, options);
});
}
function elementToHtml(element, messages, options) {
if (!options) {
throw new Error("options not set");
}
var handler = elementConverters[element.type];
if (handler) {
return handler(element, messages, options);
} else {
return [];
}
}
function convertParagraph(element, messages, options) {
return htmlPathForParagraph(element, messages).wrap(function() {
var content = convertElements(element.children, messages, options);
if (ignoreEmptyParagraphs) {
return content;
} else {
return [Html.forceWrite].concat(content);
}
});
}
function htmlPathForParagraph(element, messages) {
var style = findStyle(element);
if (style) {
return style.to;
} else {
if (element.styleId) {
messages.push(unrecognisedStyleWarning("paragraph", element));
}
return defaultParagraphStyle;
}
}
function convertRun(run, messages, options) {
var nodes = function() {
return convertElements(run.children, messages, options);
};
var paths = [];
if (run.isSmallCaps) {
paths.push(findHtmlPathForRunProperty("smallCaps"));
}
if (run.isStrikethrough) {
paths.push(findHtmlPathForRunProperty("strikethrough", "s"));
}
if (run.isUnderline) {
paths.push(findHtmlPathForRunProperty("underline"));
}
if (run.verticalAlignment === documents.verticalAlignment.subscript) {
paths.push(htmlPaths.element("sub", {}, {fresh: false}));
}
if (run.verticalAlignment === documents.verticalAlignment.superscript) {
paths.push(htmlPaths.element("sup", {}, {fresh: false}));
}
if (run.isItalic) {
paths.push(findHtmlPathForRunProperty("italic", "em"));
}
if (run.isBold) {
paths.push(findHtmlPathForRunProperty("bold", "strong"));
}
var stylePath = htmlPaths.empty;
var style = findStyle(run);
if (style) {
stylePath = style.to;
} else if (run.styleId) {
messages.push(unrecognisedStyleWarning("run", run));
}
paths.push(stylePath);
paths.forEach(function(path) {
nodes = path.wrap.bind(path, nodes);
});
return nodes();
}
function findHtmlPathForRunProperty(elementType, defaultTagName) {
var path = findHtmlPath({type: elementType});
if (path) {
return path;
} else if (defaultTagName) {
return htmlPaths.element(defaultTagName, {}, {fresh: false});
} else {
return htmlPaths.empty;
}
}
function findHtmlPath(element, defaultPath) {
var style = findStyle(element);
return style ? style.to : defaultPath;
}
function findStyle(element) {
for (var i = 0; i < styleMap.length; i++) {
if (styleMap[i].from.matches(element)) {
return styleMap[i];
}
}
}
function recoveringConvertImage(convertImage) {
return function(image, messages) {
return promises.attempt(function() {
return convertImage(image, messages);
}).caught(function(error) {
messages.push(results.error(error));
return [];
});
};
}
function noteHtmlId(note) {
return referentHtmlId(note.noteType, note.noteId);
}
function noteRefHtmlId(note) {
return referenceHtmlId(note.noteType, note.noteId);
}
function referentHtmlId(referenceType, referenceId) {
return htmlId(referenceType + "-" + referenceId);
}
function referenceHtmlId(referenceType, referenceId) {
return htmlId(referenceType + "-ref-" + referenceId);
}
function htmlId(suffix) {
return idPrefix + suffix;
}
var defaultTablePath = htmlPaths.elements([
htmlPaths.element("table", {}, {fresh: true})
]);
function convertTable(element, messages, options) {
return findHtmlPath(element, defaultTablePath).wrap(function() {
return convertTableChildren(element, messages, options);
});
}
function convertTableChildren(element, messages, options) {
var bodyIndex = _.findIndex(element.children, function(child) {
return !child.type === documents.types.tableRow || !child.isHeader;
});
if (bodyIndex === -1) {
bodyIndex = element.children.length;
}
var children;
if (bodyIndex === 0) {
children = convertElements(
element.children,
messages,
_.extend({}, options, {isTableHeader: false})
);
} else {
var headRows = convertElements(
element.children.slice(0, bodyIndex),
messages,
_.extend({}, options, {isTableHeader: true})
);
var bodyRows = convertElements(
element.children.slice(bodyIndex),
messages,
_.extend({}, options, {isTableHeader: false})
);
children = [
Html.freshElement("thead", {}, headRows),
Html.freshElement("tbody", {}, bodyRows)
];
}
return [Html.forceWrite].concat(children);
}
function convertTableRow(element, messages, options) {
return wrapChildrenInFreshElement(element, "tr", messages, options);
}
function convertTableCell(element, messages, options) {
var tagName = options.isTableHeader ? "th" : "td";
var children = convertElements(element.children, messages, options);
var attributes = {};
if (element.colSpan !== 1) {
attributes.colspan = element.colSpan.toString();
}
if (element.rowSpan !== 1) {
attributes.rowspan = element.rowSpan.toString();
}
return [
Html.freshElement(tagName, attributes, [Html.forceWrite].concat(children))
];
}
function convertCommentReference(reference, messages, options) {
return findHtmlPath(reference, htmlPaths.ignore).wrap(function() {
var comment = comments[reference.commentId];
var count = referencedComments.length + 1;
var label = "[" + commentAuthorLabel(comment) + count + "]";
referencedComments.push({label: label, comment: comment});
// TODO: remove duplication with note references
return [
Html.freshElement("a", {
href: "#" + referentHtmlId("comment", reference.commentId),
id: referenceHtmlId("comment", reference.commentId)
}, [Html.text(label)])
];
});
}
function convertComment(referencedComment, messages, options) {
// TODO: remove duplication with note references
var label = referencedComment.label;
var comment = referencedComment.comment;
var body = convertElements(comment.body, messages, options).concat([
Html.nonFreshElement("p", {}, [
Html.text(" "),
Html.freshElement("a", {"href": "#" + referenceHtmlId("comment", comment.commentId)}, [
Html.text("↑")
])
])
]);
return [
Html.freshElement(
"dt",
{"id": referentHtmlId("comment", comment.commentId)},
[Html.text("Comment " + label)]
),
Html.freshElement("dd", {}, body)
];
}
function convertBreak(element, messages, options) {
return htmlPathForBreak(element).wrap(function() {
return [];
});
}
function htmlPathForBreak(element) {
var style = findStyle(element);
if (style) {
return style.to;
} else if (element.breakType === "line") {
return htmlPaths.topLevelElement("br");
} else {
return htmlPaths.empty;
}
}
function wrapChildrenInFreshElement(element, wrapElementName, messages, options) {
var children = convertElements(element.children, messages, options);
return [
Html.freshElement(wrapElementName, {}, [Html.forceWrite].concat(children))
];
}
var elementConverters = {
"document": function(document, messages, options) {
var children = convertElements(document.children, messages, options);
var notes = noteReferences.map(function(noteReference) {
return document.notes.resolve(noteReference);
});
var notesNodes = convertElements(notes, messages, options);
return children.concat([
Html.freshElement("ol", {}, notesNodes),
Html.freshElement("dl", {}, flatMap(referencedComments, function(referencedComment) {
return convertComment(referencedComment, messages, options);
}))
]);
},
"paragraph": convertParagraph,
"run": convertRun,
"text": function(element, messages, options) {
return [Html.text(element.value)];
},
"tab": function(element, messages, options) {
return [Html.text("\t")];
},
"hyperlink": function(element, messages, options) {
var href = element.anchor ? "#" + htmlId(element.anchor) : element.href;
var attributes = {href: href};
if (element.targetFrame != null) {
attributes.target = element.targetFrame;
}
var children = convertElements(element.children, messages, options);
return [Html.freshElement("a", attributes, children)];
},
"bookmarkStart": function(element, messages, options) {
var anchor = Html.freshElement("a", {
id: htmlId(element.name)
}, [Html.forceWrite]);
return [anchor];
},
"noteReference": function(element, messages, options) {
noteReferences.push(element);
var anchor = Html.freshElement("a", {
href: "#" + noteHtmlId(element),
id: noteRefHtmlId(element)
}, [Html.text("[" + (noteNumber++) + "]")]);
return [Html.freshElement("sup", {}, [anchor])];
},
"note": function(element, messages, options) {
var children = convertElements(element.body, messages, options);
var backLink = Html.elementWithTag(htmlPaths.element("p", {}, {fresh: false}), [
Html.text(" "),
Html.freshElement("a", {href: "#" + noteRefHtmlId(element)}, [Html.text("↑")])
]);
var body = children.concat([backLink]);
return Html.freshElement("li", {id: noteHtmlId(element)}, body);
},
"commentReference": convertCommentReference,
"comment": convertComment,
"image": deferredConversion(recoveringConvertImage(options.convertImage || images.dataUri)),
"table": convertTable,
"tableRow": convertTableRow,
"tableCell": convertTableCell,
"break": convertBreak
};
return {
convertToHtml: convertToHtml
};
}
var deferredId = 1;
function deferredConversion(func) {
return function(element, messages, options) {
return [
{
type: "deferred",
id: deferredId++,
value: function() {
return func(element, messages, options);
}
}
];
};
}
function unrecognisedStyleWarning(type, element) {
return results.warning(
"Unrecognised " + type + " style: '" + element.styleName + "'" +
" (Style ID: " + element.styleId + ")"
);
}
function flatMap(values, func) {
return _.flatten(values.map(func), true);
}
function walkHtml(nodes, callback) {
nodes.forEach(function(node) {
callback(node);
if (node.children) {
walkHtml(node.children, callback);
}
});
}
var commentAuthorLabel = exports.commentAuthorLabel = function commentAuthorLabel(comment) {
return comment.authorInitials || "";
};
},{"./documents":4,"./html":18,"./images":20,"./promises":23,"./results":24,"./styles/html-paths":27,"./writers":32,"underscore":156}],4:[function(require,module,exports){
var _ = require("underscore");
var types = exports.types = {
document: "document",
paragraph: "paragraph",
run: "run",
text: "text",
tab: "tab",
hyperlink: "hyperlink",
noteReference: "noteReference",
image: "image",
note: "note",
commentReference: "commentReference",
comment: "comment",
table: "table",
tableRow: "tableRow",
tableCell: "tableCell",
"break": "break",
bookmarkStart: "bookmarkStart"
};
function Document(children, options) {
options = options || {};
return {
type: types.document,
children: children,
notes: options.notes || new Notes({}),
comments: options.comments || []
};
}
function Paragraph(children, properties) {
properties = properties || {};
return {
type: types.paragraph,
children: children,
styleId: properties.styleId || null,
styleName: properties.styleName || null,
numbering: properties.numbering || null,
alignment: properties.alignment || null
};
}
function Run(children, properties) {
properties = properties || {};
return {
type: types.run,
children: children,
styleId: properties.styleId || null,
styleName: properties.styleName || null,
isBold: properties.isBold,
isUnderline: properties.isUnderline,
isItalic: properties.isItalic,
isStrikethrough: properties.isStrikethrough,
isSmallCaps: properties.isSmallCaps,
verticalAlignment: properties.verticalAlignment || verticalAlignment.baseline,
font: properties.font || null
};
}
var verticalAlignment = {
baseline: "baseline",
superscript: "superscript",
subscript: "subscript"
};
function Text(value) {
return {
type: types.text,
value: value
};
}
function Tab() {
return {
type: types.tab
};
}
function Hyperlink(children, options) {
return {
type: types.hyperlink,
children: children,
href: options.href,
anchor: options.anchor,
targetFrame: options.targetFrame
};
}
function NoteReference(options) {
return {
type: types.noteReference,
noteType: options.noteType,
noteId: options.noteId
};
}
function Notes(notes) {
this._notes = _.indexBy(notes, function(note) {
return noteKey(note.noteType, note.noteId);
});
}
Notes.prototype.resolve = function(reference) {
return this.findNoteByKey(noteKey(reference.noteType, reference.noteId));
};
Notes.prototype.findNoteByKey = function(key) {
return this._notes[key] || null;
};
function Note(options) {
return {
type: types.note,
noteType: options.noteType,
noteId: options.noteId,
body: options.body
};
}
function commentReference(options) {
return {
type: types.commentReference,
commentId: options.commentId
};
}
function comment(options) {
return {
type: types.comment,
commentId: options.commentId,
body: options.body,
authorName: options.authorName,
authorInitials: options.authorInitials
};
}
function noteKey(noteType, id) {
return noteType + "-" + id;
}
function Image(options) {
return {
type: types.image,
read: options.readImage,
altText: options.altText,
contentType: options.contentType
};
}
function Table(children, properties) {
properties = properties || {};
return {
type: types.table,
children: children,
styleId: properties.styleId || null,
styleName: properties.styleName || null
};
}
function TableRow(children, options) {
options = options || {};
return {
type: types.tableRow,
children: children,
isHeader: options.isHeader || false
};
}
function TableCell(children, options) {
options = options || {};
return {
type: types.tableCell,
children: children,
colSpan: options.colSpan == null ? 1 : options.colSpan,
rowSpan: options.rowSpan == null ? 1 : options.rowSpan
};
}
function Break(breakType) {
return {
type: types["break"],
breakType: breakType
};
}
function BookmarkStart(options) {
return {
type: types.bookmarkStart,
name: options.name
};
}
exports.document = exports.Document = Document;
exports.paragraph = exports.Paragraph = Paragraph;
exports.run = exports.Run = Run;
exports.Text = Text;
exports.tab = exports.Tab = Tab;
exports.Hyperlink = Hyperlink;
exports.noteReference = exports.NoteReference = NoteReference;
exports.Notes = Notes;
exports.Note = Note;
exports.commentReference = commentReference;
exports.comment = comment;
exports.Image = Image;
exports.Table = Table;
exports.TableRow = TableRow;
exports.TableCell = TableCell;
exports.lineBreak = Break("line");
exports.pageBreak = Break("page");
exports.columnBreak = Break("column");
exports.BookmarkStart = BookmarkStart;
exports.verticalAlignment = verticalAlignment;
},{"underscore":156}],5:[function(require,module,exports){
exports.createBodyReader = createBodyReader;
exports._readNumberingProperties = readNumberingProperties;
var _ = require("underscore");
var documents = require("../documents");
var Result = require("../results").Result;
var warning = require("../results").warning;
var uris = require("./uris");
function createBodyReader(options) {
return {
readXmlElement: function(element) {
return new BodyReader(options).readXmlElement(element);
},
readXmlElements: function(elements) {
return new BodyReader(options).readXmlElements(elements);
}
};
}
function BodyReader(options) {
var complexFieldStack = [];
var currentInstrText = [];
var relationships = options.relationships;
var contentTypes = options.contentTypes;
var docxFile = options.docxFile;
var files = options.files;
var numbering = options.numbering;
var styles = options.styles;
function readXmlElements(elements) {
var results = elements.map(readXmlElement);
return combineResults(results);
}
function readXmlElement(element) {
if (element.type === "element") {
var handler = xmlElementReaders[element.name];
if (handler) {
return handler(element);
} else if (!Object.prototype.hasOwnProperty.call(ignoreElements, element.name)) {
var message = warning("An unrecognised element was ignored: " + element.name);
return emptyResultWithMessages([message]);
}
}
return emptyResult();
}
function readRunProperties(element) {
return readRunStyle(element).map(function(style) {
return {
type: "runProperties",
styleId: style.styleId,
styleName: style.name,
verticalAlignment: element.firstOrEmpty("w:vertAlign").attributes["w:val"],
font: element.firstOrEmpty("w:rFonts").attributes["w:ascii"],
isBold: readBooleanElement(element.first("w:b")),
isUnderline: readBooleanElement(element.first("w:u")),
isItalic: readBooleanElement(element.first("w:i")),
isStrikethrough: readBooleanElement(element.first("w:strike")),
isSmallCaps: readBooleanElement(element.first("w:smallCaps"))
};
});
}
function readBooleanElement(element) {
if (element) {
var value = element.attributes["w:val"];
return value !== "false" && value !== "0";
} else {
return false;
}
}
function readParagraphStyle(element) {
return readStyle(element, "w:pStyle", "Paragraph", styles.findParagraphStyleById);
}
function readRunStyle(element) {
return readStyle(element, "w:rStyle", "Run", styles.findCharacterStyleById);
}
function readTableStyle(element) {
return readStyle(element, "w:tblStyle", "Table", styles.findTableStyleById);
}
function readStyle(element, styleTagName, styleType, findStyleById) {
var messages = [];
var styleElement = element.first(styleTagName);
var styleId = null;
var name = null;
if (styleElement) {
styleId = styleElement.attributes["w:val"];
if (styleId) {
var style = findStyleById(styleId);
if (style) {
name = style.name;
} else {
messages.push(undefinedStyleWarning(styleType, styleId));
}
}
}
return elementResultWithMessages({styleId: styleId, name: name}, messages);
}
var unknownComplexField = {type: "unknown"};
function readFldChar(element) {
var type = element.attributes["w:fldCharType"];
if (type === "begin") {
complexFieldStack.push(unknownComplexField);
currentInstrText = [];
} else if (type === "end") {
complexFieldStack.pop();
} else if (type === "separate") {
var href = parseHyperlinkFieldCode(currentInstrText.join(''));
var complexField = href === null ? unknownComplexField : {type: "hyperlink", href: href};
complexFieldStack.pop();
complexFieldStack.push(complexField);
}
return emptyResult();
}
function currentHyperlinkHref() {
var topHyperlink = _.last(complexFieldStack.filter(function(complexField) {
return complexField.type === "hyperlink";
}));
return topHyperlink ? topHyperlink.href : null;
}
function parseHyperlinkFieldCode(code) {
var result = /\s*HYPERLINK "(.*)"/.exec(code);
if (result) {
return result[1];
} else {
return null;
}
}
function readInstrText(element) {
currentInstrText.push(element.text());
return emptyResult();
}
function noteReferenceReader(noteType) {
return function(element) {
var noteId = element.attributes["w:id"];
return elementResult(new documents.NoteReference({
noteType: noteType,
noteId: noteId
}));
};
}
function readCommentReference(element) {
return elementResult(documents.commentReference({
commentId: element.attributes["w:id"]
}));
}
function readChildElements(element) {
return readXmlElements(element.children);
}
var xmlElementReaders = {
"w:p": function(element) {
return readXmlElements(element.children)
.map(function(children) {
var properties = _.find(children, isParagraphProperties);
return new documents.Paragraph(
children.filter(negate(isParagraphProperties)),
properties
);
})
.insertExtra();
},
"w:pPr": function(element) {
return readParagraphStyle(element).map(function(style) {
return {
type: "paragraphProperties",
styleId: style.styleId,
styleName: style.name,
alignment: element.firstOrEmpty("w:jc").attributes["w:val"],
numbering: readNumberingProperties(element.firstOrEmpty("w:numPr"), numbering)
};
});
},
"w:r": function(element) {
return readXmlElements(element.children)
.map(function(children) {
var properties = _.find(children, isRunProperties);
children = children.filter(negate(isRunProperties));
var hyperlinkHref = currentHyperlinkHref();
if (hyperlinkHref !== null) {
children = [new documents.Hyperlink(children, {href: hyperlinkHref})];
}
return new documents.Run(children, properties);
});
},
"w:rPr": readRunProperties,
"w:fldChar": readFldChar,
"w:instrText": readInstrText,
"w:t": function(element) {
return elementResult(new documents.Text(element.text()));
},
"w:tab": function(element) {
return elementResult(new documents.Tab());
},
"w:noBreakHyphen": function() {
return elementResult(new documents.Text("\u2011"));
},
"w:hyperlink": function(element) {
var relationshipId = element.attributes["r:id"];
var anchor = element.attributes["w:anchor"];
return readXmlElements(element.children).map(function(children) {
function create(options) {
var targetFrame = element.attributes["w:tgtFrame"] || null;
return new documents.Hyperlink(
children,
_.extend({targetFrame: targetFrame}, options)
);
}
if (relationshipId) {
var href = relationships[relationshipId].target;
if (anchor) {
href = uris.replaceFragment(href, anchor);
}
return create({href: href});
} else if (anchor) {
return create({anchor: anchor});
} else {
return children;
}
});
},
"w:tbl": readTable,
"w:tr": readTableRow,
"w:tc": readTableCell,
"w:footnoteReference": noteReferenceReader("footnote"),
"w:endnoteReference": noteReferenceReader("endnote"),
"w:commentReference": readCommentReference,
"w:br": function(element) {
var breakType = element.attributes["w:type"];
if (breakType == null || breakType === "textWrapping") {
return elementResult(documents.lineBreak);
} else if (breakType === "page") {
return elementResult(documents.pageBreak);
} else if (breakType === "column") {
return elementResult(documents.columnBreak);
} else {
return emptyResultWithMessages([warning("Unsupported break type: " + breakType)]);
}
},
"w:bookmarkStart": function(element){
var name = element.attributes["w:name"];
if (name === "_GoBack") {
return emptyResult();
} else {
return elementResult(new documents.BookmarkStart({name: name}));
}
},
"mc:AlternateContent": function(element) {
return readChildElements(element.first("mc:Fallback"));
},
"w:sdt": function(element) {
return readXmlElements(element.firstOrEmpty("w:sdtContent").children);
},
"w:ins": readChildElements,
"w:object": readChildElements,
"w:smartTag": readChildElements,
"w:drawing": readChildElements,
"w:pict": function(element) {
return readChildElements(element).toExtra();
},
"v:roundrect": readChildElements,
"v:shape": readChildElements,
"v:textbox": readChildElements,
"w:txbxContent": readChildElements,
"wp:inline": readDrawingElement,
"wp:anchor": readDrawingElement,
"v:imagedata": readImageData,
"v:group": readChildElements
};
return {
readXmlElement: readXmlElement,
readXmlElements: readXmlElements
};
function readTable(element) {
var propertiesResult = readTableProperties(element.firstOrEmpty("w:tblPr"));
return readXmlElements(element.children)
.flatMap(calculateRowSpans)
.flatMap(function(children) {
return propertiesResult.map(function(properties) {
return documents.Table(children, properties);
});
});
}
function readTableProperties(element) {
return readTableStyle(element).map(function(style) {
return {
styleId: style.styleId,
styleName: style.name
};
});
}
function readTableRow(element) {
var properties = element.firstOrEmpty("w:trPr");
var isHeader = !!properties.first("w:tblHeader");
return readXmlElements(element.children).map(function(children) {
return documents.TableRow(children, {isHeader: isHeader});
});
}
function readTableCell(element) {
return readXmlElements(element.children).map(function(children) {
var properties = element.firstOrEmpty("w:tcPr");
var gridSpan = properties.firstOrEmpty("w:gridSpan").attributes["w:val"];
var colSpan = gridSpan ? parseInt(gridSpan, 10) : 1;
var cell = documents.TableCell(children, {colSpan: colSpan});
cell._vMerge = readVMerge(properties);
return cell;
});
}
function readVMerge(properties) {
var element = properties.first("w:vMerge");
if (element) {
var val = element.attributes["w:val"];
return val === "continue" || !val;
} else {
return null;
}
}
function calculateRowSpans(rows) {
var unexpectedNonRows = _.any(rows, function(row) {
return row.type !== documents.types.tableRow;
});
if (unexpectedNonRows) {
return elementResultWithMessages(rows, [warning(
"unexpected non-row element in table, cell merging may be incorrect"
)]);
}
var unexpectedNonCells = _.any(rows, function(row) {
return _.any(row.children, function(cell) {
return cell.type !== documents.types.tableCell;
});
});
if (unexpectedNonCells) {
return elementResultWithMessages(rows, [warning(
"unexpected non-cell element in table row, cell merging may be incorrect"
)]);
}
var columns = {};
rows.forEach(function(row) {
var cellIndex = 0;
row.children.forEach(function(cell) {
if (cell._vMerge && columns[cellIndex]) {
columns[cellIndex].rowSpan++;
} else {
columns[cellIndex] = cell;
cell._vMerge = false;
}
cellIndex += cell.colSpan;
});
});
rows.forEach(function(row) {
row.children = row.children.filter(function(cell) {
return !cell._vMerge;
});
row.children.forEach(function(cell) {
delete cell._vMerge;
});
});
return elementResult(rows);
}
function readDrawingElement(element) {
var blips = element
.getElementsByTagName("a:graphic")
.getElementsByTagName("a:graphicData")
.getElementsByTagName("pic:pic")
.getElementsByTagName("pic:blipFill")
.getElementsByTagName("a:blip");
return combineResults(blips.map(readBlip.bind(null, element)));
}
function readBlip(element, blip) {
var properties = element.first("wp:docPr").attributes;
var altText = isBlank(properties.descr) ? properties.title : properties.descr;
return readImage(findBlipImageFile(blip), altText);
}
function isBlank(value) {
return value == null || /^\s*$/.test(value);
}
function findBlipImageFile(blip) {
var embedRelationshipId = blip.attributes["r:embed"];
var linkRelationshipid = blip.attributes["r:link"];
if (embedRelationshipId) {
return findEmbeddedImageFile(embedRelationshipId);
} else {
var imagePath = relationships[linkRelationshipid].target;
return {
path: imagePath,
read: files.read.bind(files, imagePath)
};
}
}
function readImageData(element) {
var relationshipId = element.attributes['r:id'];
if (relationshipId) {
return readImage(
findEmbeddedImageFile(relationshipId),
element.attributes["o:title"]);
} else {
return emptyResultWithMessages([warning("A v:imagedata element without a relationship ID was ignored")]);
}
}
function findEmbeddedImageFile(relationshipId) {
var path = uris.uriToZipEntryName("word", relationships[relationshipId].target);
return {
path: path,
read: docxFile.read.bind(docxFile, path)
};
}
function readImage(imageFile, altText) {
var contentType = contentTypes.findContentType(imageFile.path);
var image = documents.Image({
readImage: imageFile.read,
altText: altText,
contentType: contentType
});
var warnings = supportedImageTypes[contentType] ?
[] : warning("Image of type " + contentType + " is unlikely to display in web browsers");
return elementResultWithMessages(image, warnings);
}
function undefinedStyleWarning(type, styleId) {
return warning(
type + " style with ID " + styleId + " was referenced but not defined in the document");
}
}
function readNumberingProperties(element, numbering) {
var level = element.firstOrEmpty("w:ilvl").attributes["w:val"];
var numId = element.firstOrEmpty("w:numId").attributes["w:val"];
if (level === undefined || numId === undefined) {
return null;
} else {
return numbering.findLevel(numId, level);
}
}
var supportedImageTypes = {
"image/png": true,
"image/gif": true,
"image/jpeg": true,
"image/svg+xml": true,
"image/tiff": true
};
var ignoreElements = {
"office-word:wrap": true,
"v:shadow": true,
"v:shapetype": true,
"w:annotationRef": true,
"w:bookmarkEnd": true,
"w:sectPr": true,
"w:proofErr": true,
"w:lastRenderedPageBreak": true,
"w:commentRangeStart": true,
"w:commentRangeEnd": true,
"w:del": true,
"w:footnoteRef": true,
"w:endnoteRef": true,
"w:tblPr": true,
"w:tblGrid": true,
"w:trPr": true,
"w:tcPr": true
};
function isParagraphProperties(element) {
return element.type === "paragraphProperties";
}
function isRunProperties(element) {
return element.type === "runProperties";
}
function negate(predicate) {
return function(value) {
return !predicate(value);
};
}
function emptyResultWithMessages(messages) {
return new ReadResult(null, null, messages);
}
function emptyResult() {
return new ReadResult(null);
}
function elementResult(element) {
return new ReadResult(element);
}
function elementResultWithMessages(element, messages) {
return new ReadResult(element, null, messages);
}
function ReadResult(element, extra, messages) {
this.value = element || [];
this.extra = extra;
this._result = new Result({
element: this.value,
extra: extra
}, messages);
this.messages = this._result.messages;
}
ReadResult.prototype.toExtra = function() {
return new ReadResult(null, joinElements(this.extra, this.value), this.messages);
};
ReadResult.prototype.insertExtra = function() {
var extra = this.extra;
if (extra && extra.length) {
return new ReadResult(joinElements(this.value, extra), null, this.messages);
} else {
return this;
}
};
ReadResult.prototype.map = function(func) {
var result = this._result.map(function(value) {
return func(value.element);
});
return new ReadResult(result.value, this.extra, result.messages);
};
ReadResult.prototype.flatMap = function(func) {
var result = this._result.flatMap(function(value) {
return func(value.element)._result;
});
return new ReadResult(result.value.element, joinElements(this.extra, result.value.extra), result.messages);
};
function combineResults(results) {
var result = Result.combine(_.pluck(results, "_result"));
return new ReadResult(
_.flatten(_.pluck(result.value, "element")),
_.filter(_.flatten(_.pluck(result.value, "extra")), identity),
result.messages
);
}
function joinElements(first, second) {
return _.flatten([first, second]);
}
function identity(value) {
return value;
}
},{"../documents":4,"../results":24,"./uris":16,"underscore":156}],6:[function(require,module,exports){
var documents = require("../documents");
var Result = require("../results").Result;
function createCommentsReader(bodyReader) {
function readCommentsXml(element) {
return Result.combine(element.getElementsByTagName("w:comment")
.map(readCommentElement));
}
function readCommentElement(element) {
var id = element.attributes["w:id"];
function readOptionalAttribute(name) {
return (element.attributes[name] || "").trim() || null;
}
return bodyReader.readXmlElements(element.children)
.map(function(body) {
return documents.comment({
commentId: id,
body: body,
authorName: readOptionalAttribute("w:author"),
authorInitials: readOptionalAttribute("w:initials")
});
});
}
return readCommentsXml;
}
exports.createCommentsReader = createCommentsReader;
},{"../documents":4,"../results":24}],7:[function(require,module,exports){
exports.readContentTypesFromXml = readContentTypesFromXml;
var fallbackContentTypes = {
"png": "png",
"gif": "gif",
"jpeg": "jpeg",
"jpg": "jpeg",
"tif": "tiff",
"tiff": "tiff",
"bmp": "bmp"
};
exports.defaultContentTypes = contentTypes({}, {});
function readContentTypesFromXml(element) {
var extensionDefaults = {};
var overrides = {};
element.children.forEach(function(child) {
if (child.name === "content-types:Default") {
extensionDefaults[child.attributes.Extension] = child.attributes.ContentType;
}
if (child.name === "content-types:Override") {
var name = child.attributes.PartName;
if (name.charAt(0) === "/") {
name = name.substring(1);
}
overrides[name] = child.attributes.ContentType;
}
});
return contentTypes(overrides, extensionDefaults);
}
function contentTypes(overrides, extensionDefaults) {
return {
findContentType: function(path) {
var overrideContentType = overrides[path];
if (overrideContentType) {
return overrideContentType;
} else {
var pathParts = path.split(".");
var extension = pathParts[pathParts.length - 1];
if (extensionDefaults.hasOwnProperty(extension)) {
return extensionDefaults[extension];
} else {
var fallback = fallbackContentTypes[extension.toLowerCase()];
if (fallback) {
return "image/" + fallback;
} else {
return null;
}
}
}
}
};
}
},{}],8:[function(require,module,exports){
exports.DocumentXmlReader = DocumentXmlReader;
var documents = require("../documents");
var Result = require("../results").Result;
function DocumentXmlReader(options) {
var bodyReader = options.bodyReader;
function convertXmlToDocument(element) {
var body = element.first("w:body");
var result = bodyReader.readXmlElements(body.children)
.map(function(children) {
return new documents.Document(children, {
notes: options.notes,
comments: options.comments
});
});
return new Result(result.value, result.messages);
}
return {
convertXmlToDocument: convertXmlToDocument
};
}
},{"../documents":4,"../results":24}],9:[function(require,module,exports){
exports.read = read;
var path = require("path");
var promises = require("../promises");
var documents = require("../documents");
var Result = require("../results").Result;
var readXmlFromZipFile = require("./office-xml-reader").readXmlFromZipFile;
var createBodyReader = require("./body-reader").createBodyReader;
var DocumentXmlReader = require("./document-xml-reader").DocumentXmlReader;
var relationshipsReader = require("./relationships-reader");
var contentTypesReader = require("./content-types-reader");
var numberingXml = require("./numbering-xml");
var stylesReader = require("./styles-reader");
var notesReader = require("./notes-reader");
var commentsReader = require("./comments-reader");
var Files = require("./files").Files;
function read(docxFile, input) {
input = input || {};
return promises.props({
contentTypes: readContentTypesFromZipFile(docxFile),
numbering: readNumberingFromZipFile(docxFile),
styles: readStylesFromZipFile(docxFile),
docxFile: docxFile,
files: new Files(input.path ? path.dirname(input.path) : null)
}).also(function(result) {
return {
footnotes: readXmlFileWithBody("footnotes", result, function(bodyReader, xml) {
if (xml) {
return notesReader.createFootnotesReader(bodyReader)(xml);
} else {
return new Result([]);
}
}),
endnotes: readXmlFileWithBody("endnotes", result, function(bodyReader, xml) {
if (xml) {
return notesReader.createEndnotesReader(bodyReader)(xml);
} else {
return new Result([]);
}
}),
comments: readXmlFileWithBody("comments", result, function(bodyReader, xml) {
if (xml) {
return commentsReader.createCommentsReader(bodyReader)(xml);
} else {
return new Result([]);
}
})
};
}).also(function(result) {
return {
notes: result.footnotes.flatMap(function(footnotes) {
return result.endnotes.map(function(endnotes) {
return new documents.Notes(footnotes.concat(endnotes));
});
})
};
}).then(function(result) {
return readXmlFileWithBody("document", result, function(bodyReader, xml) {
if (xml) {
return result.notes.flatMap(function(notes) {
return result.comments.flatMap(function(comments) {
var reader = new DocumentXmlReader({
bodyReader: bodyReader,
notes: notes,
comments: comments
});
return reader.convertXmlToDocument(xml);
});
});
} else {
throw new Error("Could not find word/document.xml in ZIP file. Are you sure this is a valid .docx file?");
}
});
});
}
function xmlFileReader(options) {
return function(zipFile) {
return readXmlFromZipFile(zipFile, options.filename)
.then(function(element) {
return element ? options.readElement(element) : options.defaultValue;
});
};
}
function readXmlFileWithBody(name, options, func) {
var readRelationshipsFromZipFile = xmlFileReader({
filename: "word/_rels/" + name + ".xml.rels",
readElement: relationshipsReader.readRelationships,
defaultValue: {}
});
return readRelationshipsFromZipFile(options.docxFile).then(function(relationships) {
var bodyReader = new createBodyReader({
relationships: relationships,
contentTypes: options.contentTypes,
docxFile: options.docxFile,
numbering: options.numbering,
styles: options.styles,
files: options.files
});
return readXmlFromZipFile(options.docxFile, "word/" + name + ".xml")
.then(function(xml) {
return func(bodyReader, xml);
});
});
}
var readContentTypesFromZipFile = xmlFileReader({
filename: "[Content_Types].xml",
readElement: contentTypesReader.readContentTypesFromXml,
defaultValue: contentTypesReader.defaultContentTypes
});
var readNumberingFromZipFile = xmlFileReader({
filename: "word/numbering.xml",
readElement: numberingXml.readNumberingXml,
defaultValue: numberingXml.defaultNumbering
});
var readStylesFromZipFile = xmlFileReader({
filename: "word/styles.xml",
readElement: stylesReader.readStylesXml,
defaultValue: stylesReader.defaultStyles
});
},{"../documents":4,"../promises":23,"../results":24,"./body-reader":5,"./comments-reader":6,"./content-types-reader":7,"./document-xml-reader":8,"./files":1,"./notes-reader":10,"./numbering-xml":11,"./office-xml-reader":12,"./relationships-reader":13,"./styles-reader":15,"path":82}],10:[function(require,module,exports){
var documents = require("../documents");
var Result = require("../results").Result;
exports.createFootnotesReader = createReader.bind(this, "footnote");
exports.createEndnotesReader = createReader.bind(this, "endnote");
function createReader(noteType, bodyReader) {
function readNotesXml(element) {
return Result.combine(element.getElementsByTagName("w:" + noteType)
.filter(isFootnoteElement)
.map(readFootnoteElement));
}
function isFootnoteElement(element) {
var type = element.attributes["w:type"];
return type !== "continuationSeparator" && type !== "separator";
}
function readFootnoteElement(footnoteElement) {
var id = footnoteElement.attributes["w:id"];
return bodyReader.readXmlElements(footnoteElement.children)
.map(function(body) {
return documents.Note({noteType: noteType, noteId: id, body: body});
});
}
return readNotesXml;
}
},{"../documents":4,"../results":24}],11:[function(require,module,exports){
exports.readNumberingXml = readNumberingXml;
exports.Numbering = Numbering;
exports.defaultNumbering = new Numbering({});
function Numbering(nums) {
return {
findLevel: function(numId, level) {
var num = nums[numId];
if (num) {
return num[level];
} else {
return null;
}
}
};
}
function readNumberingXml(root) {
var abstractNums = readAbstractNums(root);
var nums = readNums(root, abstractNums);
return new Numbering(nums);
}
function readAbstractNums(root) {
var abstractNums = {};
root.getElementsByTagName("w:abstractNum").forEach(function(element) {
var id = element.attributes["w:abstractNumId"];
abstractNums[id] = readAbstractNum(element);
});
return abstractNums;
}
function readAbstractNum(element) {
var levels = {};
element.getElementsByTagName("w:lvl").forEach(function(levelElement) {
var levelIndex = levelElement.attributes["w:ilvl"];
var numFmt = levelElement.first("w:numFmt").attributes["w:val"];
levels[levelIndex] = {
isOrdered: numFmt !== "bullet",
level: levelIndex
};
});
return levels;
}
function readNums(root, abstractNums) {
var nums = {};
root.getElementsByTagName("w:num").forEach(function(element) {
var id = element.attributes["w:numId"];
var abstractNumId = element.first("w:abstractNumId").attributes["w:val"];
nums[id] = abstractNums[abstractNumId];
});
return nums;
}
},{}],12:[function(require,module,exports){
var _ = require("underscore");
var promises = require("../promises");
var xml = require("../xml");
exports.read = read;
exports.readXmlFromZipFile = readXmlFromZipFile;
var xmlNamespaceMap = {
"http://schemas.openxmlformats.org/wordprocessingml/2006/main": "w",
"http://schemas.openxmlformats.org/officeDocument/2006/relationships": "r",
"http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing": "wp",
"http://schemas.openxmlformats.org/drawingml/2006/main": "a",
"http://schemas.openxmlformats.org/drawingml/2006/picture": "pic",
"http://schemas.openxmlformats.org/package/2006/content-types": "content-types",
"urn:schemas-microsoft-com:vml": "v",
"http://schemas.openxmlformats.org/markup-compatibility/2006": "mc",
"urn:schemas-microsoft-com:office:word": "office-word"
};
function read(xmlString) {
return xml.readString(xmlString, xmlNamespaceMap)
.then(function(document) {
return collapseAlternateContent(document)[0];
});
}
function readXmlFromZipFile(docxFile, path) {
if (docxFile.exists(path)) {
return docxFile.read(path, "utf-8")
.then(stripUtf8Bom)
.then(read);
} else {
return promises.resolve(null);
}
}
function stripUtf8Bom(xmlString) {
return xmlString.replace(/^\uFEFF/g, '');
}
function collapseAlternateContent(node) {
if (node.type === "element") {
if (node.name === "mc:AlternateContent") {
return node.first("mc:Fallback").children;
} else {
node.children = _.flatten(node.children.map(collapseAlternateContent, true));
return [node];
}
} else {
return [node];
}
}
},{"../promises":23,"../xml":34,"underscore":156}],13:[function(require,module,exports){
exports.readRelationships = readRelationships;
function readRelationships(element) {
var relationships = {};
element.children.forEach(function(child) {
if (child.name === "{http://schemas.openxmlformats.org/package/2006/relationships}Relationship") {
relationships[child.attributes.Id] = {
target: child.attributes.Target
};
}
});
return relationships;
}
},{}],14:[function(require,module,exports){
var _ = require("underscore");
var promises = require("../promises");
var xml = require("../xml");
exports.writeStyleMap = writeStyleMap;
exports.readStyleMap = readStyleMap;
var schema = "http://schemas.zwobble.org/mammoth/style-map";
var styleMapPath = "mammoth/style-map";
var styleMapAbsolutePath = "/" + styleMapPath;
function writeStyleMap(docxFile, styleMap) {
docxFile.write(styleMapPath, styleMap);
return updateRelationships(docxFile).then(function() {
return updateContentTypes(docxFile);
});
}
function updateRelationships(docxFile) {
var path = "word/_rels/document.xml.rels";
var relationshipsUri = "http://schemas.openxmlformats.org/package/2006/relationships";
var relationshipElementName = "{" + relationshipsUri + "}Relationship";
return docxFile.read(path, "utf8")
.then(xml.readString)
.then(function(relationshipsContainer) {
var relationships = relationshipsContainer.children;
addOrUpdateElement(relationships, relationshipElementName, "Id", {
"Id": "rMammothStyleMap",
"Type": schema,
"Target": styleMapAbsolutePath
});
var namespaces = {"": relationshipsUri};
return docxFile.write(path, xml.writeString(relationshipsContainer, namespaces));
});
}
function updateContentTypes(docxFile) {
var path = "[Content_Types].xml";
var contentTypesUri = "http://schemas.openxmlformats.org/package/2006/content-types";
var overrideName = "{" + contentTypesUri + "}Override";
return docxFile.read(path, "utf8")
.then(xml.readString)
.then(function(typesElement) {
var children = typesElement.children;
addOrUpdateElement(children, overrideName, "PartName", {
"PartName": styleMapAbsolutePath,
"ContentType": "text/prs.mammoth.style-map"
});
var namespaces = {"": contentTypesUri};
return docxFile.write(path, xml.writeString(typesElement, namespaces));
});
}
function addOrUpdateElement(elements, name, identifyingAttribute, attributes) {
var existingElement = _.find(elements, function(element) {
return element.name === name &&
element.attributes[identifyingAttribute] === attributes[identifyingAttribute];
});
if (existingElement) {
existingElement.attributes = attributes;
} else {
elements.push(xml.element(name, attributes));
}
}
function readStyleMap(docxFile) {
if (docxFile.exists(styleMapPath)) {
return docxFile.read(styleMapPath, "utf8");
} else {
return promises.resolve(null);
}
}
},{"../promises":23,"../xml":34,"underscore":156}],15:[function(require,module,exports){
exports.readStylesXml = readStylesXml;
exports.Styles = Styles;
exports.defaultStyles = new Styles({}, {});
function Styles(paragraphStyles, characterStyles, tableStyles) {
return {
findParagraphStyleById: function(styleId) {
return paragraphStyles[styleId];
},
findCharacterStyleById: function(styleId) {
return characterStyles[styleId];
},
findTableStyleById: function(styleId) {
return tableStyles[styleId];
}
};
}
Styles.EMPTY = new Styles({}, {}, {});
function readStylesXml(root) {
var paragraphStyles = {};
var characterStyles = {};
var tableStyles = {};
var styles = {
"paragraph": paragraphStyles,
"character": characterStyles,
"table": tableStyles
};
root.getElementsByTagName("w:style").forEach(function(styleElement) {
var style = readStyleElement(styleElement);
var styleSet = styles[style.type];
if (styleSet) {
styleSet[style.styleId] = style;
}
});
return new Styles(paragraphStyles, characterStyles, tableStyles);
}
function readStyleElement(styleElement) {
var type = styleElement.attributes["w:type"];
var styleId = styleElement.attributes["w:styleId"];
var name = styleName(styleElement);
return {type: type, styleId: styleId, name: name};
}
function styleName(styleElement) {
var nameElement = styleElement.first("w:name");
return nameElement ? nameElement.attributes["w:val"] : null;
}
},{}],16:[function(require,module,exports){
exports.uriToZipEntryName = uriToZipEntryName;
exports.replaceFragment = replaceFragment;
function uriToZipEntryName(base, uri) {
if (uri.charAt(0) === "/") {
return uri.substr(1);
} else {
// In general, we should check first and second for trailing and leading slashes,
// but in our specific case this seems to be sufficient
return base + "/" + uri;
}
}
function replaceFragment(uri, fragment) {
var hashIndex = uri.indexOf("#");
if (hashIndex !== -1) {
uri = uri.substring(0, hashIndex);
}
return uri + "#" + fragment;
}
},{}],17:[function(require,module,exports){
var htmlPaths = require("../styles/html-paths");
function nonFreshElement(tagName, attributes, children) {
return elementWithTag(
htmlPaths.element(tagName, attributes, {fresh: false}),
children);
}
function freshElement(tagName, attributes, children) {
var tag = htmlPaths.element(tagName, attributes, {fresh: true});
return elementWithTag(tag, children);
}
function elementWithTag(tag, children) {
return {
type: "element",
tag: tag,
children: children || []
};
}
function text(value) {
return {
type: "text",
value: value
};
}
var forceWrite = {
type: "forceWrite"
};
exports.freshElement = freshElement;
exports.nonFreshElement = nonFreshElement;
exports.elementWithTag = elementWithTag;
exports.text = text;
exports.forceWrite = forceWrite;
var voidTagNames = {
"br": true,
"hr": true,
"img": true
};
function isVoidElement(node) {
return (node.children.length === 0) && voidTagNames[node.tag.tagName];
}
exports.isVoidElement = isVoidElement;
},{"../styles/html-paths":27}],18:[function(require,module,exports){
var ast = require("./ast");
exports.freshElement = ast.freshElement;
exports.nonFreshElement = ast.nonFreshElement;
exports.elementWithTag = ast.elementWithTag;
exports.text = ast.text;
exports.forceWrite = ast.forceWrite;
exports.simplify = require("./simplify");
function write(writer, nodes) {
nodes.forEach(function(node) {
writeNode(writer, node);
});
}
function writeNode(writer, node) {
toStrings[node.type](writer, node);
}
var toStrings = {
element: generateElementString,
text: generateTextString,
forceWrite: function() { }
};
function generateElementString(writer, node) {
if (ast.isVoidElement(node)) {
writer.selfClosing(node.tag.tagName, node.tag.attributes);
} else {
writer.open(node.tag.tagName, node.tag.attributes);
write(writer, node.children);
writer.close(node.tag.tagName);
}
}
function generateTextString(writer, node) {
writer.text(node.value);
}
exports.write = write;
},{"./ast":17,"./simplify":19}],19:[function(require,module,exports){
var _ = require("underscore");
var ast = require("./ast");
function simplify(nodes) {
return collapse(removeEmpty(nodes));
}
function collapse(nodes) {
var children = [];
nodes.map(collapseNode).forEach(function(child) {
appendChild(children, child);
});
return children;
}
function collapseNode(node) {
return collapsers[node.type](node);
}
var collapsers = {
element: collapseElement,
text: identity,
forceWrite: identity
};
function collapseElement(node) {
return ast.elementWithTag(node.tag, collapse(node.children));
}
function identity(value) {
return value;
}
function appendChild(children, child) {
var lastChild = children[children.length - 1];
if (child.type === "element" && !child.tag.fresh && lastChild && lastChild.type === "element" && child.tag.matchesElement(lastChild.tag)) {
if (child.tag.separator) {
appendChild(lastChild.children, ast.text(child.tag.separator));
}
child.children.forEach(function(grandChild) {
// Mutation is fine since simplifying elements create a copy of the children.
appendChild(lastChild.children, grandChild);
});
} else {
children.push(child);
}
}
function removeEmpty(nodes) {
return flatMap(nodes, function(node) {
return emptiers[node.type](node);
});
}
function flatMap(values, func) {
return _.flatten(_.map(values, func), true);
}
var emptiers = {
element: elementEmptier,
text: textEmptier,
forceWrite: neverEmpty
};
function neverEmpty(node) {
return [node];
}
function elementEmptier(element) {
var children = removeEmpty(element.children);
if (children.length === 0 && !ast.isVoidElement(element)) {
return [];
} else {
return [ast.elementWithTag(element.tag, children)];
}
}
function textEmptier(node) {
if (node.value.length === 0) {
return [];
} else {
return [node];
}
}
module.exports = simplify;
},{"./ast":17,"underscore":156}],20:[function(require,module,exports){
var _ = require("underscore");
var promises = require("./promises");
var Html = require("./html");
exports.imgElement = imgElement;
function imgElement(func) {
return function(element, messages) {
return promises.when(func(element)).then(function(result) {
var attributes = _.clone(result);
if (element.altText) {
attributes.alt = element.altText;
}
return [Html.freshElement("img", attributes)];
});
};
}
// Undocumented, but retained for backwards-compatibility with 0.3.x
exports.inline = exports.imgElement;
exports.dataUri = imgElement(function(element) {
return element.read("base64").then(function(imageBuffer) {
return {
src: "data:" + element.contentType + ";base64," + imageBuffer
};
});
});
},{"./html":18,"./promises":23,"underscore":156}],21:[function(require,module,exports){
var _ = require("underscore");
var docxReader = require("./docx/docx-reader");
var docxStyleMap = require("./docx/style-map");
var DocumentConverter = require("./document-to-html").DocumentConverter;
var readStyle = require("./style-reader").readStyle;
var readOptions = require("./options-reader").readOptions;
var unzip = require("./unzip");
var Result = require("./results").Result;
exports.convertToHtml = convertToHtml;
exports.convertToMarkdown = convertToMarkdown;
exports.convert = convert;
exports.extractRawText = extractRawText;
exports.images = require("./images");
exports.transforms = require("./transforms");
exports.underline = require("./underline");
exports.embedStyleMap = embedStyleMap;
exports.readEmbeddedStyleMap = readEmbeddedStyleMap;
function convertToHtml(input, options) {
return convert(input, options);
}
function convertToMarkdown(input, options) {
var markdownOptions = Object.create(options || {});
markdownOptions.outputFormat = "markdown";
return convert(input, markdownOptions);
}
function convert(input, options) {
options = readOptions(options);
return unzip.openZip(input)
.tap(function(docxFile) {
return docxStyleMap.readStyleMap(docxFile).then(function(styleMap) {
options.embeddedStyleMap = styleMap;
});
})
.then(function(docxFile) {
return docxReader.read(docxFile, input)
.then(function(documentResult) {
return documentResult.map(options.transformDocument);
})
.then(function(documentResult) {
return convertDocumentToHtml(documentResult, options);
});
});
}
function readEmbeddedStyleMap(input) {
return unzip.openZip(input)
.then(docxStyleMap.readStyleMap);
}
function convertDocumentToHtml(documentResult, options) {
var styleMapResult = parseStyleMap(options.readStyleMap());
var parsedOptions = _.extend({}, options, {
styleMap: styleMapResult.value
});
var documentConverter = new DocumentConverter(parsedOptions);
return documentResult.flatMapThen(function(document) {
return styleMapResult.flatMapThen(function(styleMap) {
return documentConverter.convertToHtml(document);
});
});
}
function parseStyleMap(styleMap) {
return Result.combine((styleMap || []).map(readStyle))
.map(function(styleMap) {
return styleMap.filter(function(styleMapping) {
return !!styleMapping;
});
});
}
function extractRawText(input) {
return unzip.openZip(input)
.then(docxReader.read)
.then(function(documentResult) {
return documentResult.map(convertElementToRawText);
});
}
function convertElementToRawText(element) {
if (element.type === "text") {
return element.value;
} else {
var tail = element.type === "paragraph" ? "\n\n" : "";
return (element.children || []).map(convertElementToRawText).join("") + tail;
}
}
function embedStyleMap(input, styleMap) {
return unzip.openZip(input)
.tap(function(docxFile) {
return docxStyleMap.writeStyleMap(docxFile, styleMap);
})
.then(function(docxFile) {
return {
toBuffer: docxFile.toBuffer
};
});
}
exports.styleMapping = function() {
throw new Error('Use a raw string instead of mammoth.styleMapping e.g. "p[style-name=\'Title\'] => h1" instead of mammoth.styleMapping("p[style-name=\'Title\'] => h1")');
};
},{"./document-to-html":3,"./docx/docx-reader":9,"./docx/style-map":14,"./images":20,"./options-reader":22,"./results":24,"./style-reader":25,"./transforms":29,"./underline":30,"./unzip":2,"underscore":156}],22:[function(require,module,exports){
exports.readOptions = readOptions;
var _ = require("underscore");
var defaultStyleMap = exports._defaultStyleMap = [
"p.Heading1 => h1:fresh",
"p.Heading2 => h2:fresh",
"p.Heading3 => h3:fresh",
"p.Heading4 => h4:fresh",
"p.Heading5 => h5:fresh",
"p.Heading6 => h6:fresh",
"p[style-name='Heading 1'] => h1:fresh",
"p[style-name='Heading 2'] => h2:fresh",
"p[style-name='Heading 3'] => h3:fresh",
"p[style-name='Heading 4'] => h4:fresh",
"p[style-name='Heading 5'] => h5:fresh",
"p[style-name='Heading 6'] => h6:fresh",
"p[style-name='heading 1'] => h1:fresh",
"p[style-name='heading 2'] => h2:fresh",
"p[style-name='heading 3'] => h3:fresh",
"p[style-name='heading 4'] => h4:fresh",
"p[style-name='heading 5'] => h5:fresh",
"p[style-name='heading 6'] => h6:fresh",
"r[style-name='Strong'] => strong",
"p[style-name='footnote text'] => p",
"r[style-name='footnote reference'] =>",
"p[style-name='endnote text'] => p",
"r[style-name='endnote reference'] =>",
"p[style-name='annotation text'] => p",
"r[style-name='annotation reference'] =>",
// LibreOffice
"p[style-name='Footnote'] => p",
"r[style-name='Footnote anchor'] =>",
"p[style-name='Endnote'] => p",
"r[style-name='Endnote anchor'] =>",
"p:unordered-list(1) => ul > li:fresh",
"p:unordered-list(2) => ul|ol > li > ul > li:fresh",
"p:unordered-list(3) => ul|ol > li > ul|ol > li > ul > li:fresh",
"p:unordered-list(4) => ul|ol > li > ul|ol > li > ul|ol > li > ul > li:fresh",
"p:unordered-list(5) => ul|ol > li > ul|ol > li > ul|ol > li > ul|ol > li > ul > li:fresh",
"p:ordered-list(1) => ol > li:fresh",
"p:ordered-list(2) => ul|ol > li > ol > li:fresh",
"p:ordered-list(3) => ul|ol > li > ul|ol > li > ol > li:fresh",
"p:ordered-list(4) => ul|ol > li > ul|ol > li > ul|ol > li > ol > li:fresh",
"p:ordered-list(5) => ul|ol > li > ul|ol > li > ul|ol > li > ul|ol > li > ol > li:fresh",
"r[style-name='Hyperlink'] =>",
"p[style-name='Normal'] => p:fresh"
];
var standardOptions = exports._standardOptions = {
transformDocument: identity,
includeDefaultStyleMap: true,
includeEmbeddedStyleMap: true
};
function readOptions(options) {
options = options || {};
return _.extend({}, standardOptions, options, {
customStyleMap: readStyleMap(options.styleMap),
readStyleMap: function() {
var styleMap = this.customStyleMap;
if (this.includeEmbeddedStyleMap) {
styleMap = styleMap.concat(readStyleMap(this.embeddedStyleMap));
}
if (this.includeDefaultStyleMap) {
styleMap = styleMap.concat(defaultStyleMap);
}
return styleMap;
}
});
}
function readStyleMap(styleMap) {
if (!styleMap) {
return [];
} else if (_.isString(styleMap)) {
return styleMap.split("\n")
.map(function(line) {
return line.trim();
})
.filter(function(line) {
return line !== "" && line.charAt(0) !== "#";
});
} else {
return styleMap;
}
}
function identity(value) {
return value;
}
},{"underscore":156}],23:[function(require,module,exports){
var _ = require("underscore");
var bluebird = require("bluebird/js/release/promise")();
exports.defer = defer;
exports.when = bluebird.resolve;
exports.resolve = bluebird.resolve;
exports.all = bluebird.all;
exports.props = bluebird.props;
exports.reject = bluebird.reject;
exports.promisify = bluebird.promisify;
exports.mapSeries = bluebird.mapSeries;
exports.attempt = bluebird.attempt;
exports.nfcall = function(func) {
var args = Array.prototype.slice.call(arguments, 1);
var promisedFunc = bluebird.promisify(func);
return promisedFunc.apply(null, args);
};
bluebird.prototype.fail = bluebird.prototype.caught;
bluebird.prototype.also = function(func) {
return this.then(function(value) {
var returnValue = _.extend({}, value, func(value));
return bluebird.props(returnValue);
});
};
function defer() {
var resolve;
var reject;
var promise = new bluebird.Promise(function(resolveArg, rejectArg) {
resolve = resolveArg;
reject = rejectArg;
});
return {
resolve: resolve,
reject: reject,
promise: promise
};
}
},{"bluebird/js/release/promise":59,"underscore":156}],24:[function(require,module,exports){
var _ = require("underscore");
exports.Result = Result;
exports.success = success;
exports.warning = warning;
exports.error = error;
function Result(value, messages) {
this.value = value;
this.messages = messages || [];
}
Result.prototype.map = function(func) {
return new Result(func(this.value), this.messages);
};
Result.prototype.flatMap = function(func) {
var funcResult = func(this.value);
return new Result(funcResult.value, combineMessages([this, funcResult]));
};
Result.prototype.flatMapThen = function(func) {
var that = this;
return func(this.value).then(function(otherResult) {
return new Result(otherResult.value, combineMessages([that, otherResult]));
});
};
Result.combine = function(results) {
var values = _.flatten(_.pluck(results, "value"));
var messages = combineMessages(results);
return new Result(values, messages);
};
function success(value) {
return new Result(value, []);
}
function warning(message) {
return {
type: "warning",
message: message
};
}
function error(exception) {
return {
type: "error",
message: exception.message,
error: exception
};
}
function combineMessages(results) {
var messages = [];
_.flatten(_.pluck(results, "messages"), true).forEach(function(message) {
if (!containsMessage(messages, message)) {
messages.push(message);
}
});
return messages;
}
function containsMessage(messages, message) {
return _.find(messages, isSameMessage.bind(null, message)) !== undefined;
}
function isSameMessage(first, second) {
return first.type === second.type && first.message === second.message;
}
},{"underscore":156}],25:[function(require,module,exports){
var _ = require("underscore");
var lop = require("lop");
var documentMatchers = require("./styles/document-matchers");
var htmlPaths = require("./styles/html-paths");
var tokenise = require("./styles/parser/tokeniser").tokenise;
var results = require("./results");
exports.readHtmlPath = readHtmlPath;
exports.readDocumentMatcher = readDocumentMatcher;
exports.readStyle = readStyle;
function readStyle(string) {
return parseString(styleRule, string);
}
function createStyleRule() {
return lop.rules.sequence(
lop.rules.sequence.capture(documentMatcherRule()),
lop.rules.tokenOfType("whitespace"),
lop.rules.tokenOfType("arrow"),
lop.rules.sequence.capture(lop.rules.optional(lop.rules.sequence(
lop.rules.tokenOfType("whitespace"),
lop.rules.sequence.capture(htmlPathRule())
).head())),
lop.rules.tokenOfType("end")
).map(function(documentMatcher, htmlPath) {
return {
from: documentMatcher,
to: htmlPath.valueOrElse(htmlPaths.empty)
};
});
}
function readDocumentMatcher(string) {
return parseString(documentMatcherRule(), string);
}
function documentMatcherRule() {
var sequence = lop.rules.sequence;
var identifierToConstant = function(identifier, constant) {
return lop.rules.then(
lop.rules.token("identifier", identifier),
function() {
return constant;
}
);
};
var paragraphRule = identifierToConstant("p", documentMatchers.paragraph);
var runRule = identifierToConstant("r", documentMatchers.run);
var elementTypeRule = lop.rules.firstOf("p or r or table",
paragraphRule,
runRule
);
var styleIdRule = lop.rules.then(
classRule,
function(styleId) {
return {styleId: styleId};
}
);
var styleNameMatcherRule = lop.rules.firstOf("style name matcher",
lop.rules.then(
lop.rules.sequence(
lop.rules.tokenOfType("equals"),
lop.rules.sequence.cut(),
lop.rules.sequence.capture(stringRule)
).head(),
function(styleName) {
return {styleName: documentMatchers.equalTo(styleName)};
}
),
lop.rules.then(
lop.rules.sequence(
lop.rules.tokenOfType("startsWith"),
lop.rules.sequence.cut(),
lop.rules.sequence.capture(stringRule)
).head(),
function(styleName) {
return {styleName: documentMatchers.startsWith(styleName)};
}
)
);
var styleNameRule = lop.rules.sequence(
lop.rules.tokenOfType("open-square-bracket"),
lop.rules.sequence.cut(),
lop.rules.token("identifier", "style-name"),
lop.rules.sequence.capture(styleNameMatcherRule),
lop.rules.tokenOfType("close-square-bracket")
).head();
var listTypeRule = lop.rules.firstOf("list type",
identifierToConstant("ordered-list", {isOrdered: true}),
identifierToConstant("unordered-list", {isOrdered: false})
);
var listRule = sequence(
lop.rules.tokenOfType("colon"),
sequence.capture(listTypeRule),
sequence.cut(),
lop.rules.tokenOfType("open-paren"),
sequence.capture(integerRule),
lop.rules.tokenOfType("close-paren")
).map(function(listType, levelNumber) {
return {
list: {
isOrdered: listType.isOrdered,
levelIndex: levelNumber - 1
}
};
});
function createMatcherSuffixesRule(rules) {
var matcherSuffix = lop.rules.firstOf.apply(
lop.rules.firstOf,
["matcher suffix"].concat(rules)
);
var matcherSuffixes = lop.rules.zeroOrMore(matcherSuffix);
return lop.rules.then(matcherSuffixes, function(suffixes) {
var matcherOptions = {};
suffixes.forEach(function(suffix) {
_.extend(matcherOptions, suffix);
});
return matcherOptions;
});
}
var paragraphOrRun = sequence(
sequence.capture(elementTypeRule),
sequence.capture(createMatcherSuffixesRule([
styleIdRule,
styleNameRule,
listRule
]))
).map(function(createMatcher, matcherOptions) {
return createMatcher(matcherOptions);
});
var table = sequence(
lop.rules.token("identifier", "table"),
sequence.capture(createMatcherSuffixesRule([
styleIdRule,
styleNameRule
]))
).map(function(options) {
return documentMatchers.table(options);
});
var bold = identifierToConstant("b", documentMatchers.bold);
var italic = identifierToConstant("i", documentMatchers.italic);
var underline = identifierToConstant("u", documentMatchers.underline);
var strikethrough = identifierToConstant("strike", documentMatchers.strikethrough);
var smallCaps = identifierToConstant("small-caps", documentMatchers.smallCaps);
var commentReference = identifierToConstant("comment-reference", documentMatchers.commentReference);
var breakMatcher = sequence(
lop.rules.token("identifier", "br"),
sequence.cut(),
lop.rules.tokenOfType("open-square-bracket"),
lop.rules.token("identifier", "type"),
lop.rules.tokenOfType("equals"),
sequence.capture(stringRule),
lop.rules.tokenOfType("close-square-bracket")
).map(function(breakType) {
switch (breakType) {
case "line":
return documentMatchers.lineBreak;
case "page":
return documentMatchers.pageBreak;
case "column":
return documentMatchers.columnBreak;
default:
// TODO: handle unknown document matchers
}
});
return lop.rules.firstOf("element type",
paragraphOrRun,
table,
bold,
italic,
underline,
strikethrough,
smallCaps,
commentReference,
breakMatcher
);
}
function readHtmlPath(string) {
return parseString(htmlPathRule(), string);
}
function htmlPathRule() {
var capture = lop.rules.sequence.capture;
var whitespaceRule = lop.rules.tokenOfType("whitespace");
var freshRule = lop.rules.then(
lop.rules.optional(lop.rules.sequence(
lop.rules.tokenOfType("colon"),
lop.rules.token("identifier", "fresh")
)),
function(option) {
return option.map(function() {
return true;
}).valueOrElse(false);
}
);
var separatorRule = lop.rules.then(
lop.rules.optional(lop.rules.sequence(
lop.rules.tokenOfType("colon"),
lop.rules.token("identifier", "separator"),
lop.rules.tokenOfType("open-paren"),
capture(stringRule),
lop.rules.tokenOfType("close-paren")
).head()),
function(option) {
return option.valueOrElse("");
}
);
var tagNamesRule = lop.rules.oneOrMoreWithSeparator(
identifierRule,
lop.rules.tokenOfType("choice")
);
var styleElementRule = lop.rules.sequence(
capture(tagNamesRule),
capture(lop.rules.zeroOrMore(classRule)),
capture(freshRule),
capture(separatorRule)
).map(function(tagName, classNames, fresh, separator) {
var attributes = {};
var options = {};
if (classNames.length > 0) {
attributes["class"] = classNames.join(" ");
}
if (fresh) {
options.fresh = true;
}
if (separator) {
options.separator = separator;
}
return htmlPaths.element(tagName, attributes, options);
});
return lop.rules.firstOf("html path",
lop.rules.then(lop.rules.tokenOfType("bang"), function() {
return htmlPaths.ignore;
}),
lop.rules.then(
lop.rules.zeroOrMoreWithSeparator(
styleElementRule,
lop.rules.sequence(
whitespaceRule,
lop.rules.tokenOfType("gt"),
whitespaceRule
)
),
htmlPaths.elements
)
);
}
var identifierRule = lop.rules.then(
lop.rules.tokenOfType("identifier"),
decodeEscapeSequences
);
var integerRule = lop.rules.tokenOfType("integer");
var stringRule = lop.rules.then(
lop.rules.tokenOfType("string"),
decodeEscapeSequences
);
var escapeSequences = {
"n": "\n",
"r": "\r",
"t": "\t"
};
function decodeEscapeSequences(value) {
return value.replace(/\\(.)/g, function(match, code) {
return escapeSequences[code] || code;
});
}
var classRule = lop.rules.sequence(
lop.rules.tokenOfType("dot"),
lop.rules.sequence.cut(),
lop.rules.sequence.capture(identifierRule)
).head();
function parseString(rule, string) {
var tokens = tokenise(string);
var parser = lop.Parser();
var parseResult = parser.parseTokens(rule, tokens);
if (parseResult.isSuccess()) {
return results.success(parseResult.value());
} else {
return new results.Result(null, [results.warning(describeFailure(string, parseResult))]);
}
}
function describeFailure(input, parseResult) {
return "Did not understand this style mapping, so ignored it: " + input + "\n" +
parseResult.errors().map(describeError).join("\n");
}
function describeError(error) {
return "Error was at character number " + error.characterNumber() + ": " +
"Expected " + error.expected + " but got " + error.actual;
}
var styleRule = createStyleRule();
},{"./results":24,"./styles/document-matchers":26,"./styles/html-paths":27,"./styles/parser/tokeniser":28,"lop":142,"underscore":156}],26:[function(require,module,exports){
exports.paragraph = paragraph;
exports.run = run;
exports.table = table;
exports.bold = new Matcher("bold");
exports.italic = new Matcher("italic");
exports.underline = new Matcher("underline");
exports.strikethrough = new Matcher("strikethrough");
exports.smallCaps = new Matcher("smallCaps");
exports.commentReference = new Matcher("commentReference");
exports.lineBreak = new Matcher("break", {breakType: "line"});
exports.pageBreak = new Matcher("break", {breakType: "page"});
exports.columnBreak = new Matcher("break", {breakType: "column"});
exports.equalTo = equalTo;
exports.startsWith = startsWith;
function paragraph(options) {
return new Matcher("paragraph", options);
}
function run(options) {
return new Matcher("run", options);
}
function table(options) {
return new Matcher("table", options);
}
function Matcher(elementType, options) {
options = options || {};
this._elementType = elementType;
this._styleId = options.styleId;
this._styleName = options.styleName;
if (options.list) {
this._listIndex = options.list.levelIndex;
this._listIsOrdered = options.list.isOrdered;
}
}
Matcher.prototype.matches = function(element) {
return element.type === this._elementType &&
(this._styleId === undefined || element.styleId === this._styleId) &&
(this._styleName === undefined || (element.styleName && this._styleName.operator(this._styleName.operand, element.styleName))) &&
(this._listIndex === undefined || isList(element, this._listIndex, this._listIsOrdered)) &&
(this._breakType === undefined || this._breakType === element.breakType);
};
function isList(element, levelIndex, isOrdered) {
return element.numbering &&
element.numbering.level == levelIndex &&
element.numbering.isOrdered == isOrdered;
}
function equalTo(value) {
return {
operator: operatorEqualTo,
operand: value
};
}
function startsWith(value) {
return {
operator: operatorStartsWith,
operand: value
};
}
function operatorEqualTo(first, second) {
return first.toUpperCase() === second.toUpperCase();
}
function operatorStartsWith(first, second) {
return second.toUpperCase().indexOf(first.toUpperCase()) === 0;
}
},{}],27:[function(require,module,exports){
var _ = require("underscore");
var html = require("../html");
exports.topLevelElement = topLevelElement;
exports.elements = elements;
exports.element = element;
function topLevelElement(tagName, attributes) {
return elements([element(tagName, attributes, {fresh: true})]);
}
function elements(elementStyles) {
return new HtmlPath(elementStyles.map(function(elementStyle) {
if (_.isString(elementStyle)) {
return element(elementStyle);
} else {
return elementStyle;
}
}));
}
function HtmlPath(elements) {
this._elements = elements;
}
HtmlPath.prototype.wrap = function wrap(children) {
var result = children();
for (var index = this._elements.length - 1; index >= 0; index--) {
result = this._elements[index].wrapNodes(result);
}
return result;
};
function element(tagName, attributes, options) {
options = options || {};
return new Element(tagName, attributes, options);
}
function Element(tagName, attributes, options) {
var tagNames = {};
if (_.isArray(tagName)) {
tagName.forEach(function(tagName) {
tagNames[tagName] = true;
});
tagName = tagName[0];
} else {
tagNames[tagName] = true;
}
this.tagName = tagName;
this.tagNames = tagNames;
this.attributes = attributes || {};
this.fresh = options.fresh;
this.separator = options.separator;
}
Element.prototype.matchesElement = function(element) {
return this.tagNames[element.tagName] && _.isEqual(this.attributes || {}, element.attributes || {});
};
Element.prototype.wrap = function wrap(generateNodes) {
return this.wrapNodes(generateNodes());
};
Element.prototype.wrapNodes = function wrapNodes(nodes) {
return [html.elementWithTag(this, nodes)];
};
exports.empty = elements([]);
exports.ignore = {
wrap: function() {
return [];
}
};
},{"../html":18,"underscore":156}],28:[function(require,module,exports){
var lop = require("lop");
var RegexTokeniser = lop.RegexTokeniser;
exports.tokenise = tokenise;
var stringPrefix = "'((?:\\\\.|[^'])*)";
function tokenise(string) {
var identifierCharacter = "(?:[a-zA-Z\\-_]|\\\\.)";
var tokeniser = new RegexTokeniser([
{name: "identifier", regex: new RegExp("(" + identifierCharacter + "(?:" + identifierCharacter + "|[0-9])*)")},
{name: "dot", regex: /\./},
{name: "colon", regex: /:/},
{name: "gt", regex: />/},
{name: "whitespace", regex: /\s+/},
{name: "arrow", regex: /=>/},
{name: "equals", regex: /=/},
{name: "startsWith", regex: /\^=/},
{name: "open-paren", regex: /\(/},
{name: "close-paren", regex: /\)/},
{name: "open-square-bracket", regex: /\[/},
{name: "close-square-bracket", regex: /\]/},
{name: "string", regex: new RegExp(stringPrefix + "'")},
{name: "unterminated-string", regex: new RegExp(stringPrefix)},
{name: "integer", regex: /([0-9]+)/},
{name: "choice", regex: /\|/},
{name: "bang", regex: /(!)/}
]);
return tokeniser.tokenise(string);
}
},{"lop":142}],29:[function(require,module,exports){
var _ = require("underscore");
exports.paragraph = paragraph;
exports.run = run;
exports._elements = elements;
exports.getDescendantsOfType = getDescendantsOfType;
exports.getDescendants = getDescendants;
function paragraph(transform) {
return elementsOfType("paragraph", transform);
}
function run(transform) {
return elementsOfType("run", transform);
}
function elementsOfType(elementType, transform) {
return elements(function(element) {
if (element.type === elementType) {
return transform(element);
} else {
return element;
}
});
}
function elements(transform) {
return function transformElement(element) {
if (element.children) {
var children = _.map(element.children, transformElement);
element = _.extend(element, {children: children});
}
return transform(element);
};
}
function getDescendantsOfType(element, type) {
return getDescendants(element).filter(function(descendant) {
return descendant.type === type;
});
}
function getDescendants(element) {
var descendants = [];
visitDescendants(element, function(descendant) {
descendants.push(descendant);
});
return descendants;
}
function visitDescendants(element, visit) {
if (element.children) {
element.children.forEach(function(child) {
visitDescendants(child, visit);
visit(child);
});
}
}
},{"underscore":156}],30:[function(require,module,exports){
var htmlPaths = require("./styles/html-paths");
var Html = require("./html");
exports.element = element;
function element(name) {
return function(html) {
return Html.elementWithTag(htmlPaths.element(name), [html]);
};
}
},{"./html":18,"./styles/html-paths":27}],31:[function(require,module,exports){
var util = require("util");
var _ = require("underscore");
exports.writer = writer;
function writer(options) {
options = options || {};
if (options.prettyPrint) {
return prettyWriter();
} else {
return simpleWriter();
}
}
var indentedElements = {
div: true,
p: true,
ul: true,
li: true
};
function prettyWriter() {
var indentationLevel = 0;
var indentation = " ";
var stack = [];
var start = true;
var inText = false;
var writer = simpleWriter();
function open(tagName, attributes) {
if (indentedElements[tagName]) {
indent();
}
stack.push(tagName);
writer.open(tagName, attributes);
if (indentedElements[tagName]) {
indentationLevel++;
}
start = false;
}
function close(tagName) {
if (indentedElements[tagName]) {
indentationLevel--;
indent();
}
stack.pop();
writer.close(tagName);
}
function text(value) {
startText();
writer.text(value.replace("\n", "\n" + indentation));
}
function selfClosing(tagName, attributes) {
indent();
writer.selfClosing(tagName, attributes);
}
function append(html) {
startText();
writer.append(html.replace("\n", "\n" + indentation));
}
function insideIndentedElement() {
return stack.length === 0 || indentedElements[stack[stack.length - 1]];
}
function startText() {
if (!inText) {
indent();
inText = true;
}
}
function indent() {
inText = false;
if (!start && insideIndentedElement()) {
writer.append("\n");
for (var i = 0; i < indentationLevel; i++) {
writer.append(indentation);
}
}
}
return {
asString: writer.asString,
open: open,
close: close,
text: text,
selfClosing: selfClosing,
append: append
};
}
function simpleWriter() {
var fragments = [];
function open(tagName, attributes) {
var attributeString = generateAttributeString(attributes);
fragments.push(util.format("<%s%s>", tagName, attributeString));
}
function close(tagName) {
fragments.push(util.format("</%s>", tagName));
}
function selfClosing(tagName, attributes) {
var attributeString = generateAttributeString(attributes);
fragments.push(util.format("<%s%s />", tagName, attributeString));
}
function generateAttributeString(attributes) {
return _.map(attributes, function(value, key) {
return util.format(' %s="%s"', key, escapeHtmlAttribute(value));
}).join("");
}
function text(value) {
fragments.push(escapeHtmlText(value));
}
function append(html) {
fragments.push(html);
}
function asString() {
return fragments.join("");
}
return {
asString: asString,
open: open,
close: close,
text: text,
selfClosing: selfClosing,
append: append
};
}
function escapeHtmlText(value) {
return value
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>');
}
function escapeHtmlAttribute(value) {
return value
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/</g, '<')
.replace(/>/g, '>');
}
},{"underscore":156,"util":102}],32:[function(require,module,exports){
var htmlWriter = require("./html-writer");
var markdownWriter = require("./markdown-writer");
exports.writer = writer;
function writer(options) {
options = options || {};
if (options.outputFormat === "markdown") {
return markdownWriter.writer();
} else {
return htmlWriter.writer(options);
}
}
},{"./html-writer":31,"./markdown-writer":33}],33:[function(require,module,exports){
var _ = require("underscore");
function symmetricMarkdownElement(end) {
return markdownElement(end, end);
}
function markdownElement(start, end) {
return function() {
return {start: start, end: end};
};
}
function markdownLink(attributes) {
var href = attributes.href || "";
if (href) {
return {
start: "[",
end: "](" + href + ")",
anchorPosition: "before"
};
} else {
return {};
}
}
function markdownImage(attributes) {
var src = attributes.src || "";
var altText = attributes.alt || "";
if (src || altText) {
return {start: "![" + altText + "](" + src + ")"};
} else {
return {};
}
}
function markdownList(options) {
return function(attributes, list) {
return {
start: list ? "\n" : "",
end: list ? "" : "\n",
list: {
isOrdered: options.isOrdered,
indent: list ? list.indent + 1 : 0,
count: 0
}
};
};
}
function markdownListItem(attributes, list, listItem) {
list = list || {indent: 0, isOrdered: false, count: 0};
list.count++;
listItem.hasClosed = false;
var bullet = list.isOrdered ? list.count + "." : "-";
var start = repeatString("\t", list.indent) + bullet + " ";
return {
start: start,
end: function() {
if (!listItem.hasClosed) {
listItem.hasClosed = true;
return "\n";
}
}
};
}
var htmlToMarkdown = {
"p": markdownElement("", "\n\n"),
"br": markdownElement("", " \n"),
"ul": markdownList({isOrdered: false}),
"ol": markdownList({isOrdered: true}),
"li": markdownListItem,
"strong": symmetricMarkdownElement("__"),
"em": symmetricMarkdownElement("*"),
"a": markdownLink,
"img": markdownImage
};
(function() {
for (var i = 1; i <= 6; i++) {
htmlToMarkdown["h" + i] = markdownElement(repeatString("#", i) + " ", "\n\n");
}
})();
function repeatString(value, count) {
return new Array(count + 1).join(value);
}
function markdownWriter() {
var fragments = [];
var elementStack = [];
var list = null;
var listItem = {};
function open(tagName, attributes) {
attributes = attributes || {};
var createElement = htmlToMarkdown[tagName] || function() {
return {};
};
var element = createElement(attributes, list, listItem);
elementStack.push({end: element.end, list: list});
if (element.list) {
list = element.list;
}
var anchorBeforeStart = element.anchorPosition === "before";
if (anchorBeforeStart) {
writeAnchor(attributes);
}
fragments.push(element.start || "");
if (!anchorBeforeStart) {
writeAnchor(attributes);
}
}
function writeAnchor(attributes) {
if (attributes.id) {
fragments.push('<a id="' + attributes.id + '"></a>');
}
}
function close(tagName) {
var element = elementStack.pop();
list = element.list;
var end = _.isFunction(element.end) ? element.end() : element.end;
fragments.push(end || "");
}
function selfClosing(tagName, attributes) {
open(tagName, attributes);
close(tagName);
}
function text(value) {
fragments.push(escapeMarkdown(value));
}
function append(html) {
fragments.push(html);
}
function asString() {
return fragments.join("");
}
return {
asString: asString,
open: open,
close: close,
text: text,
selfClosing: selfClosing,
append: append
};
}
exports.writer = markdownWriter;
function escapeMarkdown(value) {
return value
.replace(/\\/g, '\\\\')
.replace(/([\`\*_\{\}\[\]\(\)\#\+\-\.\!])/g, '\\$1');
}
},{"underscore":156}],34:[function(require,module,exports){
var nodes = require("./nodes");
exports.Element = nodes.Element;
exports.element = nodes.element;
exports.text = nodes.text;
exports.readString = require("./reader").readString;
exports.writeString = require("./writer").writeString;
},{"./nodes":35,"./reader":36,"./writer":37}],35:[function(require,module,exports){
var _ = require("underscore");
exports.Element = Element;
exports.element = function(name, attributes, children) {
return new Element(name, attributes, children);
};
exports.text = function(value) {
return {
type: "text",
value: value
};
};
var emptyElement = {
first: function() {
return null;
},
firstOrEmpty: function() {
return emptyElement;
},
attributes: {}
};
function Element(name, attributes, children) {
this.type = "element";
this.name = name;
this.attributes = attributes || {};
this.children = children || [];
}
Element.prototype.first = function(name) {
return _.find(this.children, function(child) {
return child.name === name;
});
};
Element.prototype.firstOrEmpty = function(name) {
return this.first(name) || emptyElement;
};
Element.prototype.getElementsByTagName = function(name) {
var elements = _.filter(this.children, function(child) {
return child.name === name;
});
return toElementList(elements);
};
Element.prototype.text = function() {
if (this.children.length === 0) {
return "";
} else if (this.children.length !== 1 || this.children[0].type !== "text") {
throw new Error("Not implemented");
}
return this.children[0].value;
};
var elementListPrototype = {
getElementsByTagName: function(name) {
return toElementList(_.flatten(this.map(function(element) {
return element.getElementsByTagName(name);
}, true)));
}
};
function toElementList(array) {
return _.extend(array, elementListPrototype);
}
},{"underscore":156}],36:[function(require,module,exports){
var promises = require("../promises");
var sax = require("sax");
var _ = require("underscore");
var nodes = require("./nodes");
var Element = nodes.Element;
exports.readString = readString;
function readString(xmlString, namespaceMap) {
namespaceMap = namespaceMap || {};
var finished = false;
var parser = sax.parser(true, {xmlns: true, position: false});
var rootElement = {children: []};
var currentElement = rootElement;
var stack = [];
var deferred = promises.defer();
parser.onopentag = function(node) {
var attributes = mapObject(node.attributes, function(attribute) {
return attribute.value;
}, mapName);
var element = new Element(mapName(node), attributes);
currentElement.children.push(element);
stack.push(currentElement);
currentElement = element;
};
function mapName(node) {
if (node.uri) {
var mappedPrefix = namespaceMap[node.uri];
var prefix;
if (mappedPrefix) {
prefix = mappedPrefix + ":";
} else {
prefix = "{" + node.uri + "}";
}
return prefix + node.local;
} else {
return node.local;
}
}
parser.onclosetag = function(node) {
currentElement = stack.pop();
};
parser.ontext = function(text) {
if (currentElement !== rootElement) {
currentElement.children.push(nodes.text(text));
}
};
parser.onend = function() {
if (!finished) {
finished = true;
deferred.resolve(rootElement.children[0]);
}
};
parser.onerror = function(error) {
if (!finished) {
finished = true;
deferred.reject(error);
}
};
parser.write(xmlString).close();
return deferred.promise;
}
function mapObject(input, valueFunc, keyFunc) {
return _.reduce(input, function(result, value, key) {
var mappedKey = keyFunc(value, key, input);
result[mappedKey] = valueFunc(value, key, input);
return result;
}, {});
}
},{"../promises":23,"./nodes":35,"sax":155,"underscore":156}],37:[function(require,module,exports){
var _ = require("underscore");
var xmlbuilder = require("xmlbuilder");
exports.writeString = writeString;
function writeString(root, namespaces) {
var uriToPrefix = _.invert(namespaces);
var nodeWriters = {
element: writeElement,
text: writeTextNode
};
function writeNode(builder, node) {
return nodeWriters[node.type](builder, node);
}
function writeElement(builder, element) {
var elementBuilder = builder.element(mapElementName(element.name), element.attributes);
element.children.forEach(function(child) {
writeNode(elementBuilder, child);
});
}
function mapElementName(name) {
var longFormMatch = /^\{(.*)\}(.*)$/.exec(name);
if (longFormMatch) {
var prefix = uriToPrefix[longFormMatch[1]];
return prefix + (prefix === "" ? "" : ":") + longFormMatch[2];
} else {
return name;
}
}
function writeDocument(root) {
var builder = xmlbuilder
.create(mapElementName(root.name), {
version: '1.0',
encoding: 'UTF-8',
standalone: true
});
_.forEach(namespaces, function(uri, prefix) {
var key = "xmlns" + (prefix === "" ? "" : ":" + prefix);
builder.attribute(key, uri);
});
root.children.forEach(function(child) {
writeNode(builder, child);
});
return builder.end();
}
return writeDocument(root);
}
function writeTextNode(builder, node) {
builder.text(node.value);
}
},{"underscore":156,"xmlbuilder":173}],38:[function(require,module,exports){
(function (Buffer){
var JSZip = require("jszip");
var promises = require("./promises");
exports.openArrayBuffer = openArrayBuffer;
function openArrayBuffer(arrayBuffer) {
var zipFile = new JSZip(arrayBuffer);
function exists(name) {
return zipFile.file(name) !== null;
}
function read(name, encoding) {
var array = zipFile.file(name).asUint8Array();
var buffer = new Buffer(array);
if (encoding) {
return promises.when(buffer.toString(encoding));
} else {
return promises.when(buffer);
}
}
function write(name, contents) {
zipFile.file(name, contents);
}
function toBuffer() {
return zipFile.generate({type: "nodebuffer"});
}
return {
exists: exists,
read: read,
write: write,
toBuffer: toBuffer
};
}
}).call(this,require("buffer").Buffer)
},{"./promises":23,"buffer":75,"jszip":111}],39:[function(require,module,exports){
"use strict";
module.exports = function(Promise) {
var SomePromiseArray = Promise._SomePromiseArray;
function any(promises) {
var ret = new SomePromiseArray(promises);
var promise = ret.promise();
ret.setHowMany(1);
ret.setUnwrap();
ret.init();
return promise;
}
Promise.any = function (promises) {
return any(promises);
};
Promise.prototype.any = function () {
return any(this);
};
};
},{}],40:[function(require,module,exports){
(function (process){
"use strict";
var firstLineError;
try {throw new Error(); } catch (e) {firstLineError = e;}
var schedule = require("./schedule");
var Queue = require("./queue");
var util = require("./util");
function Async() {
this._customScheduler = false;
this._isTickUsed = false;
this._lateQueue = new Queue(16);
this._normalQueue = new Queue(16);
this._haveDrainedQueues = false;
this._trampolineEnabled = true;
var self = this;
this.drainQueues = function () {
self._drainQueues();
};
this._schedule = schedule;
}
Async.prototype.setScheduler = function(fn) {
var prev = this._schedule;
this._schedule = fn;
this._customScheduler = true;
return prev;
};
Async.prototype.hasCustomScheduler = function() {
return this._customScheduler;
};
Async.prototype.enableTrampoline = function() {
this._trampolineEnabled = true;
};
Async.prototype.disableTrampolineIfNecessary = function() {
if (util.hasDevTools) {
this._trampolineEnabled = false;
}
};
Async.prototype.haveItemsQueued = function () {
return this._isTickUsed || this._haveDrainedQueues;
};
Async.prototype.fatalError = function(e, isNode) {
if (isNode) {
process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e) +
"\n");
process.exit(2);
} else {
this.throwLater(e);
}
};
Async.prototype.throwLater = function(fn, arg) {
if (arguments.length === 1) {
arg = fn;
fn = function () { throw arg; };
}
if (typeof setTimeout !== "undefined") {
setTimeout(function() {
fn(arg);
}, 0);
} else try {
this._schedule(function() {
fn(arg);
});
} catch (e) {
throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
};
function AsyncInvokeLater(fn, receiver, arg) {
this._lateQueue.push(fn, receiver, arg);
this._queueTick();
}
function AsyncInvoke(fn, receiver, arg) {
this._normalQueue.push(fn, receiver, arg);
this._queueTick();
}
function AsyncSettlePromises(promise) {
this._normalQueue._pushOne(promise);
this._queueTick();
}
if (!util.hasDevTools) {
Async.prototype.invokeLater = AsyncInvokeLater;
Async.prototype.invoke = AsyncInvoke;
Async.prototype.settlePromises = AsyncSettlePromises;
} else {
Async.prototype.invokeLater = function (fn, receiver, arg) {
if (this._trampolineEnabled) {
AsyncInvokeLater.call(this, fn, receiver, arg);
} else {
this._schedule(function() {
setTimeout(function() {
fn.call(receiver, arg);
}, 100);
});
}
};
Async.prototype.invoke = function (fn, receiver, arg) {
if (this._trampolineEnabled) {
AsyncInvoke.call(this, fn, receiver, arg);
} else {
this._schedule(function() {
fn.call(receiver, arg);
});
}
};
Async.prototype.settlePromises = function(promise) {
if (this._trampolineEnabled) {
AsyncSettlePromises.call(this, promise);
} else {
this._schedule(function() {
promise._settlePromises();
});
}
};
}
Async.prototype._drainQueue = function(queue) {
while (queue.length() > 0) {
var fn = queue.shift();
if (typeof fn !== "function") {
fn._settlePromises();
continue;
}
var receiver = queue.shift();
var arg = queue.shift();
fn.call(receiver, arg);
}
};
Async.prototype._drainQueues = function () {
this._drainQueue(this._normalQueue);
this._reset();
this._haveDrainedQueues = true;
this._drainQueue(this._lateQueue);
};
Async.prototype._queueTick = function () {
if (!this._isTickUsed) {
this._isTickUsed = true;
this._schedule(this.drainQueues);
}
};
Async.prototype._reset = function () {
this._isTickUsed = false;
};
module.exports = Async;
module.exports.firstLineError = firstLineError;
}).call(this,require('_process'))
},{"./queue":63,"./schedule":66,"./util":73,"_process":83}],41:[function(require,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) {
var calledBind = false;
var rejectThis = function(_, e) {
this._reject(e);
};
var targetRejected = function(e, context) {
context.promiseRejectionQueued = true;
context.bindingPromise._then(rejectThis, rejectThis, null, this, e);
};
var bindingResolved = function(thisArg, context) {
if (((this._bitField & 50397184) === 0)) {
this._resolveCallback(context.target);
}
};
var bindingRejected = function(e, context) {
if (!context.promiseRejectionQueued) this._reject(e);
};
Promise.prototype.bind = function (thisArg) {
if (!calledBind) {
calledBind = true;
Promise.prototype._propagateFrom = debug.propagateFromFunction();
Promise.prototype._boundValue = debug.boundValueFunction();
}
var maybePromise = tryConvertToPromise(thisArg);
var ret = new Promise(INTERNAL);
ret._propagateFrom(this, 1);
var target = this._target();
ret._setBoundTo(maybePromise);
if (maybePromise instanceof Promise) {
var context = {
promiseRejectionQueued: false,
promise: ret,
target: target,
bindingPromise: maybePromise
};
target._then(INTERNAL, targetRejected, undefined, ret, context);
maybePromise._then(
bindingResolved, bindingRejected, undefined, ret, context);
ret._setOnCancel(maybePromise);
} else {
ret._resolveCallback(target);
}
return ret;
};
Promise.prototype._setBoundTo = function (obj) {
if (obj !== undefined) {
this._bitField = this._bitField | 2097152;
this._boundTo = obj;
} else {
this._bitField = this._bitField & (~2097152);
}
};
Promise.prototype._isBound = function () {
return (this._bitField & 2097152) === 2097152;
};
Promise.bind = function (thisArg, value) {
return Promise.resolve(value).bind(thisArg);
};
};
},{}],42:[function(require,module,exports){
"use strict";
var cr = Object.create;
if (cr) {
var callerCache = cr(null);
var getterCache = cr(null);
callerCache[" size"] = getterCache[" size"] = 0;
}
module.exports = function(Promise) {
var util = require("./util");
var canEvaluate = util.canEvaluate;
var isIdentifier = util.isIdentifier;
var getMethodCaller;
var getGetter;
if (!false) {
var makeMethodCaller = function (methodName) {
return new Function("ensureMethod", " \n\
return function(obj) { \n\
'use strict' \n\
var len = this.length; \n\
ensureMethod(obj, 'methodName'); \n\
switch(len) { \n\
case 1: return obj.methodName(this[0]); \n\
case 2: return obj.methodName(this[0], this[1]); \n\
case 3: return obj.methodName(this[0], this[1], this[2]); \n\
case 0: return obj.methodName(); \n\
default: \n\
return obj.methodName.apply(obj, this); \n\
} \n\
}; \n\
".replace(/methodName/g, methodName))(ensureMethod);
};
var makeGetter = function (propertyName) {
return new Function("obj", " \n\
'use strict'; \n\
return obj.propertyName; \n\
".replace("propertyName", propertyName));
};
var getCompiled = function(name, compiler, cache) {
var ret = cache[name];
if (typeof ret !== "function") {
if (!isIdentifier(name)) {
return null;
}
ret = compiler(name);
cache[name] = ret;
cache[" size"]++;
if (cache[" size"] > 512) {
var keys = Object.keys(cache);
for (var i = 0; i < 256; ++i) delete cache[keys[i]];
cache[" size"] = keys.length - 256;
}
}
return ret;
};
getMethodCaller = function(name) {
return getCompiled(name, makeMethodCaller, callerCache);
};
getGetter = function(name) {
return getCompiled(name, makeGetter, getterCache);
};
}
function ensureMethod(obj, methodName) {
var fn;
if (obj != null) fn = obj[methodName];
if (typeof fn !== "function") {
var message = "Object " + util.classString(obj) + " has no method '" +
util.toString(methodName) + "'";
throw new Promise.TypeError(message);
}
return fn;
}
function caller(obj) {
var methodName = this.pop();
var fn = ensureMethod(obj, methodName);
return fn.apply(obj, this);
}
Promise.prototype.call = function (methodName) {
var $_len = arguments.length;var args = new Array(Math.max($_len - 1, 0)); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];};
if (!false) {
if (canEvaluate) {
var maybeCaller = getMethodCaller(methodName);
if (maybeCaller !== null) {
return this._then(
maybeCaller, undefined, undefined, args, undefined);
}
}
}
args.push(methodName);
return this._then(caller, undefined, undefined, args, undefined);
};
function namedGetter(obj) {
return obj[this];
}
function indexedGetter(obj) {
var index = +this;
if (index < 0) index = Math.max(0, index + obj.length);
return obj[index];
}
Promise.prototype.get = function (propertyName) {
var isIndex = (typeof propertyName === "number");
var getter;
if (!isIndex) {
if (canEvaluate) {
var maybeGetter = getGetter(propertyName);
getter = maybeGetter !== null ? maybeGetter : namedGetter;
} else {
getter = namedGetter;
}
} else {
getter = indexedGetter;
}
return this._then(getter, undefined, undefined, propertyName, undefined);
};
};
},{"./util":73}],43:[function(require,module,exports){
"use strict";
module.exports = function(Promise, PromiseArray, apiRejection, debug) {
var util = require("./util");
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
var async = Promise._async;
Promise.prototype["break"] = Promise.prototype.cancel = function() {
if (!debug.cancellation()) return this._warn("cancellation is disabled");
var promise = this;
var child = promise;
while (promise._isCancellable()) {
if (!promise._cancelBy(child)) {
if (child._isFollowing()) {
child._followee().cancel();
} else {
child._cancelBranched();
}
break;
}
var parent = promise._cancellationParent;
if (parent == null || !parent._isCancellable()) {
if (promise._isFollowing()) {
promise._followee().cancel();
} else {
promise._cancelBranched();
}
break;
} else {
if (promise._isFollowing()) promise._followee().cancel();
promise._setWillBeCancelled();
child = promise;
promise = parent;
}
}
};
Promise.prototype._branchHasCancelled = function() {
this._branchesRemainingToCancel--;
};
Promise.prototype._enoughBranchesHaveCancelled = function() {
return this._branchesRemainingToCancel === undefined ||
this._branchesRemainingToCancel <= 0;
};
Promise.prototype._cancelBy = function(canceller) {
if (canceller === this) {
this._branchesRemainingToCancel = 0;
this._invokeOnCancel();
return true;
} else {
this._branchHasCancelled();
if (this._enoughBranchesHaveCancelled()) {
this._invokeOnCancel();
return true;
}
}
return false;
};
Promise.prototype._cancelBranched = function() {
if (this._enoughBranchesHaveCancelled()) {
this._cancel();
}
};
Promise.prototype._cancel = function() {
if (!this._isCancellable()) return;
this._setCancelled();
async.invoke(this._cancelPromises, this, undefined);
};
Promise.prototype._cancelPromises = function() {
if (this._length() > 0) this._settlePromises();
};
Promise.prototype._unsetOnCancel = function() {
this._onCancelField = undefined;
};
Promise.prototype._isCancellable = function() {
return this.isPending() && !this._isCancelled();
};
Promise.prototype.isCancellable = function() {
return this.isPending() && !this.isCancelled();
};
Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) {
if (util.isArray(onCancelCallback)) {
for (var i = 0; i < onCancelCallback.length; ++i) {
this._doInvokeOnCancel(onCancelCallback[i], internalOnly);
}
} else if (onCancelCallback !== undefined) {
if (typeof onCancelCallback === "function") {
if (!internalOnly) {
var e = tryCatch(onCancelCallback).call(this._boundValue());
if (e === errorObj) {
this._attachExtraTrace(e.e);
async.throwLater(e.e);
}
}
} else {
onCancelCallback._resultCancelled(this);
}
}
};
Promise.prototype._invokeOnCancel = function() {
var onCancelCallback = this._onCancel();
this._unsetOnCancel();
async.invoke(this._doInvokeOnCancel, this, onCancelCallback);
};
Promise.prototype._invokeInternalOnCancel = function() {
if (this._isCancellable()) {
this._doInvokeOnCancel(this._onCancel(), true);
this._unsetOnCancel();
}
};
Promise.prototype._resultCancelled = function() {
this.cancel();
};
};
},{"./util":73}],44:[function(require,module,exports){
"use strict";
module.exports = function(NEXT_FILTER) {
var util = require("./util");
var getKeys = require("./es5").keys;
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
function catchFilter(instances, cb, promise) {
return function(e) {
var boundTo = promise._boundValue();
predicateLoop: for (var i = 0; i < instances.length; ++i) {
var item = instances[i];
if (item === Error ||
(item != null && item.prototype instanceof Error)) {
if (e instanceof item) {
return tryCatch(cb).call(boundTo, e);
}
} else if (typeof item === "function") {
var matchesPredicate = tryCatch(item).call(boundTo, e);
if (matchesPredicate === errorObj) {
return matchesPredicate;
} else if (matchesPredicate) {
return tryCatch(cb).call(boundTo, e);
}
} else if (util.isObject(e)) {
var keys = getKeys(item);
for (var j = 0; j < keys.length; ++j) {
var key = keys[j];
if (item[key] != e[key]) {
continue predicateLoop;
}
}
return tryCatch(cb).call(boundTo, e);
}
}
return NEXT_FILTER;
};
}
return catchFilter;
};
},{"./es5":50,"./util":73}],45:[function(require,module,exports){
"use strict";
module.exports = function(Promise) {
var longStackTraces = false;
var contextStack = [];
Promise.prototype._promiseCreated = function() {};
Promise.prototype._pushContext = function() {};
Promise.prototype._popContext = function() {return null;};
Promise._peekContext = Promise.prototype._peekContext = function() {};
function Context() {
this._trace = new Context.CapturedTrace(peekContext());
}
Context.prototype._pushContext = function () {
if (this._trace !== undefined) {
this._trace._promiseCreated = null;
contextStack.push(this._trace);
}
};
Context.prototype._popContext = function () {
if (this._trace !== undefined) {
var trace = contextStack.pop();
var ret = trace._promiseCreated;
trace._promiseCreated = null;
return ret;
}
return null;
};
function createContext() {
if (longStackTraces) return new Context();
}
function peekContext() {
var lastIndex = contextStack.length - 1;
if (lastIndex >= 0) {
return contextStack[lastIndex];
}
return undefined;
}
Context.CapturedTrace = null;
Context.create = createContext;
Context.deactivateLongStackTraces = function() {};
Context.activateLongStackTraces = function() {
var Promise_pushContext = Promise.prototype._pushContext;
var Promise_popContext = Promise.prototype._popContext;
var Promise_PeekContext = Promise._peekContext;
var Promise_peekContext = Promise.prototype._peekContext;
var Promise_promiseCreated = Promise.prototype._promiseCreated;
Context.deactivateLongStackTraces = function() {
Promise.prototype._pushContext = Promise_pushContext;
Promise.prototype._popContext = Promise_popContext;
Promise._peekContext = Promise_PeekContext;
Promise.prototype._peekContext = Promise_peekContext;
Promise.prototype._promiseCreated = Promise_promiseCreated;
longStackTraces = false;
};
longStackTraces = true;
Promise.prototype._pushContext = Context.prototype._pushContext;
Promise.prototype._popContext = Context.prototype._popContext;
Promise._peekContext = Promise.prototype._peekContext = peekContext;
Promise.prototype._promiseCreated = function() {
var ctx = this._peekContext();
if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this;
};
};
return Context;
};
},{}],46:[function(require,module,exports){
(function (process){
"use strict";
module.exports = function(Promise, Context) {
var getDomain = Promise._getDomain;
var async = Promise._async;
var Warning = require("./errors").Warning;
var util = require("./util");
var canAttachTrace = util.canAttachTrace;
var unhandledRejectionHandled;
var possiblyUnhandledRejection;
var bluebirdFramePattern =
/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/;
var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/;
var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/;
var stackFramePattern = null;
var formatStack = null;
var indentStackFrames = false;
var printWarning;
var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 &&
(false ||
util.env("BLUEBIRD_DEBUG") ||
util.env("NODE_ENV") === "development"));
var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 &&
(debugging || util.env("BLUEBIRD_WARNINGS")));
var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 &&
(debugging || util.env("BLUEBIRD_LONG_STACK_TRACES")));
var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 &&
(warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN"));
Promise.prototype.suppressUnhandledRejections = function() {
var target = this._target();
target._bitField = ((target._bitField & (~1048576)) |
524288);
};
Promise.prototype._ensurePossibleRejectionHandled = function () {
if ((this._bitField & 524288) !== 0) return;
this._setRejectionIsUnhandled();
async.invokeLater(this._notifyUnhandledRejection, this, undefined);
};
Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
fireRejectionEvent("rejectionHandled",
unhandledRejectionHandled, undefined, this);
};
Promise.prototype._setReturnedNonUndefined = function() {
this._bitField = this._bitField | 268435456;
};
Promise.prototype._returnedNonUndefined = function() {
return (this._bitField & 268435456) !== 0;
};
Promise.prototype._notifyUnhandledRejection = function () {
if (this._isRejectionUnhandled()) {
var reason = this._settledValue();
this._setUnhandledRejectionIsNotified();
fireRejectionEvent("unhandledRejection",
possiblyUnhandledRejection, reason, this);
}
};
Promise.prototype._setUnhandledRejectionIsNotified = function () {
this._bitField = this._bitField | 262144;
};
Promise.prototype._unsetUnhandledRejectionIsNotified = function () {
this._bitField = this._bitField & (~262144);
};
Promise.prototype._isUnhandledRejectionNotified = function () {
return (this._bitField & 262144) > 0;
};
Promise.prototype._setRejectionIsUnhandled = function () {
this._bitField = this._bitField | 1048576;
};
Promise.prototype._unsetRejectionIsUnhandled = function () {
this._bitField = this._bitField & (~1048576);
if (this._isUnhandledRejectionNotified()) {
this._unsetUnhandledRejectionIsNotified();
this._notifyUnhandledRejectionIsHandled();
}
};
Promise.prototype._isRejectionUnhandled = function () {
return (this._bitField & 1048576) > 0;
};
Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) {
return warn(message, shouldUseOwnTrace, promise || this);
};
Promise.onPossiblyUnhandledRejection = function (fn) {
var domain = getDomain();
possiblyUnhandledRejection =
typeof fn === "function" ? (domain === null ?
fn : util.domainBind(domain, fn))
: undefined;
};
Promise.onUnhandledRejectionHandled = function (fn) {
var domain = getDomain();
unhandledRejectionHandled =
typeof fn === "function" ? (domain === null ?
fn : util.domainBind(domain, fn))
: undefined;
};
var disableLongStackTraces = function() {};
Promise.longStackTraces = function () {
if (async.haveItemsQueued() && !config.longStackTraces) {
throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
if (!config.longStackTraces && longStackTracesIsSupported()) {
var Promise_captureStackTrace = Promise.prototype._captureStackTrace;
var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace;
config.longStackTraces = true;
disableLongStackTraces = function() {
if (async.haveItemsQueued() && !config.longStackTraces) {
throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
Promise.prototype._captureStackTrace = Promise_captureStackTrace;
Promise.prototype._attachExtraTrace = Promise_attachExtraTrace;
Context.deactivateLongStackTraces();
async.enableTrampoline();
config.longStackTraces = false;
};
Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace;
Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace;
Context.activateLongStackTraces();
async.disableTrampolineIfNecessary();
}
};
Promise.hasLongStackTraces = function () {
return config.longStackTraces && longStackTracesIsSupported();
};
var fireDomEvent = (function() {
try {
if (typeof CustomEvent === "function") {
var event = new CustomEvent("CustomEvent");
util.global.dispatchEvent(event);
return function(name, event) {
var domEvent = new CustomEvent(name.toLowerCase(), {
detail: event,
cancelable: true
});
return !util.global.dispatchEvent(domEvent);
};
} else if (typeof Event === "function") {
var event = new Event("CustomEvent");
util.global.dispatchEvent(event);
return function(name, event) {
var domEvent = new Event(name.toLowerCase(), {
cancelable: true
});
domEvent.detail = event;
return !util.global.dispatchEvent(domEvent);
};
} else {
var event = document.createEvent("CustomEvent");
event.initCustomEvent("testingtheevent", false, true, {});
util.global.dispatchEvent(event);
return function(name, event) {
var domEvent = document.createEvent("CustomEvent");
domEvent.initCustomEvent(name.toLowerCase(), false, true,
event);
return !util.global.dispatchEvent(domEvent);
};
}
} catch (e) {}
return function() {
return false;
};
})();
var fireGlobalEvent = (function() {
if (util.isNode) {
return function() {
return process.emit.apply(process, arguments);
};
} else {
if (!util.global) {
return function() {
return false;
};
}
return function(name) {
var methodName = "on" + name.toLowerCase();
var method = util.global[methodName];
if (!method) return false;
method.apply(util.global, [].slice.call(arguments, 1));
return true;
};
}
})();
function generatePromiseLifecycleEventObject(name, promise) {
return {promise: promise};
}
var eventToObjectGenerator = {
promiseCreated: generatePromiseLifecycleEventObject,
promiseFulfilled: generatePromiseLifecycleEventObject,
promiseRejected: generatePromiseLifecycleEventObject,
promiseResolved: generatePromiseLifecycleEventObject,
promiseCancelled: generatePromiseLifecycleEventObject,
promiseChained: function(name, promise, child) {
return {promise: promise, child: child};
},
warning: function(name, warning) {
return {warning: warning};
},
unhandledRejection: function (name, reason, promise) {
return {reason: reason, promise: promise};
},
rejectionHandled: generatePromiseLifecycleEventObject
};
var activeFireEvent = function (name) {
var globalEventFired = false;
try {
globalEventFired = fireGlobalEvent.apply(null, arguments);
} catch (e) {
async.throwLater(e);
globalEventFired = true;
}
var domEventFired = false;
try {
domEventFired = fireDomEvent(name,
eventToObjectGenerator[name].apply(null, arguments));
} catch (e) {
async.throwLater(e);
domEventFired = true;
}
return domEventFired || globalEventFired;
};
Promise.config = function(opts) {
opts = Object(opts);
if ("longStackTraces" in opts) {
if (opts.longStackTraces) {
Promise.longStackTraces();
} else if (!opts.longStackTraces && Promise.hasLongStackTraces()) {
disableLongStackTraces();
}
}
if ("warnings" in opts) {
var warningsOption = opts.warnings;
config.warnings = !!warningsOption;
wForgottenReturn = config.warnings;
if (util.isObject(warningsOption)) {
if ("wForgottenReturn" in warningsOption) {
wForgottenReturn = !!warningsOption.wForgottenReturn;
}
}
}
if ("cancellation" in opts && opts.cancellation && !config.cancellation) {
if (async.haveItemsQueued()) {
throw new Error(
"cannot enable cancellation after promises are in use");
}
Promise.prototype._clearCancellationData =
cancellationClearCancellationData;
Promise.prototype._propagateFrom = cancellationPropagateFrom;
Promise.prototype._onCancel = cancellationOnCancel;
Promise.prototype._setOnCancel = cancellationSetOnCancel;
Promise.prototype._attachCancellationCallback =
cancellationAttachCancellationCallback;
Promise.prototype._execute = cancellationExecute;
propagateFromFunction = cancellationPropagateFrom;
config.cancellation = true;
}
if ("monitoring" in opts) {
if (opts.monitoring && !config.monitoring) {
config.monitoring = true;
Promise.prototype._fireEvent = activeFireEvent;
} else if (!opts.monitoring && config.monitoring) {
config.monitoring = false;
Promise.prototype._fireEvent = defaultFireEvent;
}
}
return Promise;
};
function defaultFireEvent() { return false; }
Promise.prototype._fireEvent = defaultFireEvent;
Promise.prototype._execute = function(executor, resolve, reject) {
try {
executor(resolve, reject);
} catch (e) {
return e;
}
};
Promise.prototype._onCancel = function () {};
Promise.prototype._setOnCancel = function (handler) { ; };
Promise.prototype._attachCancellationCallback = function(onCancel) {
;
};
Promise.prototype._captureStackTrace = function () {};
Promise.prototype._attachExtraTrace = function () {};
Promise.prototype._clearCancellationData = function() {};
Promise.prototype._propagateFrom = function (parent, flags) {
;
;
};
function cancellationExecute(executor, resolve, reject) {
var promise = this;
try {
executor(resolve, reject, function(onCancel) {
if (typeof onCancel !== "function") {
throw new TypeError("onCancel must be a function, got: " +
util.toString(onCancel));
}
promise._attachCancellationCallback(onCancel);
});
} catch (e) {
return e;
}
}
function cancellationAttachCancellationCallback(onCancel) {
if (!this._isCancellable()) return this;
var previousOnCancel = this._onCancel();
if (previousOnCancel !== undefined) {
if (util.isArray(previousOnCancel)) {
previousOnCancel.push(onCancel);
} else {
this._setOnCancel([previousOnCancel, onCancel]);
}
} else {
this._setOnCancel(onCancel);
}
}
function cancellationOnCancel() {
return this._onCancelField;
}
function cancellationSetOnCancel(onCancel) {
this._onCancelField = onCancel;
}
function cancellationClearCancellationData() {
this._cancellationParent = undefined;
this._onCancelField = undefined;
}
function cancellationPropagateFrom(parent, flags) {
if ((flags & 1) !== 0) {
this._cancellationParent = parent;
var branchesRemainingToCancel = parent._branchesRemainingToCancel;
if (branchesRemainingToCancel === undefined) {
branchesRemainingToCancel = 0;
}
parent._branchesRemainingToCancel = branchesRemainingToCancel + 1;
}
if ((flags & 2) !== 0 && parent._isBound()) {
this._setBoundTo(parent._boundTo);
}
}
function bindingPropagateFrom(parent, flags) {
if ((flags & 2) !== 0 && parent._isBound()) {
this._setBoundTo(parent._boundTo);
}
}
var propagateFromFunction = bindingPropagateFrom;
function boundValueFunction() {
var ret = this._boundTo;
if (ret !== undefined) {
if (ret instanceof Promise) {
if (ret.isFulfilled()) {
return ret.value();
} else {
return undefined;
}
}
}
return ret;
}
function longStackTracesCaptureStackTrace() {
this._trace = new CapturedTrace(this._peekContext());
}
function longStackTracesAttachExtraTrace(error, ignoreSelf) {
if (canAttachTrace(error)) {
var trace = this._trace;
if (trace !== undefined) {
if (ignoreSelf) trace = trace._parent;
}
if (trace !== undefined) {
trace.attachExtraTrace(error);
} else if (!error.__stackCleaned__) {
var parsed = parseStackAndMessage(error);
util.notEnumerableProp(error, "stack",
parsed.message + "\n" + parsed.stack.join("\n"));
util.notEnumerableProp(error, "__stackCleaned__", true);
}
}
}
function checkForgottenReturns(returnValue, promiseCreated, name, promise,
parent) {
if (returnValue === undefined && promiseCreated !== null &&
wForgottenReturn) {
if (parent !== undefined && parent._returnedNonUndefined()) return;
if ((promise._bitField & 65535) === 0) return;
if (name) name = name + " ";
var handlerLine = "";
var creatorLine = "";
if (promiseCreated._trace) {
var traceLines = promiseCreated._trace.stack.split("\n");
var stack = cleanStack(traceLines);
for (var i = stack.length - 1; i >= 0; --i) {
var line = stack[i];
if (!nodeFramePattern.test(line)) {
var lineMatches = line.match(parseLinePattern);
if (lineMatches) {
handlerLine = "at " + lineMatches[1] +
":" + lineMatches[2] + ":" + lineMatches[3] + " ";
}
break;
}
}
if (stack.length > 0) {
var firstUserLine = stack[0];
for (var i = 0; i < traceLines.length; ++i) {
if (traceLines[i] === firstUserLine) {
if (i > 0) {
creatorLine = "\n" + traceLines[i - 1];
}
break;
}
}
}
}
var msg = "a promise was created in a " + name +
"handler " + handlerLine + "but was not returned from it, " +
"see http://goo.gl/rRqMUw" +
creatorLine;
promise._warn(msg, true, promiseCreated);
}
}
function deprecated(name, replacement) {
var message = name +
" is deprecated and will be removed in a future version.";
if (replacement) message += " Use " + replacement + " instead.";
return warn(message);
}
function warn(message, shouldUseOwnTrace, promise) {
if (!config.warnings) return;
var warning = new Warning(message);
var ctx;
if (shouldUseOwnTrace) {
promise._attachExtraTrace(warning);
} else if (config.longStackTraces && (ctx = Promise._peekContext())) {
ctx.attachExtraTrace(warning);
} else {
var parsed = parseStackAndMessage(warning);
warning.stack = parsed.message + "\n" + parsed.stack.join("\n");
}
if (!activeFireEvent("warning", warning)) {
formatAndLogError(warning, "", true);
}
}
function reconstructStack(message, stacks) {
for (var i = 0; i < stacks.length - 1; ++i) {
stacks[i].push("From previous event:");
stacks[i] = stacks[i].join("\n");
}
if (i < stacks.length) {
stacks[i] = stacks[i].join("\n");
}
return message + "\n" + stacks.join("\n");
}
function removeDuplicateOrEmptyJumps(stacks) {
for (var i = 0; i < stacks.length; ++i) {
if (stacks[i].length === 0 ||
((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) {
stacks.splice(i, 1);
i--;
}
}
}
function removeCommonRoots(stacks) {
var current = stacks[0];
for (var i = 1; i < stacks.length; ++i) {
var prev = stacks[i];
var currentLastIndex = current.length - 1;
var currentLastLine = current[currentLastIndex];
var commonRootMeetPoint = -1;
for (var j = prev.length - 1; j >= 0; --j) {
if (prev[j] === currentLastLine) {
commonRootMeetPoint = j;
break;
}
}
for (var j = commonRootMeetPoint; j >= 0; --j) {
var line = prev[j];
if (current[currentLastIndex] === line) {
current.pop();
currentLastIndex--;
} else {
break;
}
}
current = prev;
}
}
function cleanStack(stack) {
var ret = [];
for (var i = 0; i < stack.length; ++i) {
var line = stack[i];
var isTraceLine = " (No stack trace)" === line ||
stackFramePattern.test(line);
var isInternalFrame = isTraceLine && shouldIgnore(line);
if (isTraceLine && !isInternalFrame) {
if (indentStackFrames && line.charAt(0) !== " ") {
line = " " + line;
}
ret.push(line);
}
}
return ret;
}
function stackFramesAsArray(error) {
var stack = error.stack.replace(/\s+$/g, "").split("\n");
for (var i = 0; i < stack.length; ++i) {
var line = stack[i];
if (" (No stack trace)" === line || stackFramePattern.test(line)) {
break;
}
}
if (i > 0 && error.name != "SyntaxError") {
stack = stack.slice(i);
}
return stack;
}
function parseStackAndMessage(error) {
var stack = error.stack;
var message = error.toString();
stack = typeof stack === "string" && stack.length > 0
? stackFramesAsArray(error) : [" (No stack trace)"];
return {
message: message,
stack: error.name == "SyntaxError" ? stack : cleanStack(stack)
};
}
function formatAndLogError(error, title, isSoft) {
if (typeof console !== "undefined") {
var message;
if (util.isObject(error)) {
var stack = error.stack;
message = title + formatStack(stack, error);
} else {
message = title + String(error);
}
if (typeof printWarning === "function") {
printWarning(message, isSoft);
} else if (typeof console.log === "function" ||
typeof console.log === "object") {
console.log(message);
}
}
}
function fireRejectionEvent(name, localHandler, reason, promise) {
var localEventFired = false;
try {
if (typeof localHandler === "function") {
localEventFired = true;
if (name === "rejectionHandled") {
localHandler(promise);
} else {
localHandler(reason, promise);
}
}
} catch (e) {
async.throwLater(e);
}
if (name === "unhandledRejection") {
if (!activeFireEvent(name, reason, promise) && !localEventFired) {
formatAndLogError(reason, "Unhandled rejection ");
}
} else {
activeFireEvent(name, promise);
}
}
function formatNonError(obj) {
var str;
if (typeof obj === "function") {
str = "[function " +
(obj.name || "anonymous") +
"]";
} else {
str = obj && typeof obj.toString === "function"
? obj.toString() : util.toString(obj);
var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
if (ruselessToString.test(str)) {
try {
var newStr = JSON.stringify(obj);
str = newStr;
}
catch(e) {
}
}
if (str.length === 0) {
str = "(empty array)";
}
}
return ("(<" + snip(str) + ">, no stack trace)");
}
function snip(str) {
var maxChars = 41;
if (str.length < maxChars) {
return str;
}
return str.substr(0, maxChars - 3) + "...";
}
function longStackTracesIsSupported() {
return typeof captureStackTrace === "function";
}
var shouldIgnore = function() { return false; };
var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;
function parseLineInfo(line) {
var matches = line.match(parseLineInfoRegex);
if (matches) {
return {
fileName: matches[1],
line: parseInt(matches[2], 10)
};
}
}
function setBounds(firstLineError, lastLineError) {
if (!longStackTracesIsSupported()) return;
var firstStackLines = firstLineError.stack.split("\n");
var lastStackLines = lastLineError.stack.split("\n");
var firstIndex = -1;
var lastIndex = -1;
var firstFileName;
var lastFileName;
for (var i = 0; i < firstStackLines.length; ++i) {
var result = parseLineInfo(firstStackLines[i]);
if (result) {
firstFileName = result.fileName;
firstIndex = result.line;
break;
}
}
for (var i = 0; i < lastStackLines.length; ++i) {
var result = parseLineInfo(lastStackLines[i]);
if (result) {
lastFileName = result.fileName;
lastIndex = result.line;
break;
}
}
if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName ||
firstFileName !== lastFileName || firstIndex >= lastIndex) {
return;
}
shouldIgnore = function(line) {
if (bluebirdFramePattern.test(line)) return true;
var info = parseLineInfo(line);
if (info) {
if (info.fileName === firstFileName &&
(firstIndex <= info.line && info.line <= lastIndex)) {
return true;
}
}
return false;
};
}
function CapturedTrace(parent) {
this._parent = parent;
this._promisesCreated = 0;
var length = this._length = 1 + (parent === undefined ? 0 : parent._length);
captureStackTrace(this, CapturedTrace);
if (length > 32) this.uncycle();
}
util.inherits(CapturedTrace, Error);
Context.CapturedTrace = CapturedTrace;
CapturedTrace.prototype.uncycle = function() {
var length = this._length;
if (length < 2) return;
var nodes = [];
var stackToIndex = {};
for (var i = 0, node = this; node !== undefined; ++i) {
nodes.push(node);
node = node._parent;
}
length = this._length = i;
for (var i = length - 1; i >= 0; --i) {
var stack = nodes[i].stack;
if (stackToIndex[stack] === undefined) {
stackToIndex[stack] = i;
}
}
for (var i = 0; i < length; ++i) {
var currentStack = nodes[i].stack;
var index = stackToIndex[currentStack];
if (index !== undefined && index !== i) {
if (index > 0) {
nodes[index - 1]._parent = undefined;
nodes[index - 1]._length = 1;
}
nodes[i]._parent = undefined;
nodes[i]._length = 1;
var cycleEdgeNode = i > 0 ? nodes[i - 1] : this;
if (index < length - 1) {
cycleEdgeNode._parent = nodes[index + 1];
cycleEdgeNode._parent.uncycle();
cycleEdgeNode._length =
cycleEdgeNode._parent._length + 1;
} else {
cycleEdgeNode._parent = undefined;
cycleEdgeNode._length = 1;
}
var currentChildLength = cycleEdgeNode._length + 1;
for (var j = i - 2; j >= 0; --j) {
nodes[j]._length = currentChildLength;
currentChildLength++;
}
return;
}
}
};
CapturedTrace.prototype.attachExtraTrace = function(error) {
if (error.__stackCleaned__) return;
this.uncycle();
var parsed = parseStackAndMessage(error);
var message = parsed.message;
var stacks = [parsed.stack];
var trace = this;
while (trace !== undefined) {
stacks.push(cleanStack(trace.stack.split("\n")));
trace = trace._parent;
}
removeCommonRoots(stacks);
removeDuplicateOrEmptyJumps(stacks);
util.notEnumerableProp(error, "stack", reconstructStack(message, stacks));
util.notEnumerableProp(error, "__stackCleaned__", true);
};
var captureStackTrace = (function stackDetection() {
var v8stackFramePattern = /^\s*at\s*/;
var v8stackFormatter = function(stack, error) {
if (typeof stack === "string") return stack;
if (error.name !== undefined &&
error.message !== undefined) {
return error.toString();
}
return formatNonError(error);
};
if (typeof Error.stackTraceLimit === "number" &&
typeof Error.captureStackTrace === "function") {
Error.stackTraceLimit += 6;
stackFramePattern = v8stackFramePattern;
formatStack = v8stackFormatter;
var captureStackTrace = Error.captureStackTrace;
shouldIgnore = function(line) {
return bluebirdFramePattern.test(line);
};
return function(receiver, ignoreUntil) {
Error.stackTraceLimit += 6;
captureStackTrace(receiver, ignoreUntil);
Error.stackTraceLimit -= 6;
};
}
var err = new Error();
if (typeof err.stack === "string" &&
err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) {
stackFramePattern = /@/;
formatStack = v8stackFormatter;
indentStackFrames = true;
return function captureStackTrace(o) {
o.stack = new Error().stack;
};
}
var hasStackAfterThrow;
try { throw new Error(); }
catch(e) {
hasStackAfterThrow = ("stack" in e);
}
if (!("stack" in err) && hasStackAfterThrow &&
typeof Error.stackTraceLimit === "number") {
stackFramePattern = v8stackFramePattern;
formatStack = v8stackFormatter;
return function captureStackTrace(o) {
Error.stackTraceLimit += 6;
try { throw new Error(); }
catch(e) { o.stack = e.stack; }
Error.stackTraceLimit -= 6;
};
}
formatStack = function(stack, error) {
if (typeof stack === "string") return stack;
if ((typeof error === "object" ||
typeof error === "function") &&
error.name !== undefined &&
error.message !== undefined) {
return error.toString();
}
return formatNonError(error);
};
return null;
})([]);
if (typeof console !== "undefined" && typeof console.warn !== "undefined") {
printWarning = function (message) {
console.warn(message);
};
if (util.isNode && process.stderr.isTTY) {
printWarning = function(message, isSoft) {
var color = isSoft ? "\u001b[33m" : "\u001b[31m";
console.warn(color + message + "\u001b[0m\n");
};
} else if (!util.isNode && typeof (new Error().stack) === "string") {
printWarning = function(message, isSoft) {
console.warn("%c" + message,
isSoft ? "color: darkorange" : "color: red");
};
}
}
var config = {
warnings: warnings,
longStackTraces: false,
cancellation: false,
monitoring: false
};
if (longStackTraces) Promise.longStackTraces();
return {
longStackTraces: function() {
return config.longStackTraces;
},
warnings: function() {
return config.warnings;
},
cancellation: function() {
return config.cancellation;
},
monitoring: function() {
return config.monitoring;
},
propagateFromFunction: function() {
return propagateFromFunction;
},
boundValueFunction: function() {
return boundValueFunction;
},
checkForgottenReturns: checkForgottenReturns,
setBounds: setBounds,
warn: warn,
deprecated: deprecated,
CapturedTrace: CapturedTrace,
fireDomEvent: fireDomEvent,
fireGlobalEvent: fireGlobalEvent
};
};
}).call(this,require('_process'))
},{"./errors":49,"./util":73,"_process":83}],47:[function(require,module,exports){
"use strict";
module.exports = function(Promise) {
function returner() {
return this.value;
}
function thrower() {
throw this.reason;
}
Promise.prototype["return"] =
Promise.prototype.thenReturn = function (value) {
if (value instanceof Promise) value.suppressUnhandledRejections();
return this._then(
returner, undefined, undefined, {value: value}, undefined);
};
Promise.prototype["throw"] =
Promise.prototype.thenThrow = function (reason) {
return this._then(
thrower, undefined, undefined, {reason: reason}, undefined);
};
Promise.prototype.catchThrow = function (reason) {
if (arguments.length <= 1) {
return this._then(
undefined, thrower, undefined, {reason: reason}, undefined);
} else {
var _reason = arguments[1];
var handler = function() {throw _reason;};
return this.caught(reason, handler);
}
};
Promise.prototype.catchReturn = function (value) {
if (arguments.length <= 1) {
if (value instanceof Promise) value.suppressUnhandledRejections();
return this._then(
undefined, returner, undefined, {value: value}, undefined);
} else {
var _value = arguments[1];
if (_value instanceof Promise) _value.suppressUnhandledRejections();
var handler = function() {return _value;};
return this.caught(value, handler);
}
};
};
},{}],48:[function(require,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL) {
var PromiseReduce = Promise.reduce;
var PromiseAll = Promise.all;
function promiseAllThis() {
return PromiseAll(this);
}
function PromiseMapSeries(promises, fn) {
return PromiseReduce(promises, fn, INTERNAL, INTERNAL);
}
Promise.prototype.each = function (fn) {
return PromiseReduce(this, fn, INTERNAL, 0)
._then(promiseAllThis, undefined, undefined, this, undefined);
};
Promise.prototype.mapSeries = function (fn) {
return PromiseReduce(this, fn, INTERNAL, INTERNAL);
};
Promise.each = function (promises, fn) {
return PromiseReduce(promises, fn, INTERNAL, 0)
._then(promiseAllThis, undefined, undefined, promises, undefined);
};
Promise.mapSeries = PromiseMapSeries;
};
},{}],49:[function(require,module,exports){
"use strict";
var es5 = require("./es5");
var Objectfreeze = es5.freeze;
var util = require("./util");
var inherits = util.inherits;
var notEnumerableProp = util.notEnumerableProp;
function subError(nameProperty, defaultMessage) {
function SubError(message) {
if (!(this instanceof SubError)) return new SubError(message);
notEnumerableProp(this, "message",
typeof message === "string" ? message : defaultMessage);
notEnumerableProp(this, "name", nameProperty);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
} else {
Error.call(this);
}
}
inherits(SubError, Error);
return SubError;
}
var _TypeError, _RangeError;
var Warning = subError("Warning", "warning");
var CancellationError = subError("CancellationError", "cancellation error");
var TimeoutError = subError("TimeoutError", "timeout error");
var AggregateError = subError("AggregateError", "aggregate error");
try {
_TypeError = TypeError;
_RangeError = RangeError;
} catch(e) {
_TypeError = subError("TypeError", "type error");
_RangeError = subError("RangeError", "range error");
}
var methods = ("join pop push shift unshift slice filter forEach some " +
"every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");
for (var i = 0; i < methods.length; ++i) {
if (typeof Array.prototype[methods[i]] === "function") {
AggregateError.prototype[methods[i]] = Array.prototype[methods[i]];
}
}
es5.defineProperty(AggregateError.prototype, "length", {
value: 0,
configurable: false,
writable: true,
enumerable: true
});
AggregateError.prototype["isOperational"] = true;
var level = 0;
AggregateError.prototype.toString = function() {
var indent = Array(level * 4 + 1).join(" ");
var ret = "\n" + indent + "AggregateError of:" + "\n";
level++;
indent = Array(level * 4 + 1).join(" ");
for (var i = 0; i < this.length; ++i) {
var str = this[i] === this ? "[Circular AggregateError]" : this[i] + "";
var lines = str.split("\n");
for (var j = 0; j < lines.length; ++j) {
lines[j] = indent + lines[j];
}
str = lines.join("\n");
ret += str + "\n";
}
level--;
return ret;
};
function OperationalError(message) {
if (!(this instanceof OperationalError))
return new OperationalError(message);
notEnumerableProp(this, "name", "OperationalError");
notEnumerableProp(this, "message", message);
this.cause = message;
this["isOperational"] = true;
if (message instanceof Error) {
notEnumerableProp(this, "message", message.message);
notEnumerableProp(this, "stack", message.stack);
} else if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}
inherits(OperationalError, Error);
var errorTypes = Error["__BluebirdErrorTypes__"];
if (!errorTypes) {
errorTypes = Objectfreeze({
CancellationError: CancellationError,
TimeoutError: TimeoutError,
OperationalError: OperationalError,
RejectionError: OperationalError,
AggregateError: AggregateError
});
es5.defineProperty(Error, "__BluebirdErrorTypes__", {
value: errorTypes,
writable: false,
enumerable: false,
configurable: false
});
}
module.exports = {
Error: Error,
TypeError: _TypeError,
RangeError: _RangeError,
CancellationError: errorTypes.CancellationError,
OperationalError: errorTypes.OperationalError,
TimeoutError: errorTypes.TimeoutError,
AggregateError: errorTypes.AggregateError,
Warning: Warning
};
},{"./es5":50,"./util":73}],50:[function(require,module,exports){
var isES5 = (function(){
"use strict";
return this === undefined;
})();
if (isES5) {
module.exports = {
freeze: Object.freeze,
defineProperty: Object.defineProperty,
getDescriptor: Object.getOwnPropertyDescriptor,
keys: Object.keys,
names: Object.getOwnPropertyNames,
getPrototypeOf: Object.getPrototypeOf,
isArray: Array.isArray,
isES5: isES5,
propertyIsWritable: function(obj, prop) {
var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
return !!(!descriptor || descriptor.writable || descriptor.set);
}
};
} else {
var has = {}.hasOwnProperty;
var str = {}.toString;
var proto = {}.constructor.prototype;
var ObjectKeys = function (o) {
var ret = [];
for (var key in o) {
if (has.call(o, key)) {
ret.push(key);
}
}
return ret;
};
var ObjectGetDescriptor = function(o, key) {
return {value: o[key]};
};
var ObjectDefineProperty = function (o, key, desc) {
o[key] = desc.value;
return o;
};
var ObjectFreeze = function (obj) {
return obj;
};
var ObjectGetPrototypeOf = function (obj) {
try {
return Object(obj).constructor.prototype;
}
catch (e) {
return proto;
}
};
var ArrayIsArray = function (obj) {
try {
return str.call(obj) === "[object Array]";
}
catch(e) {
return false;
}
};
module.exports = {
isArray: ArrayIsArray,
keys: ObjectKeys,
names: ObjectKeys,
defineProperty: ObjectDefineProperty,
getDescriptor: ObjectGetDescriptor,
freeze: ObjectFreeze,
getPrototypeOf: ObjectGetPrototypeOf,
isES5: isES5,
propertyIsWritable: function() {
return true;
}
};
}
},{}],51:[function(require,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL) {
var PromiseMap = Promise.map;
Promise.prototype.filter = function (fn, options) {
return PromiseMap(this, fn, options, INTERNAL);
};
Promise.filter = function (promises, fn, options) {
return PromiseMap(promises, fn, options, INTERNAL);
};
};
},{}],52:[function(require,module,exports){
"use strict";
module.exports = function(Promise, tryConvertToPromise) {
var util = require("./util");
var CancellationError = Promise.CancellationError;
var errorObj = util.errorObj;
function PassThroughHandlerContext(promise, type, handler) {
this.promise = promise;
this.type = type;
this.handler = handler;
this.called = false;
this.cancelPromise = null;
}
PassThroughHandlerContext.prototype.isFinallyHandler = function() {
return this.type === 0;
};
function FinallyHandlerCancelReaction(finallyHandler) {
this.finallyHandler = finallyHandler;
}
FinallyHandlerCancelReaction.prototype._resultCancelled = function() {
checkCancel(this.finallyHandler);
};
function checkCancel(ctx, reason) {
if (ctx.cancelPromise != null) {
if (arguments.length > 1) {
ctx.cancelPromise._reject(reason);
} else {
ctx.cancelPromise._cancel();
}
ctx.cancelPromise = null;
return true;
}
return false;
}
function succeed() {
return finallyHandler.call(this, this.promise._target()._settledValue());
}
function fail(reason) {
if (checkCancel(this, reason)) return;
errorObj.e = reason;
return errorObj;
}
function finallyHandler(reasonOrValue) {
var promise = this.promise;
var handler = this.handler;
if (!this.called) {
this.called = true;
var ret = this.isFinallyHandler()
? handler.call(promise._boundValue())
: handler.call(promise._boundValue(), reasonOrValue);
if (ret !== undefined) {
promise._setReturnedNonUndefined();
var maybePromise = tryConvertToPromise(ret, promise);
if (maybePromise instanceof Promise) {
if (this.cancelPromise != null) {
if (maybePromise._isCancelled()) {
var reason =
new CancellationError("late cancellation observer");
promise._attachExtraTrace(reason);
errorObj.e = reason;
return errorObj;
} else if (maybePromise.isPending()) {
maybePromise._attachCancellationCallback(
new FinallyHandlerCancelReaction(this));
}
}
return maybePromise._then(
succeed, fail, undefined, this, undefined);
}
}
}
if (promise.isRejected()) {
checkCancel(this);
errorObj.e = reasonOrValue;
return errorObj;
} else {
checkCancel(this);
return reasonOrValue;
}
}
Promise.prototype._passThrough = function(handler, type, success, fail) {
if (typeof handler !== "function") return this.then();
return this._then(success,
fail,
undefined,
new PassThroughHandlerContext(this, type, handler),
undefined);
};
Promise.prototype.lastly =
Promise.prototype["finally"] = function (handler) {
return this._passThrough(handler,
0,
finallyHandler,
finallyHandler);
};
Promise.prototype.tap = function (handler) {
return this._passThrough(handler, 1, finallyHandler);
};
return PassThroughHandlerContext;
};
},{"./util":73}],53:[function(require,module,exports){
"use strict";
module.exports = function(Promise,
apiRejection,
INTERNAL,
tryConvertToPromise,
Proxyable,
debug) {
var errors = require("./errors");
var TypeError = errors.TypeError;
var util = require("./util");
var errorObj = util.errorObj;
var tryCatch = util.tryCatch;
var yieldHandlers = [];
function promiseFromYieldHandler(value, yieldHandlers, traceParent) {
for (var i = 0; i < yieldHandlers.length; ++i) {
traceParent._pushContext();
var result = tryCatch(yieldHandlers[i])(value);
traceParent._popContext();
if (result === errorObj) {
traceParent._pushContext();
var ret = Promise.reject(errorObj.e);
traceParent._popContext();
return ret;
}
var maybePromise = tryConvertToPromise(result, traceParent);
if (maybePromise instanceof Promise) return maybePromise;
}
return null;
}
function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) {
if (debug.cancellation()) {
var internal = new Promise(INTERNAL);
var _finallyPromise = this._finallyPromise = new Promise(INTERNAL);
this._promise = internal.lastly(function() {
return _finallyPromise;
});
internal._captureStackTrace();
internal._setOnCancel(this);
} else {
var promise = this._promise = new Promise(INTERNAL);
promise._captureStackTrace();
}
this._stack = stack;
this._generatorFunction = generatorFunction;
this._receiver = receiver;
this._generator = undefined;
this._yieldHandlers = typeof yieldHandler === "function"
? [yieldHandler].concat(yieldHandlers)
: yieldHandlers;
this._yieldedPromise = null;
this._cancellationPhase = false;
}
util.inherits(PromiseSpawn, Proxyable);
PromiseSpawn.prototype._isResolved = function() {
return this._promise === null;
};
PromiseSpawn.prototype._cleanup = function() {
this._promise = this._generator = null;
if (debug.cancellation() && this._finallyPromise !== null) {
this._finallyPromise._fulfill();
this._finallyPromise = null;
}
};
PromiseSpawn.prototype._promiseCancelled = function() {
if (this._isResolved()) return;
var implementsReturn = typeof this._generator["return"] !== "undefined";
var result;
if (!implementsReturn) {
var reason = new Promise.CancellationError(
"generator .return() sentinel");
Promise.coroutine.returnSentinel = reason;
this._promise._attachExtraTrace(reason);
this._promise._pushContext();
result = tryCatch(this._generator["throw"]).call(this._generator,
reason);
this._promise._popContext();
} else {
this._promise._pushContext();
result = tryCatch(this._generator["return"]).call(this._generator,
undefined);
this._promise._popContext();
}
this._cancellationPhase = true;
this._yieldedPromise = null;
this._continue(result);
};
PromiseSpawn.prototype._promiseFulfilled = function(value) {
this._yieldedPromise = null;
this._promise._pushContext();
var result = tryCatch(this._generator.next).call(this._generator, value);
this._promise._popContext();
this._continue(result);
};
PromiseSpawn.prototype._promiseRejected = function(reason) {
this._yieldedPromise = null;
this._promise._attachExtraTrace(reason);
this._promise._pushContext();
var result = tryCatch(this._generator["throw"])
.call(this._generator, reason);
this._promise._popContext();
this._continue(result);
};
PromiseSpawn.prototype._resultCancelled = function() {
if (this._yieldedPromise instanceof Promise) {
var promise = this._yieldedPromise;
this._yieldedPromise = null;
promise.cancel();
}
};
PromiseSpawn.prototype.promise = function () {
return this._promise;
};
PromiseSpawn.prototype._run = function () {
this._generator = this._generatorFunction.call(this._receiver);
this._receiver =
this._generatorFunction = undefined;
this._promiseFulfilled(undefined);
};
PromiseSpawn.prototype._continue = function (result) {
var promise = this._promise;
if (result === errorObj) {
this._cleanup();
if (this._cancellationPhase) {
return promise.cancel();
} else {
return promise._rejectCallback(result.e, false);
}
}
var value = result.value;
if (result.done === true) {
this._cleanup();
if (this._cancellationPhase) {
return promise.cancel();
} else {
return promise._resolveCallback(value);
}
} else {
var maybePromise = tryConvertToPromise(value, this._promise);
if (!(maybePromise instanceof Promise)) {
maybePromise =
promiseFromYieldHandler(maybePromise,
this._yieldHandlers,
this._promise);
if (maybePromise === null) {
this._promiseRejected(
new TypeError(
"A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", value) +
"From coroutine:\u000a" +
this._stack.split("\n").slice(1, -7).join("\n")
)
);
return;
}
}
maybePromise = maybePromise._target();
var bitField = maybePromise._bitField;
;
if (((bitField & 50397184) === 0)) {
this._yieldedPromise = maybePromise;
maybePromise._proxy(this, null);
} else if (((bitField & 33554432) !== 0)) {
Promise._async.invoke(
this._promiseFulfilled, this, maybePromise._value()
);
} else if (((bitField & 16777216) !== 0)) {
Promise._async.invoke(
this._promiseRejected, this, maybePromise._reason()
);
} else {
this._promiseCancelled();
}
}
};
Promise.coroutine = function (generatorFunction, options) {
if (typeof generatorFunction !== "function") {
throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
var yieldHandler = Object(options).yieldHandler;
var PromiseSpawn$ = PromiseSpawn;
var stack = new Error().stack;
return function () {
var generator = generatorFunction.apply(this, arguments);
var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler,
stack);
var ret = spawn.promise();
spawn._generator = generator;
spawn._promiseFulfilled(undefined);
return ret;
};
};
Promise.coroutine.addYieldHandler = function(fn) {
if (typeof fn !== "function") {
throw new TypeError("expecting a function but got " + util.classString(fn));
}
yieldHandlers.push(fn);
};
Promise.spawn = function (generatorFunction) {
debug.deprecated("Promise.spawn()", "Promise.coroutine()");
if (typeof generatorFunction !== "function") {
return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
var spawn = new PromiseSpawn(generatorFunction, this);
var ret = spawn.promise();
spawn._run(Promise.spawn);
return ret;
};
};
},{"./errors":49,"./util":73}],54:[function(require,module,exports){
"use strict";
module.exports =
function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async,
getDomain) {
var util = require("./util");
var canEvaluate = util.canEvaluate;
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
var reject;
if (!false) {
if (canEvaluate) {
var thenCallback = function(i) {
return new Function("value", "holder", " \n\
'use strict'; \n\
holder.pIndex = value; \n\
holder.checkFulfillment(this); \n\
".replace(/Index/g, i));
};
var promiseSetter = function(i) {
return new Function("promise", "holder", " \n\
'use strict'; \n\
holder.pIndex = promise; \n\
".replace(/Index/g, i));
};
var generateHolderClass = function(total) {
var props = new Array(total);
for (var i = 0; i < props.length; ++i) {
props[i] = "this.p" + (i+1);
}
var assignment = props.join(" = ") + " = null;";
var cancellationCode= "var promise;\n" + props.map(function(prop) {
return " \n\
promise = " + prop + "; \n\
if (promise instanceof Promise) { \n\
promise.cancel(); \n\
} \n\
";
}).join("\n");
var passedArguments = props.join(", ");
var name = "Holder$" + total;
var code = "return function(tryCatch, errorObj, Promise, async) { \n\
'use strict'; \n\
function [TheName](fn) { \n\
[TheProperties] \n\
this.fn = fn; \n\
this.asyncNeeded = true; \n\
this.now = 0; \n\
} \n\
\n\
[TheName].prototype._callFunction = function(promise) { \n\
promise._pushContext(); \n\
var ret = tryCatch(this.fn)([ThePassedArguments]); \n\
promise._popContext(); \n\
if (ret === errorObj) { \n\
promise._rejectCallback(ret.e, false); \n\
} else { \n\
promise._resolveCallback(ret); \n\
} \n\
}; \n\
\n\
[TheName].prototype.checkFulfillment = function(promise) { \n\
var now = ++this.now; \n\
if (now === [TheTotal]) { \n\
if (this.asyncNeeded) { \n\
async.invoke(this._callFunction, this, promise); \n\
} else { \n\
this._callFunction(promise); \n\
} \n\
\n\
} \n\
}; \n\
\n\
[TheName].prototype._resultCancelled = function() { \n\
[CancellationCode] \n\
}; \n\
\n\
return [TheName]; \n\
}(tryCatch, errorObj, Promise, async); \n\
";
code = code.replace(/\[TheName\]/g, name)
.replace(/\[TheTotal\]/g, total)
.replace(/\[ThePassedArguments\]/g, passedArguments)
.replace(/\[TheProperties\]/g, assignment)
.replace(/\[CancellationCode\]/g, cancellationCode);
return new Function("tryCatch", "errorObj", "Promise", "async", code)
(tryCatch, errorObj, Promise, async);
};
var holderClasses = [];
var thenCallbacks = [];
var promiseSetters = [];
for (var i = 0; i < 8; ++i) {
holderClasses.push(generateHolderClass(i + 1));
thenCallbacks.push(thenCallback(i + 1));
promiseSetters.push(promiseSetter(i + 1));
}
reject = function (reason) {
this._reject(reason);
};
}}
Promise.join = function () {
var last = arguments.length - 1;
var fn;
if (last > 0 && typeof arguments[last] === "function") {
fn = arguments[last];
if (!false) {
if (last <= 8 && canEvaluate) {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
var HolderClass = holderClasses[last - 1];
var holder = new HolderClass(fn);
var callbacks = thenCallbacks;
for (var i = 0; i < last; ++i) {
var maybePromise = tryConvertToPromise(arguments[i], ret);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
var bitField = maybePromise._bitField;
;
if (((bitField & 50397184) === 0)) {
maybePromise._then(callbacks[i], reject,
undefined, ret, holder);
promiseSetters[i](maybePromise, holder);
holder.asyncNeeded = false;
} else if (((bitField & 33554432) !== 0)) {
callbacks[i].call(ret,
maybePromise._value(), holder);
} else if (((bitField & 16777216) !== 0)) {
ret._reject(maybePromise._reason());
} else {
ret._cancel();
}
} else {
callbacks[i].call(ret, maybePromise, holder);
}
}
if (!ret._isFateSealed()) {
if (holder.asyncNeeded) {
var domain = getDomain();
if (domain !== null) {
holder.fn = util.domainBind(domain, holder.fn);
}
}
ret._setAsyncGuaranteed();
ret._setOnCancel(holder);
}
return ret;
}
}
}
var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];};
if (fn) args.pop();
var ret = new PromiseArray(args).promise();
return fn !== undefined ? ret.spread(fn) : ret;
};
};
},{"./util":73}],55:[function(require,module,exports){
"use strict";
module.exports = function(Promise,
PromiseArray,
apiRejection,
tryConvertToPromise,
INTERNAL,
debug) {
var getDomain = Promise._getDomain;
var util = require("./util");
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
var async = Promise._async;
function MappingPromiseArray(promises, fn, limit, _filter) {
this.constructor$(promises);
this._promise._captureStackTrace();
var domain = getDomain();
this._callback = domain === null ? fn : util.domainBind(domain, fn);
this._preservedValues = _filter === INTERNAL
? new Array(this.length())
: null;
this._limit = limit;
this._inFlight = 0;
this._queue = [];
async.invoke(this._asyncInit, this, undefined);
}
util.inherits(MappingPromiseArray, PromiseArray);
MappingPromiseArray.prototype._asyncInit = function() {
this._init$(undefined, -2);
};
MappingPromiseArray.prototype._init = function () {};
MappingPromiseArray.prototype._promiseFulfilled = function (value, index) {
var values = this._values;
var length = this.length();
var preservedValues = this._preservedValues;
var limit = this._limit;
if (index < 0) {
index = (index * -1) - 1;
values[index] = value;
if (limit >= 1) {
this._inFlight--;
this._drainQueue();
if (this._isResolved()) return true;
}
} else {
if (limit >= 1 && this._inFlight >= limit) {
values[index] = value;
this._queue.push(index);
return false;
}
if (preservedValues !== null) preservedValues[index] = value;
var promise = this._promise;
var callback = this._callback;
var receiver = promise._boundValue();
promise._pushContext();
var ret = tryCatch(callback).call(receiver, value, index, length);
var promiseCreated = promise._popContext();
debug.checkForgottenReturns(
ret,
promiseCreated,
preservedValues !== null ? "Promise.filter" : "Promise.map",
promise
);
if (ret === errorObj) {
this._reject(ret.e);
return true;
}
var maybePromise = tryConvertToPromise(ret, this._promise);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
var bitField = maybePromise._bitField;
;
if (((bitField & 50397184) === 0)) {
if (limit >= 1) this._inFlight++;
values[index] = maybePromise;
maybePromise._proxy(this, (index + 1) * -1);
return false;
} else if (((bitField & 33554432) !== 0)) {
ret = maybePromise._value();
} else if (((bitField & 16777216) !== 0)) {
this._reject(maybePromise._reason());
return true;
} else {
this._cancel();
return true;
}
}
values[index] = ret;
}
var totalResolved = ++this._totalResolved;
if (totalResolved >= length) {
if (preservedValues !== null) {
this._filter(values, preservedValues);
} else {
this._resolve(values);
}
return true;
}
return false;
};
MappingPromiseArray.prototype._drainQueue = function () {
var queue = this._queue;
var limit = this._limit;
var values = this._values;
while (queue.length > 0 && this._inFlight < limit) {
if (this._isResolved()) return;
var index = queue.pop();
this._promiseFulfilled(values[index], index);
}
};
MappingPromiseArray.prototype._filter = function (booleans, values) {
var len = values.length;
var ret = new Array(len);
var j = 0;
for (var i = 0; i < len; ++i) {
if (booleans[i]) ret[j++] = values[i];
}
ret.length = j;
this._resolve(ret);
};
MappingPromiseArray.prototype.preservedValues = function () {
return this._preservedValues;
};
function map(promises, fn, options, _filter) {
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
var limit = 0;
if (options !== undefined) {
if (typeof options === "object" && options !== null) {
if (typeof options.concurrency !== "number") {
return Promise.reject(
new TypeError("'concurrency' must be a number but it is " +
util.classString(options.concurrency)));
}
limit = options.concurrency;
} else {
return Promise.reject(new TypeError(
"options argument must be an object but it is " +
util.classString(options)));
}
}
limit = typeof limit === "number" &&
isFinite(limit) && limit >= 1 ? limit : 0;
return new MappingPromiseArray(promises, fn, limit, _filter).promise();
}
Promise.prototype.map = function (fn, options) {
return map(this, fn, options, null);
};
Promise.map = function (promises, fn, options, _filter) {
return map(promises, fn, options, _filter);
};
};
},{"./util":73}],56:[function(require,module,exports){
"use strict";
module.exports =
function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) {
var util = require("./util");
var tryCatch = util.tryCatch;
Promise.method = function (fn) {
if (typeof fn !== "function") {
throw new Promise.TypeError("expecting a function but got " + util.classString(fn));
}
return function () {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._pushContext();
var value = tryCatch(fn).apply(this, arguments);
var promiseCreated = ret._popContext();
debug.checkForgottenReturns(
value, promiseCreated, "Promise.method", ret);
ret._resolveFromSyncValue(value);
return ret;
};
};
Promise.attempt = Promise["try"] = function (fn) {
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._pushContext();
var value;
if (arguments.length > 1) {
debug.deprecated("calling Promise.try with more than 1 argument");
var arg = arguments[1];
var ctx = arguments[2];
value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg)
: tryCatch(fn).call(ctx, arg);
} else {
value = tryCatch(fn)();
}
var promiseCreated = ret._popContext();
debug.checkForgottenReturns(
value, promiseCreated, "Promise.try", ret);
ret._resolveFromSyncValue(value);
return ret;
};
Promise.prototype._resolveFromSyncValue = function (value) {
if (value === util.errorObj) {
this._rejectCallback(value.e, false);
} else {
this._resolveCallback(value, true);
}
};
};
},{"./util":73}],57:[function(require,module,exports){
"use strict";
var util = require("./util");
var maybeWrapAsError = util.maybeWrapAsError;
var errors = require("./errors");
var OperationalError = errors.OperationalError;
var es5 = require("./es5");
function isUntypedError(obj) {
return obj instanceof Error &&
es5.getPrototypeOf(obj) === Error.prototype;
}
var rErrorKey = /^(?:name|message|stack|cause)$/;
function wrapAsOperationalError(obj) {
var ret;
if (isUntypedError(obj)) {
ret = new OperationalError(obj);
ret.name = obj.name;
ret.message = obj.message;
ret.stack = obj.stack;
var keys = es5.keys(obj);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (!rErrorKey.test(key)) {
ret[key] = obj[key];
}
}
return ret;
}
util.markAsOriginatingFromRejection(obj);
return obj;
}
function nodebackForPromise(promise, multiArgs) {
return function(err, value) {
if (promise === null) return;
if (err) {
var wrapped = wrapAsOperationalError(maybeWrapAsError(err));
promise._attachExtraTrace(wrapped);
promise._reject(wrapped);
} else if (!multiArgs) {
promise._fulfill(value);
} else {
var $_len = arguments.length;var args = new Array(Math.max($_len - 1, 0)); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];};
promise._fulfill(args);
}
promise = null;
};
}
module.exports = nodebackForPromise;
},{"./errors":49,"./es5":50,"./util":73}],58:[function(require,module,exports){
"use strict";
module.exports = function(Promise) {
var util = require("./util");
var async = Promise._async;
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
function spreadAdapter(val, nodeback) {
var promise = this;
if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback);
var ret =
tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val));
if (ret === errorObj) {
async.throwLater(ret.e);
}
}
function successAdapter(val, nodeback) {
var promise = this;
var receiver = promise._boundValue();
var ret = val === undefined
? tryCatch(nodeback).call(receiver, null)
: tryCatch(nodeback).call(receiver, null, val);
if (ret === errorObj) {
async.throwLater(ret.e);
}
}
function errorAdapter(reason, nodeback) {
var promise = this;
if (!reason) {
var newReason = new Error(reason + "");
newReason.cause = reason;
reason = newReason;
}
var ret = tryCatch(nodeback).call(promise._boundValue(), reason);
if (ret === errorObj) {
async.throwLater(ret.e);
}
}
Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback,
options) {
if (typeof nodeback == "function") {
var adapter = successAdapter;
if (options !== undefined && Object(options).spread) {
adapter = spreadAdapter;
}
this._then(
adapter,
errorAdapter,
undefined,
this,
nodeback
);
}
return this;
};
};
},{"./util":73}],59:[function(require,module,exports){
(function (process){
"use strict";
module.exports = function() {
var makeSelfResolutionError = function () {
return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a");
};
var reflectHandler = function() {
return new Promise.PromiseInspection(this._target());
};
var apiRejection = function(msg) {
return Promise.reject(new TypeError(msg));
};
function Proxyable() {}
var UNDEFINED_BINDING = {};
var util = require("./util");
var getDomain;
if (util.isNode) {
getDomain = function() {
var ret = process.domain;
if (ret === undefined) ret = null;
return ret;
};
} else {
getDomain = function() {
return null;
};
}
util.notEnumerableProp(Promise, "_getDomain", getDomain);
var es5 = require("./es5");
var Async = require("./async");
var async = new Async();
es5.defineProperty(Promise, "_async", {value: async});
var errors = require("./errors");
var TypeError = Promise.TypeError = errors.TypeError;
Promise.RangeError = errors.RangeError;
var CancellationError = Promise.CancellationError = errors.CancellationError;
Promise.TimeoutError = errors.TimeoutError;
Promise.OperationalError = errors.OperationalError;
Promise.RejectionError = errors.OperationalError;
Promise.AggregateError = errors.AggregateError;
var INTERNAL = function(){};
var APPLY = {};
var NEXT_FILTER = {};
var tryConvertToPromise = require("./thenables")(Promise, INTERNAL);
var PromiseArray =
require("./promise_array")(Promise, INTERNAL,
tryConvertToPromise, apiRejection, Proxyable);
var Context = require("./context")(Promise);
/*jshint unused:false*/
var createContext = Context.create;
var debug = require("./debuggability")(Promise, Context);
var CapturedTrace = debug.CapturedTrace;
var PassThroughHandlerContext =
require("./finally")(Promise, tryConvertToPromise);
var catchFilter = require("./catch_filter")(NEXT_FILTER);
var nodebackForPromise = require("./nodeback");
var errorObj = util.errorObj;
var tryCatch = util.tryCatch;
function check(self, executor) {
if (typeof executor !== "function") {
throw new TypeError("expecting a function but got " + util.classString(executor));
}
if (self.constructor !== Promise) {
throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
}
function Promise(executor) {
this._bitField = 0;
this._fulfillmentHandler0 = undefined;
this._rejectionHandler0 = undefined;
this._promise0 = undefined;
this._receiver0 = undefined;
if (executor !== INTERNAL) {
check(this, executor);
this._resolveFromExecutor(executor);
}
this._promiseCreated();
this._fireEvent("promiseCreated", this);
}
Promise.prototype.toString = function () {
return "[object Promise]";
};
Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
var len = arguments.length;
if (len > 1) {
var catchInstances = new Array(len - 1),
j = 0, i;
for (i = 0; i < len - 1; ++i) {
var item = arguments[i];
if (util.isObject(item)) {
catchInstances[j++] = item;
} else {
return apiRejection("expecting an object but got " +
"A catch statement predicate " + util.classString(item));
}
}
catchInstances.length = j;
fn = arguments[i];
return this.then(undefined, catchFilter(catchInstances, fn, this));
}
return this.then(undefined, fn);
};
Promise.prototype.reflect = function () {
return this._then(reflectHandler,
reflectHandler, undefined, this, undefined);
};
Promise.prototype.then = function (didFulfill, didReject) {
if (debug.warnings() && arguments.length > 0 &&
typeof didFulfill !== "function" &&
typeof didReject !== "function") {
var msg = ".then() only accepts functions but was passed: " +
util.classString(didFulfill);
if (arguments.length > 1) {
msg += ", " + util.classString(didReject);
}
this._warn(msg);
}
return this._then(didFulfill, didReject, undefined, undefined, undefined);
};
Promise.prototype.done = function (didFulfill, didReject) {
var promise =
this._then(didFulfill, didReject, undefined, undefined, undefined);
promise._setIsFinal();
};
Promise.prototype.spread = function (fn) {
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
return this.all()._then(fn, undefined, undefined, APPLY, undefined);
};
Promise.prototype.toJSON = function () {
var ret = {
isFulfilled: false,
isRejected: false,
fulfillmentValue: undefined,
rejectionReason: undefined
};
if (this.isFulfilled()) {
ret.fulfillmentValue = this.value();
ret.isFulfilled = true;
} else if (this.isRejected()) {
ret.rejectionReason = this.reason();
ret.isRejected = true;
}
return ret;
};
Promise.prototype.all = function () {
if (arguments.length > 0) {
this._warn(".all() was passed arguments but it does not take any");
}
return new PromiseArray(this).promise();
};
Promise.prototype.error = function (fn) {
return this.caught(util.originatesFromRejection, fn);
};
Promise.getNewLibraryCopy = module.exports;
Promise.is = function (val) {
return val instanceof Promise;
};
Promise.fromNode = Promise.fromCallback = function(fn) {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs
: false;
var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs));
if (result === errorObj) {
ret._rejectCallback(result.e, true);
}
if (!ret._isFateSealed()) ret._setAsyncGuaranteed();
return ret;
};
Promise.all = function (promises) {
return new PromiseArray(promises).promise();
};
Promise.cast = function (obj) {
var ret = tryConvertToPromise(obj);
if (!(ret instanceof Promise)) {
ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._setFulfilled();
ret._rejectionHandler0 = obj;
}
return ret;
};
Promise.resolve = Promise.fulfilled = Promise.cast;
Promise.reject = Promise.rejected = function (reason) {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._rejectCallback(reason, true);
return ret;
};
Promise.setScheduler = function(fn) {
if (typeof fn !== "function") {
throw new TypeError("expecting a function but got " + util.classString(fn));
}
return async.setScheduler(fn);
};
Promise.prototype._then = function (
didFulfill,
didReject,
_, receiver,
internalData
) {
var haveInternalData = internalData !== undefined;
var promise = haveInternalData ? internalData : new Promise(INTERNAL);
var target = this._target();
var bitField = target._bitField;
if (!haveInternalData) {
promise._propagateFrom(this, 3);
promise._captureStackTrace();
if (receiver === undefined &&
((this._bitField & 2097152) !== 0)) {
if (!((bitField & 50397184) === 0)) {
receiver = this._boundValue();
} else {
receiver = target === this ? undefined : this._boundTo;
}
}
this._fireEvent("promiseChained", this, promise);
}
var domain = getDomain();
if (!((bitField & 50397184) === 0)) {
var handler, value, settler = target._settlePromiseCtx;
if (((bitField & 33554432) !== 0)) {
value = target._rejectionHandler0;
handler = didFulfill;
} else if (((bitField & 16777216) !== 0)) {
value = target._fulfillmentHandler0;
handler = didReject;
target._unsetRejectionIsUnhandled();
} else {
settler = target._settlePromiseLateCancellationObserver;
value = new CancellationError("late cancellation observer");
target._attachExtraTrace(value);
handler = didReject;
}
async.invoke(settler, target, {
handler: domain === null ? handler
: (typeof handler === "function" &&
util.domainBind(domain, handler)),
promise: promise,
receiver: receiver,
value: value
});
} else {
target._addCallbacks(didFulfill, didReject, promise, receiver, domain);
}
return promise;
};
Promise.prototype._length = function () {
return this._bitField & 65535;
};
Promise.prototype._isFateSealed = function () {
return (this._bitField & 117506048) !== 0;
};
Promise.prototype._isFollowing = function () {
return (this._bitField & 67108864) === 67108864;
};
Promise.prototype._setLength = function (len) {
this._bitField = (this._bitField & -65536) |
(len & 65535);
};
Promise.prototype._setFulfilled = function () {
this._bitField = this._bitField | 33554432;
this._fireEvent("promiseFulfilled", this);
};
Promise.prototype._setRejected = function () {
this._bitField = this._bitField | 16777216;
this._fireEvent("promiseRejected", this);
};
Promise.prototype._setFollowing = function () {
this._bitField = this._bitField | 67108864;
this._fireEvent("promiseResolved", this);
};
Promise.prototype._setIsFinal = function () {
this._bitField = this._bitField | 4194304;
};
Promise.prototype._isFinal = function () {
return (this._bitField & 4194304) > 0;
};
Promise.prototype._unsetCancelled = function() {
this._bitField = this._bitField & (~65536);
};
Promise.prototype._setCancelled = function() {
this._bitField = this._bitField | 65536;
this._fireEvent("promiseCancelled", this);
};
Promise.prototype._setWillBeCancelled = function() {
this._bitField = this._bitField | 8388608;
};
Promise.prototype._setAsyncGuaranteed = function() {
if (async.hasCustomScheduler()) return;
this._bitField = this._bitField | 134217728;
};
Promise.prototype._receiverAt = function (index) {
var ret = index === 0 ? this._receiver0 : this[
index * 4 - 4 + 3];
if (ret === UNDEFINED_BINDING) {
return undefined;
} else if (ret === undefined && this._isBound()) {
return this._boundValue();
}
return ret;
};
Promise.prototype._promiseAt = function (index) {
return this[
index * 4 - 4 + 2];
};
Promise.prototype._fulfillmentHandlerAt = function (index) {
return this[
index * 4 - 4 + 0];
};
Promise.prototype._rejectionHandlerAt = function (index) {
return this[
index * 4 - 4 + 1];
};
Promise.prototype._boundValue = function() {};
Promise.prototype._migrateCallback0 = function (follower) {
var bitField = follower._bitField;
var fulfill = follower._fulfillmentHandler0;
var reject = follower._rejectionHandler0;
var promise = follower._promise0;
var receiver = follower._receiverAt(0);
if (receiver === undefined) receiver = UNDEFINED_BINDING;
this._addCallbacks(fulfill, reject, promise, receiver, null);
};
Promise.prototype._migrateCallbackAt = function (follower, index) {
var fulfill = follower._fulfillmentHandlerAt(index);
var reject = follower._rejectionHandlerAt(index);
var promise = follower._promiseAt(index);
var receiver = follower._receiverAt(index);
if (receiver === undefined) receiver = UNDEFINED_BINDING;
this._addCallbacks(fulfill, reject, promise, receiver, null);
};
Promise.prototype._addCallbacks = function (
fulfill,
reject,
promise,
receiver,
domain
) {
var index = this._length();
if (index >= 65535 - 4) {
index = 0;
this._setLength(0);
}
if (index === 0) {
this._promise0 = promise;
this._receiver0 = receiver;
if (typeof fulfill === "function") {
this._fulfillmentHandler0 =
domain === null ? fulfill : util.domainBind(domain, fulfill);
}
if (typeof reject === "function") {
this._rejectionHandler0 =
domain === null ? reject : util.domainBind(domain, reject);
}
} else {
var base = index * 4 - 4;
this[base + 2] = promise;
this[base + 3] = receiver;
if (typeof fulfill === "function") {
this[base + 0] =
domain === null ? fulfill : util.domainBind(domain, fulfill);
}
if (typeof reject === "function") {
this[base + 1] =
domain === null ? reject : util.domainBind(domain, reject);
}
}
this._setLength(index + 1);
return index;
};
Promise.prototype._proxy = function (proxyable, arg) {
this._addCallbacks(undefined, undefined, arg, proxyable, null);
};
Promise.prototype._resolveCallback = function(value, shouldBind) {
if (((this._bitField & 117506048) !== 0)) return;
if (value === this)
return this._rejectCallback(makeSelfResolutionError(), false);
var maybePromise = tryConvertToPromise(value, this);
if (!(maybePromise instanceof Promise)) return this._fulfill(value);
if (shouldBind) this._propagateFrom(maybePromise, 2);
var promise = maybePromise._target();
if (promise === this) {
this._reject(makeSelfResolutionError());
return;
}
var bitField = promise._bitField;
if (((bitField & 50397184) === 0)) {
var len = this._length();
if (len > 0) promise._migrateCallback0(this);
for (var i = 1; i < len; ++i) {
promise._migrateCallbackAt(this, i);
}
this._setFollowing();
this._setLength(0);
this._setFollowee(promise);
} else if (((bitField & 33554432) !== 0)) {
this._fulfill(promise._value());
} else if (((bitField & 16777216) !== 0)) {
this._reject(promise._reason());
} else {
var reason = new CancellationError("late cancellation observer");
promise._attachExtraTrace(reason);
this._reject(reason);
}
};
Promise.prototype._rejectCallback =
function(reason, synchronous, ignoreNonErrorWarnings) {
var trace = util.ensureErrorObject(reason);
var hasStack = trace === reason;
if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) {
var message = "a promise was rejected with a non-error: " +
util.classString(reason);
this._warn(message, true);
}
this._attachExtraTrace(trace, synchronous ? hasStack : false);
this._reject(reason);
};
Promise.prototype._resolveFromExecutor = function (executor) {
var promise = this;
this._captureStackTrace();
this._pushContext();
var synchronous = true;
var r = this._execute(executor, function(value) {
promise._resolveCallback(value);
}, function (reason) {
promise._rejectCallback(reason, synchronous);
});
synchronous = false;
this._popContext();
if (r !== undefined) {
promise._rejectCallback(r, true);
}
};
Promise.prototype._settlePromiseFromHandler = function (
handler, receiver, value, promise
) {
var bitField = promise._bitField;
if (((bitField & 65536) !== 0)) return;
promise._pushContext();
var x;
if (receiver === APPLY) {
if (!value || typeof value.length !== "number") {
x = errorObj;
x.e = new TypeError("cannot .spread() a non-array: " +
util.classString(value));
} else {
x = tryCatch(handler).apply(this._boundValue(), value);
}
} else {
x = tryCatch(handler).call(receiver, value);
}
var promiseCreated = promise._popContext();
bitField = promise._bitField;
if (((bitField & 65536) !== 0)) return;
if (x === NEXT_FILTER) {
promise._reject(value);
} else if (x === errorObj) {
promise._rejectCallback(x.e, false);
} else {
debug.checkForgottenReturns(x, promiseCreated, "", promise, this);
promise._resolveCallback(x);
}
};
Promise.prototype._target = function() {
var ret = this;
while (ret._isFollowing()) ret = ret._followee();
return ret;
};
Promise.prototype._followee = function() {
return this._rejectionHandler0;
};
Promise.prototype._setFollowee = function(promise) {
this._rejectionHandler0 = promise;
};
Promise.prototype._settlePromise = function(promise, handler, receiver, value) {
var isPromise = promise instanceof Promise;
var bitField = this._bitField;
var asyncGuaranteed = ((bitField & 134217728) !== 0);
if (((bitField & 65536) !== 0)) {
if (isPromise) promise._invokeInternalOnCancel();
if (receiver instanceof PassThroughHandlerContext &&
receiver.isFinallyHandler()) {
receiver.cancelPromise = promise;
if (tryCatch(handler).call(receiver, value) === errorObj) {
promise._reject(errorObj.e);
}
} else if (handler === reflectHandler) {
promise._fulfill(reflectHandler.call(receiver));
} else if (receiver instanceof Proxyable) {
receiver._promiseCancelled(promise);
} else if (isPromise || promise instanceof PromiseArray) {
promise._cancel();
} else {
receiver.cancel();
}
} else if (typeof handler === "function") {
if (!isPromise) {
handler.call(receiver, value, promise);
} else {
if (asyncGuaranteed) promise._setAsyncGuaranteed();
this._settlePromiseFromHandler(handler, receiver, value, promise);
}
} else if (receiver instanceof Proxyable) {
if (!receiver._isResolved()) {
if (((bitField & 33554432) !== 0)) {
receiver._promiseFulfilled(value, promise);
} else {
receiver._promiseRejected(value, promise);
}
}
} else if (isPromise) {
if (asyncGuaranteed) promise._setAsyncGuaranteed();
if (((bitField & 33554432) !== 0)) {
promise._fulfill(value);
} else {
promise._reject(value);
}
}
};
Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) {
var handler = ctx.handler;
var promise = ctx.promise;
var receiver = ctx.receiver;
var value = ctx.value;
if (typeof handler === "function") {
if (!(promise instanceof Promise)) {
handler.call(receiver, value, promise);
} else {
this._settlePromiseFromHandler(handler, receiver, value, promise);
}
} else if (promise instanceof Promise) {
promise._reject(value);
}
};
Promise.prototype._settlePromiseCtx = function(ctx) {
this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value);
};
Promise.prototype._settlePromise0 = function(handler, value, bitField) {
var promise = this._promise0;
var receiver = this._receiverAt(0);
this._promise0 = undefined;
this._receiver0 = undefined;
this._settlePromise(promise, handler, receiver, value);
};
Promise.prototype._clearCallbackDataAtIndex = function(index) {
var base = index * 4 - 4;
this[base + 2] =
this[base + 3] =
this[base + 0] =
this[base + 1] = undefined;
};
Promise.prototype._fulfill = function (value) {
var bitField = this._bitField;
if (((bitField & 117506048) >>> 16)) return;
if (value === this) {
var err = makeSelfResolutionError();
this._attachExtraTrace(err);
return this._reject(err);
}
this._setFulfilled();
this._rejectionHandler0 = value;
if ((bitField & 65535) > 0) {
if (((bitField & 134217728) !== 0)) {
this._settlePromises();
} else {
async.settlePromises(this);
}
}
};
Promise.prototype._reject = function (reason) {
var bitField = this._bitField;
if (((bitField & 117506048) >>> 16)) return;
this._setRejected();
this._fulfillmentHandler0 = reason;
if (this._isFinal()) {
return async.fatalError(reason, util.isNode);
}
if ((bitField & 65535) > 0) {
async.settlePromises(this);
} else {
this._ensurePossibleRejectionHandled();
}
};
Promise.prototype._fulfillPromises = function (len, value) {
for (var i = 1; i < len; i++) {
var handler = this._fulfillmentHandlerAt(i);
var promise = this._promiseAt(i);
var receiver = this._receiverAt(i);
this._clearCallbackDataAtIndex(i);
this._settlePromise(promise, handler, receiver, value);
}
};
Promise.prototype._rejectPromises = function (len, reason) {
for (var i = 1; i < len; i++) {
var handler = this._rejectionHandlerAt(i);
var promise = this._promiseAt(i);
var receiver = this._receiverAt(i);
this._clearCallbackDataAtIndex(i);
this._settlePromise(promise, handler, receiver, reason);
}
};
Promise.prototype._settlePromises = function () {
var bitField = this._bitField;
var len = (bitField & 65535);
if (len > 0) {
if (((bitField & 16842752) !== 0)) {
var reason = this._fulfillmentHandler0;
this._settlePromise0(this._rejectionHandler0, reason, bitField);
this._rejectPromises(len, reason);
} else {
var value = this._rejectionHandler0;
this._settlePromise0(this._fulfillmentHandler0, value, bitField);
this._fulfillPromises(len, value);
}
this._setLength(0);
}
this._clearCancellationData();
};
Promise.prototype._settledValue = function() {
var bitField = this._bitField;
if (((bitField & 33554432) !== 0)) {
return this._rejectionHandler0;
} else if (((bitField & 16777216) !== 0)) {
return this._fulfillmentHandler0;
}
};
function deferResolve(v) {this.promise._resolveCallback(v);}
function deferReject(v) {this.promise._rejectCallback(v, false);}
Promise.defer = Promise.pending = function() {
debug.deprecated("Promise.defer", "new Promise");
var promise = new Promise(INTERNAL);
return {
promise: promise,
resolve: deferResolve,
reject: deferReject
};
};
util.notEnumerableProp(Promise,
"_makeSelfResolutionError",
makeSelfResolutionError);
require("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection,
debug);
require("./bind")(Promise, INTERNAL, tryConvertToPromise, debug);
require("./cancel")(Promise, PromiseArray, apiRejection, debug);
require("./direct_resolve")(Promise);
require("./synchronous_inspection")(Promise);
require("./join")(
Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain);
Promise.Promise = Promise;
Promise.version = "3.4.7";
require('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
require('./call_get.js')(Promise);
require('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug);
require('./timers.js')(Promise, INTERNAL, debug);
require('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug);
require('./nodeify.js')(Promise);
require('./promisify.js')(Promise, INTERNAL);
require('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection);
require('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection);
require('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
require('./settle.js')(Promise, PromiseArray, debug);
require('./some.js')(Promise, PromiseArray, apiRejection);
require('./filter.js')(Promise, INTERNAL);
require('./each.js')(Promise, INTERNAL);
require('./any.js')(Promise);
util.toFastProperties(Promise);
util.toFastProperties(Promise.prototype);
function fillTypes(value) {
var p = new Promise(INTERNAL);
p._fulfillmentHandler0 = value;
p._rejectionHandler0 = value;
p._promise0 = value;
p._receiver0 = value;
}
// Complete slack tracking, opt out of field-type tracking and
// stabilize map
fillTypes({a: 1});
fillTypes({b: 2});
fillTypes({c: 3});
fillTypes(1);
fillTypes(function(){});
fillTypes(undefined);
fillTypes(false);
fillTypes(new Promise(INTERNAL));
debug.setBounds(Async.firstLineError, util.lastLineError);
return Promise;
};
}).call(this,require('_process'))
},{"./any.js":39,"./async":40,"./bind":41,"./call_get.js":42,"./cancel":43,"./catch_filter":44,"./context":45,"./debuggability":46,"./direct_resolve":47,"./each.js":48,"./errors":49,"./es5":50,"./filter.js":51,"./finally":52,"./generators.js":53,"./join":54,"./map.js":55,"./method":56,"./nodeback":57,"./nodeify.js":58,"./promise_array":60,"./promisify.js":61,"./props.js":62,"./race.js":64,"./reduce.js":65,"./settle.js":67,"./some.js":68,"./synchronous_inspection":69,"./thenables":70,"./timers.js":71,"./using.js":72,"./util":73,"_process":83}],60:[function(require,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL, tryConvertToPromise,
apiRejection, Proxyable) {
var util = require("./util");
var isArray = util.isArray;
function toResolutionValue(val) {
switch(val) {
case -2: return [];
case -3: return {};
}
}
function PromiseArray(values) {
var promise = this._promise = new Promise(INTERNAL);
if (values instanceof Promise) {
promise._propagateFrom(values, 3);
}
promise._setOnCancel(this);
this._values = values;
this._length = 0;
this._totalResolved = 0;
this._init(undefined, -2);
}
util.inherits(PromiseArray, Proxyable);
PromiseArray.prototype.length = function () {
return this._length;
};
PromiseArray.prototype.promise = function () {
return this._promise;
};
PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) {
var values = tryConvertToPromise(this._values, this._promise);
if (values instanceof Promise) {
values = values._target();
var bitField = values._bitField;
;
this._values = values;
if (((bitField & 50397184) === 0)) {
this._promise._setAsyncGuaranteed();
return values._then(
init,
this._reject,
undefined,
this,
resolveValueIfEmpty
);
} else if (((bitField & 33554432) !== 0)) {
values = values._value();
} else if (((bitField & 16777216) !== 0)) {
return this._reject(values._reason());
} else {
return this._cancel();
}
}
values = util.asArray(values);
if (values === null) {
var err = apiRejection(
"expecting an array or an iterable object but got " + util.classString(values)).reason();
this._promise._rejectCallback(err, false);
return;
}
if (values.length === 0) {
if (resolveValueIfEmpty === -5) {
this._resolveEmptyArray();
}
else {
this._resolve(toResolutionValue(resolveValueIfEmpty));
}
return;
}
this._iterate(values);
};
PromiseArray.prototype._iterate = function(values) {
var len = this.getActualLength(values.length);
this._length = len;
this._values = this.shouldCopyValues() ? new Array(len) : this._values;
var result = this._promise;
var isResolved = false;
var bitField = null;
for (var i = 0; i < len; ++i) {
var maybePromise = tryConvertToPromise(values[i], result);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
bitField = maybePromise._bitField;
} else {
bitField = null;
}
if (isResolved) {
if (bitField !== null) {
maybePromise.suppressUnhandledRejections();
}
} else if (bitField !== null) {
if (((bitField & 50397184) === 0)) {
maybePromise._proxy(this, i);
this._values[i] = maybePromise;
} else if (((bitField & 33554432) !== 0)) {
isResolved = this._promiseFulfilled(maybePromise._value(), i);
} else if (((bitField & 16777216) !== 0)) {
isResolved = this._promiseRejected(maybePromise._reason(), i);
} else {
isResolved = this._promiseCancelled(i);
}
} else {
isResolved = this._promiseFulfilled(maybePromise, i);
}
}
if (!isResolved) result._setAsyncGuaranteed();
};
PromiseArray.prototype._isResolved = function () {
return this._values === null;
};
PromiseArray.prototype._resolve = function (value) {
this._values = null;
this._promise._fulfill(value);
};
PromiseArray.prototype._cancel = function() {
if (this._isResolved() || !this._promise._isCancellable()) return;
this._values = null;
this._promise._cancel();
};
PromiseArray.prototype._reject = function (reason) {
this._values = null;
this._promise._rejectCallback(reason, false);
};
PromiseArray.prototype._promiseFulfilled = function (value, index) {
this._values[index] = value;
var totalResolved = ++this._totalResolved;
if (totalResolved >= this._length) {
this._resolve(this._values);
return true;
}
return false;
};
PromiseArray.prototype._promiseCancelled = function() {
this._cancel();
return true;
};
PromiseArray.prototype._promiseRejected = function (reason) {
this._totalResolved++;
this._reject(reason);
return true;
};
PromiseArray.prototype._resultCancelled = function() {
if (this._isResolved()) return;
var values = this._values;
this._cancel();
if (values instanceof Promise) {
values.cancel();
} else {
for (var i = 0; i < values.length; ++i) {
if (values[i] instanceof Promise) {
values[i].cancel();
}
}
}
};
PromiseArray.prototype.shouldCopyValues = function () {
return true;
};
PromiseArray.prototype.getActualLength = function (len) {
return len;
};
return PromiseArray;
};
},{"./util":73}],61:[function(require,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL) {
var THIS = {};
var util = require("./util");
var nodebackForPromise = require("./nodeback");
var withAppended = util.withAppended;
var maybeWrapAsError = util.maybeWrapAsError;
var canEvaluate = util.canEvaluate;
var TypeError = require("./errors").TypeError;
var defaultSuffix = "Async";
var defaultPromisified = {__isPromisified__: true};
var noCopyProps = [
"arity", "length",
"name",
"arguments",
"caller",
"callee",
"prototype",
"__isPromisified__"
];
var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$");
var defaultFilter = function(name) {
return util.isIdentifier(name) &&
name.charAt(0) !== "_" &&
name !== "constructor";
};
function propsFilter(key) {
return !noCopyPropsPattern.test(key);
}
function isPromisified(fn) {
try {
return fn.__isPromisified__ === true;
}
catch (e) {
return false;
}
}
function hasPromisified(obj, key, suffix) {
var val = util.getDataPropertyOrDefault(obj, key + suffix,
defaultPromisified);
return val ? isPromisified(val) : false;
}
function checkValid(ret, suffix, suffixRegexp) {
for (var i = 0; i < ret.length; i += 2) {
var key = ret[i];
if (suffixRegexp.test(key)) {
var keyWithoutAsyncSuffix = key.replace(suffixRegexp, "");
for (var j = 0; j < ret.length; j += 2) {
if (ret[j] === keyWithoutAsyncSuffix) {
throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a"
.replace("%s", suffix));
}
}
}
}
}
function promisifiableMethods(obj, suffix, suffixRegexp, filter) {
var keys = util.inheritedDataKeys(obj);
var ret = [];
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
var value = obj[key];
var passesDefaultFilter = filter === defaultFilter
? true : defaultFilter(key, value, obj);
if (typeof value === "function" &&
!isPromisified(value) &&
!hasPromisified(obj, key, suffix) &&
filter(key, value, obj, passesDefaultFilter)) {
ret.push(key, value);
}
}
checkValid(ret, suffix, suffixRegexp);
return ret;
}
var escapeIdentRegex = function(str) {
return str.replace(/([$])/, "\\$");
};
var makeNodePromisifiedEval;
if (!false) {
var switchCaseArgumentOrder = function(likelyArgumentCount) {
var ret = [likelyArgumentCount];
var min = Math.max(0, likelyArgumentCount - 1 - 3);
for(var i = likelyArgumentCount - 1; i >= min; --i) {
ret.push(i);
}
for(var i = likelyArgumentCount + 1; i <= 3; ++i) {
ret.push(i);
}
return ret;
};
var argumentSequence = function(argumentCount) {
return util.filledRange(argumentCount, "_arg", "");
};
var parameterDeclaration = function(parameterCount) {
return util.filledRange(
Math.max(parameterCount, 3), "_arg", "");
};
var parameterCount = function(fn) {
if (typeof fn.length === "number") {
return Math.max(Math.min(fn.length, 1023 + 1), 0);
}
return 0;
};
makeNodePromisifiedEval =
function(callback, receiver, originalName, fn, _, multiArgs) {
var newParameterCount = Math.max(0, parameterCount(fn) - 1);
var argumentOrder = switchCaseArgumentOrder(newParameterCount);
var shouldProxyThis = typeof callback === "string" || receiver === THIS;
function generateCallForArgumentCount(count) {
var args = argumentSequence(count).join(", ");
var comma = count > 0 ? ", " : "";
var ret;
if (shouldProxyThis) {
ret = "ret = callback.call(this, {{args}}, nodeback); break;\n";
} else {
ret = receiver === undefined
? "ret = callback({{args}}, nodeback); break;\n"
: "ret = callback.call(receiver, {{args}}, nodeback); break;\n";
}
return ret.replace("{{args}}", args).replace(", ", comma);
}
function generateArgumentSwitchCase() {
var ret = "";
for (var i = 0; i < argumentOrder.length; ++i) {
ret += "case " + argumentOrder[i] +":" +
generateCallForArgumentCount(argumentOrder[i]);
}
ret += " \n\
default: \n\
var args = new Array(len + 1); \n\
var i = 0; \n\
for (var i = 0; i < len; ++i) { \n\
args[i] = arguments[i]; \n\
} \n\
args[i] = nodeback; \n\
[CodeForCall] \n\
break; \n\
".replace("[CodeForCall]", (shouldProxyThis
? "ret = callback.apply(this, args);\n"
: "ret = callback.apply(receiver, args);\n"));
return ret;
}
var getFunctionCode = typeof callback === "string"
? ("this != null ? this['"+callback+"'] : fn")
: "fn";
var body = "'use strict'; \n\
var ret = function (Parameters) { \n\
'use strict'; \n\
var len = arguments.length; \n\
var promise = new Promise(INTERNAL); \n\
promise._captureStackTrace(); \n\
var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\
var ret; \n\
var callback = tryCatch([GetFunctionCode]); \n\
switch(len) { \n\
[CodeForSwitchCase] \n\
} \n\
if (ret === errorObj) { \n\
promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\
} \n\
if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\
return promise; \n\
}; \n\
notEnumerableProp(ret, '__isPromisified__', true); \n\
return ret; \n\
".replace("[CodeForSwitchCase]", generateArgumentSwitchCase())
.replace("[GetFunctionCode]", getFunctionCode);
body = body.replace("Parameters", parameterDeclaration(newParameterCount));
return new Function("Promise",
"fn",
"receiver",
"withAppended",
"maybeWrapAsError",
"nodebackForPromise",
"tryCatch",
"errorObj",
"notEnumerableProp",
"INTERNAL",
body)(
Promise,
fn,
receiver,
withAppended,
maybeWrapAsError,
nodebackForPromise,
util.tryCatch,
util.errorObj,
util.notEnumerableProp,
INTERNAL);
};
}
function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) {
var defaultThis = (function() {return this;})();
var method = callback;
if (typeof method === "string") {
callback = fn;
}
function promisified() {
var _receiver = receiver;
if (receiver === THIS) _receiver = this;
var promise = new Promise(INTERNAL);
promise._captureStackTrace();
var cb = typeof method === "string" && this !== defaultThis
? this[method] : callback;
var fn = nodebackForPromise(promise, multiArgs);
try {
cb.apply(_receiver, withAppended(arguments, fn));
} catch(e) {
promise._rejectCallback(maybeWrapAsError(e), true, true);
}
if (!promise._isFateSealed()) promise._setAsyncGuaranteed();
return promise;
}
util.notEnumerableProp(promisified, "__isPromisified__", true);
return promisified;
}
var makeNodePromisified = canEvaluate
? makeNodePromisifiedEval
: makeNodePromisifiedClosure;
function promisifyAll(obj, suffix, filter, promisifier, multiArgs) {
var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$");
var methods =
promisifiableMethods(obj, suffix, suffixRegexp, filter);
for (var i = 0, len = methods.length; i < len; i+= 2) {
var key = methods[i];
var fn = methods[i+1];
var promisifiedKey = key + suffix;
if (promisifier === makeNodePromisified) {
obj[promisifiedKey] =
makeNodePromisified(key, THIS, key, fn, suffix, multiArgs);
} else {
var promisified = promisifier(fn, function() {
return makeNodePromisified(key, THIS, key,
fn, suffix, multiArgs);
});
util.notEnumerableProp(promisified, "__isPromisified__", true);
obj[promisifiedKey] = promisified;
}
}
util.toFastProperties(obj);
return obj;
}
function promisify(callback, receiver, multiArgs) {
return makeNodePromisified(callback, receiver, undefined,
callback, null, multiArgs);
}
Promise.promisify = function (fn, options) {
if (typeof fn !== "function") {
throw new TypeError("expecting a function but got " + util.classString(fn));
}
if (isPromisified(fn)) {
return fn;
}
options = Object(options);
var receiver = options.context === undefined ? THIS : options.context;
var multiArgs = !!options.multiArgs;
var ret = promisify(fn, receiver, multiArgs);
util.copyDescriptors(fn, ret, propsFilter);
return ret;
};
Promise.promisifyAll = function (target, options) {
if (typeof target !== "function" && typeof target !== "object") {
throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
options = Object(options);
var multiArgs = !!options.multiArgs;
var suffix = options.suffix;
if (typeof suffix !== "string") suffix = defaultSuffix;
var filter = options.filter;
if (typeof filter !== "function") filter = defaultFilter;
var promisifier = options.promisifier;
if (typeof promisifier !== "function") promisifier = makeNodePromisified;
if (!util.isIdentifier(suffix)) {
throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
var keys = util.inheritedDataKeys(target);
for (var i = 0; i < keys.length; ++i) {
var value = target[keys[i]];
if (keys[i] !== "constructor" &&
util.isClass(value)) {
promisifyAll(value.prototype, suffix, filter, promisifier,
multiArgs);
promisifyAll(value, suffix, filter, promisifier, multiArgs);
}
}
return promisifyAll(target, suffix, filter, promisifier, multiArgs);
};
};
},{"./errors":49,"./nodeback":57,"./util":73}],62:[function(require,module,exports){
"use strict";
module.exports = function(
Promise, PromiseArray, tryConvertToPromise, apiRejection) {
var util = require("./util");
var isObject = util.isObject;
var es5 = require("./es5");
var Es6Map;
if (typeof Map === "function") Es6Map = Map;
var mapToEntries = (function() {
var index = 0;
var size = 0;
function extractEntry(value, key) {
this[index] = value;
this[index + size] = key;
index++;
}
return function mapToEntries(map) {
size = map.size;
index = 0;
var ret = new Array(map.size * 2);
map.forEach(extractEntry, ret);
return ret;
};
})();
var entriesToMap = function(entries) {
var ret = new Es6Map();
var length = entries.length / 2 | 0;
for (var i = 0; i < length; ++i) {
var key = entries[length + i];
var value = entries[i];
ret.set(key, value);
}
return ret;
};
function PropertiesPromiseArray(obj) {
var isMap = false;
var entries;
if (Es6Map !== undefined && obj instanceof Es6Map) {
entries = mapToEntries(obj);
isMap = true;
} else {
var keys = es5.keys(obj);
var len = keys.length;
entries = new Array(len * 2);
for (var i = 0; i < len; ++i) {
var key = keys[i];
entries[i] = obj[key];
entries[i + len] = key;
}
}
this.constructor$(entries);
this._isMap = isMap;
this._init$(undefined, -3);
}
util.inherits(PropertiesPromiseArray, PromiseArray);
PropertiesPromiseArray.prototype._init = function () {};
PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) {
this._values[index] = value;
var totalResolved = ++this._totalResolved;
if (totalResolved >= this._length) {
var val;
if (this._isMap) {
val = entriesToMap(this._values);
} else {
val = {};
var keyOffset = this.length();
for (var i = 0, len = this.length(); i < len; ++i) {
val[this._values[i + keyOffset]] = this._values[i];
}
}
this._resolve(val);
return true;
}
return false;
};
PropertiesPromiseArray.prototype.shouldCopyValues = function () {
return false;
};
PropertiesPromiseArray.prototype.getActualLength = function (len) {
return len >> 1;
};
function props(promises) {
var ret;
var castValue = tryConvertToPromise(promises);
if (!isObject(castValue)) {
return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a");
} else if (castValue instanceof Promise) {
ret = castValue._then(
Promise.props, undefined, undefined, undefined, undefined);
} else {
ret = new PropertiesPromiseArray(castValue).promise();
}
if (castValue instanceof Promise) {
ret._propagateFrom(castValue, 2);
}
return ret;
}
Promise.prototype.props = function () {
return props(this);
};
Promise.props = function (promises) {
return props(promises);
};
};
},{"./es5":50,"./util":73}],63:[function(require,module,exports){
"use strict";
function arrayMove(src, srcIndex, dst, dstIndex, len) {
for (var j = 0; j < len; ++j) {
dst[j + dstIndex] = src[j + srcIndex];
src[j + srcIndex] = void 0;
}
}
function Queue(capacity) {
this._capacity = capacity;
this._length = 0;
this._front = 0;
}
Queue.prototype._willBeOverCapacity = function (size) {
return this._capacity < size;
};
Queue.prototype._pushOne = function (arg) {
var length = this.length();
this._checkCapacity(length + 1);
var i = (this._front + length) & (this._capacity - 1);
this[i] = arg;
this._length = length + 1;
};
Queue.prototype.push = function (fn, receiver, arg) {
var length = this.length() + 3;
if (this._willBeOverCapacity(length)) {
this._pushOne(fn);
this._pushOne(receiver);
this._pushOne(arg);
return;
}
var j = this._front + length - 3;
this._checkCapacity(length);
var wrapMask = this._capacity - 1;
this[(j + 0) & wrapMask] = fn;
this[(j + 1) & wrapMask] = receiver;
this[(j + 2) & wrapMask] = arg;
this._length = length;
};
Queue.prototype.shift = function () {
var front = this._front,
ret = this[front];
this[front] = undefined;
this._front = (front + 1) & (this._capacity - 1);
this._length--;
return ret;
};
Queue.prototype.length = function () {
return this._length;
};
Queue.prototype._checkCapacity = function (size) {
if (this._capacity < size) {
this._resizeTo(this._capacity << 1);
}
};
Queue.prototype._resizeTo = function (capacity) {
var oldCapacity = this._capacity;
this._capacity = capacity;
var front = this._front;
var length = this._length;
var moveItemsCount = (front + length) & (oldCapacity - 1);
arrayMove(this, 0, this, oldCapacity, moveItemsCount);
};
module.exports = Queue;
},{}],64:[function(require,module,exports){
"use strict";
module.exports = function(
Promise, INTERNAL, tryConvertToPromise, apiRejection) {
var util = require("./util");
var raceLater = function (promise) {
return promise.then(function(array) {
return race(array, promise);
});
};
function race(promises, parent) {
var maybePromise = tryConvertToPromise(promises);
if (maybePromise instanceof Promise) {
return raceLater(maybePromise);
} else {
promises = util.asArray(promises);
if (promises === null)
return apiRejection("expecting an array or an iterable object but got " + util.classString(promises));
}
var ret = new Promise(INTERNAL);
if (parent !== undefined) {
ret._propagateFrom(parent, 3);
}
var fulfill = ret._fulfill;
var reject = ret._reject;
for (var i = 0, len = promises.length; i < len; ++i) {
var val = promises[i];
if (val === undefined && !(i in promises)) {
continue;
}
Promise.cast(val)._then(fulfill, reject, undefined, ret, null);
}
return ret;
}
Promise.race = function (promises) {
return race(promises, undefined);
};
Promise.prototype.race = function () {
return race(this, undefined);
};
};
},{"./util":73}],65:[function(require,module,exports){
"use strict";
module.exports = function(Promise,
PromiseArray,
apiRejection,
tryConvertToPromise,
INTERNAL,
debug) {
var getDomain = Promise._getDomain;
var util = require("./util");
var tryCatch = util.tryCatch;
function ReductionPromiseArray(promises, fn, initialValue, _each) {
this.constructor$(promises);
var domain = getDomain();
this._fn = domain === null ? fn : util.domainBind(domain, fn);
if (initialValue !== undefined) {
initialValue = Promise.resolve(initialValue);
initialValue._attachCancellationCallback(this);
}
this._initialValue = initialValue;
this._currentCancellable = null;
if(_each === INTERNAL) {
this._eachValues = Array(this._length);
} else if (_each === 0) {
this._eachValues = null;
} else {
this._eachValues = undefined;
}
this._promise._captureStackTrace();
this._init$(undefined, -5);
}
util.inherits(ReductionPromiseArray, PromiseArray);
ReductionPromiseArray.prototype._gotAccum = function(accum) {
if (this._eachValues !== undefined &&
this._eachValues !== null &&
accum !== INTERNAL) {
this._eachValues.push(accum);
}
};
ReductionPromiseArray.prototype._eachComplete = function(value) {
if (this._eachValues !== null) {
this._eachValues.push(value);
}
return this._eachValues;
};
ReductionPromiseArray.prototype._init = function() {};
ReductionPromiseArray.prototype._resolveEmptyArray = function() {
this._resolve(this._eachValues !== undefined ? this._eachValues
: this._initialValue);
};
ReductionPromiseArray.prototype.shouldCopyValues = function () {
return false;
};
ReductionPromiseArray.prototype._resolve = function(value) {
this._promise._resolveCallback(value);
this._values = null;
};
ReductionPromiseArray.prototype._resultCancelled = function(sender) {
if (sender === this._initialValue) return this._cancel();
if (this._isResolved()) return;
this._resultCancelled$();
if (this._currentCancellable instanceof Promise) {
this._currentCancellable.cancel();
}
if (this._initialValue instanceof Promise) {
this._initialValue.cancel();
}
};
ReductionPromiseArray.prototype._iterate = function (values) {
this._values = values;
var value;
var i;
var length = values.length;
if (this._initialValue !== undefined) {
value = this._initialValue;
i = 0;
} else {
value = Promise.resolve(values[0]);
i = 1;
}
this._currentCancellable = value;
if (!value.isRejected()) {
for (; i < length; ++i) {
var ctx = {
accum: null,
value: values[i],
index: i,
length: length,
array: this
};
value = value._then(gotAccum, undefined, undefined, ctx, undefined);
}
}
if (this._eachValues !== undefined) {
value = value
._then(this._eachComplete, undefined, undefined, this, undefined);
}
value._then(completed, completed, undefined, value, this);
};
Promise.prototype.reduce = function (fn, initialValue) {
return reduce(this, fn, initialValue, null);
};
Promise.reduce = function (promises, fn, initialValue, _each) {
return reduce(promises, fn, initialValue, _each);
};
function completed(valueOrReason, array) {
if (this.isFulfilled()) {
array._resolve(valueOrReason);
} else {
array._reject(valueOrReason);
}
}
function reduce(promises, fn, initialValue, _each) {
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
var array = new ReductionPromiseArray(promises, fn, initialValue, _each);
return array.promise();
}
function gotAccum(accum) {
this.accum = accum;
this.array._gotAccum(accum);
var value = tryConvertToPromise(this.value, this.array._promise);
if (value instanceof Promise) {
this.array._currentCancellable = value;
return value._then(gotValue, undefined, undefined, this, undefined);
} else {
return gotValue.call(this, value);
}
}
function gotValue(value) {
var array = this.array;
var promise = array._promise;
var fn = tryCatch(array._fn);
promise._pushContext();
var ret;
if (array._eachValues !== undefined) {
ret = fn.call(promise._boundValue(), value, this.index, this.length);
} else {
ret = fn.call(promise._boundValue(),
this.accum, value, this.index, this.length);
}
if (ret instanceof Promise) {
array._currentCancellable = ret;
}
var promiseCreated = promise._popContext();
debug.checkForgottenReturns(
ret,
promiseCreated,
array._eachValues !== undefined ? "Promise.each" : "Promise.reduce",
promise
);
return ret;
}
};
},{"./util":73}],66:[function(require,module,exports){
(function (process,global){
"use strict";
var util = require("./util");
var schedule;
var noAsyncScheduler = function() {
throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
};
var NativePromise = util.getNativePromise();
if (util.isNode && typeof MutationObserver === "undefined") {
var GlobalSetImmediate = global.setImmediate;
var ProcessNextTick = process.nextTick;
schedule = util.isRecentNode
? function(fn) { GlobalSetImmediate.call(global, fn); }
: function(fn) { ProcessNextTick.call(process, fn); };
} else if (typeof NativePromise === "function" &&
typeof NativePromise.resolve === "function") {
var nativePromise = NativePromise.resolve();
schedule = function(fn) {
nativePromise.then(fn);
};
} else if ((typeof MutationObserver !== "undefined") &&
!(typeof window !== "undefined" &&
window.navigator &&
(window.navigator.standalone || window.cordova))) {
schedule = (function() {
var div = document.createElement("div");
var opts = {attributes: true};
var toggleScheduled = false;
var div2 = document.createElement("div");
var o2 = new MutationObserver(function() {
div.classList.toggle("foo");
toggleScheduled = false;
});
o2.observe(div2, opts);
var scheduleToggle = function() {
if (toggleScheduled) return;
toggleScheduled = true;
div2.classList.toggle("foo");
};
return function schedule(fn) {
var o = new MutationObserver(function() {
o.disconnect();
fn();
});
o.observe(div, opts);
scheduleToggle();
};
})();
} else if (typeof setImmediate !== "undefined") {
schedule = function (fn) {
setImmediate(fn);
};
} else if (typeof setTimeout !== "undefined") {
schedule = function (fn) {
setTimeout(fn, 0);
};
} else {
schedule = noAsyncScheduler;
}
module.exports = schedule;
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./util":73,"_process":83}],67:[function(require,module,exports){
"use strict";
module.exports =
function(Promise, PromiseArray, debug) {
var PromiseInspection = Promise.PromiseInspection;
var util = require("./util");
function SettledPromiseArray(values) {
this.constructor$(values);
}
util.inherits(SettledPromiseArray, PromiseArray);
SettledPromiseArray.prototype._promiseResolved = function (index, inspection) {
this._values[index] = inspection;
var totalResolved = ++this._totalResolved;
if (totalResolved >= this._length) {
this._resolve(this._values);
return true;
}
return false;
};
SettledPromiseArray.prototype._promiseFulfilled = function (value, index) {
var ret = new PromiseInspection();
ret._bitField = 33554432;
ret._settledValueField = value;
return this._promiseResolved(index, ret);
};
SettledPromiseArray.prototype._promiseRejected = function (reason, index) {
var ret = new PromiseInspection();
ret._bitField = 16777216;
ret._settledValueField = reason;
return this._promiseResolved(index, ret);
};
Promise.settle = function (promises) {
debug.deprecated(".settle()", ".reflect()");
return new SettledPromiseArray(promises).promise();
};
Promise.prototype.settle = function () {
return Promise.settle(this);
};
};
},{"./util":73}],68:[function(require,module,exports){
"use strict";
module.exports =
function(Promise, PromiseArray, apiRejection) {
var util = require("./util");
var RangeError = require("./errors").RangeError;
var AggregateError = require("./errors").AggregateError;
var isArray = util.isArray;
var CANCELLATION = {};
function SomePromiseArray(values) {
this.constructor$(values);
this._howMany = 0;
this._unwrap = false;
this._initialized = false;
}
util.inherits(SomePromiseArray, PromiseArray);
SomePromiseArray.prototype._init = function () {
if (!this._initialized) {
return;
}
if (this._howMany === 0) {
this._resolve([]);
return;
}
this._init$(undefined, -5);
var isArrayResolved = isArray(this._values);
if (!this._isResolved() &&
isArrayResolved &&
this._howMany > this._canPossiblyFulfill()) {
this._reject(this._getRangeError(this.length()));
}
};
SomePromiseArray.prototype.init = function () {
this._initialized = true;
this._init();
};
SomePromiseArray.prototype.setUnwrap = function () {
this._unwrap = true;
};
SomePromiseArray.prototype.howMany = function () {
return this._howMany;
};
SomePromiseArray.prototype.setHowMany = function (count) {
this._howMany = count;
};
SomePromiseArray.prototype._promiseFulfilled = function (value) {
this._addFulfilled(value);
if (this._fulfilled() === this.howMany()) {
this._values.length = this.howMany();
if (this.howMany() === 1 && this._unwrap) {
this._resolve(this._values[0]);
} else {
this._resolve(this._values);
}
return true;
}
return false;
};
SomePromiseArray.prototype._promiseRejected = function (reason) {
this._addRejected(reason);
return this._checkOutcome();
};
SomePromiseArray.prototype._promiseCancelled = function () {
if (this._values instanceof Promise || this._values == null) {
return this._cancel();
}
this._addRejected(CANCELLATION);
return this._checkOutcome();
};
SomePromiseArray.prototype._checkOutcome = function() {
if (this.howMany() > this._canPossiblyFulfill()) {
var e = new AggregateError();
for (var i = this.length(); i < this._values.length; ++i) {
if (this._values[i] !== CANCELLATION) {
e.push(this._values[i]);
}
}
if (e.length > 0) {
this._reject(e);
} else {
this._cancel();
}
return true;
}
return false;
};
SomePromiseArray.prototype._fulfilled = function () {
return this._totalResolved;
};
SomePromiseArray.prototype._rejected = function () {
return this._values.length - this.length();
};
SomePromiseArray.prototype._addRejected = function (reason) {
this._values.push(reason);
};
SomePromiseArray.prototype._addFulfilled = function (value) {
this._values[this._totalResolved++] = value;
};
SomePromiseArray.prototype._canPossiblyFulfill = function () {
return this.length() - this._rejected();
};
SomePromiseArray.prototype._getRangeError = function (count) {
var message = "Input array must contain at least " +
this._howMany + " items but contains only " + count + " items";
return new RangeError(message);
};
SomePromiseArray.prototype._resolveEmptyArray = function () {
this._reject(this._getRangeError(0));
};
function some(promises, howMany) {
if ((howMany | 0) !== howMany || howMany < 0) {
return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
var ret = new SomePromiseArray(promises);
var promise = ret.promise();
ret.setHowMany(howMany);
ret.init();
return promise;
}
Promise.some = function (promises, howMany) {
return some(promises, howMany);
};
Promise.prototype.some = function (howMany) {
return some(this, howMany);
};
Promise._SomePromiseArray = SomePromiseArray;
};
},{"./errors":49,"./util":73}],69:[function(require,module,exports){
"use strict";
module.exports = function(Promise) {
function PromiseInspection(promise) {
if (promise !== undefined) {
promise = promise._target();
this._bitField = promise._bitField;
this._settledValueField = promise._isFateSealed()
? promise._settledValue() : undefined;
}
else {
this._bitField = 0;
this._settledValueField = undefined;
}
}
PromiseInspection.prototype._settledValue = function() {
return this._settledValueField;
};
var value = PromiseInspection.prototype.value = function () {
if (!this.isFulfilled()) {
throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
return this._settledValue();
};
var reason = PromiseInspection.prototype.error =
PromiseInspection.prototype.reason = function () {
if (!this.isRejected()) {
throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
return this._settledValue();
};
var isFulfilled = PromiseInspection.prototype.isFulfilled = function() {
return (this._bitField & 33554432) !== 0;
};
var isRejected = PromiseInspection.prototype.isRejected = function () {
return (this._bitField & 16777216) !== 0;
};
var isPending = PromiseInspection.prototype.isPending = function () {
return (this._bitField & 50397184) === 0;
};
var isResolved = PromiseInspection.prototype.isResolved = function () {
return (this._bitField & 50331648) !== 0;
};
PromiseInspection.prototype.isCancelled = function() {
return (this._bitField & 8454144) !== 0;
};
Promise.prototype.__isCancelled = function() {
return (this._bitField & 65536) === 65536;
};
Promise.prototype._isCancelled = function() {
return this._target().__isCancelled();
};
Promise.prototype.isCancelled = function() {
return (this._target()._bitField & 8454144) !== 0;
};
Promise.prototype.isPending = function() {
return isPending.call(this._target());
};
Promise.prototype.isRejected = function() {
return isRejected.call(this._target());
};
Promise.prototype.isFulfilled = function() {
return isFulfilled.call(this._target());
};
Promise.prototype.isResolved = function() {
return isResolved.call(this._target());
};
Promise.prototype.value = function() {
return value.call(this._target());
};
Promise.prototype.reason = function() {
var target = this._target();
target._unsetRejectionIsUnhandled();
return reason.call(target);
};
Promise.prototype._value = function() {
return this._settledValue();
};
Promise.prototype._reason = function() {
this._unsetRejectionIsUnhandled();
return this._settledValue();
};
Promise.PromiseInspection = PromiseInspection;
};
},{}],70:[function(require,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL) {
var util = require("./util");
var errorObj = util.errorObj;
var isObject = util.isObject;
function tryConvertToPromise(obj, context) {
if (isObject(obj)) {
if (obj instanceof Promise) return obj;
var then = getThen(obj);
if (then === errorObj) {
if (context) context._pushContext();
var ret = Promise.reject(then.e);
if (context) context._popContext();
return ret;
} else if (typeof then === "function") {
if (isAnyBluebirdPromise(obj)) {
var ret = new Promise(INTERNAL);
obj._then(
ret._fulfill,
ret._reject,
undefined,
ret,
null
);
return ret;
}
return doThenable(obj, then, context);
}
}
return obj;
}
function doGetThen(obj) {
return obj.then;
}
function getThen(obj) {
try {
return doGetThen(obj);
} catch (e) {
errorObj.e = e;
return errorObj;
}
}
var hasProp = {}.hasOwnProperty;
function isAnyBluebirdPromise(obj) {
try {
return hasProp.call(obj, "_promise0");
} catch (e) {
return false;
}
}
function doThenable(x, then, context) {
var promise = new Promise(INTERNAL);
var ret = promise;
if (context) context._pushContext();
promise._captureStackTrace();
if (context) context._popContext();
var synchronous = true;
var result = util.tryCatch(then).call(x, resolve, reject);
synchronous = false;
if (promise && result === errorObj) {
promise._rejectCallback(result.e, true, true);
promise = null;
}
function resolve(value) {
if (!promise) return;
promise._resolveCallback(value);
promise = null;
}
function reject(reason) {
if (!promise) return;
promise._rejectCallback(reason, synchronous, true);
promise = null;
}
return ret;
}
return tryConvertToPromise;
};
},{"./util":73}],71:[function(require,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL, debug) {
var util = require("./util");
var TimeoutError = Promise.TimeoutError;
function HandleWrapper(handle) {
this.handle = handle;
}
HandleWrapper.prototype._resultCancelled = function() {
clearTimeout(this.handle);
};
var afterValue = function(value) { return delay(+this).thenReturn(value); };
var delay = Promise.delay = function (ms, value) {
var ret;
var handle;
if (value !== undefined) {
ret = Promise.resolve(value)
._then(afterValue, null, null, ms, undefined);
if (debug.cancellation() && value instanceof Promise) {
ret._setOnCancel(value);
}
} else {
ret = new Promise(INTERNAL);
handle = setTimeout(function() { ret._fulfill(); }, +ms);
if (debug.cancellation()) {
ret._setOnCancel(new HandleWrapper(handle));
}
ret._captureStackTrace();
}
ret._setAsyncGuaranteed();
return ret;
};
Promise.prototype.delay = function (ms) {
return delay(ms, this);
};
var afterTimeout = function (promise, message, parent) {
var err;
if (typeof message !== "string") {
if (message instanceof Error) {
err = message;
} else {
err = new TimeoutError("operation timed out");
}
} else {
err = new TimeoutError(message);
}
util.markAsOriginatingFromRejection(err);
promise._attachExtraTrace(err);
promise._reject(err);
if (parent != null) {
parent.cancel();
}
};
function successClear(value) {
clearTimeout(this.handle);
return value;
}
function failureClear(reason) {
clearTimeout(this.handle);
throw reason;
}
Promise.prototype.timeout = function (ms, message) {
ms = +ms;
var ret, parent;
var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() {
if (ret.isPending()) {
afterTimeout(ret, message, parent);
}
}, ms));
if (debug.cancellation()) {
parent = this.then();
ret = parent._then(successClear, failureClear,
undefined, handleWrapper, undefined);
ret._setOnCancel(handleWrapper);
} else {
ret = this._then(successClear, failureClear,
undefined, handleWrapper, undefined);
}
return ret;
};
};
},{"./util":73}],72:[function(require,module,exports){
"use strict";
module.exports = function (Promise, apiRejection, tryConvertToPromise,
createContext, INTERNAL, debug) {
var util = require("./util");
var TypeError = require("./errors").TypeError;
var inherits = require("./util").inherits;
var errorObj = util.errorObj;
var tryCatch = util.tryCatch;
var NULL = {};
function thrower(e) {
setTimeout(function(){throw e;}, 0);
}
function castPreservingDisposable(thenable) {
var maybePromise = tryConvertToPromise(thenable);
if (maybePromise !== thenable &&
typeof thenable._isDisposable === "function" &&
typeof thenable._getDisposer === "function" &&
thenable._isDisposable()) {
maybePromise._setDisposable(thenable._getDisposer());
}
return maybePromise;
}
function dispose(resources, inspection) {
var i = 0;
var len = resources.length;
var ret = new Promise(INTERNAL);
function iterator() {
if (i >= len) return ret._fulfill();
var maybePromise = castPreservingDisposable(resources[i++]);
if (maybePromise instanceof Promise &&
maybePromise._isDisposable()) {
try {
maybePromise = tryConvertToPromise(
maybePromise._getDisposer().tryDispose(inspection),
resources.promise);
} catch (e) {
return thrower(e);
}
if (maybePromise instanceof Promise) {
return maybePromise._then(iterator, thrower,
null, null, null);
}
}
iterator();
}
iterator();
return ret;
}
function Disposer(data, promise, context) {
this._data = data;
this._promise = promise;
this._context = context;
}
Disposer.prototype.data = function () {
return this._data;
};
Disposer.prototype.promise = function () {
return this._promise;
};
Disposer.prototype.resource = function () {
if (this.promise().isFulfilled()) {
return this.promise().value();
}
return NULL;
};
Disposer.prototype.tryDispose = function(inspection) {
var resource = this.resource();
var context = this._context;
if (context !== undefined) context._pushContext();
var ret = resource !== NULL
? this.doDispose(resource, inspection) : null;
if (context !== undefined) context._popContext();
this._promise._unsetDisposable();
this._data = null;
return ret;
};
Disposer.isDisposer = function (d) {
return (d != null &&
typeof d.resource === "function" &&
typeof d.tryDispose === "function");
};
function FunctionDisposer(fn, promise, context) {
this.constructor$(fn, promise, context);
}
inherits(FunctionDisposer, Disposer);
FunctionDisposer.prototype.doDispose = function (resource, inspection) {
var fn = this.data();
return fn.call(resource, resource, inspection);
};
function maybeUnwrapDisposer(value) {
if (Disposer.isDisposer(value)) {
this.resources[this.index]._setDisposable(value);
return value.promise();
}
return value;
}
function ResourceList(length) {
this.length = length;
this.promise = null;
this[length-1] = null;
}
ResourceList.prototype._resultCancelled = function() {
var len = this.length;
for (var i = 0; i < len; ++i) {
var item = this[i];
if (item instanceof Promise) {
item.cancel();
}
}
};
Promise.using = function () {
var len = arguments.length;
if (len < 2) return apiRejection(
"you must pass at least 2 arguments to Promise.using");
var fn = arguments[len - 1];
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
var input;
var spreadArgs = true;
if (len === 2 && Array.isArray(arguments[0])) {
input = arguments[0];
len = input.length;
spreadArgs = false;
} else {
input = arguments;
len--;
}
var resources = new ResourceList(len);
for (var i = 0; i < len; ++i) {
var resource = input[i];
if (Disposer.isDisposer(resource)) {
var disposer = resource;
resource = resource.promise();
resource._setDisposable(disposer);
} else {
var maybePromise = tryConvertToPromise(resource);
if (maybePromise instanceof Promise) {
resource =
maybePromise._then(maybeUnwrapDisposer, null, null, {
resources: resources,
index: i
}, undefined);
}
}
resources[i] = resource;
}
var reflectedResources = new Array(resources.length);
for (var i = 0; i < reflectedResources.length; ++i) {
reflectedResources[i] = Promise.resolve(resources[i]).reflect();
}
var resultPromise = Promise.all(reflectedResources)
.then(function(inspections) {
for (var i = 0; i < inspections.length; ++i) {
var inspection = inspections[i];
if (inspection.isRejected()) {
errorObj.e = inspection.error();
return errorObj;
} else if (!inspection.isFulfilled()) {
resultPromise.cancel();
return;
}
inspections[i] = inspection.value();
}
promise._pushContext();
fn = tryCatch(fn);
var ret = spreadArgs
? fn.apply(undefined, inspections) : fn(inspections);
var promiseCreated = promise._popContext();
debug.checkForgottenReturns(
ret, promiseCreated, "Promise.using", promise);
return ret;
});
var promise = resultPromise.lastly(function() {
var inspection = new Promise.PromiseInspection(resultPromise);
return dispose(resources, inspection);
});
resources.promise = promise;
promise._setOnCancel(resources);
return promise;
};
Promise.prototype._setDisposable = function (disposer) {
this._bitField = this._bitField | 131072;
this._disposer = disposer;
};
Promise.prototype._isDisposable = function () {
return (this._bitField & 131072) > 0;
};
Promise.prototype._getDisposer = function () {
return this._disposer;
};
Promise.prototype._unsetDisposable = function () {
this._bitField = this._bitField & (~131072);
this._disposer = undefined;
};
Promise.prototype.disposer = function (fn) {
if (typeof fn === "function") {
return new FunctionDisposer(fn, this, createContext());
}
throw new TypeError();
};
};
},{"./errors":49,"./util":73}],73:[function(require,module,exports){
(function (process,global){
"use strict";
var es5 = require("./es5");
var canEvaluate = typeof navigator == "undefined";
var errorObj = {e: {}};
var tryCatchTarget;
var globalObject = typeof self !== "undefined" ? self :
typeof window !== "undefined" ? window :
typeof global !== "undefined" ? global :
this !== undefined ? this : null;
function tryCatcher() {
try {
var target = tryCatchTarget;
tryCatchTarget = null;
return target.apply(this, arguments);
} catch (e) {
errorObj.e = e;
return errorObj;
}
}
function tryCatch(fn) {
tryCatchTarget = fn;
return tryCatcher;
}
var inherits = function(Child, Parent) {
var hasProp = {}.hasOwnProperty;
function T() {
this.constructor = Child;
this.constructor$ = Parent;
for (var propertyName in Parent.prototype) {
if (hasProp.call(Parent.prototype, propertyName) &&
propertyName.charAt(propertyName.length-1) !== "$"
) {
this[propertyName + "$"] = Parent.prototype[propertyName];
}
}
}
T.prototype = Parent.prototype;
Child.prototype = new T();
return Child.prototype;
};
function isPrimitive(val) {
return val == null || val === true || val === false ||
typeof val === "string" || typeof val === "number";
}
function isObject(value) {
return typeof value === "function" ||
typeof value === "object" && value !== null;
}
function maybeWrapAsError(maybeError) {
if (!isPrimitive(maybeError)) return maybeError;
return new Error(safeToString(maybeError));
}
function withAppended(target, appendee) {
var len = target.length;
var ret = new Array(len + 1);
var i;
for (i = 0; i < len; ++i) {
ret[i] = target[i];
}
ret[i] = appendee;
return ret;
}
function getDataPropertyOrDefault(obj, key, defaultValue) {
if (es5.isES5) {
var desc = Object.getOwnPropertyDescriptor(obj, key);
if (desc != null) {
return desc.get == null && desc.set == null
? desc.value
: defaultValue;
}
} else {
return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
}
}
function notEnumerableProp(obj, name, value) {
if (isPrimitive(obj)) return obj;
var descriptor = {
value: value,
configurable: true,
enumerable: false,
writable: true
};
es5.defineProperty(obj, name, descriptor);
return obj;
}
function thrower(r) {
throw r;
}
var inheritedDataKeys = (function() {
var excludedPrototypes = [
Array.prototype,
Object.prototype,
Function.prototype
];
var isExcludedProto = function(val) {
for (var i = 0; i < excludedPrototypes.length; ++i) {
if (excludedPrototypes[i] === val) {
return true;
}
}
return false;
};
if (es5.isES5) {
var getKeys = Object.getOwnPropertyNames;
return function(obj) {
var ret = [];
var visitedKeys = Object.create(null);
while (obj != null && !isExcludedProto(obj)) {
var keys;
try {
keys = getKeys(obj);
} catch (e) {
return ret;
}
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (visitedKeys[key]) continue;
visitedKeys[key] = true;
var desc = Object.getOwnPropertyDescriptor(obj, key);
if (desc != null && desc.get == null && desc.set == null) {
ret.push(key);
}
}
obj = es5.getPrototypeOf(obj);
}
return ret;
};
} else {
var hasProp = {}.hasOwnProperty;
return function(obj) {
if (isExcludedProto(obj)) return [];
var ret = [];
/*jshint forin:false */
enumeration: for (var key in obj) {
if (hasProp.call(obj, key)) {
ret.push(key);
} else {
for (var i = 0; i < excludedPrototypes.length; ++i) {
if (hasProp.call(excludedPrototypes[i], key)) {
continue enumeration;
}
}
ret.push(key);
}
}
return ret;
};
}
})();
var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/;
function isClass(fn) {
try {
if (typeof fn === "function") {
var keys = es5.names(fn.prototype);
var hasMethods = es5.isES5 && keys.length > 1;
var hasMethodsOtherThanConstructor = keys.length > 0 &&
!(keys.length === 1 && keys[0] === "constructor");
var hasThisAssignmentAndStaticMethods =
thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0;
if (hasMethods || hasMethodsOtherThanConstructor ||
hasThisAssignmentAndStaticMethods) {
return true;
}
}
return false;
} catch (e) {
return false;
}
}
function toFastProperties(obj) {
/*jshint -W027,-W055,-W031*/
function FakeConstructor() {}
FakeConstructor.prototype = obj;
var l = 8;
while (l--) new FakeConstructor();
return obj;
eval(obj);
}
var rident = /^[a-z$_][a-z$_0-9]*$/i;
function isIdentifier(str) {
return rident.test(str);
}
function filledRange(count, prefix, suffix) {
var ret = new Array(count);
for(var i = 0; i < count; ++i) {
ret[i] = prefix + i + suffix;
}
return ret;
}
function safeToString(obj) {
try {
return obj + "";
} catch (e) {
return "[no string representation]";
}
}
function isError(obj) {
return obj !== null &&
typeof obj === "object" &&
typeof obj.message === "string" &&
typeof obj.name === "string";
}
function markAsOriginatingFromRejection(e) {
try {
notEnumerableProp(e, "isOperational", true);
}
catch(ignore) {}
}
function originatesFromRejection(e) {
if (e == null) return false;
return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) ||
e["isOperational"] === true);
}
function canAttachTrace(obj) {
return isError(obj) && es5.propertyIsWritable(obj, "stack");
}
var ensureErrorObject = (function() {
if (!("stack" in new Error())) {
return function(value) {
if (canAttachTrace(value)) return value;
try {throw new Error(safeToString(value));}
catch(err) {return err;}
};
} else {
return function(value) {
if (canAttachTrace(value)) return value;
return new Error(safeToString(value));
};
}
})();
function classString(obj) {
return {}.toString.call(obj);
}
function copyDescriptors(from, to, filter) {
var keys = es5.names(from);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (filter(key)) {
try {
es5.defineProperty(to, key, es5.getDescriptor(from, key));
} catch (ignore) {}
}
}
}
var asArray = function(v) {
if (es5.isArray(v)) {
return v;
}
return null;
};
if (typeof Symbol !== "undefined" && Symbol.iterator) {
var ArrayFrom = typeof Array.from === "function" ? function(v) {
return Array.from(v);
} : function(v) {
var ret = [];
var it = v[Symbol.iterator]();
var itResult;
while (!((itResult = it.next()).done)) {
ret.push(itResult.value);
}
return ret;
};
asArray = function(v) {
if (es5.isArray(v)) {
return v;
} else if (v != null && typeof v[Symbol.iterator] === "function") {
return ArrayFrom(v);
}
return null;
};
}
var isNode = typeof process !== "undefined" &&
classString(process).toLowerCase() === "[object process]";
var hasEnvVariables = typeof process !== "undefined" &&
typeof process.env !== "undefined";
function env(key) {
return hasEnvVariables ? process.env[key] : undefined;
}
function getNativePromise() {
if (typeof Promise === "function") {
try {
var promise = new Promise(function(){});
if ({}.toString.call(promise) === "[object Promise]") {
return Promise;
}
} catch (e) {}
}
}
function domainBind(self, cb) {
return self.bind(cb);
}
var ret = {
isClass: isClass,
isIdentifier: isIdentifier,
inheritedDataKeys: inheritedDataKeys,
getDataPropertyOrDefault: getDataPropertyOrDefault,
thrower: thrower,
isArray: es5.isArray,
asArray: asArray,
notEnumerableProp: notEnumerableProp,
isPrimitive: isPrimitive,
isObject: isObject,
isError: isError,
canEvaluate: canEvaluate,
errorObj: errorObj,
tryCatch: tryCatch,
inherits: inherits,
withAppended: withAppended,
maybeWrapAsError: maybeWrapAsError,
toFastProperties: toFastProperties,
filledRange: filledRange,
toString: safeToString,
canAttachTrace: canAttachTrace,
ensureErrorObject: ensureErrorObject,
originatesFromRejection: originatesFromRejection,
markAsOriginatingFromRejection: markAsOriginatingFromRejection,
classString: classString,
copyDescriptors: copyDescriptors,
hasDevTools: typeof chrome !== "undefined" && chrome &&
typeof chrome.loadTimes === "function",
isNode: isNode,
hasEnvVariables: hasEnvVariables,
env: env,
global: globalObject,
getNativePromise: getNativePromise,
domainBind: domainBind
};
ret.isRecentNode = ret.isNode && (function() {
var version = process.versions.node.split(".").map(Number);
return (version[0] === 0 && version[1] > 10) || (version[0] > 0);
})();
if (ret.isNode) ret.toFastProperties(process);
try {throw new Error(); } catch (e) {ret.lastLineError = e;}
module.exports = ret;
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./es5":50,"_process":83}],74:[function(require,module,exports){
},{}],75:[function(require,module,exports){
(function (global){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
* @license MIT
*/
/* eslint-disable no-proto */
'use strict'
var base64 = require('base64-js')
var ieee754 = require('ieee754')
var isArray = require('isarray')
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Use Object implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* Due to various browser bugs, sometimes the Object implementation will be used even
* when the browser supports typed arrays.
*
* Note:
*
* - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
* See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
*
* - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
*
* - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
* incorrect length in some situations.
* We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
* get the Object implementation, which is slower but behaves correctly.
*/
Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
? global.TYPED_ARRAY_SUPPORT
: typedArraySupport()
/*
* Export kMaxLength after typed array support is determined.
*/
exports.kMaxLength = kMaxLength()
function typedArraySupport () {
try {
var arr = new Uint8Array(1)
arr.foo = function () { return 42 }
return arr.foo() === 42 && // typed array instances can be augmented
typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
} catch (e) {
return false
}
}
function kMaxLength () {
return Buffer.TYPED_ARRAY_SUPPORT
? 0x7fffffff
: 0x3fffffff
}
function createBuffer (that, length) {
if (kMaxLength() < length) {
throw new RangeError('Invalid typed array length')
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Return an augmented `Uint8Array` instance, for best performance
that = new Uint8Array(length)
that.__proto__ = Buffer.prototype
} else {
// Fallback: Return an object instance of the Buffer class
if (that === null) {
that = new Buffer(length)
}
that.length = length
}
return that
}
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
* returns a single octet.
*
* The `Uint8Array` prototype remains unmodified.
*/
function Buffer (arg, encodingOrOffset, length) {
if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
return new Buffer(arg, encodingOrOffset, length)
}
// Common case.
if (typeof arg === 'number') {
if (typeof encodingOrOffset === 'string') {
throw new Error(
'If encoding is specified then the first argument must be a string'
)
}
return allocUnsafe(this, arg)
}
return from(this, arg, encodingOrOffset, length)
}
Buffer.poolSize = 8192 // not used by this implementation
// TODO: Legacy, not needed anymore. Remove in next major version.
Buffer._augment = function (arr) {
arr.__proto__ = Buffer.prototype
return arr
}
function from (that, value, encodingOrOffset, length) {
if (typeof value === 'number') {
throw new TypeError('"value" argument must not be a number')
}
if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
return fromArrayBuffer(that, value, encodingOrOffset, length)
}
if (typeof value === 'string') {
return fromString(that, value, encodingOrOffset)
}
return fromObject(that, value)
}
/**
* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
* if value is a number.
* Buffer.from(str[, encoding])
* Buffer.from(array)
* Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]])
**/
Buffer.from = function (value, encodingOrOffset, length) {
return from(null, value, encodingOrOffset, length)
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
Buffer.prototype.__proto__ = Uint8Array.prototype
Buffer.__proto__ = Uint8Array
if (typeof Symbol !== 'undefined' && Symbol.species &&
Buffer[Symbol.species] === Buffer) {
// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
Object.defineProperty(Buffer, Symbol.species, {
value: null,
configurable: true
})
}
}
function assertSize (size) {
if (typeof size !== 'number') {
throw new TypeError('"size" argument must be a number')
}
}
function alloc (that, size, fill, encoding) {
assertSize(size)
if (size <= 0) {
return createBuffer(that, size)
}
if (fill !== undefined) {
// Only pay attention to encoding if it's a string. This
// prevents accidentally sending in a number that would
// be interpretted as a start offset.
return typeof encoding === 'string'
? createBuffer(that, size).fill(fill, encoding)
: createBuffer(that, size).fill(fill)
}
return createBuffer(that, size)
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer.alloc = function (size, fill, encoding) {
return alloc(null, size, fill, encoding)
}
function allocUnsafe (that, size) {
assertSize(size)
that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
if (!Buffer.TYPED_ARRAY_SUPPORT) {
for (var i = 0; i < size; i++) {
that[i] = 0
}
}
return that
}
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
* */
Buffer.allocUnsafe = function (size) {
return allocUnsafe(null, size)
}
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
*/
Buffer.allocUnsafeSlow = function (size) {
return allocUnsafe(null, size)
}
function fromString (that, string, encoding) {
if (typeof encoding !== 'string' || encoding === '') {
encoding = 'utf8'
}
if (!Buffer.isEncoding(encoding)) {
throw new TypeError('"encoding" must be a valid string encoding')
}
var length = byteLength(string, encoding) | 0
that = createBuffer(that, length)
that.write(string, encoding)
return that
}
function fromArrayLike (that, array) {
var length = checked(array.length) | 0
that = createBuffer(that, length)
for (var i = 0; i < length; i += 1) {
that[i] = array[i] & 255
}
return that
}
function fromArrayBuffer (that, array, byteOffset, length) {
array.byteLength // this throws if `array` is not a valid ArrayBuffer
if (byteOffset < 0 || array.byteLength < byteOffset) {
throw new RangeError('\'offset\' is out of bounds')
}
if (array.byteLength < byteOffset + (length || 0)) {
throw new RangeError('\'length\' is out of bounds')
}
if (length === undefined) {
array = new Uint8Array(array, byteOffset)
} else {
array = new Uint8Array(array, byteOffset, length)
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Return an augmented `Uint8Array` instance, for best performance
that = array
that.__proto__ = Buffer.prototype
} else {
// Fallback: Return an object instance of the Buffer class
that = fromArrayLike(that, array)
}
return that
}
function fromObject (that, obj) {
if (Buffer.isBuffer(obj)) {
var len = checked(obj.length) | 0
that = createBuffer(that, len)
if (that.length === 0) {
return that
}
obj.copy(that, 0, 0, len)
return that
}
if (obj) {
if ((typeof ArrayBuffer !== 'undefined' &&
obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
if (typeof obj.length !== 'number' || isnan(obj.length)) {
return createBuffer(that, 0)
}
return fromArrayLike(that, obj)
}
if (obj.type === 'Buffer' && isArray(obj.data)) {
return fromArrayLike(that, obj.data)
}
}
throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
}
function checked (length) {
// Note: cannot use `length < kMaxLength` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= kMaxLength()) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
'size: 0x' + kMaxLength().toString(16) + ' bytes')
}
return length | 0
}
function SlowBuffer (length) {
if (+length != length) { // eslint-disable-line eqeqeq
length = 0
}
return Buffer.alloc(+length)
}
Buffer.isBuffer = function isBuffer (b) {
return !!(b != null && b._isBuffer)
}
Buffer.compare = function compare (a, b) {
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError('Arguments must be Buffers')
}
if (a === b) return 0
var x = a.length
var y = b.length
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i]
y = b[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
Buffer.isEncoding = function isEncoding (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'binary':
case 'base64':
case 'raw':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.concat = function concat (list, length) {
if (!isArray(list)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
if (list.length === 0) {
return Buffer.alloc(0)
}
var i
if (length === undefined) {
length = 0
for (i = 0; i < list.length; i++) {
length += list[i].length
}
}
var buffer = Buffer.allocUnsafe(length)
var pos = 0
for (i = 0; i < list.length; i++) {
var buf = list[i]
if (!Buffer.isBuffer(buf)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
buf.copy(buffer, pos)
pos += buf.length
}
return buffer
}
function byteLength (string, encoding) {
if (Buffer.isBuffer(string)) {
return string.length
}
if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
(ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
return string.byteLength
}
if (typeof string !== 'string') {
string = '' + string
}
var len = string.length
if (len === 0) return 0
// Use a for loop to avoid recursion
var loweredCase = false
for (;;) {
switch (encoding) {
case 'ascii':
case 'binary':
// Deprecated
case 'raw':
case 'raws':
return len
case 'utf8':
case 'utf-8':
case undefined:
return utf8ToBytes(string).length
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return len * 2
case 'hex':
return len >>> 1
case 'base64':
return base64ToBytes(string).length
default:
if (loweredCase) return utf8ToBytes(string).length // assume utf8
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.byteLength = byteLength
function slowToString (encoding, start, end) {
var loweredCase = false
// No need to verify that "this.length <= MAX_UINT32" since it's a read-only
// property of a typed array.
// This behaves neither like String nor Uint8Array in that we set start/end
// to their upper/lower bounds if the value passed is out of range.
// undefined is handled specially as per ECMA-262 6th Edition,
// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
if (start === undefined || start < 0) {
start = 0
}
// Return early if start > this.length. Done here to prevent potential uint32
// coercion fail below.
if (start > this.length) {
return ''
}
if (end === undefined || end > this.length) {
end = this.length
}
if (end <= 0) {
return ''
}
// Force coersion to uint32. This will also coerce falsey/NaN values to 0.
end >>>= 0
start >>>= 0
if (end <= start) {
return ''
}
if (!encoding) encoding = 'utf8'
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end)
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end)
case 'ascii':
return asciiSlice(this, start, end)
case 'binary':
return binarySlice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = (encoding + '').toLowerCase()
loweredCase = true
}
}
}
// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
// Buffer instances.
Buffer.prototype._isBuffer = true
function swap (b, n, m) {
var i = b[n]
b[n] = b[m]
b[m] = i
}
Buffer.prototype.swap16 = function swap16 () {
var len = this.length
if (len % 2 !== 0) {
throw new RangeError('Buffer size must be a multiple of 16-bits')
}
for (var i = 0; i < len; i += 2) {
swap(this, i, i + 1)
}
return this
}
Buffer.prototype.swap32 = function swap32 () {
var len = this.length
if (len % 4 !== 0) {
throw new RangeError('Buffer size must be a multiple of 32-bits')
}
for (var i = 0; i < len; i += 4) {
swap(this, i, i + 3)
swap(this, i + 1, i + 2)
}
return this
}
Buffer.prototype.toString = function toString () {
var length = this.length | 0
if (length === 0) return ''
if (arguments.length === 0) return utf8Slice(this, 0, length)
return slowToString.apply(this, arguments)
}
Buffer.prototype.equals = function equals (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return true
return Buffer.compare(this, b) === 0
}
Buffer.prototype.inspect = function inspect () {
var str = ''
var max = exports.INSPECT_MAX_BYTES
if (this.length > 0) {
str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
if (this.length > max) str += ' ... '
}
return '<Buffer ' + str + '>'
}
Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
if (!Buffer.isBuffer(target)) {
throw new TypeError('Argument must be a Buffer')
}
if (start === undefined) {
start = 0
}
if (end === undefined) {
end = target ? target.length : 0
}
if (thisStart === undefined) {
thisStart = 0
}
if (thisEnd === undefined) {
thisEnd = this.length
}
if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
throw new RangeError('out of range index')
}
if (thisStart >= thisEnd && start >= end) {
return 0
}
if (thisStart >= thisEnd) {
return -1
}
if (start >= end) {
return 1
}
start >>>= 0
end >>>= 0
thisStart >>>= 0
thisEnd >>>= 0
if (this === target) return 0
var x = thisEnd - thisStart
var y = end - start
var len = Math.min(x, y)
var thisCopy = this.slice(thisStart, thisEnd)
var targetCopy = target.slice(start, end)
for (var i = 0; i < len; ++i) {
if (thisCopy[i] !== targetCopy[i]) {
x = thisCopy[i]
y = targetCopy[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
function arrayIndexOf (arr, val, byteOffset, encoding) {
var indexSize = 1
var arrLength = arr.length
var valLength = val.length
if (encoding !== undefined) {
encoding = String(encoding).toLowerCase()
if (encoding === 'ucs2' || encoding === 'ucs-2' ||
encoding === 'utf16le' || encoding === 'utf-16le') {
if (arr.length < 2 || val.length < 2) {
return -1
}
indexSize = 2
arrLength /= 2
valLength /= 2
byteOffset /= 2
}
}
function read (buf, i) {
if (indexSize === 1) {
return buf[i]
} else {
return buf.readUInt16BE(i * indexSize)
}
}
var foundIndex = -1
for (var i = 0; byteOffset + i < arrLength; i++) {
if (read(arr, byteOffset + i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
if (foundIndex === -1) foundIndex = i
if (i - foundIndex + 1 === valLength) return (byteOffset + foundIndex) * indexSize
} else {
if (foundIndex !== -1) i -= i - foundIndex
foundIndex = -1
}
}
return -1
}
Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
if (typeof byteOffset === 'string') {
encoding = byteOffset
byteOffset = 0
} else if (byteOffset > 0x7fffffff) {
byteOffset = 0x7fffffff
} else if (byteOffset < -0x80000000) {
byteOffset = -0x80000000
}
byteOffset >>= 0
if (this.length === 0) return -1
if (byteOffset >= this.length) return -1
// Negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0)
if (typeof val === 'string') {
val = Buffer.from(val, encoding)
}
if (Buffer.isBuffer(val)) {
// special case: looking for empty string/buffer always fails
if (val.length === 0) {
return -1
}
return arrayIndexOf(this, val, byteOffset, encoding)
}
if (typeof val === 'number') {
if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') {
return Uint8Array.prototype.indexOf.call(this, val, byteOffset)
}
return arrayIndexOf(this, [ val ], byteOffset, encoding)
}
throw new TypeError('val must be string, number or Buffer')
}
Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
return this.indexOf(val, byteOffset, encoding) !== -1
}
function hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0
var remaining = buf.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
// must be an even number of digits
var strLen = string.length
if (strLen % 2 !== 0) throw new Error('Invalid hex string')
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; i++) {
var parsed = parseInt(string.substr(i * 2, 2), 16)
if (isNaN(parsed)) return i
buf[offset + i] = parsed
}
return i
}
function utf8Write (buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}
function asciiWrite (buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length)
}
function binaryWrite (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
function base64Write (buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length)
}
function ucs2Write (buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}
Buffer.prototype.write = function write (string, offset, length, encoding) {
// Buffer#write(string)
if (offset === undefined) {
encoding = 'utf8'
length = this.length
offset = 0
// Buffer#write(string, encoding)
} else if (length === undefined && typeof offset === 'string') {
encoding = offset
length = this.length
offset = 0
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
offset = offset | 0
if (isFinite(length)) {
length = length | 0
if (encoding === undefined) encoding = 'utf8'
} else {
encoding = length
length = undefined
}
// legacy write(string, encoding, offset, length) - remove in v0.13
} else {
throw new Error(
'Buffer.write(string, encoding, offset[, length]) is no longer supported'
)
}
var remaining = this.length - offset
if (length === undefined || length > remaining) length = remaining
if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
throw new RangeError('Attempt to write outside buffer bounds')
}
if (!encoding) encoding = 'utf8'
var loweredCase = false
for (;;) {
switch (encoding) {
case 'hex':
return hexWrite(this, string, offset, length)
case 'utf8':
case 'utf-8':
return utf8Write(this, string, offset, length)
case 'ascii':
return asciiWrite(this, string, offset, length)
case 'binary':
return binaryWrite(this, string, offset, length)
case 'base64':
// Warning: maxLength not taken into account in base64Write
return base64Write(this, string, offset, length)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return ucs2Write(this, string, offset, length)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.prototype.toJSON = function toJSON () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
}
function base64Slice (buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf)
} else {
return base64.fromByteArray(buf.slice(start, end))
}
}
function utf8Slice (buf, start, end) {
end = Math.min(buf.length, end)
var res = []
var i = start
while (i < end) {
var firstByte = buf[i]
var codePoint = null
var bytesPerSequence = (firstByte > 0xEF) ? 4
: (firstByte > 0xDF) ? 3
: (firstByte > 0xBF) ? 2
: 1
if (i + bytesPerSequence <= end) {
var secondByte, thirdByte, fourthByte, tempCodePoint
switch (bytesPerSequence) {
case 1:
if (firstByte < 0x80) {
codePoint = firstByte
}
break
case 2:
secondByte = buf[i + 1]
if ((secondByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
if (tempCodePoint > 0x7F) {
codePoint = tempCodePoint
}
}
break
case 3:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
codePoint = tempCodePoint
}
}
break
case 4:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
fourthByte = buf[i + 3]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
codePoint = tempCodePoint
}
}
}
}
if (codePoint === null) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xFFFD
bytesPerSequence = 1
} else if (codePoint > 0xFFFF) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000
res.push(codePoint >>> 10 & 0x3FF | 0xD800)
codePoint = 0xDC00 | codePoint & 0x3FF
}
res.push(codePoint)
i += bytesPerSequence
}
return decodeCodePointsArray(res)
}
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000
function decodeCodePointsArray (codePoints) {
var len = codePoints.length
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
}
// Decode in chunks to avoid "call stack size exceeded".
var res = ''
var i = 0
while (i < len) {
res += String.fromCharCode.apply(
String,
codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
)
}
return res
}
function asciiSlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; i++) {
ret += String.fromCharCode(buf[i] & 0x7F)
}
return ret
}
function binarySlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; i++) {
ret += String.fromCharCode(buf[i])
}
return ret
}
function hexSlice (buf, start, end) {
var len = buf.length
if (!start || start < 0) start = 0
if (!end || end < 0 || end > len) end = len
var out = ''
for (var i = start; i < end; i++) {
out += toHex(buf[i])
}
return out
}
function utf16leSlice (buf, start, end) {
var bytes = buf.slice(start, end)
var res = ''
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
}
return res
}
Buffer.prototype.slice = function slice (start, end) {
var len = this.length
start = ~~start
end = end === undefined ? len : ~~end
if (start < 0) {
start += len
if (start < 0) start = 0
} else if (start > len) {
start = len
}
if (end < 0) {
end += len
if (end < 0) end = 0
} else if (end > len) {
end = len
}
if (end < start) end = start
var newBuf
if (Buffer.TYPED_ARRAY_SUPPORT) {
newBuf = this.subarray(start, end)
newBuf.__proto__ = Buffer.prototype
} else {
var sliceLen = end - start
newBuf = new Buffer(sliceLen, undefined)
for (var i = 0; i < sliceLen; i++) {
newBuf[i] = this[i + start]
}
}
return newBuf
}
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset (offset, ext, length) {
if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
return val
}
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) {
checkOffset(offset, byteLength, this.length)
}
var val = this[offset + --byteLength]
var mul = 1
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul
}
return val
}
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length)
return this[offset]
}
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ((this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16)) +
(this[offset + 3] * 0x1000000)
}
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] * 0x1000000) +
((this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3])
}
Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var i = byteLength
var mul = 1
var val = this[offset + --i]
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length)
if (!(this[offset] & 0x80)) return (this[offset])
return ((0xff - this[offset] + 1) * -1)
}
Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset] | (this[offset + 1] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset + 1] | (this[offset] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16) |
(this[offset + 3] << 24)
}
Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
(this[offset + 3])
}
Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, false, 52, 8)
}
function checkInt (buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
if (offset + ext > buf.length) throw new RangeError('Index out of range')
}
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var mul = 1
var i = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var i = byteLength - 1
var mul = 1
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
this[offset] = (value & 0xff)
return offset + 1
}
function objectWriteUInt16 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
(littleEndian ? i : 1 - i) * 8
}
}
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
}
return offset + 2
}
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
} else {
objectWriteUInt16(this, value, offset, false)
}
return offset + 2
}
function objectWriteUInt32 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffffffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
}
}
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, true)
}
return offset + 4
}
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, false)
}
return offset + 4
}
Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = 0
var mul = 1
var sub = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = byteLength - 1
var mul = 1
var sub = 0
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
if (value < 0) value = 0xff + value + 1
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
}
return offset + 2
}
Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
} else {
objectWriteUInt16(this, value, offset, false)
}
return offset + 2
}
Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
} else {
objectWriteUInt32(this, value, offset, true)
}
return offset + 4
}
Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (value < 0) value = 0xffffffff + value + 1
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, false)
}
return offset + 4
}
function checkIEEE754 (buf, value, offset, ext, max, min) {
if (offset + ext > buf.length) throw new RangeError('Index out of range')
if (offset < 0) throw new RangeError('Index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
}
ieee754.write(buf, value, offset, littleEndian, 23, 4)
return offset + 4
}
Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert)
}
Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert)
}
function writeDouble (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
}
ieee754.write(buf, value, offset, littleEndian, 52, 8)
return offset + 8
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert)
}
Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert)
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (targetStart >= target.length) targetStart = target.length
if (!targetStart) targetStart = 0
if (end > 0 && end < start) end = start
// Copy 0 bytes; we're done
if (end === start) return 0
if (target.length === 0 || this.length === 0) return 0
// Fatal error conditions
if (targetStart < 0) {
throw new RangeError('targetStart out of bounds')
}
if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
if (end < 0) throw new RangeError('sourceEnd out of bounds')
// Are we oob?
if (end > this.length) end = this.length
if (target.length - targetStart < end - start) {
end = target.length - targetStart + start
}
var len = end - start
var i
if (this === target && start < targetStart && targetStart < end) {
// descending copy from end
for (i = len - 1; i >= 0; i--) {
target[i + targetStart] = this[i + start]
}
} else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
// ascending copy from start
for (i = 0; i < len; i++) {
target[i + targetStart] = this[i + start]
}
} else {
Uint8Array.prototype.set.call(
target,
this.subarray(start, start + len),
targetStart
)
}
return len
}
// Usage:
// buffer.fill(number[, offset[, end]])
// buffer.fill(buffer[, offset[, end]])
// buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill (val, start, end, encoding) {
// Handle string cases:
if (typeof val === 'string') {
if (typeof start === 'string') {
encoding = start
start = 0
end = this.length
} else if (typeof end === 'string') {
encoding = end
end = this.length
}
if (val.length === 1) {
var code = val.charCodeAt(0)
if (code < 256) {
val = code
}
}
if (encoding !== undefined && typeof encoding !== 'string') {
throw new TypeError('encoding must be a string')
}
if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
} else if (typeof val === 'number') {
val = val & 255
}
// Invalid ranges are not set to a default, so can range check early.
if (start < 0 || this.length < start || this.length < end) {
throw new RangeError('Out of range index')
}
if (end <= start) {
return this
}
start = start >>> 0
end = end === undefined ? this.length : end >>> 0
if (!val) val = 0
var i
if (typeof val === 'number') {
for (i = start; i < end; i++) {
this[i] = val
}
} else {
var bytes = Buffer.isBuffer(val)
? val
: utf8ToBytes(new Buffer(val, encoding).toString())
var len = bytes.length
for (i = 0; i < end - start; i++) {
this[i + start] = bytes[i % len]
}
}
return this
}
// HELPER FUNCTIONS
// ================
var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
function base64clean (str) {
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = stringtrim(str).replace(INVALID_BASE64_RE, '')
// Node converts strings with length < 2 to ''
if (str.length < 2) return ''
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '='
}
return str
}
function stringtrim (str) {
if (str.trim) return str.trim()
return str.replace(/^\s+|\s+$/g, '')
}
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
function utf8ToBytes (string, units) {
units = units || Infinity
var codePoint
var length = string.length
var leadSurrogate = null
var bytes = []
for (var i = 0; i < length; i++) {
codePoint = string.charCodeAt(i)
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (!leadSurrogate) {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
}
// valid lead
leadSurrogate = codePoint
continue
}
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = codePoint
continue
}
// valid surrogate pair
codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
}
leadSurrogate = null
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break
bytes.push(codePoint)
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break
bytes.push(
codePoint >> 0x6 | 0xC0,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break
bytes.push(
codePoint >> 0xC | 0xE0,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x110000) {
if ((units -= 4) < 0) break
bytes.push(
codePoint >> 0x12 | 0xF0,
codePoint >> 0xC & 0x3F | 0x80,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else {
throw new Error('Invalid code point')
}
}
return bytes
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; i++) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function utf16leToBytes (str, units) {
var c, hi, lo
var byteArray = []
for (var i = 0; i < str.length; i++) {
if ((units -= 2) < 0) break
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
}
return byteArray
}
function base64ToBytes (str) {
return base64.toByteArray(base64clean(str))
}
function blitBuffer (src, dst, offset, length) {
for (var i = 0; i < length; i++) {
if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i]
}
return i
}
function isnan (val) {
return val !== val // eslint-disable-line no-self-compare
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"base64-js":76,"ieee754":77,"isarray":78}],76:[function(require,module,exports){
'use strict'
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray
var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
function init () {
var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
lookup[i] = code[i]
revLookup[code.charCodeAt(i)] = i
}
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63
}
init()
function toByteArray (b64) {
var i, j, l, tmp, placeHolders, arr
var len = b64.length
if (len % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// the number of equal signs (place holders)
// if there are two placeholders, than the two characters before it
// represent one byte
// if there is only one, then the three characters before it represent 2 bytes
// this is just a cheap hack to not do indexOf twice
placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
// base64 is 4/3 + up to two characters of the original data
arr = new Arr(len * 3 / 4 - placeHolders)
// if there are placeholders, only get up to the last complete 4 chars
l = placeHolders > 0 ? len - 4 : len
var L = 0
for (i = 0, j = 0; i < l; i += 4, j += 3) {
tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
arr[L++] = (tmp >> 16) & 0xFF
arr[L++] = (tmp >> 8) & 0xFF
arr[L++] = tmp & 0xFF
}
if (placeHolders === 2) {
tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
arr[L++] = tmp & 0xFF
} else if (placeHolders === 1) {
tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
arr[L++] = (tmp >> 8) & 0xFF
arr[L++] = tmp & 0xFF
}
return arr
}
function tripletToBase64 (num) {
return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
}
function encodeChunk (uint8, start, end) {
var tmp
var output = []
for (var i = start; i < end; i += 3) {
tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
output.push(tripletToBase64(tmp))
}
return output.join('')
}
function fromByteArray (uint8) {
var tmp
var len = uint8.length
var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
var output = ''
var parts = []
var maxChunkLength = 16383 // must be multiple of 3
// go through the array every three bytes, we'll deal with trailing stuff later
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
}
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
tmp = uint8[len - 1]
output += lookup[tmp >> 2]
output += lookup[(tmp << 4) & 0x3F]
output += '=='
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
output += lookup[tmp >> 10]
output += lookup[(tmp >> 4) & 0x3F]
output += lookup[(tmp << 2) & 0x3F]
output += '='
}
parts.push(output)
return parts.join('')
}
},{}],77:[function(require,module,exports){
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
var e, m
var eLen = nBytes * 8 - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var nBits = -7
var i = isLE ? (nBytes - 1) : 0
var d = isLE ? -1 : 1
var s = buffer[offset + i]
i += d
e = s & ((1 << (-nBits)) - 1)
s >>= (-nBits)
nBits += eLen
for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
m = e & ((1 << (-nBits)) - 1)
e >>= (-nBits)
nBits += mLen
for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
if (e === 0) {
e = 1 - eBias
} else if (e === eMax) {
return m ? NaN : ((s ? -1 : 1) * Infinity)
} else {
m = m + Math.pow(2, mLen)
e = e - eBias
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}
exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c
var eLen = nBytes * 8 - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
var i = isLE ? 0 : (nBytes - 1)
var d = isLE ? 1 : -1
var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
value = Math.abs(value)
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0
e = eMax
} else {
e = Math.floor(Math.log(value) / Math.LN2)
if (value * (c = Math.pow(2, -e)) < 1) {
e--
c *= 2
}
if (e + eBias >= 1) {
value += rt / c
} else {
value += rt * Math.pow(2, 1 - eBias)
}
if (value * c >= 2) {
e++
c /= 2
}
if (e + eBias >= eMax) {
m = 0
e = eMax
} else if (e + eBias >= 1) {
m = (value * c - 1) * Math.pow(2, mLen)
e = e + eBias
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
e = 0
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
e = (e << mLen) | m
eLen += mLen
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
buffer[offset + i - d] |= s * 128
}
},{}],78:[function(require,module,exports){
var toString = {}.toString;
module.exports = Array.isArray || function (arr) {
return toString.call(arr) == '[object Array]';
};
},{}],79:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
}
throw TypeError('Uncaught, unspecified "error" event.');
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
args = Array.prototype.slice.call(arguments, 1);
handler.apply(this, args);
}
} else if (isObject(handler)) {
args = Array.prototype.slice.call(arguments, 1);
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else if (listeners) {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.prototype.listenerCount = function(type) {
if (this._events) {
var evlistener = this._events[type];
if (isFunction(evlistener))
return 1;
else if (evlistener)
return evlistener.length;
}
return 0;
};
EventEmitter.listenerCount = function(emitter, type) {
return emitter.listenerCount(type);
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
},{}],80:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
},{}],81:[function(require,module,exports){
/**
* Determine if an object is Buffer
*
* Author: Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
* License: MIT
*
* `npm install is-buffer`
*/
module.exports = function (obj) {
return !!(obj != null &&
(obj._isBuffer || // For Safari 5-7 (missing Object.prototype.constructor)
(obj.constructor &&
typeof obj.constructor.isBuffer === 'function' &&
obj.constructor.isBuffer(obj))
))
}
},{}],82:[function(require,module,exports){
(function (process){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// resolves . and .. elements in a path array with directory names there
// must be no slashes, empty elements, or device names (c:\) in the array
// (so also no leading and trailing slashes - it does not distinguish
// relative and absolute paths)
function normalizeArray(parts, allowAboveRoot) {
// if the path tries to go above the root, `up` ends up > 0
var up = 0;
for (var i = parts.length - 1; i >= 0; i--) {
var last = parts[i];
if (last === '.') {
parts.splice(i, 1);
} else if (last === '..') {
parts.splice(i, 1);
up++;
} else if (up) {
parts.splice(i, 1);
up--;
}
}
// if the path is allowed to go above the root, restore leading ..s
if (allowAboveRoot) {
for (; up--; up) {
parts.unshift('..');
}
}
return parts;
}
// Split a filename into [root, dir, basename, ext], unix version
// 'root' is just a slash, or nothing.
var splitPathRe =
/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
var splitPath = function(filename) {
return splitPathRe.exec(filename).slice(1);
};
// path.resolve([from ...], to)
// posix version
exports.resolve = function() {
var resolvedPath = '',
resolvedAbsolute = false;
for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
var path = (i >= 0) ? arguments[i] : process.cwd();
// Skip empty and invalid entries
if (typeof path !== 'string') {
throw new TypeError('Arguments to path.resolve must be strings');
} else if (!path) {
continue;
}
resolvedPath = path + '/' + resolvedPath;
resolvedAbsolute = path.charAt(0) === '/';
}
// At this point the path should be resolved to a full absolute path, but
// handle relative paths to be safe (might happen when process.cwd() fails)
// Normalize the path
resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
return !!p;
}), !resolvedAbsolute).join('/');
return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
};
// path.normalize(path)
// posix version
exports.normalize = function(path) {
var isAbsolute = exports.isAbsolute(path),
trailingSlash = substr(path, -1) === '/';
// Normalize the path
path = normalizeArray(filter(path.split('/'), function(p) {
return !!p;
}), !isAbsolute).join('/');
if (!path && !isAbsolute) {
path = '.';
}
if (path && trailingSlash) {
path += '/';
}
return (isAbsolute ? '/' : '') + path;
};
// posix version
exports.isAbsolute = function(path) {
return path.charAt(0) === '/';
};
// posix version
exports.join = function() {
var paths = Array.prototype.slice.call(arguments, 0);
return exports.normalize(filter(paths, function(p, index) {
if (typeof p !== 'string') {
throw new TypeError('Arguments to path.join must be strings');
}
return p;
}).join('/'));
};
// path.relative(from, to)
// posix version
exports.relative = function(from, to) {
from = exports.resolve(from).substr(1);
to = exports.resolve(to).substr(1);
function trim(arr) {
var start = 0;
for (; start < arr.length; start++) {
if (arr[start] !== '') break;
}
var end = arr.length - 1;
for (; end >= 0; end--) {
if (arr[end] !== '') break;
}
if (start > end) return [];
return arr.slice(start, end - start + 1);
}
var fromParts = trim(from.split('/'));
var toParts = trim(to.split('/'));
var length = Math.min(fromParts.length, toParts.length);
var samePartsLength = length;
for (var i = 0; i < length; i++) {
if (fromParts[i] !== toParts[i]) {
samePartsLength = i;
break;
}
}
var outputParts = [];
for (var i = samePartsLength; i < fromParts.length; i++) {
outputParts.push('..');
}
outputParts = outputParts.concat(toParts.slice(samePartsLength));
return outputParts.join('/');
};
exports.sep = '/';
exports.delimiter = ':';
exports.dirname = function(path) {
var result = splitPath(path),
root = result[0],
dir = result[1];
if (!root && !dir) {
// No dirname whatsoever
return '.';
}
if (dir) {
// It has a dirname, strip trailing slash
dir = dir.substr(0, dir.length - 1);
}
return root + dir;
};
exports.basename = function(path, ext) {
var f = splitPath(path)[2];
// TODO: make this comparison case-insensitive on windows?
if (ext && f.substr(-1 * ext.length) === ext) {
f = f.substr(0, f.length - ext.length);
}
return f;
};
exports.extname = function(path) {
return splitPath(path)[3];
};
function filter (xs, f) {
if (xs.filter) return xs.filter(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
if (f(xs[i], i, xs)) res.push(xs[i]);
}
return res;
}
// String.prototype.substr - negative index don't work in IE8
var substr = 'ab'.substr(-1) === 'b'
? function (str, start, len) { return str.substr(start, len) }
: function (str, start, len) {
if (start < 0) start = str.length + start;
return str.substr(start, len);
}
;
}).call(this,require('_process'))
},{"_process":83}],83:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
(function () {
try {
cachedSetTimeout = setTimeout;
} catch (e) {
cachedSetTimeout = function () {
throw new Error('setTimeout is not defined');
}
}
try {
cachedClearTimeout = clearTimeout;
} catch (e) {
cachedClearTimeout = function () {
throw new Error('clearTimeout is not defined');
}
}
} ())
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = cachedSetTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
cachedClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
cachedSetTimeout(drainQueue, 0);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],84:[function(require,module,exports){
module.exports = require("./lib/_stream_duplex.js")
},{"./lib/_stream_duplex.js":85}],85:[function(require,module,exports){
// a duplex stream is just a stream that is both readable and writable.
// Since JS doesn't have multiple prototypal inheritance, this class
// prototypally inherits from Readable, and then parasitically from
// Writable.
'use strict';
/*<replacement>*/
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) {
keys.push(key);
}return keys;
};
/*</replacement>*/
module.exports = Duplex;
/*<replacement>*/
var processNextTick = require('process-nextick-args');
/*</replacement>*/
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
var Readable = require('./_stream_readable');
var Writable = require('./_stream_writable');
util.inherits(Duplex, Readable);
var keys = objectKeys(Writable.prototype);
for (var v = 0; v < keys.length; v++) {
var method = keys[v];
if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
}
function Duplex(options) {
if (!(this instanceof Duplex)) return new Duplex(options);
Readable.call(this, options);
Writable.call(this, options);
if (options && options.readable === false) this.readable = false;
if (options && options.writable === false) this.writable = false;
this.allowHalfOpen = true;
if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
this.once('end', onend);
}
// the no-half-open enforcer
function onend() {
// if we allow half-open state, or if the writable side ended,
// then we're ok.
if (this.allowHalfOpen || this._writableState.ended) return;
// no more data can be written.
// But allow more writes to happen in this tick.
processNextTick(onEndNT, this);
}
function onEndNT(self) {
self.end();
}
function forEach(xs, f) {
for (var i = 0, l = xs.length; i < l; i++) {
f(xs[i], i);
}
}
},{"./_stream_readable":87,"./_stream_writable":89,"core-util-is":91,"inherits":80,"process-nextick-args":93}],86:[function(require,module,exports){
// a passthrough stream.
// basically just the most minimal sort of Transform stream.
// Every written chunk gets output as-is.
'use strict';
module.exports = PassThrough;
var Transform = require('./_stream_transform');
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
util.inherits(PassThrough, Transform);
function PassThrough(options) {
if (!(this instanceof PassThrough)) return new PassThrough(options);
Transform.call(this, options);
}
PassThrough.prototype._transform = function (chunk, encoding, cb) {
cb(null, chunk);
};
},{"./_stream_transform":88,"core-util-is":91,"inherits":80}],87:[function(require,module,exports){
(function (process){
'use strict';
module.exports = Readable;
/*<replacement>*/
var processNextTick = require('process-nextick-args');
/*</replacement>*/
/*<replacement>*/
var isArray = require('isarray');
/*</replacement>*/
Readable.ReadableState = ReadableState;
/*<replacement>*/
var EE = require('events').EventEmitter;
var EElistenerCount = function (emitter, type) {
return emitter.listeners(type).length;
};
/*</replacement>*/
/*<replacement>*/
var Stream;
(function () {
try {
Stream = require('st' + 'ream');
} catch (_) {} finally {
if (!Stream) Stream = require('events').EventEmitter;
}
})();
/*</replacement>*/
var Buffer = require('buffer').Buffer;
/*<replacement>*/
var bufferShim = require('buffer-shims');
/*</replacement>*/
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
/*<replacement>*/
var debugUtil = require('util');
var debug = void 0;
if (debugUtil && debugUtil.debuglog) {
debug = debugUtil.debuglog('stream');
} else {
debug = function () {};
}
/*</replacement>*/
var StringDecoder;
util.inherits(Readable, Stream);
var hasPrependListener = typeof EE.prototype.prependListener === 'function';
function prependListener(emitter, event, fn) {
if (hasPrependListener) return emitter.prependListener(event, fn);
// This is a brutally ugly hack to make sure that our error handler
// is attached before any userland ones. NEVER DO THIS. This is here
// only because this code needs to continue to work with older versions
// of Node.js that do not include the prependListener() method. The goal
// is to eventually remove this hack.
if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
}
var Duplex;
function ReadableState(options, stream) {
Duplex = Duplex || require('./_stream_duplex');
options = options || {};
// object stream flag. Used to make read(n) ignore n and to
// make all the buffer merging and length checks go away
this.objectMode = !!options.objectMode;
if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
// the point at which it stops calling _read() to fill the buffer
// Note: 0 is a valid value, means "don't call _read preemptively ever"
var hwm = options.highWaterMark;
var defaultHwm = this.objectMode ? 16 : 16 * 1024;
this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
// cast to ints.
this.highWaterMark = ~ ~this.highWaterMark;
this.buffer = [];
this.length = 0;
this.pipes = null;
this.pipesCount = 0;
this.flowing = null;
this.ended = false;
this.endEmitted = false;
this.reading = false;
// a flag to be able to tell if the onwrite cb is called immediately,
// or on a later tick. We set this to true at first, because any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
// whenever we return null, then we set a flag to say
// that we're awaiting a 'readable' event emission.
this.needReadable = false;
this.emittedReadable = false;
this.readableListening = false;
this.resumeScheduled = false;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// when piping, we only care about 'readable' events that happen
// after read()ing all the bytes and not getting any pushback.
this.ranOut = false;
// the number of writers that are awaiting a drain event in .pipe()s
this.awaitDrain = 0;
// if true, a maybeReadMore has been scheduled
this.readingMore = false;
this.decoder = null;
this.encoding = null;
if (options.encoding) {
if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
this.decoder = new StringDecoder(options.encoding);
this.encoding = options.encoding;
}
}
var Duplex;
function Readable(options) {
Duplex = Duplex || require('./_stream_duplex');
if (!(this instanceof Readable)) return new Readable(options);
this._readableState = new ReadableState(options, this);
// legacy
this.readable = true;
if (options && typeof options.read === 'function') this._read = options.read;
Stream.call(this);
}
// Manually shove something into the read() buffer.
// This returns true if the highWaterMark has not been hit yet,
// similar to how Writable.write() returns true if you should
// write() some more.
Readable.prototype.push = function (chunk, encoding) {
var state = this._readableState;
if (!state.objectMode && typeof chunk === 'string') {
encoding = encoding || state.defaultEncoding;
if (encoding !== state.encoding) {
chunk = bufferShim.from(chunk, encoding);
encoding = '';
}
}
return readableAddChunk(this, state, chunk, encoding, false);
};
// Unshift should *always* be something directly out of read()
Readable.prototype.unshift = function (chunk) {
var state = this._readableState;
return readableAddChunk(this, state, chunk, '', true);
};
Readable.prototype.isPaused = function () {
return this._readableState.flowing === false;
};
function readableAddChunk(stream, state, chunk, encoding, addToFront) {
var er = chunkInvalid(state, chunk);
if (er) {
stream.emit('error', er);
} else if (chunk === null) {
state.reading = false;
onEofChunk(stream, state);
} else if (state.objectMode || chunk && chunk.length > 0) {
if (state.ended && !addToFront) {
var e = new Error('stream.push() after EOF');
stream.emit('error', e);
} else if (state.endEmitted && addToFront) {
var _e = new Error('stream.unshift() after end event');
stream.emit('error', _e);
} else {
var skipAdd;
if (state.decoder && !addToFront && !encoding) {
chunk = state.decoder.write(chunk);
skipAdd = !state.objectMode && chunk.length === 0;
}
if (!addToFront) state.reading = false;
// Don't add to the buffer if we've decoded to an empty string chunk and
// we're not in object mode
if (!skipAdd) {
// if we want the data now, just emit it.
if (state.flowing && state.length === 0 && !state.sync) {
stream.emit('data', chunk);
stream.read(0);
} else {
// update the buffer info.
state.length += state.objectMode ? 1 : chunk.length;
if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
if (state.needReadable) emitReadable(stream);
}
}
maybeReadMore(stream, state);
}
} else if (!addToFront) {
state.reading = false;
}
return needMoreData(state);
}
// if it's past the high water mark, we can push in some more.
// Also, if we have no data yet, we can stand some
// more bytes. This is to work around cases where hwm=0,
// such as the repl. Also, if the push() triggered a
// readable event, and the user called read(largeNumber) such that
// needReadable was set, then we ought to push more, so that another
// 'readable' event will be triggered.
function needMoreData(state) {
return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
}
// backwards compatibility.
Readable.prototype.setEncoding = function (enc) {
if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
this._readableState.decoder = new StringDecoder(enc);
this._readableState.encoding = enc;
return this;
};
// Don't raise the hwm > 8MB
var MAX_HWM = 0x800000;
function computeNewHighWaterMark(n) {
if (n >= MAX_HWM) {
n = MAX_HWM;
} else {
// Get the next highest power of 2
n--;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
n++;
}
return n;
}
function howMuchToRead(n, state) {
if (state.length === 0 && state.ended) return 0;
if (state.objectMode) return n === 0 ? 0 : 1;
if (n === null || isNaN(n)) {
// only flow one buffer at a time
if (state.flowing && state.buffer.length) return state.buffer[0].length;else return state.length;
}
if (n <= 0) return 0;
// If we're asking for more than the target buffer level,
// then raise the water mark. Bump up to the next highest
// power of 2, to prevent increasing it excessively in tiny
// amounts.
if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
// don't have that much. return null, unless we've ended.
if (n > state.length) {
if (!state.ended) {
state.needReadable = true;
return 0;
} else {
return state.length;
}
}
return n;
}
// you can override either this method, or the async _read(n) below.
Readable.prototype.read = function (n) {
debug('read', n);
var state = this._readableState;
var nOrig = n;
if (typeof n !== 'number' || n > 0) state.emittedReadable = false;
// if we're doing read(0) to trigger a readable event, but we
// already have a bunch of data in the buffer, then just trigger
// the 'readable' event and move on.
if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
debug('read: emitReadable', state.length, state.ended);
if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
return null;
}
n = howMuchToRead(n, state);
// if we've ended, and we're now clear, then finish it up.
if (n === 0 && state.ended) {
if (state.length === 0) endReadable(this);
return null;
}
// All the actual chunk generation logic needs to be
// *below* the call to _read. The reason is that in certain
// synthetic stream cases, such as passthrough streams, _read
// may be a completely synchronous operation which may change
// the state of the read buffer, providing enough data when
// before there was *not* enough.
//
// So, the steps are:
// 1. Figure out what the state of things will be after we do
// a read from the buffer.
//
// 2. If that resulting state will trigger a _read, then call _read.
// Note that this may be asynchronous, or synchronous. Yes, it is
// deeply ugly to write APIs this way, but that still doesn't mean
// that the Readable class should behave improperly, as streams are
// designed to be sync/async agnostic.
// Take note if the _read call is sync or async (ie, if the read call
// has returned yet), so that we know whether or not it's safe to emit
// 'readable' etc.
//
// 3. Actually pull the requested chunks out of the buffer and return.
// if we need a readable event, then we need to do some reading.
var doRead = state.needReadable;
debug('need readable', doRead);
// if we currently have less than the highWaterMark, then also read some
if (state.length === 0 || state.length - n < state.highWaterMark) {
doRead = true;
debug('length less than watermark', doRead);
}
// however, if we've ended, then there's no point, and if we're already
// reading, then it's unnecessary.
if (state.ended || state.reading) {
doRead = false;
debug('reading or ended', doRead);
}
if (doRead) {
debug('do read');
state.reading = true;
state.sync = true;
// if the length is currently zero, then we *need* a readable event.
if (state.length === 0) state.needReadable = true;
// call internal read method
this._read(state.highWaterMark);
state.sync = false;
}
// If _read pushed data synchronously, then `reading` will be false,
// and we need to re-evaluate how much data we can return to the user.
if (doRead && !state.reading) n = howMuchToRead(nOrig, state);
var ret;
if (n > 0) ret = fromList(n, state);else ret = null;
if (ret === null) {
state.needReadable = true;
n = 0;
}
state.length -= n;
// If we have nothing in the buffer, then we want to know
// as soon as we *do* get something into the buffer.
if (state.length === 0 && !state.ended) state.needReadable = true;
// If we tried to read() past the EOF, then emit end on the next tick.
if (nOrig !== n && state.ended && state.length === 0) endReadable(this);
if (ret !== null) this.emit('data', ret);
return ret;
};
function chunkInvalid(state, chunk) {
var er = null;
if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) {
er = new TypeError('Invalid non-string/buffer chunk');
}
return er;
}
function onEofChunk(stream, state) {
if (state.ended) return;
if (state.decoder) {
var chunk = state.decoder.end();
if (chunk && chunk.length) {
state.buffer.push(chunk);
state.length += state.objectMode ? 1 : chunk.length;
}
}
state.ended = true;
// emit 'readable' now to make sure it gets picked up.
emitReadable(stream);
}
// Don't emit readable right away in sync mode, because this can trigger
// another read() call => stack overflow. This way, it might trigger
// a nextTick recursion warning, but that's not so bad.
function emitReadable(stream) {
var state = stream._readableState;
state.needReadable = false;
if (!state.emittedReadable) {
debug('emitReadable', state.flowing);
state.emittedReadable = true;
if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream);
}
}
function emitReadable_(stream) {
debug('emit readable');
stream.emit('readable');
flow(stream);
}
// at this point, the user has presumably seen the 'readable' event,
// and called read() to consume some data. that may have triggered
// in turn another _read(n) call, in which case reading = true if
// it's in progress.
// However, if we're not ended, or reading, and the length < hwm,
// then go ahead and try to read some more preemptively.
function maybeReadMore(stream, state) {
if (!state.readingMore) {
state.readingMore = true;
processNextTick(maybeReadMore_, stream, state);
}
}
function maybeReadMore_(stream, state) {
var len = state.length;
while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
debug('maybeReadMore read 0');
stream.read(0);
if (len === state.length)
// didn't get any data, stop spinning.
break;else len = state.length;
}
state.readingMore = false;
}
// abstract method. to be overridden in specific implementation classes.
// call cb(er, data) where data is <= n in length.
// for virtual (non-string, non-buffer) streams, "length" is somewhat
// arbitrary, and perhaps not very meaningful.
Readable.prototype._read = function (n) {
this.emit('error', new Error('not implemented'));
};
Readable.prototype.pipe = function (dest, pipeOpts) {
var src = this;
var state = this._readableState;
switch (state.pipesCount) {
case 0:
state.pipes = dest;
break;
case 1:
state.pipes = [state.pipes, dest];
break;
default:
state.pipes.push(dest);
break;
}
state.pipesCount += 1;
debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
var endFn = doEnd ? onend : cleanup;
if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn);
dest.on('unpipe', onunpipe);
function onunpipe(readable) {
debug('onunpipe');
if (readable === src) {
cleanup();
}
}
function onend() {
debug('onend');
dest.end();
}
// when the dest drains, it reduces the awaitDrain counter
// on the source. This would be more elegant with a .once()
// handler in flow(), but adding and removing repeatedly is
// too slow.
var ondrain = pipeOnDrain(src);
dest.on('drain', ondrain);
var cleanedUp = false;
function cleanup() {
debug('cleanup');
// cleanup event handlers once the pipe is broken
dest.removeListener('close', onclose);
dest.removeListener('finish', onfinish);
dest.removeListener('drain', ondrain);
dest.removeListener('error', onerror);
dest.removeListener('unpipe', onunpipe);
src.removeListener('end', onend);
src.removeListener('end', cleanup);
src.removeListener('data', ondata);
cleanedUp = true;
// if the reader is waiting for a drain event from this
// specific writer, then it would cause it to never start
// flowing again.
// So, if this is awaiting a drain, then we just call it now.
// If we don't know, then assume that we are waiting for one.
if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
}
src.on('data', ondata);
function ondata(chunk) {
debug('ondata');
var ret = dest.write(chunk);
if (false === ret) {
// If the user unpiped during `dest.write()`, it is possible
// to get stuck in a permanently paused state if that write
// also returned false.
// => Check whether `dest` is still a piping destination.
if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
debug('false write response, pause', src._readableState.awaitDrain);
src._readableState.awaitDrain++;
}
src.pause();
}
}
// if the dest has an error, then stop piping into it.
// however, don't suppress the throwing behavior for this.
function onerror(er) {
debug('onerror', er);
unpipe();
dest.removeListener('error', onerror);
if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
}
// Make sure our error handler is attached before userland ones.
prependListener(dest, 'error', onerror);
// Both close and finish should trigger unpipe, but only once.
function onclose() {
dest.removeListener('finish', onfinish);
unpipe();
}
dest.once('close', onclose);
function onfinish() {
debug('onfinish');
dest.removeListener('close', onclose);
unpipe();
}
dest.once('finish', onfinish);
function unpipe() {
debug('unpipe');
src.unpipe(dest);
}
// tell the dest that it's being piped to
dest.emit('pipe', src);
// start the flow if it hasn't been started already.
if (!state.flowing) {
debug('pipe resume');
src.resume();
}
return dest;
};
function pipeOnDrain(src) {
return function () {
var state = src._readableState;
debug('pipeOnDrain', state.awaitDrain);
if (state.awaitDrain) state.awaitDrain--;
if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
state.flowing = true;
flow(src);
}
};
}
Readable.prototype.unpipe = function (dest) {
var state = this._readableState;
// if we're not piping anywhere, then do nothing.
if (state.pipesCount === 0) return this;
// just one destination. most common case.
if (state.pipesCount === 1) {
// passed in one, but it's not the right one.
if (dest && dest !== state.pipes) return this;
if (!dest) dest = state.pipes;
// got a match.
state.pipes = null;
state.pipesCount = 0;
state.flowing = false;
if (dest) dest.emit('unpipe', this);
return this;
}
// slow case. multiple pipe destinations.
if (!dest) {
// remove all.
var dests = state.pipes;
var len = state.pipesCount;
state.pipes = null;
state.pipesCount = 0;
state.flowing = false;
for (var _i = 0; _i < len; _i++) {
dests[_i].emit('unpipe', this);
}return this;
}
// try to find the right one.
var i = indexOf(state.pipes, dest);
if (i === -1) return this;
state.pipes.splice(i, 1);
state.pipesCount -= 1;
if (state.pipesCount === 1) state.pipes = state.pipes[0];
dest.emit('unpipe', this);
return this;
};
// set up data events if they are asked for
// Ensure readable listeners eventually get something
Readable.prototype.on = function (ev, fn) {
var res = Stream.prototype.on.call(this, ev, fn);
// If listening to data, and it has not explicitly been paused,
// then call resume to start the flow of data on the next tick.
if (ev === 'data' && false !== this._readableState.flowing) {
this.resume();
}
if (ev === 'readable' && !this._readableState.endEmitted) {
var state = this._readableState;
if (!state.readableListening) {
state.readableListening = true;
state.emittedReadable = false;
state.needReadable = true;
if (!state.reading) {
processNextTick(nReadingNextTick, this);
} else if (state.length) {
emitReadable(this, state);
}
}
}
return res;
};
Readable.prototype.addListener = Readable.prototype.on;
function nReadingNextTick(self) {
debug('readable nexttick read 0');
self.read(0);
}
// pause() and resume() are remnants of the legacy readable stream API
// If the user uses them, then switch into old mode.
Readable.prototype.resume = function () {
var state = this._readableState;
if (!state.flowing) {
debug('resume');
state.flowing = true;
resume(this, state);
}
return this;
};
function resume(stream, state) {
if (!state.resumeScheduled) {
state.resumeScheduled = true;
processNextTick(resume_, stream, state);
}
}
function resume_(stream, state) {
if (!state.reading) {
debug('resume read 0');
stream.read(0);
}
state.resumeScheduled = false;
stream.emit('resume');
flow(stream);
if (state.flowing && !state.reading) stream.read(0);
}
Readable.prototype.pause = function () {
debug('call pause flowing=%j', this._readableState.flowing);
if (false !== this._readableState.flowing) {
debug('pause');
this._readableState.flowing = false;
this.emit('pause');
}
return this;
};
function flow(stream) {
var state = stream._readableState;
debug('flow', state.flowing);
if (state.flowing) {
do {
var chunk = stream.read();
} while (null !== chunk && state.flowing);
}
}
// wrap an old-style stream as the async data source.
// This is *not* part of the readable stream interface.
// It is an ugly unfortunate mess of history.
Readable.prototype.wrap = function (stream) {
var state = this._readableState;
var paused = false;
var self = this;
stream.on('end', function () {
debug('wrapped end');
if (state.decoder && !state.ended) {
var chunk = state.decoder.end();
if (chunk && chunk.length) self.push(chunk);
}
self.push(null);
});
stream.on('data', function (chunk) {
debug('wrapped data');
if (state.decoder) chunk = state.decoder.write(chunk);
// don't skip over falsy values in objectMode
if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
var ret = self.push(chunk);
if (!ret) {
paused = true;
stream.pause();
}
});
// proxy all the other methods.
// important when wrapping filters and duplexes.
for (var i in stream) {
if (this[i] === undefined && typeof stream[i] === 'function') {
this[i] = function (method) {
return function () {
return stream[method].apply(stream, arguments);
};
}(i);
}
}
// proxy certain important events.
var events = ['error', 'close', 'destroy', 'pause', 'resume'];
forEach(events, function (ev) {
stream.on(ev, self.emit.bind(self, ev));
});
// when we try to consume some more bytes, simply unpause the
// underlying stream.
self._read = function (n) {
debug('wrapped _read', n);
if (paused) {
paused = false;
stream.resume();
}
};
return self;
};
// exposed for testing purposes only.
Readable._fromList = fromList;
// Pluck off n bytes from an array of buffers.
// Length is the combined lengths of all the buffers in the list.
function fromList(n, state) {
var list = state.buffer;
var length = state.length;
var stringMode = !!state.decoder;
var objectMode = !!state.objectMode;
var ret;
// nothing in the list, definitely empty.
if (list.length === 0) return null;
if (length === 0) ret = null;else if (objectMode) ret = list.shift();else if (!n || n >= length) {
// read it all, truncate the array.
if (stringMode) ret = list.join('');else if (list.length === 1) ret = list[0];else ret = Buffer.concat(list, length);
list.length = 0;
} else {
// read just some of it.
if (n < list[0].length) {
// just take a part of the first list item.
// slice is the same for buffers and strings.
var buf = list[0];
ret = buf.slice(0, n);
list[0] = buf.slice(n);
} else if (n === list[0].length) {
// first list is a perfect match
ret = list.shift();
} else {
// complex case.
// we have enough to cover it, but it spans past the first buffer.
if (stringMode) ret = '';else ret = bufferShim.allocUnsafe(n);
var c = 0;
for (var i = 0, l = list.length; i < l && c < n; i++) {
var _buf = list[0];
var cpy = Math.min(n - c, _buf.length);
if (stringMode) ret += _buf.slice(0, cpy);else _buf.copy(ret, c, 0, cpy);
if (cpy < _buf.length) list[0] = _buf.slice(cpy);else list.shift();
c += cpy;
}
}
}
return ret;
}
function endReadable(stream) {
var state = stream._readableState;
// If we get here before consuming all the bytes, then that is a
// bug in node. Should never happen.
if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
if (!state.endEmitted) {
state.ended = true;
processNextTick(endReadableNT, state, stream);
}
}
function endReadableNT(state, stream) {
// Check that we didn't get one last unshift.
if (!state.endEmitted && state.length === 0) {
state.endEmitted = true;
stream.readable = false;
stream.emit('end');
}
}
function forEach(xs, f) {
for (var i = 0, l = xs.length; i < l; i++) {
f(xs[i], i);
}
}
function indexOf(xs, x) {
for (var i = 0, l = xs.length; i < l; i++) {
if (xs[i] === x) return i;
}
return -1;
}
}).call(this,require('_process'))
},{"./_stream_duplex":85,"_process":83,"buffer":75,"buffer-shims":90,"core-util-is":91,"events":79,"inherits":80,"isarray":92,"process-nextick-args":93,"string_decoder/":100,"util":74}],88:[function(require,module,exports){
// a transform stream is a readable/writable stream where you do
// something with the data. Sometimes it's called a "filter",
// but that's not a great name for it, since that implies a thing where
// some bits pass through, and others are simply ignored. (That would
// be a valid example of a transform, of course.)
//
// While the output is causally related to the input, it's not a
// necessarily symmetric or synchronous transformation. For example,
// a zlib stream might take multiple plain-text writes(), and then
// emit a single compressed chunk some time in the future.
//
// Here's how this works:
//
// The Transform stream has all the aspects of the readable and writable
// stream classes. When you write(chunk), that calls _write(chunk,cb)
// internally, and returns false if there's a lot of pending writes
// buffered up. When you call read(), that calls _read(n) until
// there's enough pending readable data buffered up.
//
// In a transform stream, the written data is placed in a buffer. When
// _read(n) is called, it transforms the queued up data, calling the
// buffered _write cb's as it consumes chunks. If consuming a single
// written chunk would result in multiple output chunks, then the first
// outputted bit calls the readcb, and subsequent chunks just go into
// the read buffer, and will cause it to emit 'readable' if necessary.
//
// This way, back-pressure is actually determined by the reading side,
// since _read has to be called to start processing a new chunk. However,
// a pathological inflate type of transform can cause excessive buffering
// here. For example, imagine a stream where every byte of input is
// interpreted as an integer from 0-255, and then results in that many
// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
// 1kb of data being output. In this case, you could write a very small
// amount of input, and end up with a very large amount of output. In
// such a pathological inflating mechanism, there'd be no way to tell
// the system to stop doing the transform. A single 4MB write could
// cause the system to run out of memory.
//
// However, even in such a pathological case, only a single written chunk
// would be consumed, and then the rest would wait (un-transformed) until
// the results of the previous transformed chunk were consumed.
'use strict';
module.exports = Transform;
var Duplex = require('./_stream_duplex');
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
util.inherits(Transform, Duplex);
function TransformState(stream) {
this.afterTransform = function (er, data) {
return afterTransform(stream, er, data);
};
this.needTransform = false;
this.transforming = false;
this.writecb = null;
this.writechunk = null;
this.writeencoding = null;
}
function afterTransform(stream, er, data) {
var ts = stream._transformState;
ts.transforming = false;
var cb = ts.writecb;
if (!cb) return stream.emit('error', new Error('no writecb in Transform class'));
ts.writechunk = null;
ts.writecb = null;
if (data !== null && data !== undefined) stream.push(data);
cb(er);
var rs = stream._readableState;
rs.reading = false;
if (rs.needReadable || rs.length < rs.highWaterMark) {
stream._read(rs.highWaterMark);
}
}
function Transform(options) {
if (!(this instanceof Transform)) return new Transform(options);
Duplex.call(this, options);
this._transformState = new TransformState(this);
// when the writable side finishes, then flush out anything remaining.
var stream = this;
// start out asking for a readable event once data is transformed.
this._readableState.needReadable = true;
// we have implemented the _read method, and done the other things
// that Readable wants before the first _read call, so unset the
// sync guard flag.
this._readableState.sync = false;
if (options) {
if (typeof options.transform === 'function') this._transform = options.transform;
if (typeof options.flush === 'function') this._flush = options.flush;
}
this.once('prefinish', function () {
if (typeof this._flush === 'function') this._flush(function (er) {
done(stream, er);
});else done(stream);
});
}
Transform.prototype.push = function (chunk, encoding) {
this._transformState.needTransform = false;
return Duplex.prototype.push.call(this, chunk, encoding);
};
// This is the part where you do stuff!
// override this function in implementation classes.
// 'chunk' is an input chunk.
//
// Call `push(newChunk)` to pass along transformed output
// to the readable side. You may call 'push' zero or more times.
//
// Call `cb(err)` when you are done with this chunk. If you pass
// an error, then that'll put the hurt on the whole operation. If you
// never call cb(), then you'll never get another chunk.
Transform.prototype._transform = function (chunk, encoding, cb) {
throw new Error('Not implemented');
};
Transform.prototype._write = function (chunk, encoding, cb) {
var ts = this._transformState;
ts.writecb = cb;
ts.writechunk = chunk;
ts.writeencoding = encoding;
if (!ts.transforming) {
var rs = this._readableState;
if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
}
};
// Doesn't matter what the args are here.
// _transform does all the work.
// That we got here means that the readable side wants more data.
Transform.prototype._read = function (n) {
var ts = this._transformState;
if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
ts.transforming = true;
this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
} else {
// mark that we need a transform, so that any data that comes in
// will get processed, now that we've asked for it.
ts.needTransform = true;
}
};
function done(stream, er) {
if (er) return stream.emit('error', er);
// if there's nothing in the write buffer, then that means
// that nothing more will ever be provided
var ws = stream._writableState;
var ts = stream._transformState;
if (ws.length) throw new Error('Calling transform done when ws.length != 0');
if (ts.transforming) throw new Error('Calling transform done when still transforming');
return stream.push(null);
}
},{"./_stream_duplex":85,"core-util-is":91,"inherits":80}],89:[function(require,module,exports){
(function (process){
// A bit simpler than readable streams.
// Implement an async ._write(chunk, encoding, cb), and it'll handle all
// the drain event emission and buffering.
'use strict';
module.exports = Writable;
/*<replacement>*/
var processNextTick = require('process-nextick-args');
/*</replacement>*/
/*<replacement>*/
var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick;
/*</replacement>*/
Writable.WritableState = WritableState;
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
/*<replacement>*/
var internalUtil = {
deprecate: require('util-deprecate')
};
/*</replacement>*/
/*<replacement>*/
var Stream;
(function () {
try {
Stream = require('st' + 'ream');
} catch (_) {} finally {
if (!Stream) Stream = require('events').EventEmitter;
}
})();
/*</replacement>*/
var Buffer = require('buffer').Buffer;
/*<replacement>*/
var bufferShim = require('buffer-shims');
/*</replacement>*/
util.inherits(Writable, Stream);
function nop() {}
function WriteReq(chunk, encoding, cb) {
this.chunk = chunk;
this.encoding = encoding;
this.callback = cb;
this.next = null;
}
var Duplex;
function WritableState(options, stream) {
Duplex = Duplex || require('./_stream_duplex');
options = options || {};
// object stream flag to indicate whether or not this stream
// contains buffers or objects.
this.objectMode = !!options.objectMode;
if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
// the point at which write() starts returning false
// Note: 0 is a valid value, means that we always return false if
// the entire buffer is not flushed immediately on write()
var hwm = options.highWaterMark;
var defaultHwm = this.objectMode ? 16 : 16 * 1024;
this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
// cast to ints.
this.highWaterMark = ~ ~this.highWaterMark;
this.needDrain = false;
// at the start of calling end()
this.ending = false;
// when end() has been called, and returned
this.ended = false;
// when 'finish' is emitted
this.finished = false;
// should we decode strings into buffers before passing to _write?
// this is here so that some node-core streams can optimize string
// handling at a lower level.
var noDecode = options.decodeStrings === false;
this.decodeStrings = !noDecode;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// not an actual buffer we keep track of, but a measurement
// of how much we're waiting to get pushed to some underlying
// socket or file.
this.length = 0;
// a flag to see when we're in the middle of a write.
this.writing = false;
// when true all writes will be buffered until .uncork() call
this.corked = 0;
// a flag to be able to tell if the onwrite cb is called immediately,
// or on a later tick. We set this to true at first, because any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
// a flag to know if we're processing previously buffered items, which
// may call the _write() callback in the same tick, so that we don't
// end up in an overlapped onwrite situation.
this.bufferProcessing = false;
// the callback that's passed to _write(chunk,cb)
this.onwrite = function (er) {
onwrite(stream, er);
};
// the callback that the user supplies to write(chunk,encoding,cb)
this.writecb = null;
// the amount that is being written when _write is called.
this.writelen = 0;
this.bufferedRequest = null;
this.lastBufferedRequest = null;
// number of pending user-supplied write callbacks
// this must be 0 before 'finish' can be emitted
this.pendingcb = 0;
// emit prefinish if the only thing we're waiting for is _write cbs
// This is relevant for synchronous Transform streams
this.prefinished = false;
// True if the error was already emitted and should not be thrown again
this.errorEmitted = false;
// count buffered requests
this.bufferedRequestCount = 0;
// allocate the first CorkedRequest, there is always
// one allocated and free to use, and we maintain at most two
this.corkedRequestsFree = new CorkedRequest(this);
}
WritableState.prototype.getBuffer = function writableStateGetBuffer() {
var current = this.bufferedRequest;
var out = [];
while (current) {
out.push(current);
current = current.next;
}
return out;
};
(function () {
try {
Object.defineProperty(WritableState.prototype, 'buffer', {
get: internalUtil.deprecate(function () {
return this.getBuffer();
}, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.')
});
} catch (_) {}
})();
var Duplex;
function Writable(options) {
Duplex = Duplex || require('./_stream_duplex');
// Writable ctor is applied to Duplexes, though they're not
// instanceof Writable, they're instanceof Readable.
if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options);
this._writableState = new WritableState(options, this);
// legacy.
this.writable = true;
if (options) {
if (typeof options.write === 'function') this._write = options.write;
if (typeof options.writev === 'function') this._writev = options.writev;
}
Stream.call(this);
}
// Otherwise people can pipe Writable streams, which is just wrong.
Writable.prototype.pipe = function () {
this.emit('error', new Error('Cannot pipe, not readable'));
};
function writeAfterEnd(stream, cb) {
var er = new Error('write after end');
// TODO: defer error events consistently everywhere, not just the cb
stream.emit('error', er);
processNextTick(cb, er);
}
// If we get something that is not a buffer, string, null, or undefined,
// and we're not in objectMode, then that's an error.
// Otherwise stream chunks are all considered to be of length=1, and the
// watermarks determine how many objects to keep in the buffer, rather than
// how many bytes or characters.
function validChunk(stream, state, chunk, cb) {
var valid = true;
var er = false;
// Always throw error if a null is written
// if we are not in object mode then throw
// if it is not a buffer, string, or undefined.
if (chunk === null) {
er = new TypeError('May not write null values to stream');
} else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
er = new TypeError('Invalid non-string/buffer chunk');
}
if (er) {
stream.emit('error', er);
processNextTick(cb, er);
valid = false;
}
return valid;
}
Writable.prototype.write = function (chunk, encoding, cb) {
var state = this._writableState;
var ret = false;
if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
if (typeof cb !== 'function') cb = nop;
if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) {
state.pendingcb++;
ret = writeOrBuffer(this, state, chunk, encoding, cb);
}
return ret;
};
Writable.prototype.cork = function () {
var state = this._writableState;
state.corked++;
};
Writable.prototype.uncork = function () {
var state = this._writableState;
if (state.corked) {
state.corked--;
if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
}
};
Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
// node::ParseEncoding() requires lower case.
if (typeof encoding === 'string') encoding = encoding.toLowerCase();
if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
this._writableState.defaultEncoding = encoding;
return this;
};
function decodeChunk(state, chunk, encoding) {
if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
chunk = bufferShim.from(chunk, encoding);
}
return chunk;
}
// if we're already writing something, then just put this
// in the queue, and wait our turn. Otherwise, call _write
// If we return false, then we need a drain event, so set that flag.
function writeOrBuffer(stream, state, chunk, encoding, cb) {
chunk = decodeChunk(state, chunk, encoding);
if (Buffer.isBuffer(chunk)) encoding = 'buffer';
var len = state.objectMode ? 1 : chunk.length;
state.length += len;
var ret = state.length < state.highWaterMark;
// we must ensure that previous needDrain will not be reset to false.
if (!ret) state.needDrain = true;
if (state.writing || state.corked) {
var last = state.lastBufferedRequest;
state.lastBufferedRequest = new WriteReq(chunk, encoding, cb);
if (last) {
last.next = state.lastBufferedRequest;
} else {
state.bufferedRequest = state.lastBufferedRequest;
}
state.bufferedRequestCount += 1;
} else {
doWrite(stream, state, false, len, chunk, encoding, cb);
}
return ret;
}
function doWrite(stream, state, writev, len, chunk, encoding, cb) {
state.writelen = len;
state.writecb = cb;
state.writing = true;
state.sync = true;
if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
state.sync = false;
}
function onwriteError(stream, state, sync, er, cb) {
--state.pendingcb;
if (sync) processNextTick(cb, er);else cb(er);
stream._writableState.errorEmitted = true;
stream.emit('error', er);
}
function onwriteStateUpdate(state) {
state.writing = false;
state.writecb = null;
state.length -= state.writelen;
state.writelen = 0;
}
function onwrite(stream, er) {
var state = stream._writableState;
var sync = state.sync;
var cb = state.writecb;
onwriteStateUpdate(state);
if (er) onwriteError(stream, state, sync, er, cb);else {
// Check if we're actually ready to finish, but don't emit yet
var finished = needFinish(state);
if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
clearBuffer(stream, state);
}
if (sync) {
/*<replacement>*/
asyncWrite(afterWrite, stream, state, finished, cb);
/*</replacement>*/
} else {
afterWrite(stream, state, finished, cb);
}
}
}
function afterWrite(stream, state, finished, cb) {
if (!finished) onwriteDrain(stream, state);
state.pendingcb--;
cb();
finishMaybe(stream, state);
}
// Must force callback to be called on nextTick, so that we don't
// emit 'drain' before the write() consumer gets the 'false' return
// value, and has a chance to attach a 'drain' listener.
function onwriteDrain(stream, state) {
if (state.length === 0 && state.needDrain) {
state.needDrain = false;
stream.emit('drain');
}
}
// if there's something in the buffer waiting, then process it
function clearBuffer(stream, state) {
state.bufferProcessing = true;
var entry = state.bufferedRequest;
if (stream._writev && entry && entry.next) {
// Fast case, write everything using _writev()
var l = state.bufferedRequestCount;
var buffer = new Array(l);
var holder = state.corkedRequestsFree;
holder.entry = entry;
var count = 0;
while (entry) {
buffer[count] = entry;
entry = entry.next;
count += 1;
}
doWrite(stream, state, true, state.length, buffer, '', holder.finish);
// doWrite is almost always async, defer these to save a bit of time
// as the hot path ends with doWrite
state.pendingcb++;
state.lastBufferedRequest = null;
if (holder.next) {
state.corkedRequestsFree = holder.next;
holder.next = null;
} else {
state.corkedRequestsFree = new CorkedRequest(state);
}
} else {
// Slow case, write chunks one-by-one
while (entry) {
var chunk = entry.chunk;
var encoding = entry.encoding;
var cb = entry.callback;
var len = state.objectMode ? 1 : chunk.length;
doWrite(stream, state, false, len, chunk, encoding, cb);
entry = entry.next;
// if we didn't call the onwrite immediately, then
// it means that we need to wait until it does.
// also, that means that the chunk and cb are currently
// being processed, so move the buffer counter past them.
if (state.writing) {
break;
}
}
if (entry === null) state.lastBufferedRequest = null;
}
state.bufferedRequestCount = 0;
state.bufferedRequest = entry;
state.bufferProcessing = false;
}
Writable.prototype._write = function (chunk, encoding, cb) {
cb(new Error('not implemented'));
};
Writable.prototype._writev = null;
Writable.prototype.end = function (chunk, encoding, cb) {
var state = this._writableState;
if (typeof chunk === 'function') {
cb = chunk;
chunk = null;
encoding = null;
} else if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
// .end() fully uncorks
if (state.corked) {
state.corked = 1;
this.uncork();
}
// ignore unnecessary end() calls.
if (!state.ending && !state.finished) endWritable(this, state, cb);
};
function needFinish(state) {
return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
}
function prefinish(stream, state) {
if (!state.prefinished) {
state.prefinished = true;
stream.emit('prefinish');
}
}
function finishMaybe(stream, state) {
var need = needFinish(state);
if (need) {
if (state.pendingcb === 0) {
prefinish(stream, state);
state.finished = true;
stream.emit('finish');
} else {
prefinish(stream, state);
}
}
return need;
}
function endWritable(stream, state, cb) {
state.ending = true;
finishMaybe(stream, state);
if (cb) {
if (state.finished) processNextTick(cb);else stream.once('finish', cb);
}
state.ended = true;
stream.writable = false;
}
// It seems a linked list but it is not
// there will be only 2 of these for each stream
function CorkedRequest(state) {
var _this = this;
this.next = null;
this.entry = null;
this.finish = function (err) {
var entry = _this.entry;
_this.entry = null;
while (entry) {
var cb = entry.callback;
state.pendingcb--;
cb(err);
entry = entry.next;
}
if (state.corkedRequestsFree) {
state.corkedRequestsFree.next = _this;
} else {
state.corkedRequestsFree = _this;
}
};
}
}).call(this,require('_process'))
},{"./_stream_duplex":85,"_process":83,"buffer":75,"buffer-shims":90,"core-util-is":91,"events":79,"inherits":80,"process-nextick-args":93,"util-deprecate":94}],90:[function(require,module,exports){
(function (global){
'use strict';
var buffer = require('buffer');
var Buffer = buffer.Buffer;
var SlowBuffer = buffer.SlowBuffer;
var MAX_LEN = buffer.kMaxLength || 2147483647;
exports.alloc = function alloc(size, fill, encoding) {
if (typeof Buffer.alloc === 'function') {
return Buffer.alloc(size, fill, encoding);
}
if (typeof encoding === 'number') {
throw new TypeError('encoding must not be number');
}
if (typeof size !== 'number') {
throw new TypeError('size must be a number');
}
if (size > MAX_LEN) {
throw new RangeError('size is too large');
}
var enc = encoding;
var _fill = fill;
if (_fill === undefined) {
enc = undefined;
_fill = 0;
}
var buf = new Buffer(size);
if (typeof _fill === 'string') {
var fillBuf = new Buffer(_fill, enc);
var flen = fillBuf.length;
var i = -1;
while (++i < size) {
buf[i] = fillBuf[i % flen];
}
} else {
buf.fill(_fill);
}
return buf;
}
exports.allocUnsafe = function allocUnsafe(size) {
if (typeof Buffer.allocUnsafe === 'function') {
return Buffer.allocUnsafe(size);
}
if (typeof size !== 'number') {
throw new TypeError('size must be a number');
}
if (size > MAX_LEN) {
throw new RangeError('size is too large');
}
return new Buffer(size);
}
exports.from = function from(value, encodingOrOffset, length) {
if (typeof Buffer.from === 'function' && (!global.Uint8Array || Uint8Array.from !== Buffer.from)) {
return Buffer.from(value, encodingOrOffset, length);
}
if (typeof value === 'number') {
throw new TypeError('"value" argument must not be a number');
}
if (typeof value === 'string') {
return new Buffer(value, encodingOrOffset);
}
if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
var offset = encodingOrOffset;
if (arguments.length === 1) {
return new Buffer(value);
}
if (typeof offset === 'undefined') {
offset = 0;
}
var len = length;
if (typeof len === 'undefined') {
len = value.byteLength - offset;
}
if (offset >= value.byteLength) {
throw new RangeError('\'offset\' is out of bounds');
}
if (len > value.byteLength - offset) {
throw new RangeError('\'length\' is out of bounds');
}
return new Buffer(value.slice(offset, offset + len));
}
if (Buffer.isBuffer(value)) {
var out = new Buffer(value.length);
value.copy(out, 0, 0, value.length);
return out;
}
if (value) {
if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buffer instanceof ArrayBuffer) || 'length' in value) {
return new Buffer(value);
}
if (value.type === 'Buffer' && Array.isArray(value.data)) {
return new Buffer(value.data);
}
}
throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.');
}
exports.allocUnsafeSlow = function allocUnsafeSlow(size) {
if (typeof Buffer.allocUnsafeSlow === 'function') {
return Buffer.allocUnsafeSlow(size);
}
if (typeof size !== 'number') {
throw new TypeError('size must be a number');
}
if (size >= MAX_LEN) {
throw new RangeError('size is too large');
}
return new SlowBuffer(size);
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"buffer":75}],91:[function(require,module,exports){
(function (Buffer){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(arg) {
if (Array.isArray) {
return Array.isArray(arg);
}
return objectToString(arg) === '[object Array]';
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return (objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = Buffer.isBuffer;
function objectToString(o) {
return Object.prototype.toString.call(o);
}
}).call(this,{"isBuffer":require("../../../../insert-module-globals/node_modules/is-buffer/index.js")})
},{"../../../../insert-module-globals/node_modules/is-buffer/index.js":81}],92:[function(require,module,exports){
arguments[4][78][0].apply(exports,arguments)
},{"dup":78}],93:[function(require,module,exports){
(function (process){
'use strict';
if (!process.version ||
process.version.indexOf('v0.') === 0 ||
process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
module.exports = nextTick;
} else {
module.exports = process.nextTick;
}
function nextTick(fn, arg1, arg2, arg3) {
if (typeof fn !== 'function') {
throw new TypeError('"callback" argument must be a function');
}
var len = arguments.length;
var args, i;
switch (len) {
case 0:
case 1:
return process.nextTick(fn);
case 2:
return process.nextTick(function afterTickOne() {
fn.call(null, arg1);
});
case 3:
return process.nextTick(function afterTickTwo() {
fn.call(null, arg1, arg2);
});
case 4:
return process.nextTick(function afterTickThree() {
fn.call(null, arg1, arg2, arg3);
});
default:
args = new Array(len - 1);
i = 0;
while (i < args.length) {
args[i++] = arguments[i];
}
return process.nextTick(function afterTick() {
fn.apply(null, args);
});
}
}
}).call(this,require('_process'))
},{"_process":83}],94:[function(require,module,exports){
(function (global){
/**
* Module exports.
*/
module.exports = deprecate;
/**
* Mark that a method should not be used.
* Returns a modified function which warns once by default.
*
* If `localStorage.noDeprecation = true` is set, then it is a no-op.
*
* If `localStorage.throwDeprecation = true` is set, then deprecated functions
* will throw an Error when invoked.
*
* If `localStorage.traceDeprecation = true` is set, then deprecated functions
* will invoke `console.trace()` instead of `console.error()`.
*
* @param {Function} fn - the function to deprecate
* @param {String} msg - the string to print to the console when `fn` is invoked
* @returns {Function} a new "deprecated" version of `fn`
* @api public
*/
function deprecate (fn, msg) {
if (config('noDeprecation')) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (config('throwDeprecation')) {
throw new Error(msg);
} else if (config('traceDeprecation')) {
console.trace(msg);
} else {
console.warn(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
}
/**
* Checks `localStorage` for boolean values for the given `name`.
*
* @param {String} name
* @returns {Boolean}
* @api private
*/
function config (name) {
// accessing global.localStorage can trigger a DOMException in sandboxed iframes
try {
if (!global.localStorage) return false;
} catch (_) {
return false;
}
var val = global.localStorage[name];
if (null == val) return false;
return String(val).toLowerCase() === 'true';
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],95:[function(require,module,exports){
module.exports = require("./lib/_stream_passthrough.js")
},{"./lib/_stream_passthrough.js":86}],96:[function(require,module,exports){
(function (process){
var Stream = (function (){
try {
return require('st' + 'ream'); // hack to fix a circular dependency issue when used with browserify
} catch(_){}
}());
exports = module.exports = require('./lib/_stream_readable.js');
exports.Stream = Stream || exports;
exports.Readable = exports;
exports.Writable = require('./lib/_stream_writable.js');
exports.Duplex = require('./lib/_stream_duplex.js');
exports.Transform = require('./lib/_stream_transform.js');
exports.PassThrough = require('./lib/_stream_passthrough.js');
if (!process.browser && process.env.READABLE_STREAM === 'disable' && Stream) {
module.exports = Stream;
}
}).call(this,require('_process'))
},{"./lib/_stream_duplex.js":85,"./lib/_stream_passthrough.js":86,"./lib/_stream_readable.js":87,"./lib/_stream_transform.js":88,"./lib/_stream_writable.js":89,"_process":83}],97:[function(require,module,exports){
module.exports = require("./lib/_stream_transform.js")
},{"./lib/_stream_transform.js":88}],98:[function(require,module,exports){
module.exports = require("./lib/_stream_writable.js")
},{"./lib/_stream_writable.js":89}],99:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
module.exports = Stream;
var EE = require('events').EventEmitter;
var inherits = require('inherits');
inherits(Stream, EE);
Stream.Readable = require('readable-stream/readable.js');
Stream.Writable = require('readable-stream/writable.js');
Stream.Duplex = require('readable-stream/duplex.js');
Stream.Transform = require('readable-stream/transform.js');
Stream.PassThrough = require('readable-stream/passthrough.js');
// Backwards-compat with node 0.4.x
Stream.Stream = Stream;
// old-style streams. Note that the pipe method (the only relevant
// part of this class) is overridden in the Readable class.
function Stream() {
EE.call(this);
}
Stream.prototype.pipe = function(dest, options) {
var source = this;
function ondata(chunk) {
if (dest.writable) {
if (false === dest.write(chunk) && source.pause) {
source.pause();
}
}
}
source.on('data', ondata);
function ondrain() {
if (source.readable && source.resume) {
source.resume();
}
}
dest.on('drain', ondrain);
// If the 'end' option is not supplied, dest.end() will be called when
// source gets the 'end' or 'close' events. Only dest.end() once.
if (!dest._isStdio && (!options || options.end !== false)) {
source.on('end', onend);
source.on('close', onclose);
}
var didOnEnd = false;
function onend() {
if (didOnEnd) return;
didOnEnd = true;
dest.end();
}
function onclose() {
if (didOnEnd) return;
didOnEnd = true;
if (typeof dest.destroy === 'function') dest.destroy();
}
// don't leave dangling pipes when there are errors.
function onerror(er) {
cleanup();
if (EE.listenerCount(this, 'error') === 0) {
throw er; // Unhandled stream error in pipe.
}
}
source.on('error', onerror);
dest.on('error', onerror);
// remove all the event listeners that were added.
function cleanup() {
source.removeListener('data', ondata);
dest.removeListener('drain', ondrain);
source.removeListener('end', onend);
source.removeListener('close', onclose);
source.removeListener('error', onerror);
dest.removeListener('error', onerror);
source.removeListener('end', cleanup);
source.removeListener('close', cleanup);
dest.removeListener('close', cleanup);
}
source.on('end', cleanup);
source.on('close', cleanup);
dest.on('close', cleanup);
dest.emit('pipe', source);
// Allow for unix-like usage: A.pipe(B).pipe(C)
return dest;
};
},{"events":79,"inherits":80,"readable-stream/duplex.js":84,"readable-stream/passthrough.js":95,"readable-stream/readable.js":96,"readable-stream/transform.js":97,"readable-stream/writable.js":98}],100:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var Buffer = require('buffer').Buffer;
var isBufferEncoding = Buffer.isEncoding
|| function(encoding) {
switch (encoding && encoding.toLowerCase()) {
case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true;
default: return false;
}
}
function assertEncoding(encoding) {
if (encoding && !isBufferEncoding(encoding)) {
throw new Error('Unknown encoding: ' + encoding);
}
}
// StringDecoder provides an interface for efficiently splitting a series of
// buffers into a series of JS strings without breaking apart multi-byte
// characters. CESU-8 is handled as part of the UTF-8 encoding.
//
// @TODO Handling all encodings inside a single object makes it very difficult
// to reason about this code, so it should be split up in the future.
// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
// points as used by CESU-8.
var StringDecoder = exports.StringDecoder = function(encoding) {
this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
assertEncoding(encoding);
switch (this.encoding) {
case 'utf8':
// CESU-8 represents each of Surrogate Pair by 3-bytes
this.surrogateSize = 3;
break;
case 'ucs2':
case 'utf16le':
// UTF-16 represents each of Surrogate Pair by 2-bytes
this.surrogateSize = 2;
this.detectIncompleteChar = utf16DetectIncompleteChar;
break;
case 'base64':
// Base-64 stores 3 bytes in 4 chars, and pads the remainder.
this.surrogateSize = 3;
this.detectIncompleteChar = base64DetectIncompleteChar;
break;
default:
this.write = passThroughWrite;
return;
}
// Enough space to store all bytes of a single character. UTF-8 needs 4
// bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
this.charBuffer = new Buffer(6);
// Number of bytes received for the current incomplete multi-byte character.
this.charReceived = 0;
// Number of bytes expected for the current incomplete multi-byte character.
this.charLength = 0;
};
// write decodes the given buffer and returns it as JS string that is
// guaranteed to not contain any partial multi-byte characters. Any partial
// character found at the end of the buffer is buffered up, and will be
// returned when calling write again with the remaining bytes.
//
// Note: Converting a Buffer containing an orphan surrogate to a String
// currently works, but converting a String to a Buffer (via `new Buffer`, or
// Buffer#write) will replace incomplete surrogates with the unicode
// replacement character. See https://codereview.chromium.org/121173009/ .
StringDecoder.prototype.write = function(buffer) {
var charStr = '';
// if our last write ended with an incomplete multibyte character
while (this.charLength) {
// determine how many remaining bytes this buffer has to offer for this char
var available = (buffer.length >= this.charLength - this.charReceived) ?
this.charLength - this.charReceived :
buffer.length;
// add the new bytes to the char buffer
buffer.copy(this.charBuffer, this.charReceived, 0, available);
this.charReceived += available;
if (this.charReceived < this.charLength) {
// still not enough chars in this buffer? wait for more ...
return '';
}
// remove bytes belonging to the current character from the buffer
buffer = buffer.slice(available, buffer.length);
// get the character that was split
charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
// CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
var charCode = charStr.charCodeAt(charStr.length - 1);
if (charCode >= 0xD800 && charCode <= 0xDBFF) {
this.charLength += this.surrogateSize;
charStr = '';
continue;
}
this.charReceived = this.charLength = 0;
// if there are no more bytes in this buffer, just emit our char
if (buffer.length === 0) {
return charStr;
}
break;
}
// determine and set charLength / charReceived
this.detectIncompleteChar(buffer);
var end = buffer.length;
if (this.charLength) {
// buffer the incomplete character bytes we got
buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
end -= this.charReceived;
}
charStr += buffer.toString(this.encoding, 0, end);
var end = charStr.length - 1;
var charCode = charStr.charCodeAt(end);
// CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
if (charCode >= 0xD800 && charCode <= 0xDBFF) {
var size = this.surrogateSize;
this.charLength += size;
this.charReceived += size;
this.charBuffer.copy(this.charBuffer, size, 0, size);
buffer.copy(this.charBuffer, 0, 0, size);
return charStr.substring(0, end);
}
// or just emit the charStr
return charStr;
};
// detectIncompleteChar determines if there is an incomplete UTF-8 character at
// the end of the given buffer. If so, it sets this.charLength to the byte
// length that character, and sets this.charReceived to the number of bytes
// that are available for this character.
StringDecoder.prototype.detectIncompleteChar = function(buffer) {
// determine how many bytes we have to check at the end of this buffer
var i = (buffer.length >= 3) ? 3 : buffer.length;
// Figure out if one of the last i bytes of our buffer announces an
// incomplete char.
for (; i > 0; i--) {
var c = buffer[buffer.length - i];
// See http://en.wikipedia.org/wiki/UTF-8#Description
// 110XXXXX
if (i == 1 && c >> 5 == 0x06) {
this.charLength = 2;
break;
}
// 1110XXXX
if (i <= 2 && c >> 4 == 0x0E) {
this.charLength = 3;
break;
}
// 11110XXX
if (i <= 3 && c >> 3 == 0x1E) {
this.charLength = 4;
break;
}
}
this.charReceived = i;
};
StringDecoder.prototype.end = function(buffer) {
var res = '';
if (buffer && buffer.length)
res = this.write(buffer);
if (this.charReceived) {
var cr = this.charReceived;
var buf = this.charBuffer;
var enc = this.encoding;
res += buf.slice(0, cr).toString(enc);
}
return res;
};
function passThroughWrite(buffer) {
return buffer.toString(this.encoding);
}
function utf16DetectIncompleteChar(buffer) {
this.charReceived = buffer.length % 2;
this.charLength = this.charReceived ? 2 : 0;
}
function base64DetectIncompleteChar(buffer) {
this.charReceived = buffer.length % 3;
this.charLength = this.charReceived ? 3 : 0;
}
},{"buffer":75}],101:[function(require,module,exports){
module.exports = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.readUInt8 === 'function';
}
},{}],102:[function(require,module,exports){
(function (process,global){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
};
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
// Allow for deprecating things in the process of starting up.
if (isUndefined(global.process)) {
return function() {
return exports.deprecate(fn, msg).apply(this, arguments);
};
}
if (process.noDeprecation === true) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (process.throwDeprecation) {
throw new Error(msg);
} else if (process.traceDeprecation) {
console.trace(msg);
} else {
console.error(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
if (isUndefined(debugEnviron))
debugEnviron = process.env.NODE_DEBUG || '';
set = set.toUpperCase();
if (!debugs[set]) {
if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
var pid = process.pid;
debugs[set] = function() {
var msg = exports.format.apply(exports, arguments);
console.error('%s %d: %s', set, pid, msg);
};
} else {
debugs[set] = function() {};
}
}
return debugs[set];
};
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39]
};
// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + inspect.colors[style][1] + 'm';
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function(val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
}
function reduceToSingleString(output, base, braces) {
var numLinesEst = 0;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = require('./support/isBuffer');
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
* @param {function} ctor Constructor function which needs to inherit the
* prototype.
* @param {function} superCtor Constructor function to inherit prototype from.
*/
exports.inherits = require('inherits');
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || !isObject(add)) return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./support/isBuffer":101,"_process":83,"inherits":80}],103:[function(require,module,exports){
'use strict';
// private property
var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
// public method for encoding
exports.encode = function(input, utf8) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
}
else if (isNaN(chr3)) {
enc4 = 64;
}
output = output + _keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
}
return output;
};
// public method for decoding
exports.decode = function(input, utf8) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < input.length) {
enc1 = _keyStr.indexOf(input.charAt(i++));
enc2 = _keyStr.indexOf(input.charAt(i++));
enc3 = _keyStr.indexOf(input.charAt(i++));
enc4 = _keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
return output;
};
},{}],104:[function(require,module,exports){
'use strict';
function CompressedObject() {
this.compressedSize = 0;
this.uncompressedSize = 0;
this.crc32 = 0;
this.compressionMethod = null;
this.compressedContent = null;
}
CompressedObject.prototype = {
/**
* Return the decompressed content in an unspecified format.
* The format will depend on the decompressor.
* @return {Object} the decompressed content.
*/
getContent: function() {
return null; // see implementation
},
/**
* Return the compressed content in an unspecified format.
* The format will depend on the compressed conten source.
* @return {Object} the compressed content.
*/
getCompressedContent: function() {
return null; // see implementation
}
};
module.exports = CompressedObject;
},{}],105:[function(require,module,exports){
'use strict';
exports.STORE = {
magic: "\x00\x00",
compress: function(content, compressionOptions) {
return content; // no compression
},
uncompress: function(content) {
return content; // no compression
},
compressInputType: null,
uncompressInputType: null
};
exports.DEFLATE = require('./flate');
},{"./flate":110}],106:[function(require,module,exports){
'use strict';
var utils = require('./utils');
var table = [
0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA,
0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,
0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC,
0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940,
0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116,
0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,
0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A,
0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818,
0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,
0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C,
0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,
0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,
0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086,
0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4,
0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,
0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,
0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,
0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE,
0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,
0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,
0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252,
0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60,
0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,
0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,
0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04,
0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A,
0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,
0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,
0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E,
0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,
0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,
0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0,
0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6,
0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,
0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D
];
/**
*
* Javascript crc32
* http://www.webtoolkit.info/
*
*/
module.exports = function crc32(input, crc) {
if (typeof input === "undefined" || !input.length) {
return 0;
}
var isArray = utils.getTypeOf(input) !== "string";
if (typeof(crc) == "undefined") {
crc = 0;
}
var x = 0;
var y = 0;
var b = 0;
crc = crc ^ (-1);
for (var i = 0, iTop = input.length; i < iTop; i++) {
b = isArray ? input[i] : input.charCodeAt(i);
y = (crc ^ b) & 0xFF;
x = table[y];
crc = (crc >>> 8) ^ x;
}
return crc ^ (-1);
};
// vim: set shiftwidth=4 softtabstop=4:
},{"./utils":123}],107:[function(require,module,exports){
'use strict';
var utils = require('./utils');
function DataReader(data) {
this.data = null; // type : see implementation
this.length = 0;
this.index = 0;
}
DataReader.prototype = {
/**
* Check that the offset will not go too far.
* @param {string} offset the additional offset to check.
* @throws {Error} an Error if the offset is out of bounds.
*/
checkOffset: function(offset) {
this.checkIndex(this.index + offset);
},
/**
* Check that the specifed index will not be too far.
* @param {string} newIndex the index to check.
* @throws {Error} an Error if the index is out of bounds.
*/
checkIndex: function(newIndex) {
if (this.length < newIndex || newIndex < 0) {
throw new Error("End of data reached (data length = " + this.length + ", asked index = " + (newIndex) + "). Corrupted zip ?");
}
},
/**
* Change the index.
* @param {number} newIndex The new index.
* @throws {Error} if the new index is out of the data.
*/
setIndex: function(newIndex) {
this.checkIndex(newIndex);
this.index = newIndex;
},
/**
* Skip the next n bytes.
* @param {number} n the number of bytes to skip.
* @throws {Error} if the new index is out of the data.
*/
skip: function(n) {
this.setIndex(this.index + n);
},
/**
* Get the byte at the specified index.
* @param {number} i the index to use.
* @return {number} a byte.
*/
byteAt: function(i) {
// see implementations
},
/**
* Get the next number with a given byte size.
* @param {number} size the number of bytes to read.
* @return {number} the corresponding number.
*/
readInt: function(size) {
var result = 0,
i;
this.checkOffset(size);
for (i = this.index + size - 1; i >= this.index; i--) {
result = (result << 8) + this.byteAt(i);
}
this.index += size;
return result;
},
/**
* Get the next string with a given byte size.
* @param {number} size the number of bytes to read.
* @return {string} the corresponding string.
*/
readString: function(size) {
return utils.transformTo("string", this.readData(size));
},
/**
* Get raw data without conversion, <size> bytes.
* @param {number} size the number of bytes to read.
* @return {Object} the raw data, implementation specific.
*/
readData: function(size) {
// see implementations
},
/**
* Find the last occurence of a zip signature (4 bytes).
* @param {string} sig the signature to find.
* @return {number} the index of the last occurence, -1 if not found.
*/
lastIndexOfSignature: function(sig) {
// see implementations
},
/**
* Get the next date.
* @return {Date} the date.
*/
readDate: function() {
var dostime = this.readInt(4);
return new Date(
((dostime >> 25) & 0x7f) + 1980, // year
((dostime >> 21) & 0x0f) - 1, // month
(dostime >> 16) & 0x1f, // day
(dostime >> 11) & 0x1f, // hour
(dostime >> 5) & 0x3f, // minute
(dostime & 0x1f) << 1); // second
}
};
module.exports = DataReader;
},{"./utils":123}],108:[function(require,module,exports){
'use strict';
exports.base64 = false;
exports.binary = false;
exports.dir = false;
exports.createFolders = false;
exports.date = null;
exports.compression = null;
exports.compressionOptions = null;
exports.comment = null;
exports.unixPermissions = null;
exports.dosPermissions = null;
},{}],109:[function(require,module,exports){
'use strict';
var utils = require('./utils');
/**
* @deprecated
* This function will be removed in a future version without replacement.
*/
exports.string2binary = function(str) {
return utils.string2binary(str);
};
/**
* @deprecated
* This function will be removed in a future version without replacement.
*/
exports.string2Uint8Array = function(str) {
return utils.transformTo("uint8array", str);
};
/**
* @deprecated
* This function will be removed in a future version without replacement.
*/
exports.uint8Array2String = function(array) {
return utils.transformTo("string", array);
};
/**
* @deprecated
* This function will be removed in a future version without replacement.
*/
exports.string2Blob = function(str) {
var buffer = utils.transformTo("arraybuffer", str);
return utils.arrayBuffer2Blob(buffer);
};
/**
* @deprecated
* This function will be removed in a future version without replacement.
*/
exports.arrayBuffer2Blob = function(buffer) {
return utils.arrayBuffer2Blob(buffer);
};
/**
* @deprecated
* This function will be removed in a future version without replacement.
*/
exports.transformTo = function(outputType, input) {
return utils.transformTo(outputType, input);
};
/**
* @deprecated
* This function will be removed in a future version without replacement.
*/
exports.getTypeOf = function(input) {
return utils.getTypeOf(input);
};
/**
* @deprecated
* This function will be removed in a future version without replacement.
*/
exports.checkSupport = function(type) {
return utils.checkSupport(type);
};
/**
* @deprecated
* This value will be removed in a future version without replacement.
*/
exports.MAX_VALUE_16BITS = utils.MAX_VALUE_16BITS;
/**
* @deprecated
* This value will be removed in a future version without replacement.
*/
exports.MAX_VALUE_32BITS = utils.MAX_VALUE_32BITS;
/**
* @deprecated
* This function will be removed in a future version without replacement.
*/
exports.pretty = function(str) {
return utils.pretty(str);
};
/**
* @deprecated
* This function will be removed in a future version without replacement.
*/
exports.findCompression = function(compressionMethod) {
return utils.findCompression(compressionMethod);
};
/**
* @deprecated
* This function will be removed in a future version without replacement.
*/
exports.isRegExp = function (object) {
return utils.isRegExp(object);
};
},{"./utils":123}],110:[function(require,module,exports){
'use strict';
var USE_TYPEDARRAY = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Uint32Array !== 'undefined');
var pako = require("pako");
exports.uncompressInputType = USE_TYPEDARRAY ? "uint8array" : "array";
exports.compressInputType = USE_TYPEDARRAY ? "uint8array" : "array";
exports.magic = "\x08\x00";
exports.compress = function(input, compressionOptions) {
return pako.deflateRaw(input, {
level : compressionOptions.level || -1 // default compression
});
};
exports.uncompress = function(input) {
return pako.inflateRaw(input);
};
},{"pako":126}],111:[function(require,module,exports){
'use strict';
var base64 = require('./base64');
/**
Usage:
zip = new JSZip();
zip.file("hello.txt", "Hello, World!").file("tempfile", "nothing");
zip.folder("images").file("smile.gif", base64Data, {base64: true});
zip.file("Xmas.txt", "Ho ho ho !", {date : new Date("December 25, 2007 00:00:01")});
zip.remove("tempfile");
base64zip = zip.generate();
**/
/**
* Representation a of zip file in js
* @constructor
* @param {String=|ArrayBuffer=|Uint8Array=} data the data to load, if any (optional).
* @param {Object=} options the options for creating this objects (optional).
*/
function JSZip(data, options) {
// if this constructor is used without `new`, it adds `new` before itself:
if(!(this instanceof JSZip)) return new JSZip(data, options);
// object containing the files :
// {
// "folder/" : {...},
// "folder/data.txt" : {...}
// }
this.files = {};
this.comment = null;
// Where we are in the hierarchy
this.root = "";
if (data) {
this.load(data, options);
}
this.clone = function() {
var newObj = new JSZip();
for (var i in this) {
if (typeof this[i] !== "function") {
newObj[i] = this[i];
}
}
return newObj;
};
}
JSZip.prototype = require('./object');
JSZip.prototype.load = require('./load');
JSZip.support = require('./support');
JSZip.defaults = require('./defaults');
/**
* @deprecated
* This namespace will be removed in a future version without replacement.
*/
JSZip.utils = require('./deprecatedPublicUtils');
JSZip.base64 = {
/**
* @deprecated
* This method will be removed in a future version without replacement.
*/
encode : function(input) {
return base64.encode(input);
},
/**
* @deprecated
* This method will be removed in a future version without replacement.
*/
decode : function(input) {
return base64.decode(input);
}
};
JSZip.compressions = require('./compressions');
module.exports = JSZip;
},{"./base64":103,"./compressions":105,"./defaults":108,"./deprecatedPublicUtils":109,"./load":112,"./object":115,"./support":119}],112:[function(require,module,exports){
'use strict';
var base64 = require('./base64');
var ZipEntries = require('./zipEntries');
module.exports = function(data, options) {
var files, zipEntries, i, input;
options = options || {};
if (options.base64) {
data = base64.decode(data);
}
zipEntries = new ZipEntries(data, options);
files = zipEntries.files;
for (i = 0; i < files.length; i++) {
input = files[i];
this.file(input.fileName, input.decompressed, {
binary: true,
optimizedBinaryString: true,
date: input.date,
dir: input.dir,
comment : input.fileComment.length ? input.fileComment : null,
unixPermissions : input.unixPermissions,
dosPermissions : input.dosPermissions,
createFolders: options.createFolders
});
}
if (zipEntries.zipComment.length) {
this.comment = zipEntries.zipComment;
}
return this;
};
},{"./base64":103,"./zipEntries":124}],113:[function(require,module,exports){
(function (Buffer){
'use strict';
module.exports = function(data, encoding){
return new Buffer(data, encoding);
};
module.exports.test = function(b){
return Buffer.isBuffer(b);
};
}).call(this,require("buffer").Buffer)
},{"buffer":75}],114:[function(require,module,exports){
'use strict';
var Uint8ArrayReader = require('./uint8ArrayReader');
function NodeBufferReader(data) {
this.data = data;
this.length = this.data.length;
this.index = 0;
}
NodeBufferReader.prototype = new Uint8ArrayReader();
/**
* @see DataReader.readData
*/
NodeBufferReader.prototype.readData = function(size) {
this.checkOffset(size);
var result = this.data.slice(this.index, this.index + size);
this.index += size;
return result;
};
module.exports = NodeBufferReader;
},{"./uint8ArrayReader":120}],115:[function(require,module,exports){
'use strict';
var support = require('./support');
var utils = require('./utils');
var crc32 = require('./crc32');
var signature = require('./signature');
var defaults = require('./defaults');
var base64 = require('./base64');
var compressions = require('./compressions');
var CompressedObject = require('./compressedObject');
var nodeBuffer = require('./nodeBuffer');
var utf8 = require('./utf8');
var StringWriter = require('./stringWriter');
var Uint8ArrayWriter = require('./uint8ArrayWriter');
/**
* Returns the raw data of a ZipObject, decompress the content if necessary.
* @param {ZipObject} file the file to use.
* @return {String|ArrayBuffer|Uint8Array|Buffer} the data.
*/
var getRawData = function(file) {
if (file._data instanceof CompressedObject) {
file._data = file._data.getContent();
file.options.binary = true;
file.options.base64 = false;
if (utils.getTypeOf(file._data) === "uint8array") {
var copy = file._data;
// when reading an arraybuffer, the CompressedObject mechanism will keep it and subarray() a Uint8Array.
// if we request a file in the same format, we might get the same Uint8Array or its ArrayBuffer (the original zip file).
file._data = new Uint8Array(copy.length);
// with an empty Uint8Array, Opera fails with a "Offset larger than array size"
if (copy.length !== 0) {
file._data.set(copy, 0);
}
}
}
return file._data;
};
/**
* Returns the data of a ZipObject in a binary form. If the content is an unicode string, encode it.
* @param {ZipObject} file the file to use.
* @return {String|ArrayBuffer|Uint8Array|Buffer} the data.
*/
var getBinaryData = function(file) {
var result = getRawData(file),
type = utils.getTypeOf(result);
if (type === "string") {
if (!file.options.binary) {
// unicode text !
// unicode string => binary string is a painful process, check if we can avoid it.
if (support.nodebuffer) {
return nodeBuffer(result, "utf-8");
}
}
return file.asBinary();
}
return result;
};
/**
* Transform this._data into a string.
* @param {function} filter a function String -> String, applied if not null on the result.
* @return {String} the string representing this._data.
*/
var dataToString = function(asUTF8) {
var result = getRawData(this);
if (result === null || typeof result === "undefined") {
return "";
}
// if the data is a base64 string, we decode it before checking the encoding !
if (this.options.base64) {
result = base64.decode(result);
}
if (asUTF8 && this.options.binary) {
// JSZip.prototype.utf8decode supports arrays as input
// skip to array => string step, utf8decode will do it.
result = out.utf8decode(result);
}
else {
// no utf8 transformation, do the array => string step.
result = utils.transformTo("string", result);
}
if (!asUTF8 && !this.options.binary) {
result = utils.transformTo("string", out.utf8encode(result));
}
return result;
};
/**
* A simple object representing a file in the zip file.
* @constructor
* @param {string} name the name of the file
* @param {String|ArrayBuffer|Uint8Array|Buffer} data the data
* @param {Object} options the options of the file
*/
var ZipObject = function(name, data, options) {
this.name = name;
this.dir = options.dir;
this.date = options.date;
this.comment = options.comment;
this.unixPermissions = options.unixPermissions;
this.dosPermissions = options.dosPermissions;
this._data = data;
this.options = options;
/*
* This object contains initial values for dir and date.
* With them, we can check if the user changed the deprecated metadata in
* `ZipObject#options` or not.
*/
this._initialMetadata = {
dir : options.dir,
date : options.date
};
};
ZipObject.prototype = {
/**
* Return the content as UTF8 string.
* @return {string} the UTF8 string.
*/
asText: function() {
return dataToString.call(this, true);
},
/**
* Returns the binary content.
* @return {string} the content as binary.
*/
asBinary: function() {
return dataToString.call(this, false);
},
/**
* Returns the content as a nodejs Buffer.
* @return {Buffer} the content as a Buffer.
*/
asNodeBuffer: function() {
var result = getBinaryData(this);
return utils.transformTo("nodebuffer", result);
},
/**
* Returns the content as an Uint8Array.
* @return {Uint8Array} the content as an Uint8Array.
*/
asUint8Array: function() {
var result = getBinaryData(this);
return utils.transformTo("uint8array", result);
},
/**
* Returns the content as an ArrayBuffer.
* @return {ArrayBuffer} the content as an ArrayBufer.
*/
asArrayBuffer: function() {
return this.asUint8Array().buffer;
}
};
/**
* Transform an integer into a string in hexadecimal.
* @private
* @param {number} dec the number to convert.
* @param {number} bytes the number of bytes to generate.
* @returns {string} the result.
*/
var decToHex = function(dec, bytes) {
var hex = "",
i;
for (i = 0; i < bytes; i++) {
hex += String.fromCharCode(dec & 0xff);
dec = dec >>> 8;
}
return hex;
};
/**
* Merge the objects passed as parameters into a new one.
* @private
* @param {...Object} var_args All objects to merge.
* @return {Object} a new object with the data of the others.
*/
var extend = function() {
var result = {}, i, attr;
for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers
for (attr in arguments[i]) {
if (arguments[i].hasOwnProperty(attr) && typeof result[attr] === "undefined") {
result[attr] = arguments[i][attr];
}
}
}
return result;
};
/**
* Transforms the (incomplete) options from the user into the complete
* set of options to create a file.
* @private
* @param {Object} o the options from the user.
* @return {Object} the complete set of options.
*/
var prepareFileAttrs = function(o) {
o = o || {};
if (o.base64 === true && (o.binary === null || o.binary === undefined)) {
o.binary = true;
}
o = extend(o, defaults);
o.date = o.date || new Date();
if (o.compression !== null) o.compression = o.compression.toUpperCase();
return o;
};
/**
* Add a file in the current folder.
* @private
* @param {string} name the name of the file
* @param {String|ArrayBuffer|Uint8Array|Buffer} data the data of the file
* @param {Object} o the options of the file
* @return {Object} the new file.
*/
var fileAdd = function(name, data, o) {
// be sure sub folders exist
var dataType = utils.getTypeOf(data),
parent;
o = prepareFileAttrs(o);
if (typeof o.unixPermissions === "string") {
o.unixPermissions = parseInt(o.unixPermissions, 8);
}
// UNX_IFDIR 0040000 see zipinfo.c
if (o.unixPermissions && (o.unixPermissions & 0x4000)) {
o.dir = true;
}
// Bit 4 Directory
if (o.dosPermissions && (o.dosPermissions & 0x0010)) {
o.dir = true;
}
if (o.dir) {
name = forceTrailingSlash(name);
}
if (o.createFolders && (parent = parentFolder(name))) {
folderAdd.call(this, parent, true);
}
if (o.dir || data === null || typeof data === "undefined") {
o.base64 = false;
o.binary = false;
data = null;
dataType = null;
}
else if (dataType === "string") {
if (o.binary && !o.base64) {
// optimizedBinaryString == true means that the file has already been filtered with a 0xFF mask
if (o.optimizedBinaryString !== true) {
// this is a string, not in a base64 format.
// Be sure that this is a correct "binary string"
data = utils.string2binary(data);
}
}
}
else { // arraybuffer, uint8array, ...
o.base64 = false;
o.binary = true;
if (!dataType && !(data instanceof CompressedObject)) {
throw new Error("The data of '" + name + "' is in an unsupported format !");
}
// special case : it's way easier to work with Uint8Array than with ArrayBuffer
if (dataType === "arraybuffer") {
data = utils.transformTo("uint8array", data);
}
}
var object = new ZipObject(name, data, o);
this.files[name] = object;
return object;
};
/**
* Find the parent folder of the path.
* @private
* @param {string} path the path to use
* @return {string} the parent folder, or ""
*/
var parentFolder = function (path) {
if (path.slice(-1) == '/') {
path = path.substring(0, path.length - 1);
}
var lastSlash = path.lastIndexOf('/');
return (lastSlash > 0) ? path.substring(0, lastSlash) : "";
};
/**
* Returns the path with a slash at the end.
* @private
* @param {String} path the path to check.
* @return {String} the path with a trailing slash.
*/
var forceTrailingSlash = function(path) {
// Check the name ends with a /
if (path.slice(-1) != "/") {
path += "/"; // IE doesn't like substr(-1)
}
return path;
};
/**
* Add a (sub) folder in the current folder.
* @private
* @param {string} name the folder's name
* @param {boolean=} [createFolders] If true, automatically create sub
* folders. Defaults to false.
* @return {Object} the new folder.
*/
var folderAdd = function(name, createFolders) {
createFolders = (typeof createFolders !== 'undefined') ? createFolders : false;
name = forceTrailingSlash(name);
// Does this folder already exist?
if (!this.files[name]) {
fileAdd.call(this, name, null, {
dir: true,
createFolders: createFolders
});
}
return this.files[name];
};
/**
* Generate a JSZip.CompressedObject for a given zipOject.
* @param {ZipObject} file the object to read.
* @param {JSZip.compression} compression the compression to use.
* @param {Object} compressionOptions the options to use when compressing.
* @return {JSZip.CompressedObject} the compressed result.
*/
var generateCompressedObjectFrom = function(file, compression, compressionOptions) {
var result = new CompressedObject(),
content;
// the data has not been decompressed, we might reuse things !
if (file._data instanceof CompressedObject) {
result.uncompressedSize = file._data.uncompressedSize;
result.crc32 = file._data.crc32;
if (result.uncompressedSize === 0 || file.dir) {
compression = compressions['STORE'];
result.compressedContent = "";
result.crc32 = 0;
}
else if (file._data.compressionMethod === compression.magic) {
result.compressedContent = file._data.getCompressedContent();
}
else {
content = file._data.getContent();
// need to decompress / recompress
result.compressedContent = compression.compress(utils.transformTo(compression.compressInputType, content), compressionOptions);
}
}
else {
// have uncompressed data
content = getBinaryData(file);
if (!content || content.length === 0 || file.dir) {
compression = compressions['STORE'];
content = "";
}
result.uncompressedSize = content.length;
result.crc32 = crc32(content);
result.compressedContent = compression.compress(utils.transformTo(compression.compressInputType, content), compressionOptions);
}
result.compressedSize = result.compressedContent.length;
result.compressionMethod = compression.magic;
return result;
};
/**
* Generate the UNIX part of the external file attributes.
* @param {Object} unixPermissions the unix permissions or null.
* @param {Boolean} isDir true if the entry is a directory, false otherwise.
* @return {Number} a 32 bit integer.
*
* adapted from http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute :
*
* TTTTsstrwxrwxrwx0000000000ADVSHR
* ^^^^____________________________ file type, see zipinfo.c (UNX_*)
* ^^^_________________________ setuid, setgid, sticky
* ^^^^^^^^^________________ permissions
* ^^^^^^^^^^______ not used ?
* ^^^^^^ DOS attribute bits : Archive, Directory, Volume label, System file, Hidden, Read only
*/
var generateUnixExternalFileAttr = function (unixPermissions, isDir) {
var result = unixPermissions;
if (!unixPermissions) {
// I can't use octal values in strict mode, hence the hexa.
// 040775 => 0x41fd
// 0100664 => 0x81b4
result = isDir ? 0x41fd : 0x81b4;
}
return (result & 0xFFFF) << 16;
};
/**
* Generate the DOS part of the external file attributes.
* @param {Object} dosPermissions the dos permissions or null.
* @param {Boolean} isDir true if the entry is a directory, false otherwise.
* @return {Number} a 32 bit integer.
*
* Bit 0 Read-Only
* Bit 1 Hidden
* Bit 2 System
* Bit 3 Volume Label
* Bit 4 Directory
* Bit 5 Archive
*/
var generateDosExternalFileAttr = function (dosPermissions, isDir) {
// the dir flag is already set for compatibility
return (dosPermissions || 0) & 0x3F;
};
/**
* Generate the various parts used in the construction of the final zip file.
* @param {string} name the file name.
* @param {ZipObject} file the file content.
* @param {JSZip.CompressedObject} compressedObject the compressed object.
* @param {number} offset the current offset from the start of the zip file.
* @param {String} platform let's pretend we are this platform (change platform dependents fields)
* @return {object} the zip parts.
*/
var generateZipParts = function(name, file, compressedObject, offset, platform) {
var data = compressedObject.compressedContent,
utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)),
comment = file.comment || "",
utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)),
useUTF8ForFileName = utfEncodedFileName.length !== file.name.length,
useUTF8ForComment = utfEncodedComment.length !== comment.length,
o = file.options,
dosTime,
dosDate,
extraFields = "",
unicodePathExtraField = "",
unicodeCommentExtraField = "",
dir, date;
// handle the deprecated options.dir
if (file._initialMetadata.dir !== file.dir) {
dir = file.dir;
} else {
dir = o.dir;
}
// handle the deprecated options.date
if(file._initialMetadata.date !== file.date) {
date = file.date;
} else {
date = o.date;
}
var extFileAttr = 0;
var versionMadeBy = 0;
if (dir) {
// dos or unix, we set the dos dir flag
extFileAttr |= 0x00010;
}
if(platform === "UNIX") {
versionMadeBy = 0x031E; // UNIX, version 3.0
extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir);
} else { // DOS or other, fallback to DOS
versionMadeBy = 0x0014; // DOS, version 2.0
extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir);
}
// date
// @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html
// @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html
// @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html
dosTime = date.getHours();
dosTime = dosTime << 6;
dosTime = dosTime | date.getMinutes();
dosTime = dosTime << 5;
dosTime = dosTime | date.getSeconds() / 2;
dosDate = date.getFullYear() - 1980;
dosDate = dosDate << 4;
dosDate = dosDate | (date.getMonth() + 1);
dosDate = dosDate << 5;
dosDate = dosDate | date.getDate();
if (useUTF8ForFileName) {
// set the unicode path extra field. unzip needs at least one extra
// field to correctly handle unicode path, so using the path is as good
// as any other information. This could improve the situation with
// other archive managers too.
// This field is usually used without the utf8 flag, with a non
// unicode path in the header (winrar, winzip). This helps (a bit)
// with the messy Windows' default compressed folders feature but
// breaks on p7zip which doesn't seek the unicode path extra field.
// So for now, UTF-8 everywhere !
unicodePathExtraField =
// Version
decToHex(1, 1) +
// NameCRC32
decToHex(crc32(utfEncodedFileName), 4) +
// UnicodeName
utfEncodedFileName;
extraFields +=
// Info-ZIP Unicode Path Extra Field
"\x75\x70" +
// size
decToHex(unicodePathExtraField.length, 2) +
// content
unicodePathExtraField;
}
if(useUTF8ForComment) {
unicodeCommentExtraField =
// Version
decToHex(1, 1) +
// CommentCRC32
decToHex(this.crc32(utfEncodedComment), 4) +
// UnicodeName
utfEncodedComment;
extraFields +=
// Info-ZIP Unicode Path Extra Field
"\x75\x63" +
// size
decToHex(unicodeCommentExtraField.length, 2) +
// content
unicodeCommentExtraField;
}
var header = "";
// version needed to extract
header += "\x0A\x00";
// general purpose bit flag
// set bit 11 if utf8
header += (useUTF8ForFileName || useUTF8ForComment) ? "\x00\x08" : "\x00\x00";
// compression method
header += compressedObject.compressionMethod;
// last mod file time
header += decToHex(dosTime, 2);
// last mod file date
header += decToHex(dosDate, 2);
// crc-32
header += decToHex(compressedObject.crc32, 4);
// compressed size
header += decToHex(compressedObject.compressedSize, 4);
// uncompressed size
header += decToHex(compressedObject.uncompressedSize, 4);
// file name length
header += decToHex(utfEncodedFileName.length, 2);
// extra field length
header += decToHex(extraFields.length, 2);
var fileRecord = signature.LOCAL_FILE_HEADER + header + utfEncodedFileName + extraFields;
var dirRecord = signature.CENTRAL_FILE_HEADER +
// version made by (00: DOS)
decToHex(versionMadeBy, 2) +
// file header (common to file and central directory)
header +
// file comment length
decToHex(utfEncodedComment.length, 2) +
// disk number start
"\x00\x00" +
// internal file attributes TODO
"\x00\x00" +
// external file attributes
decToHex(extFileAttr, 4) +
// relative offset of local header
decToHex(offset, 4) +
// file name
utfEncodedFileName +
// extra field
extraFields +
// file comment
utfEncodedComment;
return {
fileRecord: fileRecord,
dirRecord: dirRecord,
compressedObject: compressedObject
};
};
// return the actual prototype of JSZip
var out = {
/**
* Read an existing zip and merge the data in the current JSZip object.
* The implementation is in jszip-load.js, don't forget to include it.
* @param {String|ArrayBuffer|Uint8Array|Buffer} stream The stream to load
* @param {Object} options Options for loading the stream.
* options.base64 : is the stream in base64 ? default : false
* @return {JSZip} the current JSZip object
*/
load: function(stream, options) {
throw new Error("Load method is not defined. Is the file jszip-load.js included ?");
},
/**
* Filter nested files/folders with the specified function.
* @param {Function} search the predicate to use :
* function (relativePath, file) {...}
* It takes 2 arguments : the relative path and the file.
* @return {Array} An array of matching elements.
*/
filter: function(search) {
var result = [],
filename, relativePath, file, fileClone;
for (filename in this.files) {
if (!this.files.hasOwnProperty(filename)) {
continue;
}
file = this.files[filename];
// return a new object, don't let the user mess with our internal objects :)
fileClone = new ZipObject(file.name, file._data, extend(file.options));
relativePath = filename.slice(this.root.length, filename.length);
if (filename.slice(0, this.root.length) === this.root && // the file is in the current root
search(relativePath, fileClone)) { // and the file matches the function
result.push(fileClone);
}
}
return result;
},
/**
* Add a file to the zip file, or search a file.
* @param {string|RegExp} name The name of the file to add (if data is defined),
* the name of the file to find (if no data) or a regex to match files.
* @param {String|ArrayBuffer|Uint8Array|Buffer} data The file data, either raw or base64 encoded
* @param {Object} o File options
* @return {JSZip|Object|Array} this JSZip object (when adding a file),
* a file (when searching by string) or an array of files (when searching by regex).
*/
file: function(name, data, o) {
if (arguments.length === 1) {
if (utils.isRegExp(name)) {
var regexp = name;
return this.filter(function(relativePath, file) {
return !file.dir && regexp.test(relativePath);
});
}
else { // text
return this.filter(function(relativePath, file) {
return !file.dir && relativePath === name;
})[0] || null;
}
}
else { // more than one argument : we have data !
name = this.root + name;
fileAdd.call(this, name, data, o);
}
return this;
},
/**
* Add a directory to the zip file, or search.
* @param {String|RegExp} arg The name of the directory to add, or a regex to search folders.
* @return {JSZip} an object with the new directory as the root, or an array containing matching folders.
*/
folder: function(arg) {
if (!arg) {
return this;
}
if (utils.isRegExp(arg)) {
return this.filter(function(relativePath, file) {
return file.dir && arg.test(relativePath);
});
}
// else, name is a new folder
var name = this.root + arg;
var newFolder = folderAdd.call(this, name);
// Allow chaining by returning a new object with this folder as the root
var ret = this.clone();
ret.root = newFolder.name;
return ret;
},
/**
* Delete a file, or a directory and all sub-files, from the zip
* @param {string} name the name of the file to delete
* @return {JSZip} this JSZip object
*/
remove: function(name) {
name = this.root + name;
var file = this.files[name];
if (!file) {
// Look for any folders
if (name.slice(-1) != "/") {
name += "/";
}
file = this.files[name];
}
if (file && !file.dir) {
// file
delete this.files[name];
} else {
// maybe a folder, delete recursively
var kids = this.filter(function(relativePath, file) {
return file.name.slice(0, name.length) === name;
});
for (var i = 0; i < kids.length; i++) {
delete this.files[kids[i].name];
}
}
return this;
},
/**
* Generate the complete zip file
* @param {Object} options the options to generate the zip file :
* - base64, (deprecated, use type instead) true to generate base64.
* - compression, "STORE" by default.
* - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
* @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the zip file
*/
generate: function(options) {
options = extend(options || {}, {
base64: true,
compression: "STORE",
compressionOptions : null,
type: "base64",
platform: "DOS",
comment: null,
mimeType: 'application/zip'
});
utils.checkSupport(options.type);
// accept nodejs `process.platform`
if(
options.platform === 'darwin' ||
options.platform === 'freebsd' ||
options.platform === 'linux' ||
options.platform === 'sunos'
) {
options.platform = "UNIX";
}
if (options.platform === 'win32') {
options.platform = "DOS";
}
var zipData = [],
localDirLength = 0,
centralDirLength = 0,
writer, i,
utfEncodedComment = utils.transformTo("string", this.utf8encode(options.comment || this.comment || ""));
// first, generate all the zip parts.
for (var name in this.files) {
if (!this.files.hasOwnProperty(name)) {
continue;
}
var file = this.files[name];
var compressionName = file.options.compression || options.compression.toUpperCase();
var compression = compressions[compressionName];
if (!compression) {
throw new Error(compressionName + " is not a valid compression method !");
}
var compressionOptions = file.options.compressionOptions || options.compressionOptions || {};
var compressedObject = generateCompressedObjectFrom.call(this, file, compression, compressionOptions);
var zipPart = generateZipParts.call(this, name, file, compressedObject, localDirLength, options.platform);
localDirLength += zipPart.fileRecord.length + compressedObject.compressedSize;
centralDirLength += zipPart.dirRecord.length;
zipData.push(zipPart);
}
var dirEnd = "";
// end of central dir signature
dirEnd = signature.CENTRAL_DIRECTORY_END +
// number of this disk
"\x00\x00" +
// number of the disk with the start of the central directory
"\x00\x00" +
// total number of entries in the central directory on this disk
decToHex(zipData.length, 2) +
// total number of entries in the central directory
decToHex(zipData.length, 2) +
// size of the central directory 4 bytes
decToHex(centralDirLength, 4) +
// offset of start of central directory with respect to the starting disk number
decToHex(localDirLength, 4) +
// .ZIP file comment length
decToHex(utfEncodedComment.length, 2) +
// .ZIP file comment
utfEncodedComment;
// we have all the parts (and the total length)
// time to create a writer !
var typeName = options.type.toLowerCase();
if(typeName==="uint8array"||typeName==="arraybuffer"||typeName==="blob"||typeName==="nodebuffer") {
writer = new Uint8ArrayWriter(localDirLength + centralDirLength + dirEnd.length);
}else{
writer = new StringWriter(localDirLength + centralDirLength + dirEnd.length);
}
for (i = 0; i < zipData.length; i++) {
writer.append(zipData[i].fileRecord);
writer.append(zipData[i].compressedObject.compressedContent);
}
for (i = 0; i < zipData.length; i++) {
writer.append(zipData[i].dirRecord);
}
writer.append(dirEnd);
var zip = writer.finalize();
switch(options.type.toLowerCase()) {
// case "zip is an Uint8Array"
case "uint8array" :
case "arraybuffer" :
case "nodebuffer" :
return utils.transformTo(options.type.toLowerCase(), zip);
case "blob" :
return utils.arrayBuffer2Blob(utils.transformTo("arraybuffer", zip), options.mimeType);
// case "zip is a string"
case "base64" :
return (options.base64) ? base64.encode(zip) : zip;
default : // case "string" :
return zip;
}
},
/**
* @deprecated
* This method will be removed in a future version without replacement.
*/
crc32: function (input, crc) {
return crc32(input, crc);
},
/**
* @deprecated
* This method will be removed in a future version without replacement.
*/
utf8encode: function (string) {
return utils.transformTo("string", utf8.utf8encode(string));
},
/**
* @deprecated
* This method will be removed in a future version without replacement.
*/
utf8decode: function (input) {
return utf8.utf8decode(input);
}
};
module.exports = out;
},{"./base64":103,"./compressedObject":104,"./compressions":105,"./crc32":106,"./defaults":108,"./nodeBuffer":113,"./signature":116,"./stringWriter":118,"./support":119,"./uint8ArrayWriter":121,"./utf8":122,"./utils":123}],116:[function(require,module,exports){
'use strict';
exports.LOCAL_FILE_HEADER = "PK\x03\x04";
exports.CENTRAL_FILE_HEADER = "PK\x01\x02";
exports.CENTRAL_DIRECTORY_END = "PK\x05\x06";
exports.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x06\x07";
exports.ZIP64_CENTRAL_DIRECTORY_END = "PK\x06\x06";
exports.DATA_DESCRIPTOR = "PK\x07\x08";
},{}],117:[function(require,module,exports){
'use strict';
var DataReader = require('./dataReader');
var utils = require('./utils');
function StringReader(data, optimizedBinaryString) {
this.data = data;
if (!optimizedBinaryString) {
this.data = utils.string2binary(this.data);
}
this.length = this.data.length;
this.index = 0;
}
StringReader.prototype = new DataReader();
/**
* @see DataReader.byteAt
*/
StringReader.prototype.byteAt = function(i) {
return this.data.charCodeAt(i);
};
/**
* @see DataReader.lastIndexOfSignature
*/
StringReader.prototype.lastIndexOfSignature = function(sig) {
return this.data.lastIndexOf(sig);
};
/**
* @see DataReader.readData
*/
StringReader.prototype.readData = function(size) {
this.checkOffset(size);
// this will work because the constructor applied the "& 0xff" mask.
var result = this.data.slice(this.index, this.index + size);
this.index += size;
return result;
};
module.exports = StringReader;
},{"./dataReader":107,"./utils":123}],118:[function(require,module,exports){
'use strict';
var utils = require('./utils');
/**
* An object to write any content to a string.
* @constructor
*/
var StringWriter = function() {
this.data = [];
};
StringWriter.prototype = {
/**
* Append any content to the current string.
* @param {Object} input the content to add.
*/
append: function(input) {
input = utils.transformTo("string", input);
this.data.push(input);
},
/**
* Finalize the construction an return the result.
* @return {string} the generated string.
*/
finalize: function() {
return this.data.join("");
}
};
module.exports = StringWriter;
},{"./utils":123}],119:[function(require,module,exports){
(function (Buffer){
'use strict';
exports.base64 = true;
exports.array = true;
exports.string = true;
exports.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined";
// contains true if JSZip can read/generate nodejs Buffer, false otherwise.
// Browserify will provide a Buffer implementation for browsers, which is
// an augmented Uint8Array (i.e., can be used as either Buffer or U8).
exports.nodebuffer = typeof Buffer !== "undefined";
// contains true if JSZip can read/generate Uint8Array, false otherwise.
exports.uint8array = typeof Uint8Array !== "undefined";
if (typeof ArrayBuffer === "undefined") {
exports.blob = false;
}
else {
var buffer = new ArrayBuffer(0);
try {
exports.blob = new Blob([buffer], {
type: "application/zip"
}).size === 0;
}
catch (e) {
try {
var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
var builder = new Builder();
builder.append(buffer);
exports.blob = builder.getBlob('application/zip').size === 0;
}
catch (e) {
exports.blob = false;
}
}
}
}).call(this,require("buffer").Buffer)
},{"buffer":75}],120:[function(require,module,exports){
'use strict';
var DataReader = require('./dataReader');
function Uint8ArrayReader(data) {
if (data) {
this.data = data;
this.length = this.data.length;
this.index = 0;
}
}
Uint8ArrayReader.prototype = new DataReader();
/**
* @see DataReader.byteAt
*/
Uint8ArrayReader.prototype.byteAt = function(i) {
return this.data[i];
};
/**
* @see DataReader.lastIndexOfSignature
*/
Uint8ArrayReader.prototype.lastIndexOfSignature = function(sig) {
var sig0 = sig.charCodeAt(0),
sig1 = sig.charCodeAt(1),
sig2 = sig.charCodeAt(2),
sig3 = sig.charCodeAt(3);
for (var i = this.length - 4; i >= 0; --i) {
if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) {
return i;
}
}
return -1;
};
/**
* @see DataReader.readData
*/
Uint8ArrayReader.prototype.readData = function(size) {
this.checkOffset(size);
if(size === 0) {
// in IE10, when using subarray(idx, idx), we get the array [0x00] instead of [].
return new Uint8Array(0);
}
var result = this.data.subarray(this.index, this.index + size);
this.index += size;
return result;
};
module.exports = Uint8ArrayReader;
},{"./dataReader":107}],121:[function(require,module,exports){
'use strict';
var utils = require('./utils');
/**
* An object to write any content to an Uint8Array.
* @constructor
* @param {number} length The length of the array.
*/
var Uint8ArrayWriter = function(length) {
this.data = new Uint8Array(length);
this.index = 0;
};
Uint8ArrayWriter.prototype = {
/**
* Append any content to the current array.
* @param {Object} input the content to add.
*/
append: function(input) {
if (input.length !== 0) {
// with an empty Uint8Array, Opera fails with a "Offset larger than array size"
input = utils.transformTo("uint8array", input);
this.data.set(input, this.index);
this.index += input.length;
}
},
/**
* Finalize the construction an return the result.
* @return {Uint8Array} the generated array.
*/
finalize: function() {
return this.data;
}
};
module.exports = Uint8ArrayWriter;
},{"./utils":123}],122:[function(require,module,exports){
'use strict';
var utils = require('./utils');
var support = require('./support');
var nodeBuffer = require('./nodeBuffer');
/**
* The following functions come from pako, from pako/lib/utils/strings
* released under the MIT license, see pako https://github.com/nodeca/pako/
*/
// Table with utf8 lengths (calculated by first byte of sequence)
// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
// because max possible codepoint is 0x10ffff
var _utf8len = new Array(256);
for (var i=0; i<256; i++) {
_utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
}
_utf8len[254]=_utf8len[254]=1; // Invalid sequence start
// convert string to array (typed, when possible)
var string2buf = function (str) {
var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
// count binary size
for (m_pos = 0; m_pos < str_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
c2 = str.charCodeAt(m_pos+1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
m_pos++;
}
}
buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
}
// allocate buffer
if (support.uint8array) {
buf = new Uint8Array(buf_len);
} else {
buf = new Array(buf_len);
}
// convert
for (i=0, m_pos = 0; i < buf_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
c2 = str.charCodeAt(m_pos+1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
m_pos++;
}
}
if (c < 0x80) {
/* one byte */
buf[i++] = c;
} else if (c < 0x800) {
/* two bytes */
buf[i++] = 0xC0 | (c >>> 6);
buf[i++] = 0x80 | (c & 0x3f);
} else if (c < 0x10000) {
/* three bytes */
buf[i++] = 0xE0 | (c >>> 12);
buf[i++] = 0x80 | (c >>> 6 & 0x3f);
buf[i++] = 0x80 | (c & 0x3f);
} else {
/* four bytes */
buf[i++] = 0xf0 | (c >>> 18);
buf[i++] = 0x80 | (c >>> 12 & 0x3f);
buf[i++] = 0x80 | (c >>> 6 & 0x3f);
buf[i++] = 0x80 | (c & 0x3f);
}
}
return buf;
};
// Calculate max possible position in utf8 buffer,
// that will not break sequence. If that's not possible
// - (very small limits) return max size as is.
//
// buf[] - utf8 bytes array
// max - length limit (mandatory);
var utf8border = function(buf, max) {
var pos;
max = max || buf.length;
if (max > buf.length) { max = buf.length; }
// go back from last position, until start of sequence found
pos = max-1;
while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
// Fuckup - very small and broken sequence,
// return max, because we should return something anyway.
if (pos < 0) { return max; }
// If we came to start of buffer - that means vuffer is too small,
// return max too.
if (pos === 0) { return max; }
return (pos + _utf8len[buf[pos]] > max) ? pos : max;
};
// convert array to string
var buf2string = function (buf) {
var str, i, out, c, c_len;
var len = buf.length;
// Reserve max possible length (2 words per char)
// NB: by unknown reasons, Array is significantly faster for
// String.fromCharCode.apply than Uint16Array.
var utf16buf = new Array(len*2);
for (out=0, i=0; i<len;) {
c = buf[i++];
// quick process ascii
if (c < 0x80) { utf16buf[out++] = c; continue; }
c_len = _utf8len[c];
// skip 5 & 6 byte codes
if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
// apply mask on first byte
c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
// join the rest
while (c_len > 1 && i < len) {
c = (c << 6) | (buf[i++] & 0x3f);
c_len--;
}
// terminated by end of string?
if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
if (c < 0x10000) {
utf16buf[out++] = c;
} else {
c -= 0x10000;
utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
utf16buf[out++] = 0xdc00 | (c & 0x3ff);
}
}
// shrinkBuf(utf16buf, out)
if (utf16buf.length !== out) {
if(utf16buf.subarray) {
utf16buf = utf16buf.subarray(0, out);
} else {
utf16buf.length = out;
}
}
// return String.fromCharCode.apply(null, utf16buf);
return utils.applyFromCharCode(utf16buf);
};
// That's all for the pako functions.
/**
* Transform a javascript string into an array (typed if possible) of bytes,
* UTF-8 encoded.
* @param {String} str the string to encode
* @return {Array|Uint8Array|Buffer} the UTF-8 encoded string.
*/
exports.utf8encode = function utf8encode(str) {
if (support.nodebuffer) {
return nodeBuffer(str, "utf-8");
}
return string2buf(str);
};
/**
* Transform a bytes array (or a representation) representing an UTF-8 encoded
* string into a javascript string.
* @param {Array|Uint8Array|Buffer} buf the data de decode
* @return {String} the decoded string.
*/
exports.utf8decode = function utf8decode(buf) {
if (support.nodebuffer) {
return utils.transformTo("nodebuffer", buf).toString("utf-8");
}
buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf);
// return buf2string(buf);
// Chrome prefers to work with "small" chunks of data
// for the method buf2string.
// Firefox and Chrome has their own shortcut, IE doesn't seem to really care.
var result = [], k = 0, len = buf.length, chunk = 65536;
while (k < len) {
var nextBoundary = utf8border(buf, Math.min(k + chunk, len));
if (support.uint8array) {
result.push(buf2string(buf.subarray(k, nextBoundary)));
} else {
result.push(buf2string(buf.slice(k, nextBoundary)));
}
k = nextBoundary;
}
return result.join("");
};
// vim: set shiftwidth=4 softtabstop=4:
},{"./nodeBuffer":113,"./support":119,"./utils":123}],123:[function(require,module,exports){
'use strict';
var support = require('./support');
var compressions = require('./compressions');
var nodeBuffer = require('./nodeBuffer');
/**
* Convert a string to a "binary string" : a string containing only char codes between 0 and 255.
* @param {string} str the string to transform.
* @return {String} the binary string.
*/
exports.string2binary = function(str) {
var result = "";
for (var i = 0; i < str.length; i++) {
result += String.fromCharCode(str.charCodeAt(i) & 0xff);
}
return result;
};
exports.arrayBuffer2Blob = function(buffer, mimeType) {
exports.checkSupport("blob");
mimeType = mimeType || 'application/zip';
try {
// Blob constructor
return new Blob([buffer], {
type: mimeType
});
}
catch (e) {
try {
// deprecated, browser only, old way
var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
var builder = new Builder();
builder.append(buffer);
return builder.getBlob(mimeType);
}
catch (e) {
// well, fuck ?!
throw new Error("Bug : can't construct the Blob.");
}
}
};
/**
* The identity function.
* @param {Object} input the input.
* @return {Object} the same input.
*/
function identity(input) {
return input;
}
/**
* Fill in an array with a string.
* @param {String} str the string to use.
* @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated).
* @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array.
*/
function stringToArrayLike(str, array) {
for (var i = 0; i < str.length; ++i) {
array[i] = str.charCodeAt(i) & 0xFF;
}
return array;
}
/**
* Transform an array-like object to a string.
* @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
* @return {String} the result.
*/
function arrayLikeToString(array) {
// Performances notes :
// --------------------
// String.fromCharCode.apply(null, array) is the fastest, see
// see http://jsperf.com/converting-a-uint8array-to-a-string/2
// but the stack is limited (and we can get huge arrays !).
//
// result += String.fromCharCode(array[i]); generate too many strings !
//
// This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2
var chunk = 65536;
var result = [],
len = array.length,
type = exports.getTypeOf(array),
k = 0,
canUseApply = true;
try {
switch(type) {
case "uint8array":
String.fromCharCode.apply(null, new Uint8Array(0));
break;
case "nodebuffer":
String.fromCharCode.apply(null, nodeBuffer(0));
break;
}
} catch(e) {
canUseApply = false;
}
// no apply : slow and painful algorithm
// default browser on android 4.*
if (!canUseApply) {
var resultStr = "";
for(var i = 0; i < array.length;i++) {
resultStr += String.fromCharCode(array[i]);
}
return resultStr;
}
while (k < len && chunk > 1) {
try {
if (type === "array" || type === "nodebuffer") {
result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len))));
}
else {
result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len))));
}
k += chunk;
}
catch (e) {
chunk = Math.floor(chunk / 2);
}
}
return result.join("");
}
exports.applyFromCharCode = arrayLikeToString;
/**
* Copy the data from an array-like to an other array-like.
* @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array.
* @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated.
* @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array.
*/
function arrayLikeToArrayLike(arrayFrom, arrayTo) {
for (var i = 0; i < arrayFrom.length; i++) {
arrayTo[i] = arrayFrom[i];
}
return arrayTo;
}
// a matrix containing functions to transform everything into everything.
var transform = {};
// string to ?
transform["string"] = {
"string": identity,
"array": function(input) {
return stringToArrayLike(input, new Array(input.length));
},
"arraybuffer": function(input) {
return transform["string"]["uint8array"](input).buffer;
},
"uint8array": function(input) {
return stringToArrayLike(input, new Uint8Array(input.length));
},
"nodebuffer": function(input) {
return stringToArrayLike(input, nodeBuffer(input.length));
}
};
// array to ?
transform["array"] = {
"string": arrayLikeToString,
"array": identity,
"arraybuffer": function(input) {
return (new Uint8Array(input)).buffer;
},
"uint8array": function(input) {
return new Uint8Array(input);
},
"nodebuffer": function(input) {
return nodeBuffer(input);
}
};
// arraybuffer to ?
transform["arraybuffer"] = {
"string": function(input) {
return arrayLikeToString(new Uint8Array(input));
},
"array": function(input) {
return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength));
},
"arraybuffer": identity,
"uint8array": function(input) {
return new Uint8Array(input);
},
"nodebuffer": function(input) {
return nodeBuffer(new Uint8Array(input));
}
};
// uint8array to ?
transform["uint8array"] = {
"string": arrayLikeToString,
"array": function(input) {
return arrayLikeToArrayLike(input, new Array(input.length));
},
"arraybuffer": function(input) {
return input.buffer;
},
"uint8array": identity,
"nodebuffer": function(input) {
return nodeBuffer(input);
}
};
// nodebuffer to ?
transform["nodebuffer"] = {
"string": arrayLikeToString,
"array": function(input) {
return arrayLikeToArrayLike(input, new Array(input.length));
},
"arraybuffer": function(input) {
return transform["nodebuffer"]["uint8array"](input).buffer;
},
"uint8array": function(input) {
return arrayLikeToArrayLike(input, new Uint8Array(input.length));
},
"nodebuffer": identity
};
/**
* Transform an input into any type.
* The supported output type are : string, array, uint8array, arraybuffer, nodebuffer.
* If no output type is specified, the unmodified input will be returned.
* @param {String} outputType the output type.
* @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert.
* @throws {Error} an Error if the browser doesn't support the requested output type.
*/
exports.transformTo = function(outputType, input) {
if (!input) {
// undefined, null, etc
// an empty string won't harm.
input = "";
}
if (!outputType) {
return input;
}
exports.checkSupport(outputType);
var inputType = exports.getTypeOf(input);
var result = transform[inputType][outputType](input);
return result;
};
/**
* Return the type of the input.
* The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer.
* @param {Object} input the input to identify.
* @return {String} the (lowercase) type of the input.
*/
exports.getTypeOf = function(input) {
if (typeof input === "string") {
return "string";
}
if (Object.prototype.toString.call(input) === "[object Array]") {
return "array";
}
if (support.nodebuffer && nodeBuffer.test(input)) {
return "nodebuffer";
}
if (support.uint8array && input instanceof Uint8Array) {
return "uint8array";
}
if (support.arraybuffer && input instanceof ArrayBuffer) {
return "arraybuffer";
}
};
/**
* Throw an exception if the type is not supported.
* @param {String} type the type to check.
* @throws {Error} an Error if the browser doesn't support the requested type.
*/
exports.checkSupport = function(type) {
var supported = support[type.toLowerCase()];
if (!supported) {
throw new Error(type + " is not supported by this browser");
}
};
exports.MAX_VALUE_16BITS = 65535;
exports.MAX_VALUE_32BITS = -1; // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1
/**
* Prettify a string read as binary.
* @param {string} str the string to prettify.
* @return {string} a pretty string.
*/
exports.pretty = function(str) {
var res = '',
code, i;
for (i = 0; i < (str || "").length; i++) {
code = str.charCodeAt(i);
res += '\\x' + (code < 16 ? "0" : "") + code.toString(16).toUpperCase();
}
return res;
};
/**
* Find a compression registered in JSZip.
* @param {string} compressionMethod the method magic to find.
* @return {Object|null} the JSZip compression object, null if none found.
*/
exports.findCompression = function(compressionMethod) {
for (var method in compressions) {
if (!compressions.hasOwnProperty(method)) {
continue;
}
if (compressions[method].magic === compressionMethod) {
return compressions[method];
}
}
return null;
};
/**
* Cross-window, cross-Node-context regular expression detection
* @param {Object} object Anything
* @return {Boolean} true if the object is a regular expression,
* false otherwise
*/
exports.isRegExp = function (object) {
return Object.prototype.toString.call(object) === "[object RegExp]";
};
},{"./compressions":105,"./nodeBuffer":113,"./support":119}],124:[function(require,module,exports){
'use strict';
var StringReader = require('./stringReader');
var NodeBufferReader = require('./nodeBufferReader');
var Uint8ArrayReader = require('./uint8ArrayReader');
var utils = require('./utils');
var sig = require('./signature');
var ZipEntry = require('./zipEntry');
var support = require('./support');
var jszipProto = require('./object');
// class ZipEntries {{{
/**
* All the entries in the zip file.
* @constructor
* @param {String|ArrayBuffer|Uint8Array} data the binary stream to load.
* @param {Object} loadOptions Options for loading the stream.
*/
function ZipEntries(data, loadOptions) {
this.files = [];
this.loadOptions = loadOptions;
if (data) {
this.load(data);
}
}
ZipEntries.prototype = {
/**
* Check that the reader is on the speficied signature.
* @param {string} expectedSignature the expected signature.
* @throws {Error} if it is an other signature.
*/
checkSignature: function(expectedSignature) {
var signature = this.reader.readString(4);
if (signature !== expectedSignature) {
throw new Error("Corrupted zip or bug : unexpected signature " + "(" + utils.pretty(signature) + ", expected " + utils.pretty(expectedSignature) + ")");
}
},
/**
* Read the end of the central directory.
*/
readBlockEndOfCentral: function() {
this.diskNumber = this.reader.readInt(2);
this.diskWithCentralDirStart = this.reader.readInt(2);
this.centralDirRecordsOnThisDisk = this.reader.readInt(2);
this.centralDirRecords = this.reader.readInt(2);
this.centralDirSize = this.reader.readInt(4);
this.centralDirOffset = this.reader.readInt(4);
this.zipCommentLength = this.reader.readInt(2);
// warning : the encoding depends of the system locale
// On a linux machine with LANG=en_US.utf8, this field is utf8 encoded.
// On a windows machine, this field is encoded with the localized windows code page.
this.zipComment = this.reader.readString(this.zipCommentLength);
// To get consistent behavior with the generation part, we will assume that
// this is utf8 encoded.
this.zipComment = jszipProto.utf8decode(this.zipComment);
},
/**
* Read the end of the Zip 64 central directory.
* Not merged with the method readEndOfCentral :
* The end of central can coexist with its Zip64 brother,
* I don't want to read the wrong number of bytes !
*/
readBlockZip64EndOfCentral: function() {
this.zip64EndOfCentralSize = this.reader.readInt(8);
this.versionMadeBy = this.reader.readString(2);
this.versionNeeded = this.reader.readInt(2);
this.diskNumber = this.reader.readInt(4);
this.diskWithCentralDirStart = this.reader.readInt(4);
this.centralDirRecordsOnThisDisk = this.reader.readInt(8);
this.centralDirRecords = this.reader.readInt(8);
this.centralDirSize = this.reader.readInt(8);
this.centralDirOffset = this.reader.readInt(8);
this.zip64ExtensibleData = {};
var extraDataSize = this.zip64EndOfCentralSize - 44,
index = 0,
extraFieldId,
extraFieldLength,
extraFieldValue;
while (index < extraDataSize) {
extraFieldId = this.reader.readInt(2);
extraFieldLength = this.reader.readInt(4);
extraFieldValue = this.reader.readString(extraFieldLength);
this.zip64ExtensibleData[extraFieldId] = {
id: extraFieldId,
length: extraFieldLength,
value: extraFieldValue
};
}
},
/**
* Read the end of the Zip 64 central directory locator.
*/
readBlockZip64EndOfCentralLocator: function() {
this.diskWithZip64CentralDirStart = this.reader.readInt(4);
this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8);
this.disksCount = this.reader.readInt(4);
if (this.disksCount > 1) {
throw new Error("Multi-volumes zip are not supported");
}
},
/**
* Read the local files, based on the offset read in the central part.
*/
readLocalFiles: function() {
var i, file;
for (i = 0; i < this.files.length; i++) {
file = this.files[i];
this.reader.setIndex(file.localHeaderOffset);
this.checkSignature(sig.LOCAL_FILE_HEADER);
file.readLocalPart(this.reader);
file.handleUTF8();
file.processAttributes();
}
},
/**
* Read the central directory.
*/
readCentralDir: function() {
var file;
this.reader.setIndex(this.centralDirOffset);
while (this.reader.readString(4) === sig.CENTRAL_FILE_HEADER) {
file = new ZipEntry({
zip64: this.zip64
}, this.loadOptions);
file.readCentralPart(this.reader);
this.files.push(file);
}
},
/**
* Read the end of central directory.
*/
readEndOfCentral: function() {
var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END);
if (offset === -1) {
// Check if the content is a truncated zip or complete garbage.
// A "LOCAL_FILE_HEADER" is not required at the beginning (auto
// extractible zip for example) but it can give a good hint.
// If an ajax request was used without responseType, we will also
// get unreadable data.
var isGarbage = true;
try {
this.reader.setIndex(0);
this.checkSignature(sig.LOCAL_FILE_HEADER);
isGarbage = false;
} catch (e) {}
if (isGarbage) {
throw new Error("Can't find end of central directory : is this a zip file ? " +
"If it is, see http://stuk.github.io/jszip/documentation/howto/read_zip.html");
} else {
throw new Error("Corrupted zip : can't find end of central directory");
}
}
this.reader.setIndex(offset);
this.checkSignature(sig.CENTRAL_DIRECTORY_END);
this.readBlockEndOfCentral();
/* extract from the zip spec :
4) If one of the fields in the end of central directory
record is too small to hold required data, the field
should be set to -1 (0xFFFF or 0xFFFFFFFF) and the
ZIP64 format record should be created.
5) The end of central directory record and the
Zip64 end of central directory locator record must
reside on the same disk when splitting or spanning
an archive.
*/
if (this.diskNumber === utils.MAX_VALUE_16BITS || this.diskWithCentralDirStart === utils.MAX_VALUE_16BITS || this.centralDirRecordsOnThisDisk === utils.MAX_VALUE_16BITS || this.centralDirRecords === utils.MAX_VALUE_16BITS || this.centralDirSize === utils.MAX_VALUE_32BITS || this.centralDirOffset === utils.MAX_VALUE_32BITS) {
this.zip64 = true;
/*
Warning : the zip64 extension is supported, but ONLY if the 64bits integer read from
the zip file can fit into a 32bits integer. This cannot be solved : Javascript represents
all numbers as 64-bit double precision IEEE 754 floating point numbers.
So, we have 53bits for integers and bitwise operations treat everything as 32bits.
see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators
and http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf section 8.5
*/
// should look for a zip64 EOCD locator
offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
if (offset === -1) {
throw new Error("Corrupted zip : can't find the ZIP64 end of central directory locator");
}
this.reader.setIndex(offset);
this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
this.readBlockZip64EndOfCentralLocator();
// now the zip64 EOCD record
this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir);
this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
this.readBlockZip64EndOfCentral();
}
},
prepareReader: function(data) {
var type = utils.getTypeOf(data);
if (type === "string" && !support.uint8array) {
this.reader = new StringReader(data, this.loadOptions.optimizedBinaryString);
}
else if (type === "nodebuffer") {
this.reader = new NodeBufferReader(data);
}
else {
this.reader = new Uint8ArrayReader(utils.transformTo("uint8array", data));
}
},
/**
* Read a zip file and create ZipEntries.
* @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file.
*/
load: function(data) {
this.prepareReader(data);
this.readEndOfCentral();
this.readCentralDir();
this.readLocalFiles();
}
};
// }}} end of ZipEntries
module.exports = ZipEntries;
},{"./nodeBufferReader":114,"./object":115,"./signature":116,"./stringReader":117,"./support":119,"./uint8ArrayReader":120,"./utils":123,"./zipEntry":125}],125:[function(require,module,exports){
'use strict';
var StringReader = require('./stringReader');
var utils = require('./utils');
var CompressedObject = require('./compressedObject');
var jszipProto = require('./object');
var MADE_BY_DOS = 0x00;
var MADE_BY_UNIX = 0x03;
// class ZipEntry {{{
/**
* An entry in the zip file.
* @constructor
* @param {Object} options Options of the current file.
* @param {Object} loadOptions Options for loading the stream.
*/
function ZipEntry(options, loadOptions) {
this.options = options;
this.loadOptions = loadOptions;
}
ZipEntry.prototype = {
/**
* say if the file is encrypted.
* @return {boolean} true if the file is encrypted, false otherwise.
*/
isEncrypted: function() {
// bit 1 is set
return (this.bitFlag & 0x0001) === 0x0001;
},
/**
* say if the file has utf-8 filename/comment.
* @return {boolean} true if the filename/comment is in utf-8, false otherwise.
*/
useUTF8: function() {
// bit 11 is set
return (this.bitFlag & 0x0800) === 0x0800;
},
/**
* Prepare the function used to generate the compressed content from this ZipFile.
* @param {DataReader} reader the reader to use.
* @param {number} from the offset from where we should read the data.
* @param {number} length the length of the data to read.
* @return {Function} the callback to get the compressed content (the type depends of the DataReader class).
*/
prepareCompressedContent: function(reader, from, length) {
return function() {
var previousIndex = reader.index;
reader.setIndex(from);
var compressedFileData = reader.readData(length);
reader.setIndex(previousIndex);
return compressedFileData;
};
},
/**
* Prepare the function used to generate the uncompressed content from this ZipFile.
* @param {DataReader} reader the reader to use.
* @param {number} from the offset from where we should read the data.
* @param {number} length the length of the data to read.
* @param {JSZip.compression} compression the compression used on this file.
* @param {number} uncompressedSize the uncompressed size to expect.
* @return {Function} the callback to get the uncompressed content (the type depends of the DataReader class).
*/
prepareContent: function(reader, from, length, compression, uncompressedSize) {
return function() {
var compressedFileData = utils.transformTo(compression.uncompressInputType, this.getCompressedContent());
var uncompressedFileData = compression.uncompress(compressedFileData);
if (uncompressedFileData.length !== uncompressedSize) {
throw new Error("Bug : uncompressed data size mismatch");
}
return uncompressedFileData;
};
},
/**
* Read the local part of a zip file and add the info in this object.
* @param {DataReader} reader the reader to use.
*/
readLocalPart: function(reader) {
var compression, localExtraFieldsLength;
// we already know everything from the central dir !
// If the central dir data are false, we are doomed.
// On the bright side, the local part is scary : zip64, data descriptors, both, etc.
// The less data we get here, the more reliable this should be.
// Let's skip the whole header and dash to the data !
reader.skip(22);
// in some zip created on windows, the filename stored in the central dir contains \ instead of /.
// Strangely, the filename here is OK.
// I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes
// or APPNOTE#4.4.17.1, "All slashes MUST be forward slashes '/'") but there are a lot of bad zip generators...
// Search "unzip mismatching "local" filename continuing with "central" filename version" on
// the internet.
//
// I think I see the logic here : the central directory is used to display
// content and the local directory is used to extract the files. Mixing / and \
// may be used to display \ to windows users and use / when extracting the files.
// Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/394
this.fileNameLength = reader.readInt(2);
localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir
this.fileName = reader.readString(this.fileNameLength);
reader.skip(localExtraFieldsLength);
if (this.compressedSize == -1 || this.uncompressedSize == -1) {
throw new Error("Bug or corrupted zip : didn't get enough informations from the central directory " + "(compressedSize == -1 || uncompressedSize == -1)");
}
compression = utils.findCompression(this.compressionMethod);
if (compression === null) { // no compression found
throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + this.fileName + ")");
}
this.decompressed = new CompressedObject();
this.decompressed.compressedSize = this.compressedSize;
this.decompressed.uncompressedSize = this.uncompressedSize;
this.decompressed.crc32 = this.crc32;
this.decompressed.compressionMethod = this.compressionMethod;
this.decompressed.getCompressedContent = this.prepareCompressedContent(reader, reader.index, this.compressedSize, compression);
this.decompressed.getContent = this.prepareContent(reader, reader.index, this.compressedSize, compression, this.uncompressedSize);
// we need to compute the crc32...
if (this.loadOptions.checkCRC32) {
this.decompressed = utils.transformTo("string", this.decompressed.getContent());
if (jszipProto.crc32(this.decompressed) !== this.crc32) {
throw new Error("Corrupted zip : CRC32 mismatch");
}
}
},
/**
* Read the central part of a zip file and add the info in this object.
* @param {DataReader} reader the reader to use.
*/
readCentralPart: function(reader) {
this.versionMadeBy = reader.readInt(2);
this.versionNeeded = reader.readInt(2);
this.bitFlag = reader.readInt(2);
this.compressionMethod = reader.readString(2);
this.date = reader.readDate();
this.crc32 = reader.readInt(4);
this.compressedSize = reader.readInt(4);
this.uncompressedSize = reader.readInt(4);
this.fileNameLength = reader.readInt(2);
this.extraFieldsLength = reader.readInt(2);
this.fileCommentLength = reader.readInt(2);
this.diskNumberStart = reader.readInt(2);
this.internalFileAttributes = reader.readInt(2);
this.externalFileAttributes = reader.readInt(4);
this.localHeaderOffset = reader.readInt(4);
if (this.isEncrypted()) {
throw new Error("Encrypted zip are not supported");
}
this.fileName = reader.readString(this.fileNameLength);
this.readExtraFields(reader);
this.parseZIP64ExtraField(reader);
this.fileComment = reader.readString(this.fileCommentLength);
},
/**
* Parse the external file attributes and get the unix/dos permissions.
*/
processAttributes: function () {
this.unixPermissions = null;
this.dosPermissions = null;
var madeBy = this.versionMadeBy >> 8;
// Check if we have the DOS directory flag set.
// We look for it in the DOS and UNIX permissions
// but some unknown platform could set it as a compatibility flag.
this.dir = this.externalFileAttributes & 0x0010 ? true : false;
if(madeBy === MADE_BY_DOS) {
// first 6 bits (0 to 5)
this.dosPermissions = this.externalFileAttributes & 0x3F;
}
if(madeBy === MADE_BY_UNIX) {
this.unixPermissions = (this.externalFileAttributes >> 16) & 0xFFFF;
// the octal permissions are in (this.unixPermissions & 0x01FF).toString(8);
}
// fail safe : if the name ends with a / it probably means a folder
if (!this.dir && this.fileName.slice(-1) === '/') {
this.dir = true;
}
},
/**
* Parse the ZIP64 extra field and merge the info in the current ZipEntry.
* @param {DataReader} reader the reader to use.
*/
parseZIP64ExtraField: function(reader) {
if (!this.extraFields[0x0001]) {
return;
}
// should be something, preparing the extra reader
var extraReader = new StringReader(this.extraFields[0x0001].value);
// I really hope that these 64bits integer can fit in 32 bits integer, because js
// won't let us have more.
if (this.uncompressedSize === utils.MAX_VALUE_32BITS) {
this.uncompressedSize = extraReader.readInt(8);
}
if (this.compressedSize === utils.MAX_VALUE_32BITS) {
this.compressedSize = extraReader.readInt(8);
}
if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) {
this.localHeaderOffset = extraReader.readInt(8);
}
if (this.diskNumberStart === utils.MAX_VALUE_32BITS) {
this.diskNumberStart = extraReader.readInt(4);
}
},
/**
* Read the central part of a zip file and add the info in this object.
* @param {DataReader} reader the reader to use.
*/
readExtraFields: function(reader) {
var start = reader.index,
extraFieldId,
extraFieldLength,
extraFieldValue;
this.extraFields = this.extraFields || {};
while (reader.index < start + this.extraFieldsLength) {
extraFieldId = reader.readInt(2);
extraFieldLength = reader.readInt(2);
extraFieldValue = reader.readString(extraFieldLength);
this.extraFields[extraFieldId] = {
id: extraFieldId,
length: extraFieldLength,
value: extraFieldValue
};
}
},
/**
* Apply an UTF8 transformation if needed.
*/
handleUTF8: function() {
if (this.useUTF8()) {
this.fileName = jszipProto.utf8decode(this.fileName);
this.fileComment = jszipProto.utf8decode(this.fileComment);
} else {
var upath = this.findExtraFieldUnicodePath();
if (upath !== null) {
this.fileName = upath;
}
var ucomment = this.findExtraFieldUnicodeComment();
if (ucomment !== null) {
this.fileComment = ucomment;
}
}
},
/**
* Find the unicode path declared in the extra field, if any.
* @return {String} the unicode path, null otherwise.
*/
findExtraFieldUnicodePath: function() {
var upathField = this.extraFields[0x7075];
if (upathField) {
var extraReader = new StringReader(upathField.value);
// wrong version
if (extraReader.readInt(1) !== 1) {
return null;
}
// the crc of the filename changed, this field is out of date.
if (jszipProto.crc32(this.fileName) !== extraReader.readInt(4)) {
return null;
}
return jszipProto.utf8decode(extraReader.readString(upathField.length - 5));
}
return null;
},
/**
* Find the unicode comment declared in the extra field, if any.
* @return {String} the unicode comment, null otherwise.
*/
findExtraFieldUnicodeComment: function() {
var ucommentField = this.extraFields[0x6375];
if (ucommentField) {
var extraReader = new StringReader(ucommentField.value);
// wrong version
if (extraReader.readInt(1) !== 1) {
return null;
}
// the crc of the comment changed, this field is out of date.
if (jszipProto.crc32(this.fileComment) !== extraReader.readInt(4)) {
return null;
}
return jszipProto.utf8decode(extraReader.readString(ucommentField.length - 5));
}
return null;
}
};
module.exports = ZipEntry;
},{"./compressedObject":104,"./object":115,"./stringReader":117,"./utils":123}],126:[function(require,module,exports){
// Top level file is just a mixin of submodules & constants
'use strict';
var assign = require('./lib/utils/common').assign;
var deflate = require('./lib/deflate');
var inflate = require('./lib/inflate');
var constants = require('./lib/zlib/constants');
var pako = {};
assign(pako, deflate, inflate, constants);
module.exports = pako;
},{"./lib/deflate":127,"./lib/inflate":128,"./lib/utils/common":129,"./lib/zlib/constants":132}],127:[function(require,module,exports){
'use strict';
var zlib_deflate = require('./zlib/deflate.js');
var utils = require('./utils/common');
var strings = require('./utils/strings');
var msg = require('./zlib/messages');
var zstream = require('./zlib/zstream');
var toString = Object.prototype.toString;
/* Public constants ==========================================================*/
/* ===========================================================================*/
var Z_NO_FLUSH = 0;
var Z_FINISH = 4;
var Z_OK = 0;
var Z_STREAM_END = 1;
var Z_SYNC_FLUSH = 2;
var Z_DEFAULT_COMPRESSION = -1;
var Z_DEFAULT_STRATEGY = 0;
var Z_DEFLATED = 8;
/* ===========================================================================*/
/**
* class Deflate
*
* Generic JS-style wrapper for zlib calls. If you don't need
* streaming behaviour - use more simple functions: [[deflate]],
* [[deflateRaw]] and [[gzip]].
**/
/* internal
* Deflate.chunks -> Array
*
* Chunks of output data, if [[Deflate#onData]] not overriden.
**/
/**
* Deflate.result -> Uint8Array|Array
*
* Compressed result, generated by default [[Deflate#onData]]
* and [[Deflate#onEnd]] handlers. Filled after you push last chunk
* (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
* push a chunk with explicit flush (call [[Deflate#push]] with
* `Z_SYNC_FLUSH` param).
**/
/**
* Deflate.err -> Number
*
* Error code after deflate finished. 0 (Z_OK) on success.
* You will not need it in real life, because deflate errors
* are possible only on wrong options or bad `onData` / `onEnd`
* custom handlers.
**/
/**
* Deflate.msg -> String
*
* Error message, if [[Deflate.err]] != 0
**/
/**
* new Deflate(options)
* - options (Object): zlib deflate options.
*
* Creates new deflator instance with specified params. Throws exception
* on bad params. Supported options:
*
* - `level`
* - `windowBits`
* - `memLevel`
* - `strategy`
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Additional options, for internal needs:
*
* - `chunkSize` - size of generated data chunks (16K by default)
* - `raw` (Boolean) - do raw deflate
* - `gzip` (Boolean) - create gzip wrapper
* - `to` (String) - if equal to 'string', then result will be "binary string"
* (each char code [0..255])
* - `header` (Object) - custom header for gzip
* - `text` (Boolean) - true if compressed data believed to be text
* - `time` (Number) - modification time, unix timestamp
* - `os` (Number) - operation system code
* - `extra` (Array) - array of bytes with extra data (max 65536)
* - `name` (String) - file name (binary string)
* - `comment` (String) - comment (binary string)
* - `hcrc` (Boolean) - true if header crc should be added
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
* , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
*
* var deflate = new pako.Deflate({ level: 3});
*
* deflate.push(chunk1, false);
* deflate.push(chunk2, true); // true -> last chunk
*
* if (deflate.err) { throw new Error(deflate.err); }
*
* console.log(deflate.result);
* ```
**/
var Deflate = function(options) {
this.options = utils.assign({
level: Z_DEFAULT_COMPRESSION,
method: Z_DEFLATED,
chunkSize: 16384,
windowBits: 15,
memLevel: 8,
strategy: Z_DEFAULT_STRATEGY,
to: ''
}, options || {});
var opt = this.options;
if (opt.raw && (opt.windowBits > 0)) {
opt.windowBits = -opt.windowBits;
}
else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
opt.windowBits += 16;
}
this.err = 0; // error code, if happens (0 = Z_OK)
this.msg = ''; // error message
this.ended = false; // used to avoid multiple onEnd() calls
this.chunks = []; // chunks of compressed data
this.strm = new zstream();
this.strm.avail_out = 0;
var status = zlib_deflate.deflateInit2(
this.strm,
opt.level,
opt.method,
opt.windowBits,
opt.memLevel,
opt.strategy
);
if (status !== Z_OK) {
throw new Error(msg[status]);
}
if (opt.header) {
zlib_deflate.deflateSetHeader(this.strm, opt.header);
}
};
/**
* Deflate#push(data[, mode]) -> Boolean
* - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
* converted to utf8 byte sequence.
* - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
* See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
*
* Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
* new compressed chunks. Returns `true` on success. The last data block must have
* mode Z_FINISH (or `true`). That will flush internal pending buffers and call
* [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
* can use mode Z_SYNC_FLUSH, keeping the compression context.
*
* On fail call [[Deflate#onEnd]] with error code and return false.
*
* We strongly recommend to use `Uint8Array` on input for best speed (output
* array format is detected automatically). Also, don't skip last param and always
* use the same type in your code (boolean or number). That will improve JS speed.
*
* For regular `Array`-s make sure all elements are [0..255].
*
* ##### Example
*
* ```javascript
* push(chunk, false); // push one of data chunks
* ...
* push(chunk, true); // push last chunk
* ```
**/
Deflate.prototype.push = function(data, mode) {
var strm = this.strm;
var chunkSize = this.options.chunkSize;
var status, _mode;
if (this.ended) { return false; }
_mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
// Convert data if needed
if (typeof data === 'string') {
// If we need to compress text, change encoding to utf8.
strm.input = strings.string2buf(data);
} else if (toString.call(data) === '[object ArrayBuffer]') {
strm.input = new Uint8Array(data);
} else {
strm.input = data;
}
strm.next_in = 0;
strm.avail_in = strm.input.length;
do {
if (strm.avail_out === 0) {
strm.output = new utils.Buf8(chunkSize);
strm.next_out = 0;
strm.avail_out = chunkSize;
}
status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
if (status !== Z_STREAM_END && status !== Z_OK) {
this.onEnd(status);
this.ended = true;
return false;
}
if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
if (this.options.to === 'string') {
this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
} else {
this.onData(utils.shrinkBuf(strm.output, strm.next_out));
}
}
} while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
// Finalize on the last chunk.
if (_mode === Z_FINISH) {
status = zlib_deflate.deflateEnd(this.strm);
this.onEnd(status);
this.ended = true;
return status === Z_OK;
}
// callback interim results if Z_SYNC_FLUSH.
if (_mode === Z_SYNC_FLUSH) {
this.onEnd(Z_OK);
strm.avail_out = 0;
return true;
}
return true;
};
/**
* Deflate#onData(chunk) -> Void
* - chunk (Uint8Array|Array|String): ouput data. Type of array depends
* on js engine support. When string output requested, each chunk
* will be string.
*
* By default, stores data blocks in `chunks[]` property and glue
* those in `onEnd`. Override this handler, if you need another behaviour.
**/
Deflate.prototype.onData = function(chunk) {
this.chunks.push(chunk);
};
/**
* Deflate#onEnd(status) -> Void
* - status (Number): deflate status. 0 (Z_OK) on success,
* other if not.
*
* Called once after you tell deflate that the input stream is
* complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
* or if an error happened. By default - join collected chunks,
* free memory and fill `results` / `err` properties.
**/
Deflate.prototype.onEnd = function(status) {
// On success - join
if (status === Z_OK) {
if (this.options.to === 'string') {
this.result = this.chunks.join('');
} else {
this.result = utils.flattenChunks(this.chunks);
}
}
this.chunks = [];
this.err = status;
this.msg = this.strm.msg;
};
/**
* deflate(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* Compress `data` with deflate alrorythm and `options`.
*
* Supported options are:
*
* - level
* - windowBits
* - memLevel
* - strategy
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Sugar (options):
*
* - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
* negative windowBits implicitly.
* - `to` (String) - if equal to 'string', then result will be "binary string"
* (each char code [0..255])
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
*
* console.log(pako.deflate(data));
* ```
**/
function deflate(input, options) {
var deflator = new Deflate(options);
deflator.push(input, true);
// That will never happens, if you don't cheat with options :)
if (deflator.err) { throw deflator.msg; }
return deflator.result;
}
/**
* deflateRaw(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* The same as [[deflate]], but creates raw data, without wrapper
* (header and adler32 crc).
**/
function deflateRaw(input, options) {
options = options || {};
options.raw = true;
return deflate(input, options);
}
/**
* gzip(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* The same as [[deflate]], but create gzip wrapper instead of
* deflate one.
**/
function gzip(input, options) {
options = options || {};
options.gzip = true;
return deflate(input, options);
}
exports.Deflate = Deflate;
exports.deflate = deflate;
exports.deflateRaw = deflateRaw;
exports.gzip = gzip;
},{"./utils/common":129,"./utils/strings":130,"./zlib/deflate.js":134,"./zlib/messages":139,"./zlib/zstream":141}],128:[function(require,module,exports){
'use strict';
var zlib_inflate = require('./zlib/inflate.js');
var utils = require('./utils/common');
var strings = require('./utils/strings');
var c = require('./zlib/constants');
var msg = require('./zlib/messages');
var zstream = require('./zlib/zstream');
var gzheader = require('./zlib/gzheader');
var toString = Object.prototype.toString;
/**
* class Inflate
*
* Generic JS-style wrapper for zlib calls. If you don't need
* streaming behaviour - use more simple functions: [[inflate]]
* and [[inflateRaw]].
**/
/* internal
* inflate.chunks -> Array
*
* Chunks of output data, if [[Inflate#onData]] not overriden.
**/
/**
* Inflate.result -> Uint8Array|Array|String
*
* Uncompressed result, generated by default [[Inflate#onData]]
* and [[Inflate#onEnd]] handlers. Filled after you push last chunk
* (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
* push a chunk with explicit flush (call [[Inflate#push]] with
* `Z_SYNC_FLUSH` param).
**/
/**
* Inflate.err -> Number
*
* Error code after inflate finished. 0 (Z_OK) on success.
* Should be checked if broken data possible.
**/
/**
* Inflate.msg -> String
*
* Error message, if [[Inflate.err]] != 0
**/
/**
* new Inflate(options)
* - options (Object): zlib inflate options.
*
* Creates new inflator instance with specified params. Throws exception
* on bad params. Supported options:
*
* - `windowBits`
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Additional options, for internal needs:
*
* - `chunkSize` - size of generated data chunks (16K by default)
* - `raw` (Boolean) - do raw inflate
* - `to` (String) - if equal to 'string', then result will be converted
* from utf8 to utf16 (javascript) string. When string output requested,
* chunk length can differ from `chunkSize`, depending on content.
*
* By default, when no options set, autodetect deflate/gzip data format via
* wrapper header.
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
* , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
*
* var inflate = new pako.Inflate({ level: 3});
*
* inflate.push(chunk1, false);
* inflate.push(chunk2, true); // true -> last chunk
*
* if (inflate.err) { throw new Error(inflate.err); }
*
* console.log(inflate.result);
* ```
**/
var Inflate = function(options) {
this.options = utils.assign({
chunkSize: 16384,
windowBits: 0,
to: ''
}, options || {});
var opt = this.options;
// Force window size for `raw` data, if not set directly,
// because we have no header for autodetect.
if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
opt.windowBits = -opt.windowBits;
if (opt.windowBits === 0) { opt.windowBits = -15; }
}
// If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
!(options && options.windowBits)) {
opt.windowBits += 32;
}
// Gzip header has no info about windows size, we can do autodetect only
// for deflate. So, if window size not set, force it to max when gzip possible
if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
// bit 3 (16) -> gzipped data
// bit 4 (32) -> autodetect gzip/deflate
if ((opt.windowBits & 15) === 0) {
opt.windowBits |= 15;
}
}
this.err = 0; // error code, if happens (0 = Z_OK)
this.msg = ''; // error message
this.ended = false; // used to avoid multiple onEnd() calls
this.chunks = []; // chunks of compressed data
this.strm = new zstream();
this.strm.avail_out = 0;
var status = zlib_inflate.inflateInit2(
this.strm,
opt.windowBits
);
if (status !== c.Z_OK) {
throw new Error(msg[status]);
}
this.header = new gzheader();
zlib_inflate.inflateGetHeader(this.strm, this.header);
};
/**
* Inflate#push(data[, mode]) -> Boolean
* - data (Uint8Array|Array|ArrayBuffer|String): input data
* - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
* See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
*
* Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
* new output chunks. Returns `true` on success. The last data block must have
* mode Z_FINISH (or `true`). That will flush internal pending buffers and call
* [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
* can use mode Z_SYNC_FLUSH, keeping the decompression context.
*
* On fail call [[Inflate#onEnd]] with error code and return false.
*
* We strongly recommend to use `Uint8Array` on input for best speed (output
* format is detected automatically). Also, don't skip last param and always
* use the same type in your code (boolean or number). That will improve JS speed.
*
* For regular `Array`-s make sure all elements are [0..255].
*
* ##### Example
*
* ```javascript
* push(chunk, false); // push one of data chunks
* ...
* push(chunk, true); // push last chunk
* ```
**/
Inflate.prototype.push = function(data, mode) {
var strm = this.strm;
var chunkSize = this.options.chunkSize;
var status, _mode;
var next_out_utf8, tail, utf8str;
if (this.ended) { return false; }
_mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
// Convert data if needed
if (typeof data === 'string') {
// Only binary strings can be decompressed on practice
strm.input = strings.binstring2buf(data);
} else if (toString.call(data) === '[object ArrayBuffer]') {
strm.input = new Uint8Array(data);
} else {
strm.input = data;
}
strm.next_in = 0;
strm.avail_in = strm.input.length;
do {
if (strm.avail_out === 0) {
strm.output = new utils.Buf8(chunkSize);
strm.next_out = 0;
strm.avail_out = chunkSize;
}
status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
this.onEnd(status);
this.ended = true;
return false;
}
if (strm.next_out) {
if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
if (this.options.to === 'string') {
next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
tail = strm.next_out - next_out_utf8;
utf8str = strings.buf2string(strm.output, next_out_utf8);
// move tail
strm.next_out = tail;
strm.avail_out = chunkSize - tail;
if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
this.onData(utf8str);
} else {
this.onData(utils.shrinkBuf(strm.output, strm.next_out));
}
}
}
} while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
if (status === c.Z_STREAM_END) {
_mode = c.Z_FINISH;
}
// Finalize on the last chunk.
if (_mode === c.Z_FINISH) {
status = zlib_inflate.inflateEnd(this.strm);
this.onEnd(status);
this.ended = true;
return status === c.Z_OK;
}
// callback interim results if Z_SYNC_FLUSH.
if (_mode === c.Z_SYNC_FLUSH) {
this.onEnd(c.Z_OK);
strm.avail_out = 0;
return true;
}
return true;
};
/**
* Inflate#onData(chunk) -> Void
* - chunk (Uint8Array|Array|String): ouput data. Type of array depends
* on js engine support. When string output requested, each chunk
* will be string.
*
* By default, stores data blocks in `chunks[]` property and glue
* those in `onEnd`. Override this handler, if you need another behaviour.
**/
Inflate.prototype.onData = function(chunk) {
this.chunks.push(chunk);
};
/**
* Inflate#onEnd(status) -> Void
* - status (Number): inflate status. 0 (Z_OK) on success,
* other if not.
*
* Called either after you tell inflate that the input stream is
* complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
* or if an error happened. By default - join collected chunks,
* free memory and fill `results` / `err` properties.
**/
Inflate.prototype.onEnd = function(status) {
// On success - join
if (status === c.Z_OK) {
if (this.options.to === 'string') {
// Glue & convert here, until we teach pako to send
// utf8 alligned strings to onData
this.result = this.chunks.join('');
} else {
this.result = utils.flattenChunks(this.chunks);
}
}
this.chunks = [];
this.err = status;
this.msg = this.strm.msg;
};
/**
* inflate(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to decompress.
* - options (Object): zlib inflate options.
*
* Decompress `data` with inflate/ungzip and `options`. Autodetect
* format via wrapper header by default. That's why we don't provide
* separate `ungzip` method.
*
* Supported options are:
*
* - windowBits
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information.
*
* Sugar (options):
*
* - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
* negative windowBits implicitly.
* - `to` (String) - if equal to 'string', then result will be converted
* from utf8 to utf16 (javascript) string. When string output requested,
* chunk length can differ from `chunkSize`, depending on content.
*
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , input = pako.deflate([1,2,3,4,5,6,7,8,9])
* , output;
*
* try {
* output = pako.inflate(input);
* } catch (err)
* console.log(err);
* }
* ```
**/
function inflate(input, options) {
var inflator = new Inflate(options);
inflator.push(input, true);
// That will never happens, if you don't cheat with options :)
if (inflator.err) { throw inflator.msg; }
return inflator.result;
}
/**
* inflateRaw(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to decompress.
* - options (Object): zlib inflate options.
*
* The same as [[inflate]], but creates raw data, without wrapper
* (header and adler32 crc).
**/
function inflateRaw(input, options) {
options = options || {};
options.raw = true;
return inflate(input, options);
}
/**
* ungzip(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to decompress.
* - options (Object): zlib inflate options.
*
* Just shortcut to [[inflate]], because it autodetects format
* by header.content. Done for convenience.
**/
exports.Inflate = Inflate;
exports.inflate = inflate;
exports.inflateRaw = inflateRaw;
exports.ungzip = inflate;
},{"./utils/common":129,"./utils/strings":130,"./zlib/constants":132,"./zlib/gzheader":135,"./zlib/inflate.js":137,"./zlib/messages":139,"./zlib/zstream":141}],129:[function(require,module,exports){
'use strict';
var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
(typeof Uint16Array !== 'undefined') &&
(typeof Int32Array !== 'undefined');
exports.assign = function (obj /*from1, from2, from3, ...*/) {
var sources = Array.prototype.slice.call(arguments, 1);
while (sources.length) {
var source = sources.shift();
if (!source) { continue; }
if (typeof source !== 'object') {
throw new TypeError(source + 'must be non-object');
}
for (var p in source) {
if (source.hasOwnProperty(p)) {
obj[p] = source[p];
}
}
}
return obj;
};
// reduce buffer size, avoiding mem copy
exports.shrinkBuf = function (buf, size) {
if (buf.length === size) { return buf; }
if (buf.subarray) { return buf.subarray(0, size); }
buf.length = size;
return buf;
};
var fnTyped = {
arraySet: function (dest, src, src_offs, len, dest_offs) {
if (src.subarray && dest.subarray) {
dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
return;
}
// Fallback to ordinary array
for (var i=0; i<len; i++) {
dest[dest_offs + i] = src[src_offs + i];
}
},
// Join array of chunks to single array.
flattenChunks: function(chunks) {
var i, l, len, pos, chunk, result;
// calculate data length
len = 0;
for (i=0, l=chunks.length; i<l; i++) {
len += chunks[i].length;
}
// join chunks
result = new Uint8Array(len);
pos = 0;
for (i=0, l=chunks.length; i<l; i++) {
chunk = chunks[i];
result.set(chunk, pos);
pos += chunk.length;
}
return result;
}
};
var fnUntyped = {
arraySet: function (dest, src, src_offs, len, dest_offs) {
for (var i=0; i<len; i++) {
dest[dest_offs + i] = src[src_offs + i];
}
},
// Join array of chunks to single array.
flattenChunks: function(chunks) {
return [].concat.apply([], chunks);
}
};
// Enable/Disable typed arrays use, for testing
//
exports.setTyped = function (on) {
if (on) {
exports.Buf8 = Uint8Array;
exports.Buf16 = Uint16Array;
exports.Buf32 = Int32Array;
exports.assign(exports, fnTyped);
} else {
exports.Buf8 = Array;
exports.Buf16 = Array;
exports.Buf32 = Array;
exports.assign(exports, fnUntyped);
}
};
exports.setTyped(TYPED_OK);
},{}],130:[function(require,module,exports){
// String encode/decode helpers
'use strict';
var utils = require('./common');
// Quick check if we can use fast array to bin string conversion
//
// - apply(Array) can fail on Android 2.2
// - apply(Uint8Array) can fail on iOS 5.1 Safary
//
var STR_APPLY_OK = true;
var STR_APPLY_UIA_OK = true;
try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
// Table with utf8 lengths (calculated by first byte of sequence)
// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
// because max possible codepoint is 0x10ffff
var _utf8len = new utils.Buf8(256);
for (var q=0; q<256; q++) {
_utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
}
_utf8len[254]=_utf8len[254]=1; // Invalid sequence start
// convert string to array (typed, when possible)
exports.string2buf = function (str) {
var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
// count binary size
for (m_pos = 0; m_pos < str_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
c2 = str.charCodeAt(m_pos+1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
m_pos++;
}
}
buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
}
// allocate buffer
buf = new utils.Buf8(buf_len);
// convert
for (i=0, m_pos = 0; i < buf_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
c2 = str.charCodeAt(m_pos+1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
m_pos++;
}
}
if (c < 0x80) {
/* one byte */
buf[i++] = c;
} else if (c < 0x800) {
/* two bytes */
buf[i++] = 0xC0 | (c >>> 6);
buf[i++] = 0x80 | (c & 0x3f);
} else if (c < 0x10000) {
/* three bytes */
buf[i++] = 0xE0 | (c >>> 12);
buf[i++] = 0x80 | (c >>> 6 & 0x3f);
buf[i++] = 0x80 | (c & 0x3f);
} else {
/* four bytes */
buf[i++] = 0xf0 | (c >>> 18);
buf[i++] = 0x80 | (c >>> 12 & 0x3f);
buf[i++] = 0x80 | (c >>> 6 & 0x3f);
buf[i++] = 0x80 | (c & 0x3f);
}
}
return buf;
};
// Helper (used in 2 places)
function buf2binstring(buf, len) {
// use fallback for big arrays to avoid stack overflow
if (len < 65537) {
if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
}
}
var result = '';
for (var i=0; i < len; i++) {
result += String.fromCharCode(buf[i]);
}
return result;
}
// Convert byte array to binary string
exports.buf2binstring = function(buf) {
return buf2binstring(buf, buf.length);
};
// Convert binary string (typed, when possible)
exports.binstring2buf = function(str) {
var buf = new utils.Buf8(str.length);
for (var i=0, len=buf.length; i < len; i++) {
buf[i] = str.charCodeAt(i);
}
return buf;
};
// convert array to string
exports.buf2string = function (buf, max) {
var i, out, c, c_len;
var len = max || buf.length;
// Reserve max possible length (2 words per char)
// NB: by unknown reasons, Array is significantly faster for
// String.fromCharCode.apply than Uint16Array.
var utf16buf = new Array(len*2);
for (out=0, i=0; i<len;) {
c = buf[i++];
// quick process ascii
if (c < 0x80) { utf16buf[out++] = c; continue; }
c_len = _utf8len[c];
// skip 5 & 6 byte codes
if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
// apply mask on first byte
c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
// join the rest
while (c_len > 1 && i < len) {
c = (c << 6) | (buf[i++] & 0x3f);
c_len--;
}
// terminated by end of string?
if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
if (c < 0x10000) {
utf16buf[out++] = c;
} else {
c -= 0x10000;
utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
utf16buf[out++] = 0xdc00 | (c & 0x3ff);
}
}
return buf2binstring(utf16buf, out);
};
// Calculate max possible position in utf8 buffer,
// that will not break sequence. If that's not possible
// - (very small limits) return max size as is.
//
// buf[] - utf8 bytes array
// max - length limit (mandatory);
exports.utf8border = function(buf, max) {
var pos;
max = max || buf.length;
if (max > buf.length) { max = buf.length; }
// go back from last position, until start of sequence found
pos = max-1;
while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
// Fuckup - very small and broken sequence,
// return max, because we should return something anyway.
if (pos < 0) { return max; }
// If we came to start of buffer - that means vuffer is too small,
// return max too.
if (pos === 0) { return max; }
return (pos + _utf8len[buf[pos]] > max) ? pos : max;
};
},{"./common":129}],131:[function(require,module,exports){
'use strict';
// Note: adler32 takes 12% for level 0 and 2% for level 6.
// It doesn't worth to make additional optimizationa as in original.
// Small size is preferable.
function adler32(adler, buf, len, pos) {
var s1 = (adler & 0xffff) |0,
s2 = ((adler >>> 16) & 0xffff) |0,
n = 0;
while (len !== 0) {
// Set limit ~ twice less than 5552, to keep
// s2 in 31-bits, because we force signed ints.
// in other case %= will fail.
n = len > 2000 ? 2000 : len;
len -= n;
do {
s1 = (s1 + buf[pos++]) |0;
s2 = (s2 + s1) |0;
} while (--n);
s1 %= 65521;
s2 %= 65521;
}
return (s1 | (s2 << 16)) |0;
}
module.exports = adler32;
},{}],132:[function(require,module,exports){
module.exports = {
/* Allowed flush values; see deflate() and inflate() below for details */
Z_NO_FLUSH: 0,
Z_PARTIAL_FLUSH: 1,
Z_SYNC_FLUSH: 2,
Z_FULL_FLUSH: 3,
Z_FINISH: 4,
Z_BLOCK: 5,
Z_TREES: 6,
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
Z_OK: 0,
Z_STREAM_END: 1,
Z_NEED_DICT: 2,
Z_ERRNO: -1,
Z_STREAM_ERROR: -2,
Z_DATA_ERROR: -3,
//Z_MEM_ERROR: -4,
Z_BUF_ERROR: -5,
//Z_VERSION_ERROR: -6,
/* compression levels */
Z_NO_COMPRESSION: 0,
Z_BEST_SPEED: 1,
Z_BEST_COMPRESSION: 9,
Z_DEFAULT_COMPRESSION: -1,
Z_FILTERED: 1,
Z_HUFFMAN_ONLY: 2,
Z_RLE: 3,
Z_FIXED: 4,
Z_DEFAULT_STRATEGY: 0,
/* Possible values of the data_type field (though see inflate()) */
Z_BINARY: 0,
Z_TEXT: 1,
//Z_ASCII: 1, // = Z_TEXT (deprecated)
Z_UNKNOWN: 2,
/* The deflate compression method */
Z_DEFLATED: 8
//Z_NULL: null // Use -1 or null inline, depending on var type
};
},{}],133:[function(require,module,exports){
'use strict';
// Note: we can't get significant speed boost here.
// So write code to minimize size - no pregenerated tables
// and array tools dependencies.
// Use ordinary array, since untyped makes no boost here
function makeTable() {
var c, table = [];
for (var n =0; n < 256; n++) {
c = n;
for (var k =0; k < 8; k++) {
c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
}
table[n] = c;
}
return table;
}
// Create table on load. Just 255 signed longs. Not a problem.
var crcTable = makeTable();
function crc32(crc, buf, len, pos) {
var t = crcTable,
end = pos + len;
crc = crc ^ (-1);
for (var i = pos; i < end; i++) {
crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
}
return (crc ^ (-1)); // >>> 0;
}
module.exports = crc32;
},{}],134:[function(require,module,exports){
'use strict';
var utils = require('../utils/common');
var trees = require('./trees');
var adler32 = require('./adler32');
var crc32 = require('./crc32');
var msg = require('./messages');
/* Public constants ==========================================================*/
/* ===========================================================================*/
/* Allowed flush values; see deflate() and inflate() below for details */
var Z_NO_FLUSH = 0;
var Z_PARTIAL_FLUSH = 1;
//var Z_SYNC_FLUSH = 2;
var Z_FULL_FLUSH = 3;
var Z_FINISH = 4;
var Z_BLOCK = 5;
//var Z_TREES = 6;
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
var Z_OK = 0;
var Z_STREAM_END = 1;
//var Z_NEED_DICT = 2;
//var Z_ERRNO = -1;
var Z_STREAM_ERROR = -2;
var Z_DATA_ERROR = -3;
//var Z_MEM_ERROR = -4;
var Z_BUF_ERROR = -5;
//var Z_VERSION_ERROR = -6;
/* compression levels */
//var Z_NO_COMPRESSION = 0;
//var Z_BEST_SPEED = 1;
//var Z_BEST_COMPRESSION = 9;
var Z_DEFAULT_COMPRESSION = -1;
var Z_FILTERED = 1;
var Z_HUFFMAN_ONLY = 2;
var Z_RLE = 3;
var Z_FIXED = 4;
var Z_DEFAULT_STRATEGY = 0;
/* Possible values of the data_type field (though see inflate()) */
//var Z_BINARY = 0;
//var Z_TEXT = 1;
//var Z_ASCII = 1; // = Z_TEXT
var Z_UNKNOWN = 2;
/* The deflate compression method */
var Z_DEFLATED = 8;
/*============================================================================*/
var MAX_MEM_LEVEL = 9;
/* Maximum value for memLevel in deflateInit2 */
var MAX_WBITS = 15;
/* 32K LZ77 window */
var DEF_MEM_LEVEL = 8;
var LENGTH_CODES = 29;
/* number of length codes, not counting the special END_BLOCK code */
var LITERALS = 256;
/* number of literal bytes 0..255 */
var L_CODES = LITERALS + 1 + LENGTH_CODES;
/* number of Literal or Length codes, including the END_BLOCK code */
var D_CODES = 30;
/* number of distance codes */
var BL_CODES = 19;
/* number of codes used to transfer the bit lengths */
var HEAP_SIZE = 2*L_CODES + 1;
/* maximum heap size */
var MAX_BITS = 15;
/* All codes must not exceed MAX_BITS bits */
var MIN_MATCH = 3;
var MAX_MATCH = 258;
var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
var PRESET_DICT = 0x20;
var INIT_STATE = 42;
var EXTRA_STATE = 69;
var NAME_STATE = 73;
var COMMENT_STATE = 91;
var HCRC_STATE = 103;
var BUSY_STATE = 113;
var FINISH_STATE = 666;
var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
var BS_BLOCK_DONE = 2; /* block flush performed */
var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
function err(strm, errorCode) {
strm.msg = msg[errorCode];
return errorCode;
}
function rank(f) {
return ((f) << 1) - ((f) > 4 ? 9 : 0);
}
function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
/* =========================================================================
* Flush as much pending output as possible. All deflate() output goes
* through this function so some applications may wish to modify it
* to avoid allocating a large strm->output buffer and copying into it.
* (See also read_buf()).
*/
function flush_pending(strm) {
var s = strm.state;
//_tr_flush_bits(s);
var len = s.pending;
if (len > strm.avail_out) {
len = strm.avail_out;
}
if (len === 0) { return; }
utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
strm.next_out += len;
s.pending_out += len;
strm.total_out += len;
strm.avail_out -= len;
s.pending -= len;
if (s.pending === 0) {
s.pending_out = 0;
}
}
function flush_block_only (s, last) {
trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
s.block_start = s.strstart;
flush_pending(s.strm);
}
function put_byte(s, b) {
s.pending_buf[s.pending++] = b;
}
/* =========================================================================
* Put a short in the pending buffer. The 16-bit value is put in MSB order.
* IN assertion: the stream state is correct and there is enough room in
* pending_buf.
*/
function putShortMSB(s, b) {
// put_byte(s, (Byte)(b >> 8));
// put_byte(s, (Byte)(b & 0xff));
s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
s.pending_buf[s.pending++] = b & 0xff;
}
/* ===========================================================================
* Read a new buffer from the current input stream, update the adler32
* and total number of bytes read. All deflate() input goes through
* this function so some applications may wish to modify it to avoid
* allocating a large strm->input buffer and copying from it.
* (See also flush_pending()).
*/
function read_buf(strm, buf, start, size) {
var len = strm.avail_in;
if (len > size) { len = size; }
if (len === 0) { return 0; }
strm.avail_in -= len;
utils.arraySet(buf, strm.input, strm.next_in, len, start);
if (strm.state.wrap === 1) {
strm.adler = adler32(strm.adler, buf, len, start);
}
else if (strm.state.wrap === 2) {
strm.adler = crc32(strm.adler, buf, len, start);
}
strm.next_in += len;
strm.total_in += len;
return len;
}
/* ===========================================================================
* Set match_start to the longest match starting at the given string and
* return its length. Matches shorter or equal to prev_length are discarded,
* in which case the result is equal to prev_length and match_start is
* garbage.
* IN assertions: cur_match is the head of the hash chain for the current
* string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
* OUT assertion: the match length is not greater than s->lookahead.
*/
function longest_match(s, cur_match) {
var chain_length = s.max_chain_length; /* max hash chain length */
var scan = s.strstart; /* current string */
var match; /* matched string */
var len; /* length of current match */
var best_len = s.prev_length; /* best match length so far */
var nice_match = s.nice_match; /* stop if match long enough */
var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
var _win = s.window; // shortcut
var wmask = s.w_mask;
var prev = s.prev;
/* Stop when cur_match becomes <= limit. To simplify the code,
* we prevent matches with the string of window index 0.
*/
var strend = s.strstart + MAX_MATCH;
var scan_end1 = _win[scan + best_len - 1];
var scan_end = _win[scan + best_len];
/* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
* It is easy to get rid of this optimization if necessary.
*/
// Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
/* Do not waste too much time if we already have a good match: */
if (s.prev_length >= s.good_match) {
chain_length >>= 2;
}
/* Do not look for matches beyond the end of the input. This is necessary
* to make deflate deterministic.
*/
if (nice_match > s.lookahead) { nice_match = s.lookahead; }
// Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
do {
// Assert(cur_match < s->strstart, "no future");
match = cur_match;
/* Skip to next match if the match length cannot increase
* or if the match length is less than 2. Note that the checks below
* for insufficient lookahead only occur occasionally for performance
* reasons. Therefore uninitialized memory will be accessed, and
* conditional jumps will be made that depend on those values.
* However the length of the match is limited to the lookahead, so
* the output of deflate is not affected by the uninitialized values.
*/
if (_win[match + best_len] !== scan_end ||
_win[match + best_len - 1] !== scan_end1 ||
_win[match] !== _win[scan] ||
_win[++match] !== _win[scan + 1]) {
continue;
}
/* The check at best_len-1 can be removed because it will be made
* again later. (This heuristic is not always a win.)
* It is not necessary to compare scan[2] and match[2] since they
* are always equal when the other bytes match, given that
* the hash keys are equal and that HASH_BITS >= 8.
*/
scan += 2;
match++;
// Assert(*scan == *match, "match[2]?");
/* We check for insufficient lookahead only every 8th comparison;
* the 256th check will be made at strstart+258.
*/
do {
/*jshint noempty:false*/
} while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
scan < strend);
// Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
len = MAX_MATCH - (strend - scan);
scan = strend - MAX_MATCH;
if (len > best_len) {
s.match_start = cur_match;
best_len = len;
if (len >= nice_match) {
break;
}
scan_end1 = _win[scan + best_len - 1];
scan_end = _win[scan + best_len];
}
} while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
if (best_len <= s.lookahead) {
return best_len;
}
return s.lookahead;
}
/* ===========================================================================
* Fill the window when the lookahead becomes insufficient.
* Updates strstart and lookahead.
*
* IN assertion: lookahead < MIN_LOOKAHEAD
* OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
* At least one byte has been read, or avail_in == 0; reads are
* performed for at least two bytes (required for the zip translate_eol
* option -- not supported here).
*/
function fill_window(s) {
var _w_size = s.w_size;
var p, n, m, more, str;
//Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
do {
more = s.window_size - s.lookahead - s.strstart;
// JS ints have 32 bit, block below not needed
/* Deal with !@#$% 64K limit: */
//if (sizeof(int) <= 2) {
// if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
// more = wsize;
//
// } else if (more == (unsigned)(-1)) {
// /* Very unlikely, but possible on 16 bit machine if
// * strstart == 0 && lookahead == 1 (input done a byte at time)
// */
// more--;
// }
//}
/* If the window is almost full and there is insufficient lookahead,
* move the upper half to the lower one to make room in the upper half.
*/
if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
s.match_start -= _w_size;
s.strstart -= _w_size;
/* we now have strstart >= MAX_DIST */
s.block_start -= _w_size;
/* Slide the hash table (could be avoided with 32 bit values
at the expense of memory usage). We slide even when level == 0
to keep the hash table consistent if we switch back to level > 0
later. (Using level 0 permanently is not an optimal usage of
zlib, so we don't care about this pathological case.)
*/
n = s.hash_size;
p = n;
do {
m = s.head[--p];
s.head[p] = (m >= _w_size ? m - _w_size : 0);
} while (--n);
n = _w_size;
p = n;
do {
m = s.prev[--p];
s.prev[p] = (m >= _w_size ? m - _w_size : 0);
/* If n is not on any hash chain, prev[n] is garbage but
* its value will never be used.
*/
} while (--n);
more += _w_size;
}
if (s.strm.avail_in === 0) {
break;
}
/* If there was no sliding:
* strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
* more == window_size - lookahead - strstart
* => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
* => more >= window_size - 2*WSIZE + 2
* In the BIG_MEM or MMAP case (not yet supported),
* window_size == input_size + MIN_LOOKAHEAD &&
* strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
* Otherwise, window_size == 2*WSIZE so more >= 2.
* If there was sliding, more >= WSIZE. So in all cases, more >= 2.
*/
//Assert(more >= 2, "more < 2");
n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
s.lookahead += n;
/* Initialize the hash value now that we have some input: */
if (s.lookahead + s.insert >= MIN_MATCH) {
str = s.strstart - s.insert;
s.ins_h = s.window[str];
/* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
//#if MIN_MATCH != 3
// Call update_hash() MIN_MATCH-3 more times
//#endif
while (s.insert) {
/* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
s.prev[str & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = str;
str++;
s.insert--;
if (s.lookahead + s.insert < MIN_MATCH) {
break;
}
}
}
/* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
* but this is not important since only literal bytes will be emitted.
*/
} while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
/* If the WIN_INIT bytes after the end of the current data have never been
* written, then zero those bytes in order to avoid memory check reports of
* the use of uninitialized (or uninitialised as Julian writes) bytes by
* the longest match routines. Update the high water mark for the next
* time through here. WIN_INIT is set to MAX_MATCH since the longest match
* routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
*/
// if (s.high_water < s.window_size) {
// var curr = s.strstart + s.lookahead;
// var init = 0;
//
// if (s.high_water < curr) {
// /* Previous high water mark below current data -- zero WIN_INIT
// * bytes or up to end of window, whichever is less.
// */
// init = s.window_size - curr;
// if (init > WIN_INIT)
// init = WIN_INIT;
// zmemzero(s->window + curr, (unsigned)init);
// s->high_water = curr + init;
// }
// else if (s->high_water < (ulg)curr + WIN_INIT) {
// /* High water mark at or above current data, but below current data
// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
// * to end of window, whichever is less.
// */
// init = (ulg)curr + WIN_INIT - s->high_water;
// if (init > s->window_size - s->high_water)
// init = s->window_size - s->high_water;
// zmemzero(s->window + s->high_water, (unsigned)init);
// s->high_water += init;
// }
// }
//
// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
// "not enough room for search");
}
/* ===========================================================================
* Copy without compression as much as possible from the input stream, return
* the current block state.
* This function does not insert new strings in the dictionary since
* uncompressible data is probably not useful. This function is used
* only for the level=0 compression option.
* NOTE: this function should be optimized to avoid extra copying from
* window to pending_buf.
*/
function deflate_stored(s, flush) {
/* Stored blocks are limited to 0xffff bytes, pending_buf is limited
* to pending_buf_size, and each stored block has a 5 byte header:
*/
var max_block_size = 0xffff;
if (max_block_size > s.pending_buf_size - 5) {
max_block_size = s.pending_buf_size - 5;
}
/* Copy as much as possible from input to output: */
for (;;) {
/* Fill the window as much as possible: */
if (s.lookahead <= 1) {
//Assert(s->strstart < s->w_size+MAX_DIST(s) ||
// s->block_start >= (long)s->w_size, "slide too late");
// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
// s.block_start >= s.w_size)) {
// throw new Error("slide too late");
// }
fill_window(s);
if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) {
break;
}
/* flush the current block */
}
//Assert(s->block_start >= 0L, "block gone");
// if (s.block_start < 0) throw new Error("block gone");
s.strstart += s.lookahead;
s.lookahead = 0;
/* Emit a stored block if pending_buf will be full: */
var max_start = s.block_start + max_block_size;
if (s.strstart === 0 || s.strstart >= max_start) {
/* strstart == 0 is possible when wraparound on 16-bit machine */
s.lookahead = s.strstart - max_start;
s.strstart = max_start;
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
/* Flush if we may have to slide, otherwise block_start may become
* negative and the data will be gone:
*/
if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.strstart > s.block_start) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_NEED_MORE;
}
/* ===========================================================================
* Compress as much as possible from the input stream, return the current
* block state.
* This function does not perform lazy evaluation of matches and inserts
* new strings in the dictionary only for unmatched strings or for short
* matches. It is used only for the fast compression options.
*/
function deflate_fast(s, flush) {
var hash_head; /* head of the hash chain */
var bflush; /* set if current block must be flushed */
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
if (s.lookahead < MIN_LOOKAHEAD) {
fill_window(s);
if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) {
break; /* flush the current block */
}
}
/* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
hash_head = 0/*NIL*/;
if (s.lookahead >= MIN_MATCH) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
/* Find the longest match, discarding those <= prev_length.
* At this point we have always match_length < MIN_MATCH
*/
if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
s.match_length = longest_match(s, hash_head);
/* longest_match() sets match_start */
}
if (s.match_length >= MIN_MATCH) {
// check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
/*** _tr_tally_dist(s, s.strstart - s.match_start,
s.match_length - MIN_MATCH, bflush); ***/
bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
s.lookahead -= s.match_length;
/* Insert new strings in the hash table only if the match length
* is not too large. This saves time but degrades compression.
*/
if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
s.match_length--; /* string at strstart already in table */
do {
s.strstart++;
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
/* strstart never exceeds WSIZE-MAX_MATCH, so there are
* always MIN_MATCH bytes ahead.
*/
} while (--s.match_length !== 0);
s.strstart++;
} else
{
s.strstart += s.match_length;
s.match_length = 0;
s.ins_h = s.window[s.strstart];
/* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
//#if MIN_MATCH != 3
// Call UPDATE_HASH() MIN_MATCH-3 more times
//#endif
/* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
* matter since it will be recomputed at next deflate call.
*/
}
} else {
/* No match, output a literal byte */
//Tracevv((stderr,"%c", s.window[s.strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
}
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* Same as above, but achieves better compression. We use a lazy
* evaluation for matches: a match is finally adopted only if there is
* no better match at the next window position.
*/
function deflate_slow(s, flush) {
var hash_head; /* head of hash chain */
var bflush; /* set if current block must be flushed */
var max_insert;
/* Process the input block. */
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
if (s.lookahead < MIN_LOOKAHEAD) {
fill_window(s);
if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) { break; } /* flush the current block */
}
/* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
hash_head = 0/*NIL*/;
if (s.lookahead >= MIN_MATCH) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
/* Find the longest match, discarding those <= prev_length.
*/
s.prev_length = s.match_length;
s.prev_match = s.match_start;
s.match_length = MIN_MATCH-1;
if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
s.match_length = longest_match(s, hash_head);
/* longest_match() sets match_start */
if (s.match_length <= 5 &&
(s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
/* If prev_match is also MIN_MATCH, match_start is garbage
* but we will ignore the current match anyway.
*/
s.match_length = MIN_MATCH-1;
}
}
/* If there was a match at the previous step and the current
* match is not better, output the previous match:
*/
if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
max_insert = s.strstart + s.lookahead - MIN_MATCH;
/* Do not insert strings in hash table beyond this. */
//check_match(s, s.strstart-1, s.prev_match, s.prev_length);
/***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
s.prev_length - MIN_MATCH, bflush);***/
bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
/* Insert in hash table all strings up to the end of the match.
* strstart-1 and strstart are already inserted. If there is not
* enough lookahead, the last two strings are not inserted in
* the hash table.
*/
s.lookahead -= s.prev_length-1;
s.prev_length -= 2;
do {
if (++s.strstart <= max_insert) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
} while (--s.prev_length !== 0);
s.match_available = 0;
s.match_length = MIN_MATCH-1;
s.strstart++;
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
} else if (s.match_available) {
/* If there was no match at the previous position, output a
* single literal. If there was a match but the current match
* is longer, truncate the previous match to a single literal.
*/
//Tracevv((stderr,"%c", s->window[s->strstart-1]));
/*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
if (bflush) {
/*** FLUSH_BLOCK_ONLY(s, 0) ***/
flush_block_only(s, false);
/***/
}
s.strstart++;
s.lookahead--;
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
} else {
/* There is no previous match to compare with, wait for
* the next step to decide.
*/
s.match_available = 1;
s.strstart++;
s.lookahead--;
}
}
//Assert (flush != Z_NO_FLUSH, "no flush?");
if (s.match_available) {
//Tracevv((stderr,"%c", s->window[s->strstart-1]));
/*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
s.match_available = 0;
}
s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* For Z_RLE, simply look for runs of bytes, generate matches only of distance
* one. Do not maintain a hash table. (It will be regenerated if this run of
* deflate switches away from Z_RLE.)
*/
function deflate_rle(s, flush) {
var bflush; /* set if current block must be flushed */
var prev; /* byte at distance one to match */
var scan, strend; /* scan goes up to strend for length of run */
var _win = s.window;
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the longest run, plus one for the unrolled loop.
*/
if (s.lookahead <= MAX_MATCH) {
fill_window(s);
if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) { break; } /* flush the current block */
}
/* See how many times the previous byte repeats */
s.match_length = 0;
if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
scan = s.strstart - 1;
prev = _win[scan];
if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
strend = s.strstart + MAX_MATCH;
do {
/*jshint noempty:false*/
} while (prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
scan < strend);
s.match_length = MAX_MATCH - (strend - scan);
if (s.match_length > s.lookahead) {
s.match_length = s.lookahead;
}
}
//Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
}
/* Emit match if have run of MIN_MATCH or longer, else emit literal */
if (s.match_length >= MIN_MATCH) {
//check_match(s, s.strstart, s.strstart - 1, s.match_length);
/*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
s.lookahead -= s.match_length;
s.strstart += s.match_length;
s.match_length = 0;
} else {
/* No match, output a literal byte */
//Tracevv((stderr,"%c", s->window[s->strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
}
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
* (It will be regenerated if this run of deflate switches away from Huffman.)
*/
function deflate_huff(s, flush) {
var bflush; /* set if current block must be flushed */
for (;;) {
/* Make sure that we have a literal to write. */
if (s.lookahead === 0) {
fill_window(s);
if (s.lookahead === 0) {
if (flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
break; /* flush the current block */
}
}
/* Output a literal byte */
s.match_length = 0;
//Tracevv((stderr,"%c", s->window[s->strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* Values for max_lazy_match, good_match and max_chain_length, depending on
* the desired pack level (0..9). The values given below have been tuned to
* exclude worst case performance for pathological files. Better values may be
* found for specific files.
*/
var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
this.good_length = good_length;
this.max_lazy = max_lazy;
this.nice_length = nice_length;
this.max_chain = max_chain;
this.func = func;
};
var configuration_table;
configuration_table = [
/* good lazy nice chain */
new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
new Config(4, 5, 16, 8, deflate_fast), /* 2 */
new Config(4, 6, 32, 32, deflate_fast), /* 3 */
new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
new Config(8, 16, 32, 32, deflate_slow), /* 5 */
new Config(8, 16, 128, 128, deflate_slow), /* 6 */
new Config(8, 32, 128, 256, deflate_slow), /* 7 */
new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
];
/* ===========================================================================
* Initialize the "longest match" routines for a new zlib stream
*/
function lm_init(s) {
s.window_size = 2 * s.w_size;
/*** CLEAR_HASH(s); ***/
zero(s.head); // Fill with NIL (= 0);
/* Set the default configuration parameters:
*/
s.max_lazy_match = configuration_table[s.level].max_lazy;
s.good_match = configuration_table[s.level].good_length;
s.nice_match = configuration_table[s.level].nice_length;
s.max_chain_length = configuration_table[s.level].max_chain;
s.strstart = 0;
s.block_start = 0;
s.lookahead = 0;
s.insert = 0;
s.match_length = s.prev_length = MIN_MATCH - 1;
s.match_available = 0;
s.ins_h = 0;
}
function DeflateState() {
this.strm = null; /* pointer back to this zlib stream */
this.status = 0; /* as the name implies */
this.pending_buf = null; /* output still pending */
this.pending_buf_size = 0; /* size of pending_buf */
this.pending_out = 0; /* next pending byte to output to the stream */
this.pending = 0; /* nb of bytes in the pending buffer */
this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
this.gzhead = null; /* gzip header information to write */
this.gzindex = 0; /* where in extra, name, or comment */
this.method = Z_DEFLATED; /* can only be DEFLATED */
this.last_flush = -1; /* value of flush param for previous deflate call */
this.w_size = 0; /* LZ77 window size (32K by default) */
this.w_bits = 0; /* log2(w_size) (8..16) */
this.w_mask = 0; /* w_size - 1 */
this.window = null;
/* Sliding window. Input bytes are read into the second half of the window,
* and move to the first half later to keep a dictionary of at least wSize
* bytes. With this organization, matches are limited to a distance of
* wSize-MAX_MATCH bytes, but this ensures that IO is always
* performed with a length multiple of the block size.
*/
this.window_size = 0;
/* Actual size of window: 2*wSize, except when the user input buffer
* is directly used as sliding window.
*/
this.prev = null;
/* Link to older string with same hash index. To limit the size of this
* array to 64K, this link is maintained only for the last 32K strings.
* An index in this array is thus a window index modulo 32K.
*/
this.head = null; /* Heads of the hash chains or NIL. */
this.ins_h = 0; /* hash index of string to be inserted */
this.hash_size = 0; /* number of elements in hash table */
this.hash_bits = 0; /* log2(hash_size) */
this.hash_mask = 0; /* hash_size-1 */
this.hash_shift = 0;
/* Number of bits by which ins_h must be shifted at each input
* step. It must be such that after MIN_MATCH steps, the oldest
* byte no longer takes part in the hash key, that is:
* hash_shift * MIN_MATCH >= hash_bits
*/
this.block_start = 0;
/* Window position at the beginning of the current output block. Gets
* negative when the window is moved backwards.
*/
this.match_length = 0; /* length of best match */
this.prev_match = 0; /* previous match */
this.match_available = 0; /* set if previous match exists */
this.strstart = 0; /* start of string to insert */
this.match_start = 0; /* start of matching string */
this.lookahead = 0; /* number of valid bytes ahead in window */
this.prev_length = 0;
/* Length of the best match at previous step. Matches not greater than this
* are discarded. This is used in the lazy match evaluation.
*/
this.max_chain_length = 0;
/* To speed up deflation, hash chains are never searched beyond this
* length. A higher limit improves compression ratio but degrades the
* speed.
*/
this.max_lazy_match = 0;
/* Attempt to find a better match only when the current match is strictly
* smaller than this value. This mechanism is used only for compression
* levels >= 4.
*/
// That's alias to max_lazy_match, don't use directly
//this.max_insert_length = 0;
/* Insert new strings in the hash table only if the match length is not
* greater than this length. This saves time but degrades compression.
* max_insert_length is used only for compression levels <= 3.
*/
this.level = 0; /* compression level (1..9) */
this.strategy = 0; /* favor or force Huffman coding*/
this.good_match = 0;
/* Use a faster search when the previous match is longer than this */
this.nice_match = 0; /* Stop searching when current match exceeds this */
/* used by trees.c: */
/* Didn't use ct_data typedef below to suppress compiler warning */
// struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
// struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
// struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
// Use flat array of DOUBLE size, with interleaved fata,
// because JS does not support effective
this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
zero(this.dyn_ltree);
zero(this.dyn_dtree);
zero(this.bl_tree);
this.l_desc = null; /* desc. for literal tree */
this.d_desc = null; /* desc. for distance tree */
this.bl_desc = null; /* desc. for bit length tree */
//ush bl_count[MAX_BITS+1];
this.bl_count = new utils.Buf16(MAX_BITS+1);
/* number of codes at each bit length for an optimal tree */
//int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
zero(this.heap);
this.heap_len = 0; /* number of elements in the heap */
this.heap_max = 0; /* element of largest frequency */
/* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
* The same heap array is used to build all trees.
*/
this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
zero(this.depth);
/* Depth of each subtree used as tie breaker for trees of equal frequency
*/
this.l_buf = 0; /* buffer index for literals or lengths */
this.lit_bufsize = 0;
/* Size of match buffer for literals/lengths. There are 4 reasons for
* limiting lit_bufsize to 64K:
* - frequencies can be kept in 16 bit counters
* - if compression is not successful for the first block, all input
* data is still in the window so we can still emit a stored block even
* when input comes from standard input. (This can also be done for
* all blocks if lit_bufsize is not greater than 32K.)
* - if compression is not successful for a file smaller than 64K, we can
* even emit a stored file instead of a stored block (saving 5 bytes).
* This is applicable only for zip (not gzip or zlib).
* - creating new Huffman trees less frequently may not provide fast
* adaptation to changes in the input data statistics. (Take for
* example a binary file with poorly compressible code followed by
* a highly compressible string table.) Smaller buffer sizes give
* fast adaptation but have of course the overhead of transmitting
* trees more frequently.
* - I can't count above 4
*/
this.last_lit = 0; /* running index in l_buf */
this.d_buf = 0;
/* Buffer index for distances. To simplify the code, d_buf and l_buf have
* the same number of elements. To use different lengths, an extra flag
* array would be necessary.
*/
this.opt_len = 0; /* bit length of current block with optimal trees */
this.static_len = 0; /* bit length of current block with static trees */
this.matches = 0; /* number of string matches in current block */
this.insert = 0; /* bytes at end of window left to insert */
this.bi_buf = 0;
/* Output buffer. bits are inserted starting at the bottom (least
* significant bits).
*/
this.bi_valid = 0;
/* Number of valid bits in bi_buf. All bits above the last valid bit
* are always zero.
*/
// Used for window memory init. We safely ignore it for JS. That makes
// sense only for pointers and memory check tools.
//this.high_water = 0;
/* High water mark offset in window for initialized bytes -- bytes above
* this are set to zero in order to avoid memory check warnings when
* longest match routines access bytes past the input. This is then
* updated to the new high water mark.
*/
}
function deflateResetKeep(strm) {
var s;
if (!strm || !strm.state) {
return err(strm, Z_STREAM_ERROR);
}
strm.total_in = strm.total_out = 0;
strm.data_type = Z_UNKNOWN;
s = strm.state;
s.pending = 0;
s.pending_out = 0;
if (s.wrap < 0) {
s.wrap = -s.wrap;
/* was made negative by deflate(..., Z_FINISH); */
}
s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
strm.adler = (s.wrap === 2) ?
0 // crc32(0, Z_NULL, 0)
:
1; // adler32(0, Z_NULL, 0)
s.last_flush = Z_NO_FLUSH;
trees._tr_init(s);
return Z_OK;
}
function deflateReset(strm) {
var ret = deflateResetKeep(strm);
if (ret === Z_OK) {
lm_init(strm.state);
}
return ret;
}
function deflateSetHeader(strm, head) {
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
strm.state.gzhead = head;
return Z_OK;
}
function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
if (!strm) { // === Z_NULL
return Z_STREAM_ERROR;
}
var wrap = 1;
if (level === Z_DEFAULT_COMPRESSION) {
level = 6;
}
if (windowBits < 0) { /* suppress zlib wrapper */
wrap = 0;
windowBits = -windowBits;
}
else if (windowBits > 15) {
wrap = 2; /* write gzip wrapper instead */
windowBits -= 16;
}
if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
strategy < 0 || strategy > Z_FIXED) {
return err(strm, Z_STREAM_ERROR);
}
if (windowBits === 8) {
windowBits = 9;
}
/* until 256-byte window bug fixed */
var s = new DeflateState();
strm.state = s;
s.strm = strm;
s.wrap = wrap;
s.gzhead = null;
s.w_bits = windowBits;
s.w_size = 1 << s.w_bits;
s.w_mask = s.w_size - 1;
s.hash_bits = memLevel + 7;
s.hash_size = 1 << s.hash_bits;
s.hash_mask = s.hash_size - 1;
s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
s.window = new utils.Buf8(s.w_size * 2);
s.head = new utils.Buf16(s.hash_size);
s.prev = new utils.Buf16(s.w_size);
// Don't need mem init magic for JS.
//s.high_water = 0; /* nothing written to s->window yet */
s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
s.pending_buf_size = s.lit_bufsize * 4;
s.pending_buf = new utils.Buf8(s.pending_buf_size);
s.d_buf = s.lit_bufsize >> 1;
s.l_buf = (1 + 2) * s.lit_bufsize;
s.level = level;
s.strategy = strategy;
s.method = method;
return deflateReset(strm);
}
function deflateInit(strm, level) {
return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
}
function deflate(strm, flush) {
var old_flush, s;
var beg, val; // for gzip header write only
if (!strm || !strm.state ||
flush > Z_BLOCK || flush < 0) {
return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
}
s = strm.state;
if (!strm.output ||
(!strm.input && strm.avail_in !== 0) ||
(s.status === FINISH_STATE && flush !== Z_FINISH)) {
return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
}
s.strm = strm; /* just in case */
old_flush = s.last_flush;
s.last_flush = flush;
/* Write the header */
if (s.status === INIT_STATE) {
if (s.wrap === 2) { // GZIP header
strm.adler = 0; //crc32(0L, Z_NULL, 0);
put_byte(s, 31);
put_byte(s, 139);
put_byte(s, 8);
if (!s.gzhead) { // s->gzhead == Z_NULL
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, s.level === 9 ? 2 :
(s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
4 : 0));
put_byte(s, OS_CODE);
s.status = BUSY_STATE;
}
else {
put_byte(s, (s.gzhead.text ? 1 : 0) +
(s.gzhead.hcrc ? 2 : 0) +
(!s.gzhead.extra ? 0 : 4) +
(!s.gzhead.name ? 0 : 8) +
(!s.gzhead.comment ? 0 : 16)
);
put_byte(s, s.gzhead.time & 0xff);
put_byte(s, (s.gzhead.time >> 8) & 0xff);
put_byte(s, (s.gzhead.time >> 16) & 0xff);
put_byte(s, (s.gzhead.time >> 24) & 0xff);
put_byte(s, s.level === 9 ? 2 :
(s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
4 : 0));
put_byte(s, s.gzhead.os & 0xff);
if (s.gzhead.extra && s.gzhead.extra.length) {
put_byte(s, s.gzhead.extra.length & 0xff);
put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
}
if (s.gzhead.hcrc) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
}
s.gzindex = 0;
s.status = EXTRA_STATE;
}
}
else // DEFLATE header
{
var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
var level_flags = -1;
if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
level_flags = 0;
} else if (s.level < 6) {
level_flags = 1;
} else if (s.level === 6) {
level_flags = 2;
} else {
level_flags = 3;
}
header |= (level_flags << 6);
if (s.strstart !== 0) { header |= PRESET_DICT; }
header += 31 - (header % 31);
s.status = BUSY_STATE;
putShortMSB(s, header);
/* Save the adler32 of the preset dictionary: */
if (s.strstart !== 0) {
putShortMSB(s, strm.adler >>> 16);
putShortMSB(s, strm.adler & 0xffff);
}
strm.adler = 1; // adler32(0L, Z_NULL, 0);
}
}
//#ifdef GZIP
if (s.status === EXTRA_STATE) {
if (s.gzhead.extra/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
break;
}
}
put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
s.gzindex++;
}
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (s.gzindex === s.gzhead.extra.length) {
s.gzindex = 0;
s.status = NAME_STATE;
}
}
else {
s.status = NAME_STATE;
}
}
if (s.status === NAME_STATE) {
if (s.gzhead.name/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
//int val;
do {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
val = 1;
break;
}
}
// JS specific: little magic to add zero terminator to end of string
if (s.gzindex < s.gzhead.name.length) {
val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
} else {
val = 0;
}
put_byte(s, val);
} while (val !== 0);
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (val === 0) {
s.gzindex = 0;
s.status = COMMENT_STATE;
}
}
else {
s.status = COMMENT_STATE;
}
}
if (s.status === COMMENT_STATE) {
if (s.gzhead.comment/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
//int val;
do {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
val = 1;
break;
}
}
// JS specific: little magic to add zero terminator to end of string
if (s.gzindex < s.gzhead.comment.length) {
val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
} else {
val = 0;
}
put_byte(s, val);
} while (val !== 0);
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (val === 0) {
s.status = HCRC_STATE;
}
}
else {
s.status = HCRC_STATE;
}
}
if (s.status === HCRC_STATE) {
if (s.gzhead.hcrc) {
if (s.pending + 2 > s.pending_buf_size) {
flush_pending(strm);
}
if (s.pending + 2 <= s.pending_buf_size) {
put_byte(s, strm.adler & 0xff);
put_byte(s, (strm.adler >> 8) & 0xff);
strm.adler = 0; //crc32(0L, Z_NULL, 0);
s.status = BUSY_STATE;
}
}
else {
s.status = BUSY_STATE;
}
}
//#endif
/* Flush as much pending output as possible */
if (s.pending !== 0) {
flush_pending(strm);
if (strm.avail_out === 0) {
/* Since avail_out is 0, deflate will be called again with
* more output space, but possibly with both pending and
* avail_in equal to zero. There won't be anything to do,
* but this is not an error situation so make sure we
* return OK instead of BUF_ERROR at next call of deflate:
*/
s.last_flush = -1;
return Z_OK;
}
/* Make sure there is something to do and avoid duplicate consecutive
* flushes. For repeated and useless calls with Z_FINISH, we keep
* returning Z_STREAM_END instead of Z_BUF_ERROR.
*/
} else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
flush !== Z_FINISH) {
return err(strm, Z_BUF_ERROR);
}
/* User must not provide more input after the first FINISH: */
if (s.status === FINISH_STATE && strm.avail_in !== 0) {
return err(strm, Z_BUF_ERROR);
}
/* Start a new block or continue the current one.
*/
if (strm.avail_in !== 0 || s.lookahead !== 0 ||
(flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
(s.strategy === Z_RLE ? deflate_rle(s, flush) :
configuration_table[s.level].func(s, flush));
if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
s.status = FINISH_STATE;
}
if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
if (strm.avail_out === 0) {
s.last_flush = -1;
/* avoid BUF_ERROR next call, see above */
}
return Z_OK;
/* If flush != Z_NO_FLUSH && avail_out == 0, the next call
* of deflate should use the same flush parameter to make sure
* that the flush is complete. So we don't have to output an
* empty block here, this will be done at next call. This also
* ensures that for a very small output buffer, we emit at most
* one empty block.
*/
}
if (bstate === BS_BLOCK_DONE) {
if (flush === Z_PARTIAL_FLUSH) {
trees._tr_align(s);
}
else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
trees._tr_stored_block(s, 0, 0, false);
/* For a full flush, this empty block will be recognized
* as a special marker by inflate_sync().
*/
if (flush === Z_FULL_FLUSH) {
/*** CLEAR_HASH(s); ***/ /* forget history */
zero(s.head); // Fill with NIL (= 0);
if (s.lookahead === 0) {
s.strstart = 0;
s.block_start = 0;
s.insert = 0;
}
}
}
flush_pending(strm);
if (strm.avail_out === 0) {
s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
return Z_OK;
}
}
}
//Assert(strm->avail_out > 0, "bug2");
//if (strm.avail_out <= 0) { throw new Error("bug2");}
if (flush !== Z_FINISH) { return Z_OK; }
if (s.wrap <= 0) { return Z_STREAM_END; }
/* Write the trailer */
if (s.wrap === 2) {
put_byte(s, strm.adler & 0xff);
put_byte(s, (strm.adler >> 8) & 0xff);
put_byte(s, (strm.adler >> 16) & 0xff);
put_byte(s, (strm.adler >> 24) & 0xff);
put_byte(s, strm.total_in & 0xff);
put_byte(s, (strm.total_in >> 8) & 0xff);
put_byte(s, (strm.total_in >> 16) & 0xff);
put_byte(s, (strm.total_in >> 24) & 0xff);
}
else
{
putShortMSB(s, strm.adler >>> 16);
putShortMSB(s, strm.adler & 0xffff);
}
flush_pending(strm);
/* If avail_out is zero, the application will call deflate again
* to flush the rest.
*/
if (s.wrap > 0) { s.wrap = -s.wrap; }
/* write the trailer only once! */
return s.pending !== 0 ? Z_OK : Z_STREAM_END;
}
function deflateEnd(strm) {
var status;
if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
return Z_STREAM_ERROR;
}
status = strm.state.status;
if (status !== INIT_STATE &&
status !== EXTRA_STATE &&
status !== NAME_STATE &&
status !== COMMENT_STATE &&
status !== HCRC_STATE &&
status !== BUSY_STATE &&
status !== FINISH_STATE
) {
return err(strm, Z_STREAM_ERROR);
}
strm.state = null;
return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
}
/* =========================================================================
* Copy the source state to the destination state
*/
//function deflateCopy(dest, source) {
//
//}
exports.deflateInit = deflateInit;
exports.deflateInit2 = deflateInit2;
exports.deflateReset = deflateReset;
exports.deflateResetKeep = deflateResetKeep;
exports.deflateSetHeader = deflateSetHeader;
exports.deflate = deflate;
exports.deflateEnd = deflateEnd;
exports.deflateInfo = 'pako deflate (from Nodeca project)';
/* Not implemented
exports.deflateBound = deflateBound;
exports.deflateCopy = deflateCopy;
exports.deflateSetDictionary = deflateSetDictionary;
exports.deflateParams = deflateParams;
exports.deflatePending = deflatePending;
exports.deflatePrime = deflatePrime;
exports.deflateTune = deflateTune;
*/
},{"../utils/common":129,"./adler32":131,"./crc32":133,"./messages":139,"./trees":140}],135:[function(require,module,exports){
'use strict';
function GZheader() {
/* true if compressed data believed to be text */
this.text = 0;
/* modification time */
this.time = 0;
/* extra flags (not used when writing a gzip file) */
this.xflags = 0;
/* operating system */
this.os = 0;
/* pointer to extra field or Z_NULL if none */
this.extra = null;
/* extra field length (valid if extra != Z_NULL) */
this.extra_len = 0; // Actually, we don't need it in JS,
// but leave for few code modifications
//
// Setup limits is not necessary because in js we should not preallocate memory
// for inflate use constant limit in 65536 bytes
//
/* space at extra (only when reading header) */
// this.extra_max = 0;
/* pointer to zero-terminated file name or Z_NULL */
this.name = '';
/* space at name (only when reading header) */
// this.name_max = 0;
/* pointer to zero-terminated comment or Z_NULL */
this.comment = '';
/* space at comment (only when reading header) */
// this.comm_max = 0;
/* true if there was or will be a header crc */
this.hcrc = 0;
/* true when done reading gzip header (not used when writing a gzip file) */
this.done = false;
}
module.exports = GZheader;
},{}],136:[function(require,module,exports){
'use strict';
// See state defs from inflate.js
var BAD = 30; /* got a data error -- remain here until reset */
var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
/*
Decode literal, length, and distance codes and write out the resulting
literal and match bytes until either not enough input or output is
available, an end-of-block is encountered, or a data error is encountered.
When large enough input and output buffers are supplied to inflate(), for
example, a 16K input buffer and a 64K output buffer, more than 95% of the
inflate execution time is spent in this routine.
Entry assumptions:
state.mode === LEN
strm.avail_in >= 6
strm.avail_out >= 258
start >= strm.avail_out
state.bits < 8
On return, state.mode is one of:
LEN -- ran out of enough output space or enough available input
TYPE -- reached end of block code, inflate() to interpret next block
BAD -- error in block data
Notes:
- The maximum input bits used by a length/distance pair is 15 bits for the
length code, 5 bits for the length extra, 15 bits for the distance code,
and 13 bits for the distance extra. This totals 48 bits, or six bytes.
Therefore if strm.avail_in >= 6, then there is enough input to avoid
checking for available input while decoding.
- The maximum bytes that a single length/distance pair can output is 258
bytes, which is the maximum length that can be coded. inflate_fast()
requires strm.avail_out >= 258 for each loop to avoid checking for
output space.
*/
module.exports = function inflate_fast(strm, start) {
var state;
var _in; /* local strm.input */
var last; /* have enough input while in < last */
var _out; /* local strm.output */
var beg; /* inflate()'s initial strm.output */
var end; /* while out < end, enough space available */
//#ifdef INFLATE_STRICT
var dmax; /* maximum distance from zlib header */
//#endif
var wsize; /* window size or zero if not using window */
var whave; /* valid bytes in the window */
var wnext; /* window write index */
var window; /* allocated sliding window, if wsize != 0 */
var hold; /* local strm.hold */
var bits; /* local strm.bits */
var lcode; /* local strm.lencode */
var dcode; /* local strm.distcode */
var lmask; /* mask for first level of length codes */
var dmask; /* mask for first level of distance codes */
var here; /* retrieved table entry */
var op; /* code bits, operation, extra bits, or */
/* window position, window bytes to copy */
var len; /* match length, unused bytes */
var dist; /* match distance */
var from; /* where to copy match from */
var from_source;
var input, output; // JS specific, because we have no pointers
/* copy state to local variables */
state = strm.state;
//here = state.here;
_in = strm.next_in;
input = strm.input;
last = _in + (strm.avail_in - 5);
_out = strm.next_out;
output = strm.output;
beg = _out - (start - strm.avail_out);
end = _out + (strm.avail_out - 257);
//#ifdef INFLATE_STRICT
dmax = state.dmax;
//#endif
wsize = state.wsize;
whave = state.whave;
wnext = state.wnext;
window = state.window;
hold = state.hold;
bits = state.bits;
lcode = state.lencode;
dcode = state.distcode;
lmask = (1 << state.lenbits) - 1;
dmask = (1 << state.distbits) - 1;
/* decode literals and length/distances until end-of-block or not enough
input data or output space */
top:
do {
if (bits < 15) {
hold += input[_in++] << bits;
bits += 8;
hold += input[_in++] << bits;
bits += 8;
}
here = lcode[hold & lmask];
dolen:
for (;;) { // Goto emulation
op = here >>> 24/*here.bits*/;
hold >>>= op;
bits -= op;
op = (here >>> 16) & 0xff/*here.op*/;
if (op === 0) { /* literal */
//Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
// "inflate: literal '%c'\n" :
// "inflate: literal 0x%02x\n", here.val));
output[_out++] = here & 0xffff/*here.val*/;
}
else if (op & 16) { /* length base */
len = here & 0xffff/*here.val*/;
op &= 15; /* number of extra bits */
if (op) {
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
}
len += hold & ((1 << op) - 1);
hold >>>= op;
bits -= op;
}
//Tracevv((stderr, "inflate: length %u\n", len));
if (bits < 15) {
hold += input[_in++] << bits;
bits += 8;
hold += input[_in++] << bits;
bits += 8;
}
here = dcode[hold & dmask];
dodist:
for (;;) { // goto emulation
op = here >>> 24/*here.bits*/;
hold >>>= op;
bits -= op;
op = (here >>> 16) & 0xff/*here.op*/;
if (op & 16) { /* distance base */
dist = here & 0xffff/*here.val*/;
op &= 15; /* number of extra bits */
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
}
}
dist += hold & ((1 << op) - 1);
//#ifdef INFLATE_STRICT
if (dist > dmax) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break top;
}
//#endif
hold >>>= op;
bits -= op;
//Tracevv((stderr, "inflate: distance %u\n", dist));
op = _out - beg; /* max distance in output */
if (dist > op) { /* see if copy from window */
op = dist - op; /* distance back in window */
if (op > whave) {
if (state.sane) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break top;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
// if (len <= op - whave) {
// do {
// output[_out++] = 0;
// } while (--len);
// continue top;
// }
// len -= op - whave;
// do {
// output[_out++] = 0;
// } while (--op > whave);
// if (op === 0) {
// from = _out - dist;
// do {
// output[_out++] = output[from++];
// } while (--len);
// continue top;
// }
//#endif
}
from = 0; // window index
from_source = window;
if (wnext === 0) { /* very common case */
from += wsize - op;
if (op < len) { /* some from window */
len -= op;
do {
output[_out++] = window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
else if (wnext < op) { /* wrap around window */
from += wsize + wnext - op;
op -= wnext;
if (op < len) { /* some from end of window */
len -= op;
do {
output[_out++] = window[from++];
} while (--op);
from = 0;
if (wnext < len) { /* some from start of window */
op = wnext;
len -= op;
do {
output[_out++] = window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
}
else { /* contiguous in window */
from += wnext - op;
if (op < len) { /* some from window */
len -= op;
do {
output[_out++] = window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
while (len > 2) {
output[_out++] = from_source[from++];
output[_out++] = from_source[from++];
output[_out++] = from_source[from++];
len -= 3;
}
if (len) {
output[_out++] = from_source[from++];
if (len > 1) {
output[_out++] = from_source[from++];
}
}
}
else {
from = _out - dist; /* copy direct from output */
do { /* minimum length is three */
output[_out++] = output[from++];
output[_out++] = output[from++];
output[_out++] = output[from++];
len -= 3;
} while (len > 2);
if (len) {
output[_out++] = output[from++];
if (len > 1) {
output[_out++] = output[from++];
}
}
}
}
else if ((op & 64) === 0) { /* 2nd level distance code */
here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
continue dodist;
}
else {
strm.msg = 'invalid distance code';
state.mode = BAD;
break top;
}
break; // need to emulate goto via "continue"
}
}
else if ((op & 64) === 0) { /* 2nd level length code */
here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
continue dolen;
}
else if (op & 32) { /* end-of-block */
//Tracevv((stderr, "inflate: end of block\n"));
state.mode = TYPE;
break top;
}
else {
strm.msg = 'invalid literal/length code';
state.mode = BAD;
break top;
}
break; // need to emulate goto via "continue"
}
} while (_in < last && _out < end);
/* return unused bytes (on entry, bits < 8, so in won't go too far back) */
len = bits >> 3;
_in -= len;
bits -= len << 3;
hold &= (1 << bits) - 1;
/* update state and return */
strm.next_in = _in;
strm.next_out = _out;
strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
state.hold = hold;
state.bits = bits;
return;
};
},{}],137:[function(require,module,exports){
'use strict';
var utils = require('../utils/common');
var adler32 = require('./adler32');
var crc32 = require('./crc32');
var inflate_fast = require('./inffast');
var inflate_table = require('./inftrees');
var CODES = 0;
var LENS = 1;
var DISTS = 2;
/* Public constants ==========================================================*/
/* ===========================================================================*/
/* Allowed flush values; see deflate() and inflate() below for details */
//var Z_NO_FLUSH = 0;
//var Z_PARTIAL_FLUSH = 1;
//var Z_SYNC_FLUSH = 2;
//var Z_FULL_FLUSH = 3;
var Z_FINISH = 4;
var Z_BLOCK = 5;
var Z_TREES = 6;
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
var Z_OK = 0;
var Z_STREAM_END = 1;
var Z_NEED_DICT = 2;
//var Z_ERRNO = -1;
var Z_STREAM_ERROR = -2;
var Z_DATA_ERROR = -3;
var Z_MEM_ERROR = -4;
var Z_BUF_ERROR = -5;
//var Z_VERSION_ERROR = -6;
/* The deflate compression method */
var Z_DEFLATED = 8;
/* STATES ====================================================================*/
/* ===========================================================================*/
var HEAD = 1; /* i: waiting for magic header */
var FLAGS = 2; /* i: waiting for method and flags (gzip) */
var TIME = 3; /* i: waiting for modification time (gzip) */
var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
var EXLEN = 5; /* i: waiting for extra length (gzip) */
var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
var NAME = 7; /* i: waiting for end of file name (gzip) */
var COMMENT = 8; /* i: waiting for end of comment (gzip) */
var HCRC = 9; /* i: waiting for header crc (gzip) */
var DICTID = 10; /* i: waiting for dictionary check value */
var DICT = 11; /* waiting for inflateSetDictionary() call */
var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
var STORED = 14; /* i: waiting for stored size (length and complement) */
var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
var COPY = 16; /* i/o: waiting for input or output to copy stored block */
var TABLE = 17; /* i: waiting for dynamic block table lengths */
var LENLENS = 18; /* i: waiting for code length code lengths */
var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
var LEN_ = 20; /* i: same as LEN below, but only first time in */
var LEN = 21; /* i: waiting for length/lit/eob code */
var LENEXT = 22; /* i: waiting for length extra bits */
var DIST = 23; /* i: waiting for distance code */
var DISTEXT = 24; /* i: waiting for distance extra bits */
var MATCH = 25; /* o: waiting for output space to copy string */
var LIT = 26; /* o: waiting for output space to write literal */
var CHECK = 27; /* i: waiting for 32-bit check value */
var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
var DONE = 29; /* finished check, done -- remain here until reset */
var BAD = 30; /* got a data error -- remain here until reset */
var MEM = 31; /* got an inflate() memory error -- remain here until reset */
var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
/* ===========================================================================*/
var ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592;
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
var MAX_WBITS = 15;
/* 32K LZ77 window */
var DEF_WBITS = MAX_WBITS;
function ZSWAP32(q) {
return (((q >>> 24) & 0xff) +
((q >>> 8) & 0xff00) +
((q & 0xff00) << 8) +
((q & 0xff) << 24));
}
function InflateState() {
this.mode = 0; /* current inflate mode */
this.last = false; /* true if processing last block */
this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
this.havedict = false; /* true if dictionary provided */
this.flags = 0; /* gzip header method and flags (0 if zlib) */
this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
this.check = 0; /* protected copy of check value */
this.total = 0; /* protected copy of output count */
// TODO: may be {}
this.head = null; /* where to save gzip header information */
/* sliding window */
this.wbits = 0; /* log base 2 of requested window size */
this.wsize = 0; /* window size or zero if not using window */
this.whave = 0; /* valid bytes in the window */
this.wnext = 0; /* window write index */
this.window = null; /* allocated sliding window, if needed */
/* bit accumulator */
this.hold = 0; /* input bit accumulator */
this.bits = 0; /* number of bits in "in" */
/* for string and stored block copying */
this.length = 0; /* literal or length of data to copy */
this.offset = 0; /* distance back to copy string from */
/* for table and code decoding */
this.extra = 0; /* extra bits needed */
/* fixed and dynamic code tables */
this.lencode = null; /* starting table for length/literal codes */
this.distcode = null; /* starting table for distance codes */
this.lenbits = 0; /* index bits for lencode */
this.distbits = 0; /* index bits for distcode */
/* dynamic table building */
this.ncode = 0; /* number of code length code lengths */
this.nlen = 0; /* number of length code lengths */
this.ndist = 0; /* number of distance code lengths */
this.have = 0; /* number of code lengths in lens[] */
this.next = null; /* next available space in codes[] */
this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
this.work = new utils.Buf16(288); /* work area for code table building */
/*
because we don't have pointers in js, we use lencode and distcode directly
as buffers so we don't need codes
*/
//this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
this.distdyn = null; /* dynamic table for distance codes (JS specific) */
this.sane = 0; /* if false, allow invalid distance too far */
this.back = 0; /* bits back of last unprocessed length/lit */
this.was = 0; /* initial length of match */
}
function inflateResetKeep(strm) {
var state;
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
strm.total_in = strm.total_out = state.total = 0;
strm.msg = ''; /*Z_NULL*/
if (state.wrap) { /* to support ill-conceived Java test suite */
strm.adler = state.wrap & 1;
}
state.mode = HEAD;
state.last = 0;
state.havedict = 0;
state.dmax = 32768;
state.head = null/*Z_NULL*/;
state.hold = 0;
state.bits = 0;
//state.lencode = state.distcode = state.next = state.codes;
state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
state.sane = 1;
state.back = -1;
//Tracev((stderr, "inflate: reset\n"));
return Z_OK;
}
function inflateReset(strm) {
var state;
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
state.wsize = 0;
state.whave = 0;
state.wnext = 0;
return inflateResetKeep(strm);
}
function inflateReset2(strm, windowBits) {
var wrap;
var state;
/* get the state */
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
/* extract wrap request from windowBits parameter */
if (windowBits < 0) {
wrap = 0;
windowBits = -windowBits;
}
else {
wrap = (windowBits >> 4) + 1;
if (windowBits < 48) {
windowBits &= 15;
}
}
/* set number of window bits, free window if different */
if (windowBits && (windowBits < 8 || windowBits > 15)) {
return Z_STREAM_ERROR;
}
if (state.window !== null && state.wbits !== windowBits) {
state.window = null;
}
/* update state and reset the rest of it */
state.wrap = wrap;
state.wbits = windowBits;
return inflateReset(strm);
}
function inflateInit2(strm, windowBits) {
var ret;
var state;
if (!strm) { return Z_STREAM_ERROR; }
//strm.msg = Z_NULL; /* in case we return an error */
state = new InflateState();
//if (state === Z_NULL) return Z_MEM_ERROR;
//Tracev((stderr, "inflate: allocated\n"));
strm.state = state;
state.window = null/*Z_NULL*/;
ret = inflateReset2(strm, windowBits);
if (ret !== Z_OK) {
strm.state = null/*Z_NULL*/;
}
return ret;
}
function inflateInit(strm) {
return inflateInit2(strm, DEF_WBITS);
}
/*
Return state with length and distance decoding tables and index sizes set to
fixed code decoding. Normally this returns fixed tables from inffixed.h.
If BUILDFIXED is defined, then instead this routine builds the tables the
first time it's called, and returns those tables the first time and
thereafter. This reduces the size of the code by about 2K bytes, in
exchange for a little execution time. However, BUILDFIXED should not be
used for threaded applications, since the rewriting of the tables and virgin
may not be thread-safe.
*/
var virgin = true;
var lenfix, distfix; // We have no pointers in JS, so keep tables separate
function fixedtables(state) {
/* build fixed huffman tables if first call (may not be thread safe) */
if (virgin) {
var sym;
lenfix = new utils.Buf32(512);
distfix = new utils.Buf32(32);
/* literal/length table */
sym = 0;
while (sym < 144) { state.lens[sym++] = 8; }
while (sym < 256) { state.lens[sym++] = 9; }
while (sym < 280) { state.lens[sym++] = 7; }
while (sym < 288) { state.lens[sym++] = 8; }
inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
/* distance table */
sym = 0;
while (sym < 32) { state.lens[sym++] = 5; }
inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
/* do this just once */
virgin = false;
}
state.lencode = lenfix;
state.lenbits = 9;
state.distcode = distfix;
state.distbits = 5;
}
/*
Update the window with the last wsize (normally 32K) bytes written before
returning. If window does not exist yet, create it. This is only called
when a window is already in use, or when output has been written during this
inflate call, but the end of the deflate stream has not been reached yet.
It is also called to create a window for dictionary data when a dictionary
is loaded.
Providing output buffers larger than 32K to inflate() should provide a speed
advantage, since only the last 32K of output is copied to the sliding window
upon return from inflate(), and since all distances after the first 32K of
output will fall in the output data, making match copies simpler and faster.
The advantage may be dependent on the size of the processor's data caches.
*/
function updatewindow(strm, src, end, copy) {
var dist;
var state = strm.state;
/* if it hasn't been done already, allocate space for the window */
if (state.window === null) {
state.wsize = 1 << state.wbits;
state.wnext = 0;
state.whave = 0;
state.window = new utils.Buf8(state.wsize);
}
/* copy state->wsize or less output bytes into the circular window */
if (copy >= state.wsize) {
utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
state.wnext = 0;
state.whave = state.wsize;
}
else {
dist = state.wsize - state.wnext;
if (dist > copy) {
dist = copy;
}
//zmemcpy(state->window + state->wnext, end - copy, dist);
utils.arraySet(state.window,src, end - copy, dist, state.wnext);
copy -= dist;
if (copy) {
//zmemcpy(state->window, end - copy, copy);
utils.arraySet(state.window,src, end - copy, copy, 0);
state.wnext = copy;
state.whave = state.wsize;
}
else {
state.wnext += dist;
if (state.wnext === state.wsize) { state.wnext = 0; }
if (state.whave < state.wsize) { state.whave += dist; }
}
}
return 0;
}
function inflate(strm, flush) {
var state;
var input, output; // input/output buffers
var next; /* next input INDEX */
var put; /* next output INDEX */
var have, left; /* available input and output */
var hold; /* bit buffer */
var bits; /* bits in bit buffer */
var _in, _out; /* save starting available input and output */
var copy; /* number of stored or match bytes to copy */
var from; /* where to copy match bytes from */
var from_source;
var here = 0; /* current decoding table entry */
var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
//var last; /* parent table entry */
var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
var len; /* length to copy for repeats, bits to drop */
var ret; /* return code */
var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
var opts;
var n; // temporary var for NEED_BITS
var order = /* permutation of code lengths */
[16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
if (!strm || !strm.state || !strm.output ||
(!strm.input && strm.avail_in !== 0)) {
return Z_STREAM_ERROR;
}
state = strm.state;
if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
//--- LOAD() ---
put = strm.next_out;
output = strm.output;
left = strm.avail_out;
next = strm.next_in;
input = strm.input;
have = strm.avail_in;
hold = state.hold;
bits = state.bits;
//---
_in = have;
_out = left;
ret = Z_OK;
inf_leave: // goto emulation
for (;;) {
switch (state.mode) {
case HEAD:
if (state.wrap === 0) {
state.mode = TYPEDO;
break;
}
//=== NEEDBITS(16);
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
state.check = 0/*crc32(0L, Z_NULL, 0)*/;
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = FLAGS;
break;
}
state.flags = 0; /* expect zlib header */
if (state.head) {
state.head.done = false;
}
if (!(state.wrap & 1) || /* check if zlib header allowed */
(((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
strm.msg = 'incorrect header check';
state.mode = BAD;
break;
}
if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
strm.msg = 'unknown compression method';
state.mode = BAD;
break;
}
//--- DROPBITS(4) ---//
hold >>>= 4;
bits -= 4;
//---//
len = (hold & 0x0f)/*BITS(4)*/ + 8;
if (state.wbits === 0) {
state.wbits = len;
}
else if (len > state.wbits) {
strm.msg = 'invalid window size';
state.mode = BAD;
break;
}
state.dmax = 1 << len;
//Tracev((stderr, "inflate: zlib header ok\n"));
strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
state.mode = hold & 0x200 ? DICTID : TYPE;
//=== INITBITS();
hold = 0;
bits = 0;
//===//
break;
case FLAGS:
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.flags = hold;
if ((state.flags & 0xff) !== Z_DEFLATED) {
strm.msg = 'unknown compression method';
state.mode = BAD;
break;
}
if (state.flags & 0xe000) {
strm.msg = 'unknown header flags set';
state.mode = BAD;
break;
}
if (state.head) {
state.head.text = ((hold >> 8) & 1);
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = TIME;
/* falls through */
case TIME:
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (state.head) {
state.head.time = hold;
}
if (state.flags & 0x0200) {
//=== CRC4(state.check, hold)
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
hbuf[2] = (hold >>> 16) & 0xff;
hbuf[3] = (hold >>> 24) & 0xff;
state.check = crc32(state.check, hbuf, 4, 0);
//===
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = OS;
/* falls through */
case OS:
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (state.head) {
state.head.xflags = (hold & 0xff);
state.head.os = (hold >> 8);
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = EXLEN;
/* falls through */
case EXLEN:
if (state.flags & 0x0400) {
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.length = hold;
if (state.head) {
state.head.extra_len = hold;
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
}
else if (state.head) {
state.head.extra = null/*Z_NULL*/;
}
state.mode = EXTRA;
/* falls through */
case EXTRA:
if (state.flags & 0x0400) {
copy = state.length;
if (copy > have) { copy = have; }
if (copy) {
if (state.head) {
len = state.head.extra_len - state.length;
if (!state.head.extra) {
// Use untyped array for more conveniend processing later
state.head.extra = new Array(state.head.extra_len);
}
utils.arraySet(
state.head.extra,
input,
next,
// extra field is limited to 65536 bytes
// - no need for additional size check
copy,
/*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
len
);
//zmemcpy(state.head.extra + len, next,
// len + copy > state.head.extra_max ?
// state.head.extra_max - len : copy);
}
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
state.length -= copy;
}
if (state.length) { break inf_leave; }
}
state.length = 0;
state.mode = NAME;
/* falls through */
case NAME:
if (state.flags & 0x0800) {
if (have === 0) { break inf_leave; }
copy = 0;
do {
// TODO: 2 or 1 bytes?
len = input[next + copy++];
/* use constant limit because in js we should not preallocate memory */
if (state.head && len &&
(state.length < 65536 /*state.head.name_max*/)) {
state.head.name += String.fromCharCode(len);
}
} while (len && copy < have);
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
if (len) { break inf_leave; }
}
else if (state.head) {
state.head.name = null;
}
state.length = 0;
state.mode = COMMENT;
/* falls through */
case COMMENT:
if (state.flags & 0x1000) {
if (have === 0) { break inf_leave; }
copy = 0;
do {
len = input[next + copy++];
/* use constant limit because in js we should not preallocate memory */
if (state.head && len &&
(state.length < 65536 /*state.head.comm_max*/)) {
state.head.comment += String.fromCharCode(len);
}
} while (len && copy < have);
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
if (len) { break inf_leave; }
}
else if (state.head) {
state.head.comment = null;
}
state.mode = HCRC;
/* falls through */
case HCRC:
if (state.flags & 0x0200) {
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (hold !== (state.check & 0xffff)) {
strm.msg = 'header crc mismatch';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
}
if (state.head) {
state.head.hcrc = ((state.flags >> 9) & 1);
state.head.done = true;
}
strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
state.mode = TYPE;
break;
case DICTID:
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
strm.adler = state.check = ZSWAP32(hold);
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = DICT;
/* falls through */
case DICT:
if (state.havedict === 0) {
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
return Z_NEED_DICT;
}
strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
state.mode = TYPE;
/* falls through */
case TYPE:
if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
/* falls through */
case TYPEDO:
if (state.last) {
//--- BYTEBITS() ---//
hold >>>= bits & 7;
bits -= bits & 7;
//---//
state.mode = CHECK;
break;
}
//=== NEEDBITS(3); */
while (bits < 3) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.last = (hold & 0x01)/*BITS(1)*/;
//--- DROPBITS(1) ---//
hold >>>= 1;
bits -= 1;
//---//
switch ((hold & 0x03)/*BITS(2)*/) {
case 0: /* stored block */
//Tracev((stderr, "inflate: stored block%s\n",
// state.last ? " (last)" : ""));
state.mode = STORED;
break;
case 1: /* fixed block */
fixedtables(state);
//Tracev((stderr, "inflate: fixed codes block%s\n",
// state.last ? " (last)" : ""));
state.mode = LEN_; /* decode codes */
if (flush === Z_TREES) {
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
break inf_leave;
}
break;
case 2: /* dynamic block */
//Tracev((stderr, "inflate: dynamic codes block%s\n",
// state.last ? " (last)" : ""));
state.mode = TABLE;
break;
case 3:
strm.msg = 'invalid block type';
state.mode = BAD;
}
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
break;
case STORED:
//--- BYTEBITS() ---// /* go to byte boundary */
hold >>>= bits & 7;
bits -= bits & 7;
//---//
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
strm.msg = 'invalid stored block lengths';
state.mode = BAD;
break;
}
state.length = hold & 0xffff;
//Tracev((stderr, "inflate: stored length %u\n",
// state.length));
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = COPY_;
if (flush === Z_TREES) { break inf_leave; }
/* falls through */
case COPY_:
state.mode = COPY;
/* falls through */
case COPY:
copy = state.length;
if (copy) {
if (copy > have) { copy = have; }
if (copy > left) { copy = left; }
if (copy === 0) { break inf_leave; }
//--- zmemcpy(put, next, copy); ---
utils.arraySet(output, input, next, copy, put);
//---//
have -= copy;
next += copy;
left -= copy;
put += copy;
state.length -= copy;
break;
}
//Tracev((stderr, "inflate: stored end\n"));
state.mode = TYPE;
break;
case TABLE:
//=== NEEDBITS(14); */
while (bits < 14) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
//--- DROPBITS(5) ---//
hold >>>= 5;
bits -= 5;
//---//
state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
//--- DROPBITS(5) ---//
hold >>>= 5;
bits -= 5;
//---//
state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
//--- DROPBITS(4) ---//
hold >>>= 4;
bits -= 4;
//---//
//#ifndef PKZIP_BUG_WORKAROUND
if (state.nlen > 286 || state.ndist > 30) {
strm.msg = 'too many length or distance symbols';
state.mode = BAD;
break;
}
//#endif
//Tracev((stderr, "inflate: table sizes ok\n"));
state.have = 0;
state.mode = LENLENS;
/* falls through */
case LENLENS:
while (state.have < state.ncode) {
//=== NEEDBITS(3);
while (bits < 3) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
//--- DROPBITS(3) ---//
hold >>>= 3;
bits -= 3;
//---//
}
while (state.have < 19) {
state.lens[order[state.have++]] = 0;
}
// We have separate tables & no pointers. 2 commented lines below not needed.
//state.next = state.codes;
//state.lencode = state.next;
// Switch to use dynamic table
state.lencode = state.lendyn;
state.lenbits = 7;
opts = {bits: state.lenbits};
ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
state.lenbits = opts.bits;
if (ret) {
strm.msg = 'invalid code lengths set';
state.mode = BAD;
break;
}
//Tracev((stderr, "inflate: code lengths ok\n"));
state.have = 0;
state.mode = CODELENS;
/* falls through */
case CODELENS:
while (state.have < state.nlen + state.ndist) {
for (;;) {
here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if (here_val < 16) {
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.lens[state.have++] = here_val;
}
else {
if (here_val === 16) {
//=== NEEDBITS(here.bits + 2);
n = here_bits + 2;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
if (state.have === 0) {
strm.msg = 'invalid bit length repeat';
state.mode = BAD;
break;
}
len = state.lens[state.have - 1];
copy = 3 + (hold & 0x03);//BITS(2);
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
}
else if (here_val === 17) {
//=== NEEDBITS(here.bits + 3);
n = here_bits + 3;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
len = 0;
copy = 3 + (hold & 0x07);//BITS(3);
//--- DROPBITS(3) ---//
hold >>>= 3;
bits -= 3;
//---//
}
else {
//=== NEEDBITS(here.bits + 7);
n = here_bits + 7;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
len = 0;
copy = 11 + (hold & 0x7f);//BITS(7);
//--- DROPBITS(7) ---//
hold >>>= 7;
bits -= 7;
//---//
}
if (state.have + copy > state.nlen + state.ndist) {
strm.msg = 'invalid bit length repeat';
state.mode = BAD;
break;
}
while (copy--) {
state.lens[state.have++] = len;
}
}
}
/* handle error breaks in while */
if (state.mode === BAD) { break; }
/* check for end-of-block code (better have one) */
if (state.lens[256] === 0) {
strm.msg = 'invalid code -- missing end-of-block';
state.mode = BAD;
break;
}
/* build code tables -- note: do not change the lenbits or distbits
values here (9 and 6) without reading the comments in inftrees.h
concerning the ENOUGH constants, which depend on those values */
state.lenbits = 9;
opts = {bits: state.lenbits};
ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
// We have separate tables & no pointers. 2 commented lines below not needed.
// state.next_index = opts.table_index;
state.lenbits = opts.bits;
// state.lencode = state.next;
if (ret) {
strm.msg = 'invalid literal/lengths set';
state.mode = BAD;
break;
}
state.distbits = 6;
//state.distcode.copy(state.codes);
// Switch to use dynamic table
state.distcode = state.distdyn;
opts = {bits: state.distbits};
ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
// We have separate tables & no pointers. 2 commented lines below not needed.
// state.next_index = opts.table_index;
state.distbits = opts.bits;
// state.distcode = state.next;
if (ret) {
strm.msg = 'invalid distances set';
state.mode = BAD;
break;
}
//Tracev((stderr, 'inflate: codes ok\n'));
state.mode = LEN_;
if (flush === Z_TREES) { break inf_leave; }
/* falls through */
case LEN_:
state.mode = LEN;
/* falls through */
case LEN:
if (have >= 6 && left >= 258) {
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
inflate_fast(strm, _out);
//--- LOAD() ---
put = strm.next_out;
output = strm.output;
left = strm.avail_out;
next = strm.next_in;
input = strm.input;
have = strm.avail_in;
hold = state.hold;
bits = state.bits;
//---
if (state.mode === TYPE) {
state.back = -1;
}
break;
}
state.back = 0;
for (;;) {
here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if (here_bits <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if (here_op && (here_op & 0xf0) === 0) {
last_bits = here_bits;
last_op = here_op;
last_val = here_val;
for (;;) {
here = state.lencode[last_val +
((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((last_bits + here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
//--- DROPBITS(last.bits) ---//
hold >>>= last_bits;
bits -= last_bits;
//---//
state.back += last_bits;
}
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.back += here_bits;
state.length = here_val;
if (here_op === 0) {
//Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
// "inflate: literal '%c'\n" :
// "inflate: literal 0x%02x\n", here.val));
state.mode = LIT;
break;
}
if (here_op & 32) {
//Tracevv((stderr, "inflate: end of block\n"));
state.back = -1;
state.mode = TYPE;
break;
}
if (here_op & 64) {
strm.msg = 'invalid literal/length code';
state.mode = BAD;
break;
}
state.extra = here_op & 15;
state.mode = LENEXT;
/* falls through */
case LENEXT:
if (state.extra) {
//=== NEEDBITS(state.extra);
n = state.extra;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
//--- DROPBITS(state.extra) ---//
hold >>>= state.extra;
bits -= state.extra;
//---//
state.back += state.extra;
}
//Tracevv((stderr, "inflate: length %u\n", state.length));
state.was = state.length;
state.mode = DIST;
/* falls through */
case DIST:
for (;;) {
here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if ((here_op & 0xf0) === 0) {
last_bits = here_bits;
last_op = here_op;
last_val = here_val;
for (;;) {
here = state.distcode[last_val +
((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((last_bits + here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
//--- DROPBITS(last.bits) ---//
hold >>>= last_bits;
bits -= last_bits;
//---//
state.back += last_bits;
}
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.back += here_bits;
if (here_op & 64) {
strm.msg = 'invalid distance code';
state.mode = BAD;
break;
}
state.offset = here_val;
state.extra = (here_op) & 15;
state.mode = DISTEXT;
/* falls through */
case DISTEXT:
if (state.extra) {
//=== NEEDBITS(state.extra);
n = state.extra;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
//--- DROPBITS(state.extra) ---//
hold >>>= state.extra;
bits -= state.extra;
//---//
state.back += state.extra;
}
//#ifdef INFLATE_STRICT
if (state.offset > state.dmax) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break;
}
//#endif
//Tracevv((stderr, "inflate: distance %u\n", state.offset));
state.mode = MATCH;
/* falls through */
case MATCH:
if (left === 0) { break inf_leave; }
copy = _out - left;
if (state.offset > copy) { /* copy from window */
copy = state.offset - copy;
if (copy > state.whave) {
if (state.sane) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
// Trace((stderr, "inflate.c too far\n"));
// copy -= state.whave;
// if (copy > state.length) { copy = state.length; }
// if (copy > left) { copy = left; }
// left -= copy;
// state.length -= copy;
// do {
// output[put++] = 0;
// } while (--copy);
// if (state.length === 0) { state.mode = LEN; }
// break;
//#endif
}
if (copy > state.wnext) {
copy -= state.wnext;
from = state.wsize - copy;
}
else {
from = state.wnext - copy;
}
if (copy > state.length) { copy = state.length; }
from_source = state.window;
}
else { /* copy from output */
from_source = output;
from = put - state.offset;
copy = state.length;
}
if (copy > left) { copy = left; }
left -= copy;
state.length -= copy;
do {
output[put++] = from_source[from++];
} while (--copy);
if (state.length === 0) { state.mode = LEN; }
break;
case LIT:
if (left === 0) { break inf_leave; }
output[put++] = state.length;
left--;
state.mode = LEN;
break;
case CHECK:
if (state.wrap) {
//=== NEEDBITS(32);
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
// Use '|' insdead of '+' to make sure that result is signed
hold |= input[next++] << bits;
bits += 8;
}
//===//
_out -= left;
strm.total_out += _out;
state.total += _out;
if (_out) {
strm.adler = state.check =
/*UPDATE(state.check, put - _out, _out);*/
(state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
}
_out = left;
// NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
strm.msg = 'incorrect data check';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
//Tracev((stderr, "inflate: check matches trailer\n"));
}
state.mode = LENGTH;
/* falls through */
case LENGTH:
if (state.wrap && state.flags) {
//=== NEEDBITS(32);
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (hold !== (state.total & 0xffffffff)) {
strm.msg = 'incorrect length check';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
//Tracev((stderr, "inflate: length matches trailer\n"));
}
state.mode = DONE;
/* falls through */
case DONE:
ret = Z_STREAM_END;
break inf_leave;
case BAD:
ret = Z_DATA_ERROR;
break inf_leave;
case MEM:
return Z_MEM_ERROR;
case SYNC:
/* falls through */
default:
return Z_STREAM_ERROR;
}
}
// inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
/*
Return from inflate(), updating the total counts and the check value.
If there was no progress during the inflate() call, return a buffer
error. Call updatewindow() to create and/or update the window state.
Note: a memory error from inflate() is non-recoverable.
*/
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
(state.mode < CHECK || flush !== Z_FINISH))) {
if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
state.mode = MEM;
return Z_MEM_ERROR;
}
}
_in -= strm.avail_in;
_out -= strm.avail_out;
strm.total_in += _in;
strm.total_out += _out;
state.total += _out;
if (state.wrap && _out) {
strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
(state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
}
strm.data_type = state.bits + (state.last ? 64 : 0) +
(state.mode === TYPE ? 128 : 0) +
(state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
ret = Z_BUF_ERROR;
}
return ret;
}
function inflateEnd(strm) {
if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
return Z_STREAM_ERROR;
}
var state = strm.state;
if (state.window) {
state.window = null;
}
strm.state = null;
return Z_OK;
}
function inflateGetHeader(strm, head) {
var state;
/* check state */
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
/* save header structure */
state.head = head;
head.done = false;
return Z_OK;
}
exports.inflateReset = inflateReset;
exports.inflateReset2 = inflateReset2;
exports.inflateResetKeep = inflateResetKeep;
exports.inflateInit = inflateInit;
exports.inflateInit2 = inflateInit2;
exports.inflate = inflate;
exports.inflateEnd = inflateEnd;
exports.inflateGetHeader = inflateGetHeader;
exports.inflateInfo = 'pako inflate (from Nodeca project)';
/* Not implemented
exports.inflateCopy = inflateCopy;
exports.inflateGetDictionary = inflateGetDictionary;
exports.inflateMark = inflateMark;
exports.inflatePrime = inflatePrime;
exports.inflateSetDictionary = inflateSetDictionary;
exports.inflateSync = inflateSync;
exports.inflateSyncPoint = inflateSyncPoint;
exports.inflateUndermine = inflateUndermine;
*/
},{"../utils/common":129,"./adler32":131,"./crc32":133,"./inffast":136,"./inftrees":138}],138:[function(require,module,exports){
'use strict';
var utils = require('../utils/common');
var MAXBITS = 15;
var ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592;
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
var CODES = 0;
var LENS = 1;
var DISTS = 2;
var lbase = [ /* Length codes 257..285 base */
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
];
var lext = [ /* Length codes 257..285 extra */
16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
];
var dbase = [ /* Distance codes 0..29 base */
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
8193, 12289, 16385, 24577, 0, 0
];
var dext = [ /* Distance codes 0..29 extra */
16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
28, 28, 29, 29, 64, 64
];
module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
{
var bits = opts.bits;
//here = opts.here; /* table entry for duplication */
var len = 0; /* a code's length in bits */
var sym = 0; /* index of code symbols */
var min = 0, max = 0; /* minimum and maximum code lengths */
var root = 0; /* number of index bits for root table */
var curr = 0; /* number of index bits for current table */
var drop = 0; /* code bits to drop for sub-table */
var left = 0; /* number of prefix codes available */
var used = 0; /* code entries in table used */
var huff = 0; /* Huffman code */
var incr; /* for incrementing code, index */
var fill; /* index for replicating entries */
var low; /* low bits for current root entry */
var mask; /* mask for low root bits */
var next; /* next available space in table */
var base = null; /* base value table to use */
var base_index = 0;
// var shoextra; /* extra bits table to use */
var end; /* use base and extra for symbol > end */
var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
var extra = null;
var extra_index = 0;
var here_bits, here_op, here_val;
/*
Process a set of code lengths to create a canonical Huffman code. The
code lengths are lens[0..codes-1]. Each length corresponds to the
symbols 0..codes-1. The Huffman code is generated by first sorting the
symbols by length from short to long, and retaining the symbol order
for codes with equal lengths. Then the code starts with all zero bits
for the first code of the shortest length, and the codes are integer
increments for the same length, and zeros are appended as the length
increases. For the deflate format, these bits are stored backwards
from their more natural integer increment ordering, and so when the
decoding tables are built in the large loop below, the integer codes
are incremented backwards.
This routine assumes, but does not check, that all of the entries in
lens[] are in the range 0..MAXBITS. The caller must assure this.
1..MAXBITS is interpreted as that code length. zero means that that
symbol does not occur in this code.
The codes are sorted by computing a count of codes for each length,
creating from that a table of starting indices for each length in the
sorted table, and then entering the symbols in order in the sorted
table. The sorted table is work[], with that space being provided by
the caller.
The length counts are used for other purposes as well, i.e. finding
the minimum and maximum length codes, determining if there are any
codes at all, checking for a valid set of lengths, and looking ahead
at length counts to determine sub-table sizes when building the
decoding tables.
*/
/* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
for (len = 0; len <= MAXBITS; len++) {
count[len] = 0;
}
for (sym = 0; sym < codes; sym++) {
count[lens[lens_index + sym]]++;
}
/* bound code lengths, force root to be within code lengths */
root = bits;
for (max = MAXBITS; max >= 1; max--) {
if (count[max] !== 0) { break; }
}
if (root > max) {
root = max;
}
if (max === 0) { /* no symbols to code at all */
//table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
//table.bits[opts.table_index] = 1; //here.bits = (var char)1;
//table.val[opts.table_index++] = 0; //here.val = (var short)0;
table[table_index++] = (1 << 24) | (64 << 16) | 0;
//table.op[opts.table_index] = 64;
//table.bits[opts.table_index] = 1;
//table.val[opts.table_index++] = 0;
table[table_index++] = (1 << 24) | (64 << 16) | 0;
opts.bits = 1;
return 0; /* no symbols, but wait for decoding to report error */
}
for (min = 1; min < max; min++) {
if (count[min] !== 0) { break; }
}
if (root < min) {
root = min;
}
/* check for an over-subscribed or incomplete set of lengths */
left = 1;
for (len = 1; len <= MAXBITS; len++) {
left <<= 1;
left -= count[len];
if (left < 0) {
return -1;
} /* over-subscribed */
}
if (left > 0 && (type === CODES || max !== 1)) {
return -1; /* incomplete set */
}
/* generate offsets into symbol table for each length for sorting */
offs[1] = 0;
for (len = 1; len < MAXBITS; len++) {
offs[len + 1] = offs[len] + count[len];
}
/* sort symbols by length, by symbol order within each length */
for (sym = 0; sym < codes; sym++) {
if (lens[lens_index + sym] !== 0) {
work[offs[lens[lens_index + sym]]++] = sym;
}
}
/*
Create and fill in decoding tables. In this loop, the table being
filled is at next and has curr index bits. The code being used is huff
with length len. That code is converted to an index by dropping drop
bits off of the bottom. For codes where len is less than drop + curr,
those top drop + curr - len bits are incremented through all values to
fill the table with replicated entries.
root is the number of index bits for the root table. When len exceeds
root, sub-tables are created pointed to by the root entry with an index
of the low root bits of huff. This is saved in low to check for when a
new sub-table should be started. drop is zero when the root table is
being filled, and drop is root when sub-tables are being filled.
When a new sub-table is needed, it is necessary to look ahead in the
code lengths to determine what size sub-table is needed. The length
counts are used for this, and so count[] is decremented as codes are
entered in the tables.
used keeps track of how many table entries have been allocated from the
provided *table space. It is checked for LENS and DIST tables against
the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
the initial root table size constants. See the comments in inftrees.h
for more information.
sym increments through all symbols, and the loop terminates when
all codes of length max, i.e. all codes, have been processed. This
routine permits incomplete codes, so another loop after this one fills
in the rest of the decoding tables with invalid code markers.
*/
/* set up for code type */
// poor man optimization - use if-else instead of switch,
// to avoid deopts in old v8
if (type === CODES) {
base = extra = work; /* dummy value--not used */
end = 19;
} else if (type === LENS) {
base = lbase;
base_index -= 257;
extra = lext;
extra_index -= 257;
end = 256;
} else { /* DISTS */
base = dbase;
extra = dext;
end = -1;
}
/* initialize opts for loop */
huff = 0; /* starting code */
sym = 0; /* starting code symbol */
len = min; /* starting code length */
next = table_index; /* current table to fill in */
curr = root; /* current table index bits */
drop = 0; /* current bits to drop from code for index */
low = -1; /* trigger new sub-table when len > root */
used = 1 << root; /* use root table entries */
mask = used - 1; /* mask for comparing low */
/* check available table space */
if ((type === LENS && used > ENOUGH_LENS) ||
(type === DISTS && used > ENOUGH_DISTS)) {
return 1;
}
var i=0;
/* process all codes and make table entries */
for (;;) {
i++;
/* create table entry */
here_bits = len - drop;
if (work[sym] < end) {
here_op = 0;
here_val = work[sym];
}
else if (work[sym] > end) {
here_op = extra[extra_index + work[sym]];
here_val = base[base_index + work[sym]];
}
else {
here_op = 32 + 64; /* end of block */
here_val = 0;
}
/* replicate for those indices with low len bits equal to huff */
incr = 1 << (len - drop);
fill = 1 << curr;
min = fill; /* save offset to next table */
do {
fill -= incr;
table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
} while (fill !== 0);
/* backwards increment the len-bit code huff */
incr = 1 << (len - 1);
while (huff & incr) {
incr >>= 1;
}
if (incr !== 0) {
huff &= incr - 1;
huff += incr;
} else {
huff = 0;
}
/* go to next symbol, update count, len */
sym++;
if (--count[len] === 0) {
if (len === max) { break; }
len = lens[lens_index + work[sym]];
}
/* create new sub-table if needed */
if (len > root && (huff & mask) !== low) {
/* if first time, transition to sub-tables */
if (drop === 0) {
drop = root;
}
/* increment past last table */
next += min; /* here min is 1 << curr */
/* determine length of next table */
curr = len - drop;
left = 1 << curr;
while (curr + drop < max) {
left -= count[curr + drop];
if (left <= 0) { break; }
curr++;
left <<= 1;
}
/* check for enough space */
used += 1 << curr;
if ((type === LENS && used > ENOUGH_LENS) ||
(type === DISTS && used > ENOUGH_DISTS)) {
return 1;
}
/* point entry in root table to sub-table */
low = huff & mask;
/*table.op[low] = curr;
table.bits[low] = root;
table.val[low] = next - opts.table_index;*/
table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
}
}
/* fill in remaining table entry if code is incomplete (guaranteed to have
at most one remaining entry, since if the code is incomplete, the
maximum code length that was allowed to get this far is one bit) */
if (huff !== 0) {
//table.op[next + huff] = 64; /* invalid code marker */
//table.bits[next + huff] = len - drop;
//table.val[next + huff] = 0;
table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
}
/* set return parameters */
//opts.table_index += used;
opts.bits = root;
return 0;
};
},{"../utils/common":129}],139:[function(require,module,exports){
'use strict';
module.exports = {
'2': 'need dictionary', /* Z_NEED_DICT 2 */
'1': 'stream end', /* Z_STREAM_END 1 */
'0': '', /* Z_OK 0 */
'-1': 'file error', /* Z_ERRNO (-1) */
'-2': 'stream error', /* Z_STREAM_ERROR (-2) */
'-3': 'data error', /* Z_DATA_ERROR (-3) */
'-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
'-5': 'buffer error', /* Z_BUF_ERROR (-5) */
'-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
};
},{}],140:[function(require,module,exports){
'use strict';
var utils = require('../utils/common');
/* Public constants ==========================================================*/
/* ===========================================================================*/
//var Z_FILTERED = 1;
//var Z_HUFFMAN_ONLY = 2;
//var Z_RLE = 3;
var Z_FIXED = 4;
//var Z_DEFAULT_STRATEGY = 0;
/* Possible values of the data_type field (though see inflate()) */
var Z_BINARY = 0;
var Z_TEXT = 1;
//var Z_ASCII = 1; // = Z_TEXT
var Z_UNKNOWN = 2;
/*============================================================================*/
function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
// From zutil.h
var STORED_BLOCK = 0;
var STATIC_TREES = 1;
var DYN_TREES = 2;
/* The three kinds of block type */
var MIN_MATCH = 3;
var MAX_MATCH = 258;
/* The minimum and maximum match lengths */
// From deflate.h
/* ===========================================================================
* Internal compression state.
*/
var LENGTH_CODES = 29;
/* number of length codes, not counting the special END_BLOCK code */
var LITERALS = 256;
/* number of literal bytes 0..255 */
var L_CODES = LITERALS + 1 + LENGTH_CODES;
/* number of Literal or Length codes, including the END_BLOCK code */
var D_CODES = 30;
/* number of distance codes */
var BL_CODES = 19;
/* number of codes used to transfer the bit lengths */
var HEAP_SIZE = 2*L_CODES + 1;
/* maximum heap size */
var MAX_BITS = 15;
/* All codes must not exceed MAX_BITS bits */
var Buf_size = 16;
/* size of bit buffer in bi_buf */
/* ===========================================================================
* Constants
*/
var MAX_BL_BITS = 7;
/* Bit length codes must not exceed MAX_BL_BITS bits */
var END_BLOCK = 256;
/* end of block literal code */
var REP_3_6 = 16;
/* repeat previous bit length 3-6 times (2 bits of repeat count) */
var REPZ_3_10 = 17;
/* repeat a zero length 3-10 times (3 bits of repeat count) */
var REPZ_11_138 = 18;
/* repeat a zero length 11-138 times (7 bits of repeat count) */
var extra_lbits = /* extra bits for each length code */
[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];
var extra_dbits = /* extra bits for each distance code */
[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];
var extra_blbits = /* extra bits for each bit length code */
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
var bl_order =
[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
/* The lengths of the bit length codes are sent in order of decreasing
* probability, to avoid transmitting the lengths for unused bit length codes.
*/
/* ===========================================================================
* Local data. These are initialized only once.
*/
// We pre-fill arrays with 0 to avoid uninitialized gaps
var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
// !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
var static_ltree = new Array((L_CODES+2) * 2);
zero(static_ltree);
/* The static literal tree. Since the bit lengths are imposed, there is no
* need for the L_CODES extra codes used during heap construction. However
* The codes 286 and 287 are needed to build a canonical tree (see _tr_init
* below).
*/
var static_dtree = new Array(D_CODES * 2);
zero(static_dtree);
/* The static distance tree. (Actually a trivial tree since all codes use
* 5 bits.)
*/
var _dist_code = new Array(DIST_CODE_LEN);
zero(_dist_code);
/* Distance codes. The first 256 values correspond to the distances
* 3 .. 258, the last 256 values correspond to the top 8 bits of
* the 15 bit distances.
*/
var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
zero(_length_code);
/* length code for each normalized match length (0 == MIN_MATCH) */
var base_length = new Array(LENGTH_CODES);
zero(base_length);
/* First normalized length for each code (0 = MIN_MATCH) */
var base_dist = new Array(D_CODES);
zero(base_dist);
/* First normalized distance for each code (0 = distance of 1) */
var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
this.static_tree = static_tree; /* static tree or NULL */
this.extra_bits = extra_bits; /* extra bits for each code or NULL */
this.extra_base = extra_base; /* base index for extra_bits */
this.elems = elems; /* max number of elements in the tree */
this.max_length = max_length; /* max bit length for the codes */
// show if `static_tree` has data or dummy - needed for monomorphic objects
this.has_stree = static_tree && static_tree.length;
};
var static_l_desc;
var static_d_desc;
var static_bl_desc;
var TreeDesc = function(dyn_tree, stat_desc) {
this.dyn_tree = dyn_tree; /* the dynamic tree */
this.max_code = 0; /* largest code with non zero frequency */
this.stat_desc = stat_desc; /* the corresponding static tree */
};
function d_code(dist) {
return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
}
/* ===========================================================================
* Output a short LSB first on the stream.
* IN assertion: there is enough room in pendingBuf.
*/
function put_short (s, w) {
// put_byte(s, (uch)((w) & 0xff));
// put_byte(s, (uch)((ush)(w) >> 8));
s.pending_buf[s.pending++] = (w) & 0xff;
s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
}
/* ===========================================================================
* Send a value on a given number of bits.
* IN assertion: length <= 16 and value fits in length bits.
*/
function send_bits(s, value, length) {
if (s.bi_valid > (Buf_size - length)) {
s.bi_buf |= (value << s.bi_valid) & 0xffff;
put_short(s, s.bi_buf);
s.bi_buf = value >> (Buf_size - s.bi_valid);
s.bi_valid += length - Buf_size;
} else {
s.bi_buf |= (value << s.bi_valid) & 0xffff;
s.bi_valid += length;
}
}
function send_code(s, c, tree) {
send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
}
/* ===========================================================================
* Reverse the first len bits of a code, using straightforward code (a faster
* method would use a table)
* IN assertion: 1 <= len <= 15
*/
function bi_reverse(code, len) {
var res = 0;
do {
res |= code & 1;
code >>>= 1;
res <<= 1;
} while (--len > 0);
return res >>> 1;
}
/* ===========================================================================
* Flush the bit buffer, keeping at most 7 bits in it.
*/
function bi_flush(s) {
if (s.bi_valid === 16) {
put_short(s, s.bi_buf);
s.bi_buf = 0;
s.bi_valid = 0;
} else if (s.bi_valid >= 8) {
s.pending_buf[s.pending++] = s.bi_buf & 0xff;
s.bi_buf >>= 8;
s.bi_valid -= 8;
}
}
/* ===========================================================================
* Compute the optimal bit lengths for a tree and update the total bit length
* for the current block.
* IN assertion: the fields freq and dad are set, heap[heap_max] and
* above are the tree nodes sorted by increasing frequency.
* OUT assertions: the field len is set to the optimal bit length, the
* array bl_count contains the frequencies for each bit length.
* The length opt_len is updated; static_len is also updated if stree is
* not null.
*/
function gen_bitlen(s, desc)
// deflate_state *s;
// tree_desc *desc; /* the tree descriptor */
{
var tree = desc.dyn_tree;
var max_code = desc.max_code;
var stree = desc.stat_desc.static_tree;
var has_stree = desc.stat_desc.has_stree;
var extra = desc.stat_desc.extra_bits;
var base = desc.stat_desc.extra_base;
var max_length = desc.stat_desc.max_length;
var h; /* heap index */
var n, m; /* iterate over the tree elements */
var bits; /* bit length */
var xbits; /* extra bits */
var f; /* frequency */
var overflow = 0; /* number of elements with bit length too large */
for (bits = 0; bits <= MAX_BITS; bits++) {
s.bl_count[bits] = 0;
}
/* In a first pass, compute the optimal bit lengths (which may
* overflow in the case of the bit length tree).
*/
tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
n = s.heap[h];
bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
if (bits > max_length) {
bits = max_length;
overflow++;
}
tree[n*2 + 1]/*.Len*/ = bits;
/* We overwrite tree[n].Dad which is no longer needed */
if (n > max_code) { continue; } /* not a leaf node */
s.bl_count[bits]++;
xbits = 0;
if (n >= base) {
xbits = extra[n-base];
}
f = tree[n * 2]/*.Freq*/;
s.opt_len += f * (bits + xbits);
if (has_stree) {
s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
}
}
if (overflow === 0) { return; }
// Trace((stderr,"\nbit length overflow\n"));
/* This happens for example on obj2 and pic of the Calgary corpus */
/* Find the first bit length which could increase: */
do {
bits = max_length-1;
while (s.bl_count[bits] === 0) { bits--; }
s.bl_count[bits]--; /* move one leaf down the tree */
s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
s.bl_count[max_length]--;
/* The brother of the overflow item also moves one step up,
* but this does not affect bl_count[max_length]
*/
overflow -= 2;
} while (overflow > 0);
/* Now recompute all bit lengths, scanning in increasing frequency.
* h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
* lengths instead of fixing only the wrong ones. This idea is taken
* from 'ar' written by Haruhiko Okumura.)
*/
for (bits = max_length; bits !== 0; bits--) {
n = s.bl_count[bits];
while (n !== 0) {
m = s.heap[--h];
if (m > max_code) { continue; }
if (tree[m*2 + 1]/*.Len*/ !== bits) {
// Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
tree[m*2 + 1]/*.Len*/ = bits;
}
n--;
}
}
}
/* ===========================================================================
* Generate the codes for a given tree and bit counts (which need not be
* optimal).
* IN assertion: the array bl_count contains the bit length statistics for
* the given tree and the field len is set for all tree elements.
* OUT assertion: the field code is set for all tree elements of non
* zero code length.
*/
function gen_codes(tree, max_code, bl_count)
// ct_data *tree; /* the tree to decorate */
// int max_code; /* largest code with non zero frequency */
// ushf *bl_count; /* number of codes at each bit length */
{
var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
var code = 0; /* running code value */
var bits; /* bit index */
var n; /* code index */
/* The distribution counts are first used to generate the code values
* without bit reversal.
*/
for (bits = 1; bits <= MAX_BITS; bits++) {
next_code[bits] = code = (code + bl_count[bits-1]) << 1;
}
/* Check that the bit counts in bl_count are consistent. The last code
* must be all ones.
*/
//Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
// "inconsistent bit counts");
//Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
for (n = 0; n <= max_code; n++) {
var len = tree[n*2 + 1]/*.Len*/;
if (len === 0) { continue; }
/* Now reverse the bits */
tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
//Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
// n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
}
}
/* ===========================================================================
* Initialize the various 'constant' tables.
*/
function tr_static_init() {
var n; /* iterates over tree elements */
var bits; /* bit counter */
var length; /* length value */
var code; /* code value */
var dist; /* distance index */
var bl_count = new Array(MAX_BITS+1);
/* number of codes at each bit length for an optimal tree */
// do check in _tr_init()
//if (static_init_done) return;
/* For some embedded targets, global variables are not initialized: */
/*#ifdef NO_INIT_GLOBAL_POINTERS
static_l_desc.static_tree = static_ltree;
static_l_desc.extra_bits = extra_lbits;
static_d_desc.static_tree = static_dtree;
static_d_desc.extra_bits = extra_dbits;
static_bl_desc.extra_bits = extra_blbits;
#endif*/
/* Initialize the mapping length (0..255) -> length code (0..28) */
length = 0;
for (code = 0; code < LENGTH_CODES-1; code++) {
base_length[code] = length;
for (n = 0; n < (1<<extra_lbits[code]); n++) {
_length_code[length++] = code;
}
}
//Assert (length == 256, "tr_static_init: length != 256");
/* Note that the length 255 (match length 258) can be represented
* in two different ways: code 284 + 5 bits or code 285, so we
* overwrite length_code[255] to use the best encoding:
*/
_length_code[length-1] = code;
/* Initialize the mapping dist (0..32K) -> dist code (0..29) */
dist = 0;
for (code = 0 ; code < 16; code++) {
base_dist[code] = dist;
for (n = 0; n < (1<<extra_dbits[code]); n++) {
_dist_code[dist++] = code;
}
}
//Assert (dist == 256, "tr_static_init: dist != 256");
dist >>= 7; /* from now on, all distances are divided by 128 */
for (; code < D_CODES; code++) {
base_dist[code] = dist << 7;
for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
_dist_code[256 + dist++] = code;
}
}
//Assert (dist == 256, "tr_static_init: 256+dist != 512");
/* Construct the codes of the static literal tree */
for (bits = 0; bits <= MAX_BITS; bits++) {
bl_count[bits] = 0;
}
n = 0;
while (n <= 143) {
static_ltree[n*2 + 1]/*.Len*/ = 8;
n++;
bl_count[8]++;
}
while (n <= 255) {
static_ltree[n*2 + 1]/*.Len*/ = 9;
n++;
bl_count[9]++;
}
while (n <= 279) {
static_ltree[n*2 + 1]/*.Len*/ = 7;
n++;
bl_count[7]++;
}
while (n <= 287) {
static_ltree[n*2 + 1]/*.Len*/ = 8;
n++;
bl_count[8]++;
}
/* Codes 286 and 287 do not exist, but we must include them in the
* tree construction to get a canonical Huffman tree (longest code
* all ones)
*/
gen_codes(static_ltree, L_CODES+1, bl_count);
/* The static distance tree is trivial: */
for (n = 0; n < D_CODES; n++) {
static_dtree[n*2 + 1]/*.Len*/ = 5;
static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
}
// Now data ready and we can init static trees
static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
//static_init_done = true;
}
/* ===========================================================================
* Initialize a new block.
*/
function init_block(s) {
var n; /* iterates over tree elements */
/* Initialize the trees. */
for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
s.opt_len = s.static_len = 0;
s.last_lit = s.matches = 0;
}
/* ===========================================================================
* Flush the bit buffer and align the output on a byte boundary
*/
function bi_windup(s)
{
if (s.bi_valid > 8) {
put_short(s, s.bi_buf);
} else if (s.bi_valid > 0) {
//put_byte(s, (Byte)s->bi_buf);
s.pending_buf[s.pending++] = s.bi_buf;
}
s.bi_buf = 0;
s.bi_valid = 0;
}
/* ===========================================================================
* Copy a stored block, storing first the length and its
* one's complement if requested.
*/
function copy_block(s, buf, len, header)
//DeflateState *s;
//charf *buf; /* the input data */
//unsigned len; /* its length */
//int header; /* true if block header must be written */
{
bi_windup(s); /* align on byte boundary */
if (header) {
put_short(s, len);
put_short(s, ~len);
}
// while (len--) {
// put_byte(s, *buf++);
// }
utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
s.pending += len;
}
/* ===========================================================================
* Compares to subtrees, using the tree depth as tie breaker when
* the subtrees have equal frequency. This minimizes the worst case length.
*/
function smaller(tree, n, m, depth) {
var _n2 = n*2;
var _m2 = m*2;
return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
(tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
}
/* ===========================================================================
* Restore the heap property by moving down the tree starting at node k,
* exchanging a node with the smallest of its two sons if necessary, stopping
* when the heap property is re-established (each father smaller than its
* two sons).
*/
function pqdownheap(s, tree, k)
// deflate_state *s;
// ct_data *tree; /* the tree to restore */
// int k; /* node to move down */
{
var v = s.heap[k];
var j = k << 1; /* left son of k */
while (j <= s.heap_len) {
/* Set j to the smallest of the two sons: */
if (j < s.heap_len &&
smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
j++;
}
/* Exit if v is smaller than both sons */
if (smaller(tree, v, s.heap[j], s.depth)) { break; }
/* Exchange v with the smallest son */
s.heap[k] = s.heap[j];
k = j;
/* And continue down the tree, setting j to the left son of k */
j <<= 1;
}
s.heap[k] = v;
}
// inlined manually
// var SMALLEST = 1;
/* ===========================================================================
* Send the block data compressed using the given Huffman trees
*/
function compress_block(s, ltree, dtree)
// deflate_state *s;
// const ct_data *ltree; /* literal tree */
// const ct_data *dtree; /* distance tree */
{
var dist; /* distance of matched string */
var lc; /* match length or unmatched char (if dist == 0) */
var lx = 0; /* running index in l_buf */
var code; /* the code to send */
var extra; /* number of extra bits to send */
if (s.last_lit !== 0) {
do {
dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
lc = s.pending_buf[s.l_buf + lx];
lx++;
if (dist === 0) {
send_code(s, lc, ltree); /* send a literal byte */
//Tracecv(isgraph(lc), (stderr," '%c' ", lc));
} else {
/* Here, lc is the match length - MIN_MATCH */
code = _length_code[lc];
send_code(s, code+LITERALS+1, ltree); /* send the length code */
extra = extra_lbits[code];
if (extra !== 0) {
lc -= base_length[code];
send_bits(s, lc, extra); /* send the extra length bits */
}
dist--; /* dist is now the match distance - 1 */
code = d_code(dist);
//Assert (code < D_CODES, "bad d_code");
send_code(s, code, dtree); /* send the distance code */
extra = extra_dbits[code];
if (extra !== 0) {
dist -= base_dist[code];
send_bits(s, dist, extra); /* send the extra distance bits */
}
} /* literal or match pair ? */
/* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
//Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
// "pendingBuf overflow");
} while (lx < s.last_lit);
}
send_code(s, END_BLOCK, ltree);
}
/* ===========================================================================
* Construct one Huffman tree and assigns the code bit strings and lengths.
* Update the total bit length for the current block.
* IN assertion: the field freq is set for all tree elements.
* OUT assertions: the fields len and code are set to the optimal bit length
* and corresponding code. The length opt_len is updated; static_len is
* also updated if stree is not null. The field max_code is set.
*/
function build_tree(s, desc)
// deflate_state *s;
// tree_desc *desc; /* the tree descriptor */
{
var tree = desc.dyn_tree;
var stree = desc.stat_desc.static_tree;
var has_stree = desc.stat_desc.has_stree;
var elems = desc.stat_desc.elems;
var n, m; /* iterate over heap elements */
var max_code = -1; /* largest code with non zero frequency */
var node; /* new node being created */
/* Construct the initial heap, with least frequent element in
* heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
* heap[0] is not used.
*/
s.heap_len = 0;
s.heap_max = HEAP_SIZE;
for (n = 0; n < elems; n++) {
if (tree[n * 2]/*.Freq*/ !== 0) {
s.heap[++s.heap_len] = max_code = n;
s.depth[n] = 0;
} else {
tree[n*2 + 1]/*.Len*/ = 0;
}
}
/* The pkzip format requires that at least one distance code exists,
* and that at least one bit should be sent even if there is only one
* possible code. So to avoid special checks later on we force at least
* two codes of non zero frequency.
*/
while (s.heap_len < 2) {
node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
tree[node * 2]/*.Freq*/ = 1;
s.depth[node] = 0;
s.opt_len--;
if (has_stree) {
s.static_len -= stree[node*2 + 1]/*.Len*/;
}
/* node is 0 or 1 so it does not have extra bits */
}
desc.max_code = max_code;
/* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
* establish sub-heaps of increasing lengths:
*/
for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
/* Construct the Huffman tree by repeatedly combining the least two
* frequent nodes.
*/
node = elems; /* next internal node of the tree */
do {
//pqremove(s, tree, n); /* n = node of least frequency */
/*** pqremove ***/
n = s.heap[1/*SMALLEST*/];
s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
pqdownheap(s, tree, 1/*SMALLEST*/);
/***/
m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
s.heap[--s.heap_max] = m;
/* Create a new node father of n and m */
tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
/* and insert the new node in the heap */
s.heap[1/*SMALLEST*/] = node++;
pqdownheap(s, tree, 1/*SMALLEST*/);
} while (s.heap_len >= 2);
s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
/* At this point, the fields freq and dad are set. We can now
* generate the bit lengths.
*/
gen_bitlen(s, desc);
/* The field len is now set, we can generate the bit codes */
gen_codes(tree, max_code, s.bl_count);
}
/* ===========================================================================
* Scan a literal or distance tree to determine the frequencies of the codes
* in the bit length tree.
*/
function scan_tree(s, tree, max_code)
// deflate_state *s;
// ct_data *tree; /* the tree to be scanned */
// int max_code; /* and its largest code of non zero frequency */
{
var n; /* iterates over all tree elements */
var prevlen = -1; /* last emitted length */
var curlen; /* length of current code */
var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
var count = 0; /* repeat count of the current code */
var max_count = 7; /* max repeat count */
var min_count = 4; /* min repeat count */
if (nextlen === 0) {
max_count = 138;
min_count = 3;
}
tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
for (n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[(n+1)*2 + 1]/*.Len*/;
if (++count < max_count && curlen === nextlen) {
continue;
} else if (count < min_count) {
s.bl_tree[curlen * 2]/*.Freq*/ += count;
} else if (curlen !== 0) {
if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
s.bl_tree[REP_3_6*2]/*.Freq*/++;
} else if (count <= 10) {
s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
} else {
s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
}
count = 0;
prevlen = curlen;
if (nextlen === 0) {
max_count = 138;
min_count = 3;
} else if (curlen === nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
/* ===========================================================================
* Send a literal or distance tree in compressed form, using the codes in
* bl_tree.
*/
function send_tree(s, tree, max_code)
// deflate_state *s;
// ct_data *tree; /* the tree to be scanned */
// int max_code; /* and its largest code of non zero frequency */
{
var n; /* iterates over all tree elements */
var prevlen = -1; /* last emitted length */
var curlen; /* length of current code */
var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
var count = 0; /* repeat count of the current code */
var max_count = 7; /* max repeat count */
var min_count = 4; /* min repeat count */
/* tree[max_code+1].Len = -1; */ /* guard already set */
if (nextlen === 0) {
max_count = 138;
min_count = 3;
}
for (n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[(n+1)*2 + 1]/*.Len*/;
if (++count < max_count && curlen === nextlen) {
continue;
} else if (count < min_count) {
do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
} else if (curlen !== 0) {
if (curlen !== prevlen) {
send_code(s, curlen, s.bl_tree);
count--;
}
//Assert(count >= 3 && count <= 6, " 3_6?");
send_code(s, REP_3_6, s.bl_tree);
send_bits(s, count-3, 2);
} else if (count <= 10) {
send_code(s, REPZ_3_10, s.bl_tree);
send_bits(s, count-3, 3);
} else {
send_code(s, REPZ_11_138, s.bl_tree);
send_bits(s, count-11, 7);
}
count = 0;
prevlen = curlen;
if (nextlen === 0) {
max_count = 138;
min_count = 3;
} else if (curlen === nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
/* ===========================================================================
* Construct the Huffman tree for the bit lengths and return the index in
* bl_order of the last bit length code to send.
*/
function build_bl_tree(s) {
var max_blindex; /* index of last bit length code of non zero freq */
/* Determine the bit length frequencies for literal and distance trees */
scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
/* Build the bit length tree: */
build_tree(s, s.bl_desc);
/* opt_len now includes the length of the tree representations, except
* the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
*/
/* Determine the number of bit length codes to send. The pkzip format
* requires that at least 4 bit length codes be sent. (appnote.txt says
* 3 but the actual value used is 4.)
*/
for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
break;
}
}
/* Update opt_len to include the bit length tree and counts */
s.opt_len += 3*(max_blindex+1) + 5+5+4;
//Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
// s->opt_len, s->static_len));
return max_blindex;
}
/* ===========================================================================
* Send the header for a block using dynamic Huffman trees: the counts, the
* lengths of the bit length codes, the literal tree and the distance tree.
* IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
*/
function send_all_trees(s, lcodes, dcodes, blcodes)
// deflate_state *s;
// int lcodes, dcodes, blcodes; /* number of codes for each tree */
{
var rank; /* index in bl_order */
//Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
//Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
// "too many codes");
//Tracev((stderr, "\nbl counts: "));
send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
send_bits(s, dcodes-1, 5);
send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
for (rank = 0; rank < blcodes; rank++) {
//Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
}
//Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
//Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
//Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
}
/* ===========================================================================
* Check if the data type is TEXT or BINARY, using the following algorithm:
* - TEXT if the two conditions below are satisfied:
* a) There are no non-portable control characters belonging to the
* "black list" (0..6, 14..25, 28..31).
* b) There is at least one printable character belonging to the
* "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
* - BINARY otherwise.
* - The following partially-portable control characters form a
* "gray list" that is ignored in this detection algorithm:
* (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
* IN assertion: the fields Freq of dyn_ltree are set.
*/
function detect_data_type(s) {
/* black_mask is the bit mask of black-listed bytes
* set bits 0..6, 14..25, and 28..31
* 0xf3ffc07f = binary 11110011111111111100000001111111
*/
var black_mask = 0xf3ffc07f;
var n;
/* Check for non-textual ("black-listed") bytes. */
for (n = 0; n <= 31; n++, black_mask >>>= 1) {
if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
return Z_BINARY;
}
}
/* Check for textual ("white-listed") bytes. */
if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
return Z_TEXT;
}
for (n = 32; n < LITERALS; n++) {
if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
return Z_TEXT;
}
}
/* There are no "black-listed" or "white-listed" bytes:
* this stream either is empty or has tolerated ("gray-listed") bytes only.
*/
return Z_BINARY;
}
var static_init_done = false;
/* ===========================================================================
* Initialize the tree data structures for a new zlib stream.
*/
function _tr_init(s)
{
if (!static_init_done) {
tr_static_init();
static_init_done = true;
}
s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
s.bi_buf = 0;
s.bi_valid = 0;
/* Initialize the first block of the first file: */
init_block(s);
}
/* ===========================================================================
* Send a stored block
*/
function _tr_stored_block(s, buf, stored_len, last)
//DeflateState *s;
//charf *buf; /* input block */
//ulg stored_len; /* length of input block */
//int last; /* one if this is the last block for a file */
{
send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
copy_block(s, buf, stored_len, true); /* with header */
}
/* ===========================================================================
* Send one empty static block to give enough lookahead for inflate.
* This takes 10 bits, of which 7 may remain in the bit buffer.
*/
function _tr_align(s) {
send_bits(s, STATIC_TREES<<1, 3);
send_code(s, END_BLOCK, static_ltree);
bi_flush(s);
}
/* ===========================================================================
* Determine the best encoding for the current block: dynamic trees, static
* trees or store, and output the encoded block to the zip file.
*/
function _tr_flush_block(s, buf, stored_len, last)
//DeflateState *s;
//charf *buf; /* input block, or NULL if too old */
//ulg stored_len; /* length of input block */
//int last; /* one if this is the last block for a file */
{
var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
var max_blindex = 0; /* index of last bit length code of non zero freq */
/* Build the Huffman trees unless a stored block is forced */
if (s.level > 0) {
/* Check if the file is binary or text */
if (s.strm.data_type === Z_UNKNOWN) {
s.strm.data_type = detect_data_type(s);
}
/* Construct the literal and distance trees */
build_tree(s, s.l_desc);
// Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
// s->static_len));
build_tree(s, s.d_desc);
// Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
// s->static_len));
/* At this point, opt_len and static_len are the total bit lengths of
* the compressed block data, excluding the tree representations.
*/
/* Build the bit length tree for the above two trees, and get the index
* in bl_order of the last bit length code to send.
*/
max_blindex = build_bl_tree(s);
/* Determine the best encoding. Compute the block lengths in bytes. */
opt_lenb = (s.opt_len+3+7) >>> 3;
static_lenb = (s.static_len+3+7) >>> 3;
// Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
// opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
// s->last_lit));
if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
} else {
// Assert(buf != (char*)0, "lost buf");
opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
}
if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
/* 4: two words for the lengths */
/* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
* Otherwise we can't have processed more than WSIZE input bytes since
* the last block flush, because compression would have been
* successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
* transform a block into a stored block.
*/
_tr_stored_block(s, buf, stored_len, last);
} else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
compress_block(s, static_ltree, static_dtree);
} else {
send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
compress_block(s, s.dyn_ltree, s.dyn_dtree);
}
// Assert (s->compressed_len == s->bits_sent, "bad compressed size");
/* The above check is made mod 2^32, for files larger than 512 MB
* and uLong implemented on 32 bits.
*/
init_block(s);
if (last) {
bi_windup(s);
}
// Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
// s->compressed_len-7*last));
}
/* ===========================================================================
* Save the match info and tally the frequency counts. Return true if
* the current block must be flushed.
*/
function _tr_tally(s, dist, lc)
// deflate_state *s;
// unsigned dist; /* distance of matched string */
// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
{
//var out_length, in_length, dcode;
s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
s.last_lit++;
if (dist === 0) {
/* lc is the unmatched char */
s.dyn_ltree[lc*2]/*.Freq*/++;
} else {
s.matches++;
/* Here, lc is the match length - MIN_MATCH */
dist--; /* dist = match distance - 1 */
//Assert((ush)dist < (ush)MAX_DIST(s) &&
// (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
// (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef TRUNCATE_BLOCK
// /* Try to guess if it is profitable to stop the current block here */
// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
// /* Compute an upper bound for the compressed length */
// out_length = s.last_lit*8;
// in_length = s.strstart - s.block_start;
//
// for (dcode = 0; dcode < D_CODES; dcode++) {
// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
// }
// out_length >>>= 3;
// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
// // s->last_lit, in_length, out_length,
// // 100L - out_length*100L/in_length));
// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
// return true;
// }
// }
//#endif
return (s.last_lit === s.lit_bufsize-1);
/* We avoid equality with lit_bufsize because of wraparound at 64K
* on 16 bit machines and because stored blocks are restricted to
* 64K-1 bytes.
*/
}
exports._tr_init = _tr_init;
exports._tr_stored_block = _tr_stored_block;
exports._tr_flush_block = _tr_flush_block;
exports._tr_tally = _tr_tally;
exports._tr_align = _tr_align;
},{"../utils/common":129}],141:[function(require,module,exports){
'use strict';
function ZStream() {
/* next input byte */
this.input = null; // JS specific, because we have no pointers
this.next_in = 0;
/* number of bytes available at input */
this.avail_in = 0;
/* total number of input bytes read so far */
this.total_in = 0;
/* next output byte should be put there */
this.output = null; // JS specific, because we have no pointers
this.next_out = 0;
/* remaining free space at output */
this.avail_out = 0;
/* total number of bytes output so far */
this.total_out = 0;
/* last error message, NULL if no error */
this.msg = ''/*Z_NULL*/;
/* not visible by applications */
this.state = null;
/* best guess about the data type: binary or text */
this.data_type = 2/*Z_UNKNOWN*/;
/* adler32 value of the uncompressed data */
this.adler = 0;
}
module.exports = ZStream;
},{}],142:[function(require,module,exports){
exports.Parser = require("./lib/parser").Parser;
exports.rules = require("./lib/rules");
exports.errors = require("./lib/errors");
exports.results = require("./lib/parsing-results");
exports.StringSource = require("./lib/StringSource");
exports.Token = require("./lib/Token");
exports.bottomUp = require("./lib/bottom-up");
exports.RegexTokeniser = require("./lib/regex-tokeniser").RegexTokeniser;
exports.rule = function(ruleBuilder) {
var rule;
return function(input) {
if (!rule) {
rule = ruleBuilder();
}
return rule(input);
};
};
},{"./lib/StringSource":143,"./lib/Token":144,"./lib/bottom-up":146,"./lib/errors":147,"./lib/parser":149,"./lib/parsing-results":150,"./lib/regex-tokeniser":151,"./lib/rules":152}],143:[function(require,module,exports){
var util = require("util");
var StringSource = module.exports = function(string, description) {
var self = {
asString: function() {
return string;
},
range: function(startIndex, endIndex) {
return new StringSourceRange(string, description, startIndex, endIndex);
}
};
return self;
};
var StringSourceRange = function(string, description, startIndex, endIndex) {
this._string = string;
this._description = description;
this._startIndex = startIndex;
this._endIndex = endIndex;
};
StringSourceRange.prototype.to = function(otherRange) {
// TODO: Assert that tokens are the same across both iterators
return new StringSourceRange(this._string, this._description, this._startIndex, otherRange._endIndex);
};
StringSourceRange.prototype.describe = function() {
var position = this._position();
var description = this._description ? this._description + "\n" : "";
return util.format("%sLine number: %s\nCharacter number: %s",
description, position.lineNumber, position.characterNumber);
};
StringSourceRange.prototype.lineNumber = function() {
return this._position().lineNumber;
};
StringSourceRange.prototype.characterNumber = function() {
return this._position().characterNumber;
};
StringSourceRange.prototype._position = function() {
var self = this;
var index = 0;
var nextNewLine = function() {
return self._string.indexOf("\n", index);
};
var lineNumber = 1;
while (nextNewLine() !== -1 && nextNewLine() < this._startIndex) {
index = nextNewLine() + 1;
lineNumber += 1;
}
var characterNumber = this._startIndex - index + 1;
return {lineNumber: lineNumber, characterNumber: characterNumber};
};
},{"util":102}],144:[function(require,module,exports){
module.exports = function(name, value, source) {
this.name = name;
this.value = value;
if (source) {
this.source = source;
}
};
},{}],145:[function(require,module,exports){
var TokenIterator = module.exports = function(tokens, startIndex) {
this._tokens = tokens;
this._startIndex = startIndex || 0;
};
TokenIterator.prototype.head = function() {
return this._tokens[this._startIndex];
};
TokenIterator.prototype.tail = function(startIndex) {
return new TokenIterator(this._tokens, this._startIndex + 1);
};
TokenIterator.prototype.toArray = function() {
return this._tokens.slice(this._startIndex);
};
TokenIterator.prototype.end = function() {
return this._tokens[this._tokens.length - 1];
};
// TODO: doesn't need to be a method, can be a separate function,
// which simplifies implementation of the TokenIterator interface
TokenIterator.prototype.to = function(end) {
var start = this.head().source;
var endToken = end.head() || end.end();
return start.to(endToken.source);
};
},{}],146:[function(require,module,exports){
var rules = require("./rules");
var results = require("./parsing-results");
exports.parser = function(name, prefixRules, infixRuleBuilders) {
var self = {
rule: rule,
leftAssociative: leftAssociative,
rightAssociative: rightAssociative
};
var infixRules = new InfixRules(infixRuleBuilders.map(createInfixRule));
var prefixRule = rules.firstOf(name, prefixRules);
function createInfixRule(infixRuleBuilder) {
return {
name: infixRuleBuilder.name,
rule: lazyRule(infixRuleBuilder.ruleBuilder.bind(null, self))
};
}
function rule() {
return createRule(infixRules);
}
function leftAssociative(name) {
return createRule(infixRules.untilExclusive(name));
}
function rightAssociative(name) {
return createRule(infixRules.untilInclusive(name));
}
function createRule(infixRules) {
return apply.bind(null, infixRules);
}
function apply(infixRules, tokens) {
var leftResult = prefixRule(tokens);
if (leftResult.isSuccess()) {
return infixRules.apply(leftResult);
} else {
return leftResult;
}
}
return self;
};
function InfixRules(infixRules) {
function untilExclusive(name) {
return new InfixRules(infixRules.slice(0, ruleNames().indexOf(name)));
}
function untilInclusive(name) {
return new InfixRules(infixRules.slice(0, ruleNames().indexOf(name) + 1));
}
function ruleNames() {
return infixRules.map(function(rule) {
return rule.name;
});
}
function apply(leftResult) {
var currentResult;
var source;
while (true) {
currentResult = applyToTokens(leftResult.remaining());
if (currentResult.isSuccess()) {
source = leftResult.source().to(currentResult.source());
leftResult = results.success(
currentResult.value()(leftResult.value(), source),
currentResult.remaining(),
source
)
} else if (currentResult.isFailure()) {
return leftResult;
} else {
return currentResult;
}
}
}
function applyToTokens(tokens) {
return rules.firstOf("infix", infixRules.map(function(infix) {
return infix.rule;
}))(tokens);
}
return {
apply: apply,
untilExclusive: untilExclusive,
untilInclusive: untilInclusive
}
}
exports.infix = function(name, ruleBuilder) {
function map(func) {
return exports.infix(name, function(parser) {
var rule = ruleBuilder(parser);
return function(tokens) {
var result = rule(tokens);
return result.map(function(right) {
return function(left, source) {
return func(left, right, source);
};
});
};
});
}
return {
name: name,
ruleBuilder: ruleBuilder,
map: map
};
}
// TODO: move into a sensible place and remove duplication
var lazyRule = function(ruleBuilder) {
var rule;
return function(input) {
if (!rule) {
rule = ruleBuilder();
}
return rule(input);
};
};
},{"./parsing-results":150,"./rules":152}],147:[function(require,module,exports){
exports.error = function(options) {
return new Error(options);
};
var Error = function(options) {
this.expected = options.expected;
this.actual = options.actual;
this._location = options.location;
};
Error.prototype.describe = function() {
var locationDescription = this._location ? this._location.describe() + ":\n" : "";
return locationDescription + "Expected " + this.expected + "\nbut got " + this.actual;
};
Error.prototype.lineNumber = function() {
return this._location.lineNumber();
};
Error.prototype.characterNumber = function() {
return this._location.characterNumber();
};
},{}],148:[function(require,module,exports){
var fromArray = exports.fromArray = function(array) {
var index = 0;
var hasNext = function() {
return index < array.length;
};
return new LazyIterator({
hasNext: hasNext,
next: function() {
if (!hasNext()) {
throw new Error("No more elements");
} else {
return array[index++];
}
}
});
};
var LazyIterator = function(iterator) {
this._iterator = iterator;
};
LazyIterator.prototype.map = function(func) {
var iterator = this._iterator;
return new LazyIterator({
hasNext: function() {
return iterator.hasNext();
},
next: function() {
return func(iterator.next());
}
});
};
LazyIterator.prototype.filter = function(condition) {
var iterator = this._iterator;
var moved = false;
var hasNext = false;
var next;
var moveIfNecessary = function() {
if (moved) {
return;
}
moved = true;
hasNext = false;
while (iterator.hasNext() && !hasNext) {
next = iterator.next();
hasNext = condition(next);
}
};
return new LazyIterator({
hasNext: function() {
moveIfNecessary();
return hasNext;
},
next: function() {
moveIfNecessary();
var toReturn = next;
moved = false;
return toReturn;
}
});
};
LazyIterator.prototype.first = function() {
var iterator = this._iterator;
if (this._iterator.hasNext()) {
return iterator.next();
} else {
return null;
}
};
LazyIterator.prototype.toArray = function() {
var result = [];
while (this._iterator.hasNext()) {
result.push(this._iterator.next());
}
return result;
};
},{}],149:[function(require,module,exports){
var TokenIterator = require("./TokenIterator");
exports.Parser = function(options) {
var parseTokens = function(parser, tokens) {
return parser(new TokenIterator(tokens));
};
return {
parseTokens: parseTokens
};
};
},{"./TokenIterator":145}],150:[function(require,module,exports){
module.exports = {
failure: function(errors, remaining) {
if (errors.length < 1) {
throw new Error("Failure must have errors");
}
return new Result({
status: "failure",
remaining: remaining,
errors: errors
});
},
error: function(errors, remaining) {
if (errors.length < 1) {
throw new Error("Failure must have errors");
}
return new Result({
status: "error",
remaining: remaining,
errors: errors
});
},
success: function(value, remaining, source) {
return new Result({
status: "success",
value: value,
source: source,
remaining: remaining,
errors: []
});
},
cut: function(remaining) {
return new Result({
status: "cut",
remaining: remaining,
errors: []
});
}
};
var Result = function(options) {
this._value = options.value;
this._status = options.status;
this._hasValue = options.value !== undefined;
this._remaining = options.remaining;
this._source = options.source;
this._errors = options.errors;
};
Result.prototype.map = function(func) {
if (this._hasValue) {
return new Result({
value: func(this._value, this._source),
status: this._status,
remaining: this._remaining,
source: this._source,
errors: this._errors
});
} else {
return this;
}
};
Result.prototype.changeRemaining = function(remaining) {
return new Result({
value: this._value,
status: this._status,
remaining: remaining,
source: this._source,
errors: this._errors
});
};
Result.prototype.isSuccess = function() {
return this._status === "success" || this._status === "cut";
};
Result.prototype.isFailure = function() {
return this._status === "failure";
};
Result.prototype.isError = function() {
return this._status === "error";
};
Result.prototype.isCut = function() {
return this._status === "cut";
};
Result.prototype.value = function() {
return this._value;
};
Result.prototype.remaining = function() {
return this._remaining;
};
Result.prototype.source = function() {
return this._source;
};
Result.prototype.errors = function() {
return this._errors;
};
},{}],151:[function(require,module,exports){
var Token = require("./Token");
var StringSource = require("./StringSource");
exports.RegexTokeniser = RegexTokeniser;
function RegexTokeniser(rules) {
rules = rules.map(function(rule) {
return {
name: rule.name,
regex: new RegExp(rule.regex.source, "g")
};
});
function tokenise(input, description) {
var source = new StringSource(input, description);
var index = 0;
var tokens = [];
while (index < input.length) {
var result = readNextToken(input, index, source);
index = result.endIndex;
tokens.push(result.token);
}
tokens.push(endToken(input, source));
return tokens;
}
function readNextToken(string, startIndex, source) {
for (var i = 0; i < rules.length; i++) {
var regex = rules[i].regex;
regex.lastIndex = startIndex;
var result = regex.exec(string);
if (result) {
var endIndex = startIndex + result[0].length;
if (result.index === startIndex && endIndex > startIndex) {
var value = result[1];
var token = new Token(
rules[i].name,
value,
source.range(startIndex, endIndex)
);
return {token: token, endIndex: endIndex};
}
}
}
var endIndex = startIndex + 1;
var token = new Token(
"unrecognisedCharacter",
string.substring(startIndex, endIndex),
source.range(startIndex, endIndex)
);
return {token: token, endIndex: endIndex};
}
function endToken(input, source) {
return new Token(
"end",
null,
source.range(input.length, input.length)
);
}
return {
tokenise: tokenise
}
}
},{"./StringSource":143,"./Token":144}],152:[function(require,module,exports){
var _ = require("underscore");
var options = require("option");
var results = require("./parsing-results");
var errors = require("./errors");
var lazyIterators = require("./lazy-iterators");
exports.token = function(tokenType, value) {
var matchValue = value !== undefined;
return function(input) {
var token = input.head();
if (token && token.name === tokenType && (!matchValue || token.value === value)) {
return results.success(token.value, input.tail(), token.source);
} else {
var expected = describeToken({name: tokenType, value: value});
return describeTokenMismatch(input, expected);
}
};
};
exports.tokenOfType = function(tokenType) {
return exports.token(tokenType);
};
exports.firstOf = function(name, parsers) {
if (!_.isArray(parsers)) {
parsers = Array.prototype.slice.call(arguments, 1);
}
return function(input) {
return lazyIterators
.fromArray(parsers)
.map(function(parser) {
return parser(input);
})
.filter(function(result) {
return result.isSuccess() || result.isError();
})
.first() || describeTokenMismatch(input, name);
};
};
exports.then = function(parser, func) {
return function(input) {
var result = parser(input);
if (!result.map) {
console.log(result);
}
return result.map(func);
};
};
exports.sequence = function() {
var parsers = Array.prototype.slice.call(arguments, 0);
var rule = function(input) {
var result = _.foldl(parsers, function(memo, parser) {
var result = memo.result;
var hasCut = memo.hasCut;
if (!result.isSuccess()) {
return {result: result, hasCut: hasCut};
}
var subResult = parser(result.remaining());
if (subResult.isCut()) {
return {result: result, hasCut: true};
} else if (subResult.isSuccess()) {
var values;
if (parser.isCaptured) {
values = result.value().withValue(parser, subResult.value());
} else {
values = result.value();
}
var remaining = subResult.remaining();
var source = input.to(remaining);
return {
result: results.success(values, remaining, source),
hasCut: hasCut
};
} else if (hasCut) {
return {result: results.error(subResult.errors(), subResult.remaining()), hasCut: hasCut};
} else {
return {result: subResult, hasCut: hasCut};
}
}, {result: results.success(new SequenceValues(), input), hasCut: false}).result;
var source = input.to(result.remaining());
return result.map(function(values) {
return values.withValue(exports.sequence.source, source);
});
};
rule.head = function() {
var firstCapture = _.find(parsers, isCapturedRule);
return exports.then(
rule,
exports.sequence.extract(firstCapture)
);
};
rule.map = function(func) {
return exports.then(
rule,
function(result) {
return func.apply(this, result.toArray());
}
);
};
function isCapturedRule(subRule) {
return subRule.isCaptured;
}
return rule;
};
var SequenceValues = function(values, valuesArray) {
this._values = values || {};
this._valuesArray = valuesArray || [];
};
SequenceValues.prototype.withValue = function(rule, value) {
if (rule.captureName && rule.captureName in this._values) {
throw new Error("Cannot add second value for capture \"" + rule.captureName + "\"");
} else {
var newValues = _.clone(this._values);
newValues[rule.captureName] = value;
var newValuesArray = this._valuesArray.concat([value]);
return new SequenceValues(newValues, newValuesArray);
}
};
SequenceValues.prototype.get = function(rule) {
if (rule.captureName in this._values) {
return this._values[rule.captureName];
} else {
throw new Error("No value for capture \"" + rule.captureName + "\"");
}
};
SequenceValues.prototype.toArray = function() {
return this._valuesArray;
};
exports.sequence.capture = function(rule, name) {
var captureRule = function() {
return rule.apply(this, arguments);
};
captureRule.captureName = name;
captureRule.isCaptured = true;
return captureRule;
};
exports.sequence.extract = function(rule) {
return function(result) {
return result.get(rule);
};
};
exports.sequence.applyValues = function(func) {
// TODO: check captureName doesn't conflict with source or other captures
var rules = Array.prototype.slice.call(arguments, 1);
return function(result) {
var values = rules.map(function(rule) {
return result.get(rule);
});
return func.apply(this, values);
};
};
exports.sequence.source = {
captureName: "☃source☃"
};
exports.sequence.cut = function() {
return function(input) {
return results.cut(input);
};
};
exports.optional = function(rule) {
return function(input) {
var result = rule(input);
if (result.isSuccess()) {
return result.map(options.some);
} else if (result.isFailure()) {
return results.success(options.none, input);
} else {
return result;
}
};
};
exports.zeroOrMoreWithSeparator = function(rule, separator) {
return repeatedWithSeparator(rule, separator, false);
};
exports.oneOrMoreWithSeparator = function(rule, separator) {
return repeatedWithSeparator(rule, separator, true);
};
var zeroOrMore = exports.zeroOrMore = function(rule) {
return function(input) {
var values = [];
var result;
while ((result = rule(input)) && result.isSuccess()) {
input = result.remaining();
values.push(result.value());
}
if (result.isError()) {
return result;
} else {
return results.success(values, input);
}
};
};
exports.oneOrMore = function(rule) {
return exports.oneOrMoreWithSeparator(rule, noOpRule);
};
function noOpRule(input) {
return results.success(null, input);
}
var repeatedWithSeparator = function(rule, separator, isOneOrMore) {
return function(input) {
var result = rule(input);
if (result.isSuccess()) {
var mainRule = exports.sequence.capture(rule, "main");
var remainingRule = zeroOrMore(exports.then(
exports.sequence(separator, mainRule),
exports.sequence.extract(mainRule)
));
var remainingResult = remainingRule(result.remaining());
return results.success([result.value()].concat(remainingResult.value()), remainingResult.remaining());
} else if (isOneOrMore || result.isError()) {
return result;
} else {
return results.success([], input);
}
};
};
exports.leftAssociative = function(leftRule, rightRule, func) {
var rights;
if (func) {
rights = [{func: func, rule: rightRule}];
} else {
rights = rightRule;
}
rights = rights.map(function(right) {
return exports.then(right.rule, function(rightValue) {
return function(leftValue, source) {
return right.func(leftValue, rightValue, source);
};
});
});
var repeatedRule = exports.firstOf.apply(null, ["rules"].concat(rights));
return function(input) {
var start = input;
var leftResult = leftRule(input);
if (!leftResult.isSuccess()) {
return leftResult;
}
var repeatedResult = repeatedRule(leftResult.remaining());
while (repeatedResult.isSuccess()) {
var remaining = repeatedResult.remaining();
var source = start.to(repeatedResult.remaining());
var right = repeatedResult.value();
leftResult = results.success(
right(leftResult.value(), source),
remaining,
source
);
repeatedResult = repeatedRule(leftResult.remaining());
}
if (repeatedResult.isError()) {
return repeatedResult;
}
return leftResult;
};
};
exports.leftAssociative.firstOf = function() {
return Array.prototype.slice.call(arguments, 0);
};
exports.nonConsuming = function(rule) {
return function(input) {
return rule(input).changeRemaining(input);
};
};
var describeToken = function(token) {
if (token.value) {
return token.name + " \"" + token.value + "\"";
} else {
return token.name;
}
};
function describeTokenMismatch(input, expected) {
var error;
var token = input.head();
if (token) {
error = errors.error({
expected: expected,
actual: describeToken(token),
location: token.source
});
} else {
error = errors.error({
expected: expected,
actual: "end of tokens"
});
}
return results.failure([error], input);
}
},{"./errors":147,"./lazy-iterators":148,"./parsing-results":150,"option":153,"underscore":154}],153:[function(require,module,exports){
exports.none = Object.create({
value: function() {
throw new Error('Called value on none');
},
isNone: function() {
return true;
},
isSome: function() {
return false;
},
map: function() {
return exports.none;
},
flatMap: function() {
return exports.none;
},
toArray: function() {
return [];
},
orElse: callOrReturn,
valueOrElse: callOrReturn
});
function callOrReturn(value) {
if (typeof(value) == "function") {
return value();
} else {
return value;
}
}
exports.some = function(value) {
return new Some(value);
};
var Some = function(value) {
this._value = value;
};
Some.prototype.value = function() {
return this._value;
};
Some.prototype.isNone = function() {
return false;
};
Some.prototype.isSome = function() {
return true;
};
Some.prototype.map = function(func) {
return new Some(func(this._value));
};
Some.prototype.flatMap = function(func) {
return func(this._value);
};
Some.prototype.toArray = function() {
return [this._value];
};
Some.prototype.orElse = function(value) {
return this;
};
Some.prototype.valueOrElse = function(value) {
return this._value;
};
exports.isOption = function(value) {
return value === exports.none || value instanceof Some;
};
exports.fromNullable = function(value) {
if (value == null) {
return exports.none;
}
return new Some(value);
}
},{}],154:[function(require,module,exports){
// Underscore.js 1.4.4
// http://underscorejs.org
// (c) 2009-2013 Jeremy Ashkenas, DocumentCloud Inc.
// Underscore may be freely distributed under the MIT license.
(function() {
// Baseline setup
// --------------
// Establish the root object, `window` in the browser, or `global` on the server.
var root = this;
// Save the previous value of the `_` variable.
var previousUnderscore = root._;
// Establish the object that gets returned to break out of a loop iteration.
var breaker = {};
// Save bytes in the minified (but not gzipped) version:
var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
// Create quick reference variables for speed access to core prototypes.
var push = ArrayProto.push,
slice = ArrayProto.slice,
concat = ArrayProto.concat,
toString = ObjProto.toString,
hasOwnProperty = ObjProto.hasOwnProperty;
// All **ECMAScript 5** native function implementations that we hope to use
// are declared here.
var
nativeForEach = ArrayProto.forEach,
nativeMap = ArrayProto.map,
nativeReduce = ArrayProto.reduce,
nativeReduceRight = ArrayProto.reduceRight,
nativeFilter = ArrayProto.filter,
nativeEvery = ArrayProto.every,
nativeSome = ArrayProto.some,
nativeIndexOf = ArrayProto.indexOf,
nativeLastIndexOf = ArrayProto.lastIndexOf,
nativeIsArray = Array.isArray,
nativeKeys = Object.keys,
nativeBind = FuncProto.bind;
// Create a safe reference to the Underscore object for use below.
var _ = function(obj) {
if (obj instanceof _) return obj;
if (!(this instanceof _)) return new _(obj);
this._wrapped = obj;
};
// Export the Underscore object for **Node.js**, with
// backwards-compatibility for the old `require()` API. If we're in
// the browser, add `_` as a global object via a string identifier,
// for Closure Compiler "advanced" mode.
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = _;
}
exports._ = _;
} else {
root._ = _;
}
// Current version.
_.VERSION = '1.4.4';
// Collection Functions
// --------------------
// The cornerstone, an `each` implementation, aka `forEach`.
// Handles objects with the built-in `forEach`, arrays, and raw objects.
// Delegates to **ECMAScript 5**'s native `forEach` if available.
var each = _.each = _.forEach = function(obj, iterator, context) {
if (obj == null) return;
if (nativeForEach && obj.forEach === nativeForEach) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
for (var i = 0, l = obj.length; i < l; i++) {
if (iterator.call(context, obj[i], i, obj) === breaker) return;
}
} else {
for (var key in obj) {
if (_.has(obj, key)) {
if (iterator.call(context, obj[key], key, obj) === breaker) return;
}
}
}
};
// Return the results of applying the iterator to each element.
// Delegates to **ECMAScript 5**'s native `map` if available.
_.map = _.collect = function(obj, iterator, context) {
var results = [];
if (obj == null) return results;
if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
each(obj, function(value, index, list) {
results[results.length] = iterator.call(context, value, index, list);
});
return results;
};
var reduceError = 'Reduce of empty array with no initial value';
// **Reduce** builds up a single result from a list of values, aka `inject`,
// or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
_.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
var initial = arguments.length > 2;
if (obj == null) obj = [];
if (nativeReduce && obj.reduce === nativeReduce) {
if (context) iterator = _.bind(iterator, context);
return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
}
each(obj, function(value, index, list) {
if (!initial) {
memo = value;
initial = true;
} else {
memo = iterator.call(context, memo, value, index, list);
}
});
if (!initial) throw new TypeError(reduceError);
return memo;
};
// The right-associative version of reduce, also known as `foldr`.
// Delegates to **ECMAScript 5**'s native `reduceRight` if available.
_.reduceRight = _.foldr = function(obj, iterator, memo, context) {
var initial = arguments.length > 2;
if (obj == null) obj = [];
if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
if (context) iterator = _.bind(iterator, context);
return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
}
var length = obj.length;
if (length !== +length) {
var keys = _.keys(obj);
length = keys.length;
}
each(obj, function(value, index, list) {
index = keys ? keys[--length] : --length;
if (!initial) {
memo = obj[index];
initial = true;
} else {
memo = iterator.call(context, memo, obj[index], index, list);
}
});
if (!initial) throw new TypeError(reduceError);
return memo;
};
// Return the first value which passes a truth test. Aliased as `detect`.
_.find = _.detect = function(obj, iterator, context) {
var result;
any(obj, function(value, index, list) {
if (iterator.call(context, value, index, list)) {
result = value;
return true;
}
});
return result;
};
// Return all the elements that pass a truth test.
// Delegates to **ECMAScript 5**'s native `filter` if available.
// Aliased as `select`.
_.filter = _.select = function(obj, iterator, context) {
var results = [];
if (obj == null) return results;
if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
each(obj, function(value, index, list) {
if (iterator.call(context, value, index, list)) results[results.length] = value;
});
return results;
};
// Return all the elements for which a truth test fails.
_.reject = function(obj, iterator, context) {
return _.filter(obj, function(value, index, list) {
return !iterator.call(context, value, index, list);
}, context);
};
// Determine whether all of the elements match a truth test.
// Delegates to **ECMAScript 5**'s native `every` if available.
// Aliased as `all`.
_.every = _.all = function(obj, iterator, context) {
iterator || (iterator = _.identity);
var result = true;
if (obj == null) return result;
if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
each(obj, function(value, index, list) {
if (!(result = result && iterator.call(context, value, index, list))) return breaker;
});
return !!result;
};
// Determine if at least one element in the object matches a truth test.
// Delegates to **ECMAScript 5**'s native `some` if available.
// Aliased as `any`.
var any = _.some = _.any = function(obj, iterator, context) {
iterator || (iterator = _.identity);
var result = false;
if (obj == null) return result;
if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
each(obj, function(value, index, list) {
if (result || (result = iterator.call(context, value, index, list))) return breaker;
});
return !!result;
};
// Determine if the array or object contains a given value (using `===`).
// Aliased as `include`.
_.contains = _.include = function(obj, target) {
if (obj == null) return false;
if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
return any(obj, function(value) {
return value === target;
});
};
// Invoke a method (with arguments) on every item in a collection.
_.invoke = function(obj, method) {
var args = slice.call(arguments, 2);
var isFunc = _.isFunction(method);
return _.map(obj, function(value) {
return (isFunc ? method : value[method]).apply(value, args);
});
};
// Convenience version of a common use case of `map`: fetching a property.
_.pluck = function(obj, key) {
return _.map(obj, function(value){ return value[key]; });
};
// Convenience version of a common use case of `filter`: selecting only objects
// containing specific `key:value` pairs.
_.where = function(obj, attrs, first) {
if (_.isEmpty(attrs)) return first ? null : [];
return _[first ? 'find' : 'filter'](obj, function(value) {
for (var key in attrs) {
if (attrs[key] !== value[key]) return false;
}
return true;
});
};
// Convenience version of a common use case of `find`: getting the first object
// containing specific `key:value` pairs.
_.findWhere = function(obj, attrs) {
return _.where(obj, attrs, true);
};
// Return the maximum element or (element-based computation).
// Can't optimize arrays of integers longer than 65,535 elements.
// See: https://bugs.webkit.org/show_bug.cgi?id=80797
_.max = function(obj, iterator, context) {
if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
return Math.max.apply(Math, obj);
}
if (!iterator && _.isEmpty(obj)) return -Infinity;
var result = {computed : -Infinity, value: -Infinity};
each(obj, function(value, index, list) {
var computed = iterator ? iterator.call(context, value, index, list) : value;
computed >= result.computed && (result = {value : value, computed : computed});
});
return result.value;
};
// Return the minimum element (or element-based computation).
_.min = function(obj, iterator, context) {
if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
return Math.min.apply(Math, obj);
}
if (!iterator && _.isEmpty(obj)) return Infinity;
var result = {computed : Infinity, value: Infinity};
each(obj, function(value, index, list) {
var computed = iterator ? iterator.call(context, value, index, list) : value;
computed < result.computed && (result = {value : value, computed : computed});
});
return result.value;
};
// Shuffle an array.
_.shuffle = function(obj) {
var rand;
var index = 0;
var shuffled = [];
each(obj, function(value) {
rand = _.random(index++);
shuffled[index - 1] = shuffled[rand];
shuffled[rand] = value;
});
return shuffled;
};
// An internal function to generate lookup iterators.
var lookupIterator = function(value) {
return _.isFunction(value) ? value : function(obj){ return obj[value]; };
};
// Sort the object's values by a criterion produced by an iterator.
_.sortBy = function(obj, value, context) {
var iterator = lookupIterator(value);
return _.pluck(_.map(obj, function(value, index, list) {
return {
value : value,
index : index,
criteria : iterator.call(context, value, index, list)
};
}).sort(function(left, right) {
var a = left.criteria;
var b = right.criteria;
if (a !== b) {
if (a > b || a === void 0) return 1;
if (a < b || b === void 0) return -1;
}
return left.index < right.index ? -1 : 1;
}), 'value');
};
// An internal function used for aggregate "group by" operations.
var group = function(obj, value, context, behavior) {
var result = {};
var iterator = lookupIterator(value || _.identity);
each(obj, function(value, index) {
var key = iterator.call(context, value, index, obj);
behavior(result, key, value);
});
return result;
};
// Groups the object's values by a criterion. Pass either a string attribute
// to group by, or a function that returns the criterion.
_.groupBy = function(obj, value, context) {
return group(obj, value, context, function(result, key, value) {
(_.has(result, key) ? result[key] : (result[key] = [])).push(value);
});
};
// Counts instances of an object that group by a certain criterion. Pass
// either a string attribute to count by, or a function that returns the
// criterion.
_.countBy = function(obj, value, context) {
return group(obj, value, context, function(result, key) {
if (!_.has(result, key)) result[key] = 0;
result[key]++;
});
};
// Use a comparator function to figure out the smallest index at which
// an object should be inserted so as to maintain order. Uses binary search.
_.sortedIndex = function(array, obj, iterator, context) {
iterator = iterator == null ? _.identity : lookupIterator(iterator);
var value = iterator.call(context, obj);
var low = 0, high = array.length;
while (low < high) {
var mid = (low + high) >>> 1;
iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid;
}
return low;
};
// Safely convert anything iterable into a real, live array.
_.toArray = function(obj) {
if (!obj) return [];
if (_.isArray(obj)) return slice.call(obj);
if (obj.length === +obj.length) return _.map(obj, _.identity);
return _.values(obj);
};
// Return the number of elements in an object.
_.size = function(obj) {
if (obj == null) return 0;
return (obj.length === +obj.length) ? obj.length : _.keys(obj).length;
};
// Array Functions
// ---------------
// Get the first element of an array. Passing **n** will return the first N
// values in the array. Aliased as `head` and `take`. The **guard** check
// allows it to work with `_.map`.
_.first = _.head = _.take = function(array, n, guard) {
if (array == null) return void 0;
return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
};
// Returns everything but the last entry of the array. Especially useful on
// the arguments object. Passing **n** will return all the values in
// the array, excluding the last N. The **guard** check allows it to work with
// `_.map`.
_.initial = function(array, n, guard) {
return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
};
// Get the last element of an array. Passing **n** will return the last N
// values in the array. The **guard** check allows it to work with `_.map`.
_.last = function(array, n, guard) {
if (array == null) return void 0;
if ((n != null) && !guard) {
return slice.call(array, Math.max(array.length - n, 0));
} else {
return array[array.length - 1];
}
};
// Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
// Especially useful on the arguments object. Passing an **n** will return
// the rest N values in the array. The **guard**
// check allows it to work with `_.map`.
_.rest = _.tail = _.drop = function(array, n, guard) {
return slice.call(array, (n == null) || guard ? 1 : n);
};
// Trim out all falsy values from an array.
_.compact = function(array) {
return _.filter(array, _.identity);
};
// Internal implementation of a recursive `flatten` function.
var flatten = function(input, shallow, output) {
each(input, function(value) {
if (_.isArray(value)) {
shallow ? push.apply(output, value) : flatten(value, shallow, output);
} else {
output.push(value);
}
});
return output;
};
// Return a completely flattened version of an array.
_.flatten = function(array, shallow) {
return flatten(array, shallow, []);
};
// Return a version of the array that does not contain the specified value(s).
_.without = function(array) {
return _.difference(array, slice.call(arguments, 1));
};
// Produce a duplicate-free version of the array. If the array has already
// been sorted, you have the option of using a faster algorithm.
// Aliased as `unique`.
_.uniq = _.unique = function(array, isSorted, iterator, context) {
if (_.isFunction(isSorted)) {
context = iterator;
iterator = isSorted;
isSorted = false;
}
var initial = iterator ? _.map(array, iterator, context) : array;
var results = [];
var seen = [];
each(initial, function(value, index) {
if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) {
seen.push(value);
results.push(array[index]);
}
});
return results;
};
// Produce an array that contains the union: each distinct element from all of
// the passed-in arrays.
_.union = function() {
return _.uniq(concat.apply(ArrayProto, arguments));
};
// Produce an array that contains every item shared between all the
// passed-in arrays.
_.intersection = function(array) {
var rest = slice.call(arguments, 1);
return _.filter(_.uniq(array), function(item) {
return _.every(rest, function(other) {
return _.indexOf(other, item) >= 0;
});
});
};
// Take the difference between one array and a number of other arrays.
// Only the elements present in just the first array will remain.
_.difference = function(array) {
var rest = concat.apply(ArrayProto, slice.call(arguments, 1));
return _.filter(array, function(value){ return !_.contains(rest, value); });
};
// Zip together multiple lists into a single array -- elements that share
// an index go together.
_.zip = function() {
var args = slice.call(arguments);
var length = _.max(_.pluck(args, 'length'));
var results = new Array(length);
for (var i = 0; i < length; i++) {
results[i] = _.pluck(args, "" + i);
}
return results;
};
// Converts lists into objects. Pass either a single array of `[key, value]`
// pairs, or two parallel arrays of the same length -- one of keys, and one of
// the corresponding values.
_.object = function(list, values) {
if (list == null) return {};
var result = {};
for (var i = 0, l = list.length; i < l; i++) {
if (values) {
result[list[i]] = values[i];
} else {
result[list[i][0]] = list[i][1];
}
}
return result;
};
// If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
// we need this function. Return the position of the first occurrence of an
// item in an array, or -1 if the item is not included in the array.
// Delegates to **ECMAScript 5**'s native `indexOf` if available.
// If the array is large and already in sort order, pass `true`
// for **isSorted** to use binary search.
_.indexOf = function(array, item, isSorted) {
if (array == null) return -1;
var i = 0, l = array.length;
if (isSorted) {
if (typeof isSorted == 'number') {
i = (isSorted < 0 ? Math.max(0, l + isSorted) : isSorted);
} else {
i = _.sortedIndex(array, item);
return array[i] === item ? i : -1;
}
}
if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
for (; i < l; i++) if (array[i] === item) return i;
return -1;
};
// Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
_.lastIndexOf = function(array, item, from) {
if (array == null) return -1;
var hasIndex = from != null;
if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) {
return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item);
}
var i = (hasIndex ? from : array.length);
while (i--) if (array[i] === item) return i;
return -1;
};
// Generate an integer Array containing an arithmetic progression. A port of
// the native Python `range()` function. See
// [the Python documentation](http://docs.python.org/library/functions.html#range).
_.range = function(start, stop, step) {
if (arguments.length <= 1) {
stop = start || 0;
start = 0;
}
step = arguments[2] || 1;
var len = Math.max(Math.ceil((stop - start) / step), 0);
var idx = 0;
var range = new Array(len);
while(idx < len) {
range[idx++] = start;
start += step;
}
return range;
};
// Function (ahem) Functions
// ------------------
// Create a function bound to a given object (assigning `this`, and arguments,
// optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
// available.
_.bind = function(func, context) {
if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
var args = slice.call(arguments, 2);
return function() {
return func.apply(context, args.concat(slice.call(arguments)));
};
};
// Partially apply a function by creating a version that has had some of its
// arguments pre-filled, without changing its dynamic `this` context.
_.partial = function(func) {
var args = slice.call(arguments, 1);
return function() {
return func.apply(this, args.concat(slice.call(arguments)));
};
};
// Bind all of an object's methods to that object. Useful for ensuring that
// all callbacks defined on an object belong to it.
_.bindAll = function(obj) {
var funcs = slice.call(arguments, 1);
if (funcs.length === 0) funcs = _.functions(obj);
each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
return obj;
};
// Memoize an expensive function by storing its results.
_.memoize = function(func, hasher) {
var memo = {};
hasher || (hasher = _.identity);
return function() {
var key = hasher.apply(this, arguments);
return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
};
};
// Delays a function for the given number of milliseconds, and then calls
// it with the arguments supplied.
_.delay = function(func, wait) {
var args = slice.call(arguments, 2);
return setTimeout(function(){ return func.apply(null, args); }, wait);
};
// Defers a function, scheduling it to run after the current call stack has
// cleared.
_.defer = function(func) {
return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
};
// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time.
_.throttle = function(func, wait) {
var context, args, timeout, result;
var previous = 0;
var later = function() {
previous = new Date;
timeout = null;
result = func.apply(context, args);
};
return function() {
var now = new Date;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(context, args);
} else if (!timeout) {
timeout = setTimeout(later, remaining);
}
return result;
};
};
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
_.debounce = function(func, wait, immediate) {
var timeout, result;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) result = func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) result = func.apply(context, args);
return result;
};
};
// Returns a function that will be executed at most one time, no matter how
// often you call it. Useful for lazy initialization.
_.once = function(func) {
var ran = false, memo;
return function() {
if (ran) return memo;
ran = true;
memo = func.apply(this, arguments);
func = null;
return memo;
};
};
// Returns the first function passed as an argument to the second,
// allowing you to adjust arguments, run code before and after, and
// conditionally execute the original function.
_.wrap = function(func, wrapper) {
return function() {
var args = [func];
push.apply(args, arguments);
return wrapper.apply(this, args);
};
};
// Returns a function that is the composition of a list of functions, each
// consuming the return value of the function that follows.
_.compose = function() {
var funcs = arguments;
return function() {
var args = arguments;
for (var i = funcs.length - 1; i >= 0; i--) {
args = [funcs[i].apply(this, args)];
}
return args[0];
};
};
// Returns a function that will only be executed after being called N times.
_.after = function(times, func) {
if (times <= 0) return func();
return function() {
if (--times < 1) {
return func.apply(this, arguments);
}
};
};
// Object Functions
// ----------------
// Retrieve the names of an object's properties.
// Delegates to **ECMAScript 5**'s native `Object.keys`
_.keys = nativeKeys || function(obj) {
if (obj !== Object(obj)) throw new TypeError('Invalid object');
var keys = [];
for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key;
return keys;
};
// Retrieve the values of an object's properties.
_.values = function(obj) {
var values = [];
for (var key in obj) if (_.has(obj, key)) values.push(obj[key]);
return values;
};
// Convert an object into a list of `[key, value]` pairs.
_.pairs = function(obj) {
var pairs = [];
for (var key in obj) if (_.has(obj, key)) pairs.push([key, obj[key]]);
return pairs;
};
// Invert the keys and values of an object. The values must be serializable.
_.invert = function(obj) {
var result = {};
for (var key in obj) if (_.has(obj, key)) result[obj[key]] = key;
return result;
};
// Return a sorted list of the function names available on the object.
// Aliased as `methods`
_.functions = _.methods = function(obj) {
var names = [];
for (var key in obj) {
if (_.isFunction(obj[key])) names.push(key);
}
return names.sort();
};
// Extend a given object with all the properties in passed-in object(s).
_.extend = function(obj) {
each(slice.call(arguments, 1), function(source) {
if (source) {
for (var prop in source) {
obj[prop] = source[prop];
}
}
});
return obj;
};
// Return a copy of the object only containing the whitelisted properties.
_.pick = function(obj) {
var copy = {};
var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
each(keys, function(key) {
if (key in obj) copy[key] = obj[key];
});
return copy;
};
// Return a copy of the object without the blacklisted properties.
_.omit = function(obj) {
var copy = {};
var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
for (var key in obj) {
if (!_.contains(keys, key)) copy[key] = obj[key];
}
return copy;
};
// Fill in a given object with default properties.
_.defaults = function(obj) {
each(slice.call(arguments, 1), function(source) {
if (source) {
for (var prop in source) {
if (obj[prop] == null) obj[prop] = source[prop];
}
}
});
return obj;
};
// Create a (shallow-cloned) duplicate of an object.
_.clone = function(obj) {
if (!_.isObject(obj)) return obj;
return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
};
// Invokes interceptor with the obj, and then returns obj.
// The primary purpose of this method is to "tap into" a method chain, in
// order to perform operations on intermediate results within the chain.
_.tap = function(obj, interceptor) {
interceptor(obj);
return obj;
};
// Internal recursive comparison function for `isEqual`.
var eq = function(a, b, aStack, bStack) {
// Identical objects are equal. `0 === -0`, but they aren't identical.
// See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
if (a === b) return a !== 0 || 1 / a == 1 / b;
// A strict comparison is necessary because `null == undefined`.
if (a == null || b == null) return a === b;
// Unwrap any wrapped objects.
if (a instanceof _) a = a._wrapped;
if (b instanceof _) b = b._wrapped;
// Compare `[[Class]]` names.
var className = toString.call(a);
if (className != toString.call(b)) return false;
switch (className) {
// Strings, numbers, dates, and booleans are compared by value.
case '[object String]':
// Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
// equivalent to `new String("5")`.
return a == String(b);
case '[object Number]':
// `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
// other numeric values.
return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
case '[object Date]':
case '[object Boolean]':
// Coerce dates and booleans to numeric primitive values. Dates are compared by their
// millisecond representations. Note that invalid dates with millisecond representations
// of `NaN` are not equivalent.
return +a == +b;
// RegExps are compared by their source patterns and flags.
case '[object RegExp]':
return a.source == b.source &&
a.global == b.global &&
a.multiline == b.multiline &&
a.ignoreCase == b.ignoreCase;
}
if (typeof a != 'object' || typeof b != 'object') return false;
// Assume equality for cyclic structures. The algorithm for detecting cyclic
// structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
var length = aStack.length;
while (length--) {
// Linear search. Performance is inversely proportional to the number of
// unique nested structures.
if (aStack[length] == a) return bStack[length] == b;
}
// Add the first object to the stack of traversed objects.
aStack.push(a);
bStack.push(b);
var size = 0, result = true;
// Recursively compare objects and arrays.
if (className == '[object Array]') {
// Compare array lengths to determine if a deep comparison is necessary.
size = a.length;
result = size == b.length;
if (result) {
// Deep compare the contents, ignoring non-numeric properties.
while (size--) {
if (!(result = eq(a[size], b[size], aStack, bStack))) break;
}
}
} else {
// Objects with different constructors are not equivalent, but `Object`s
// from different frames are.
var aCtor = a.constructor, bCtor = b.constructor;
if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) &&
_.isFunction(bCtor) && (bCtor instanceof bCtor))) {
return false;
}
// Deep compare objects.
for (var key in a) {
if (_.has(a, key)) {
// Count the expected number of properties.
size++;
// Deep compare each member.
if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
}
}
// Ensure that both objects contain the same number of properties.
if (result) {
for (key in b) {
if (_.has(b, key) && !(size--)) break;
}
result = !size;
}
}
// Remove the first object from the stack of traversed objects.
aStack.pop();
bStack.pop();
return result;
};
// Perform a deep comparison to check if two objects are equal.
_.isEqual = function(a, b) {
return eq(a, b, [], []);
};
// Is a given array, string, or object empty?
// An "empty" object has no enumerable own-properties.
_.isEmpty = function(obj) {
if (obj == null) return true;
if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
for (var key in obj) if (_.has(obj, key)) return false;
return true;
};
// Is a given value a DOM element?
_.isElement = function(obj) {
return !!(obj && obj.nodeType === 1);
};
// Is a given value an array?
// Delegates to ECMA5's native Array.isArray
_.isArray = nativeIsArray || function(obj) {
return toString.call(obj) == '[object Array]';
};
// Is a given variable an object?
_.isObject = function(obj) {
return obj === Object(obj);
};
// Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp.
each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {
_['is' + name] = function(obj) {
return toString.call(obj) == '[object ' + name + ']';
};
});
// Define a fallback version of the method in browsers (ahem, IE), where
// there isn't any inspectable "Arguments" type.
if (!_.isArguments(arguments)) {
_.isArguments = function(obj) {
return !!(obj && _.has(obj, 'callee'));
};
}
// Optimize `isFunction` if appropriate.
if (typeof (/./) !== 'function') {
_.isFunction = function(obj) {
return typeof obj === 'function';
};
}
// Is a given object a finite number?
_.isFinite = function(obj) {
return isFinite(obj) && !isNaN(parseFloat(obj));
};
// Is the given value `NaN`? (NaN is the only number which does not equal itself).
_.isNaN = function(obj) {
return _.isNumber(obj) && obj != +obj;
};
// Is a given value a boolean?
_.isBoolean = function(obj) {
return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
};
// Is a given value equal to null?
_.isNull = function(obj) {
return obj === null;
};
// Is a given variable undefined?
_.isUndefined = function(obj) {
return obj === void 0;
};
// Shortcut function for checking if an object has a given property directly
// on itself (in other words, not on a prototype).
_.has = function(obj, key) {
return hasOwnProperty.call(obj, key);
};
// Utility Functions
// -----------------
// Run Underscore.js in *noConflict* mode, returning the `_` variable to its
// previous owner. Returns a reference to the Underscore object.
_.noConflict = function() {
root._ = previousUnderscore;
return this;
};
// Keep the identity function around for default iterators.
_.identity = function(value) {
return value;
};
// Run a function **n** times.
_.times = function(n, iterator, context) {
var accum = Array(n);
for (var i = 0; i < n; i++) accum[i] = iterator.call(context, i);
return accum;
};
// Return a random integer between min and max (inclusive).
_.random = function(min, max) {
if (max == null) {
max = min;
min = 0;
}
return min + Math.floor(Math.random() * (max - min + 1));
};
// List of HTML entities for escaping.
var entityMap = {
escape: {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/'
}
};
entityMap.unescape = _.invert(entityMap.escape);
// Regexes containing the keys and values listed immediately above.
var entityRegexes = {
escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'),
unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g')
};
// Functions for escaping and unescaping strings to/from HTML interpolation.
_.each(['escape', 'unescape'], function(method) {
_[method] = function(string) {
if (string == null) return '';
return ('' + string).replace(entityRegexes[method], function(match) {
return entityMap[method][match];
});
};
});
// If the value of the named property is a function then invoke it;
// otherwise, return it.
_.result = function(object, property) {
if (object == null) return null;
var value = object[property];
return _.isFunction(value) ? value.call(object) : value;
};
// Add your own custom functions to the Underscore object.
_.mixin = function(obj) {
each(_.functions(obj), function(name){
var func = _[name] = obj[name];
_.prototype[name] = function() {
var args = [this._wrapped];
push.apply(args, arguments);
return result.call(this, func.apply(_, args));
};
});
};
// Generate a unique integer id (unique within the entire client session).
// Useful for temporary DOM ids.
var idCounter = 0;
_.uniqueId = function(prefix) {
var id = ++idCounter + '';
return prefix ? prefix + id : id;
};
// By default, Underscore uses ERB-style template delimiters, change the
// following template settings to use alternative delimiters.
_.templateSettings = {
evaluate : /<%([\s\S]+?)%>/g,
interpolate : /<%=([\s\S]+?)%>/g,
escape : /<%-([\s\S]+?)%>/g
};
// When customizing `templateSettings`, if you don't want to define an
// interpolation, evaluation or escaping regex, we need one that is
// guaranteed not to match.
var noMatch = /(.)^/;
// Certain characters need to be escaped so that they can be put into a
// string literal.
var escapes = {
"'": "'",
'\\': '\\',
'\r': 'r',
'\n': 'n',
'\t': 't',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;
// JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code.
_.template = function(text, data, settings) {
var render;
settings = _.defaults({}, settings, _.templateSettings);
// Combine delimiters into one regular expression via alternation.
var matcher = new RegExp([
(settings.escape || noMatch).source,
(settings.interpolate || noMatch).source,
(settings.evaluate || noMatch).source
].join('|') + '|$', 'g');
// Compile the template source, escaping string literals appropriately.
var index = 0;
var source = "__p+='";
text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
source += text.slice(index, offset)
.replace(escaper, function(match) { return '\\' + escapes[match]; });
if (escape) {
source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
}
if (interpolate) {
source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
}
if (evaluate) {
source += "';\n" + evaluate + "\n__p+='";
}
index = offset + match.length;
return match;
});
source += "';\n";
// If a variable is not specified, place data values in local scope.
if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
source = "var __t,__p='',__j=Array.prototype.join," +
"print=function(){__p+=__j.call(arguments,'');};\n" +
source + "return __p;\n";
try {
render = new Function(settings.variable || 'obj', '_', source);
} catch (e) {
e.source = source;
throw e;
}
if (data) return render(data, _);
var template = function(data) {
return render.call(this, data, _);
};
// Provide the compiled function source as a convenience for precompilation.
template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';
return template;
};
// Add a "chain" function, which will delegate to the wrapper.
_.chain = function(obj) {
return _(obj).chain();
};
// OOP
// ---------------
// If Underscore is called as a function, it returns a wrapped object that
// can be used OO-style. This wrapper holds altered versions of all the
// underscore functions. Wrapped objects may be chained.
// Helper function to continue chaining intermediate results.
var result = function(obj) {
return this._chain ? _(obj).chain() : obj;
};
// Add all of the Underscore functions to the wrapper object.
_.mixin(_);
// Add all mutator Array functions to the wrapper.
each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
var method = ArrayProto[name];
_.prototype[name] = function() {
var obj = this._wrapped;
method.apply(obj, arguments);
if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0];
return result.call(this, obj);
};
});
// Add all accessor Array functions to the wrapper.
each(['concat', 'join', 'slice'], function(name) {
var method = ArrayProto[name];
_.prototype[name] = function() {
return result.call(this, method.apply(this._wrapped, arguments));
};
});
_.extend(_.prototype, {
// Start chaining a wrapped Underscore object.
chain: function() {
this._chain = true;
return this;
},
// Extracts the result from a wrapped and chained object.
value: function() {
return this._wrapped;
}
});
}).call(this);
},{}],155:[function(require,module,exports){
(function (Buffer){
;(function (sax) { // wrapper for non-node envs
sax.parser = function (strict, opt) { return new SAXParser(strict, opt) }
sax.SAXParser = SAXParser
sax.SAXStream = SAXStream
sax.createStream = createStream
// When we pass the MAX_BUFFER_LENGTH position, start checking for buffer overruns.
// When we check, schedule the next check for MAX_BUFFER_LENGTH - (max(buffer lengths)),
// since that's the earliest that a buffer overrun could occur. This way, checks are
// as rare as required, but as often as necessary to ensure never crossing this bound.
// Furthermore, buffers are only tested at most once per write(), so passing a very
// large string into write() might have undesirable effects, but this is manageable by
// the caller, so it is assumed to be safe. Thus, a call to write() may, in the extreme
// edge case, result in creating at most one complete copy of the string passed in.
// Set to Infinity to have unlimited buffers.
sax.MAX_BUFFER_LENGTH = 64 * 1024
var buffers = [
'comment', 'sgmlDecl', 'textNode', 'tagName', 'doctype',
'procInstName', 'procInstBody', 'entity', 'attribName',
'attribValue', 'cdata', 'script'
]
sax.EVENTS = [
'text',
'processinginstruction',
'sgmldeclaration',
'doctype',
'comment',
'attribute',
'opentag',
'closetag',
'opencdata',
'cdata',
'closecdata',
'error',
'end',
'ready',
'script',
'opennamespace',
'closenamespace'
]
function SAXParser (strict, opt) {
if (!(this instanceof SAXParser)) {
return new SAXParser(strict, opt)
}
var parser = this
clearBuffers(parser)
parser.q = parser.c = ''
parser.bufferCheckPosition = sax.MAX_BUFFER_LENGTH
parser.opt = opt || {}
parser.opt.lowercase = parser.opt.lowercase || parser.opt.lowercasetags
parser.looseCase = parser.opt.lowercase ? 'toLowerCase' : 'toUpperCase'
parser.tags = []
parser.closed = parser.closedRoot = parser.sawRoot = false
parser.tag = parser.error = null
parser.strict = !!strict
parser.noscript = !!(strict || parser.opt.noscript)
parser.state = S.BEGIN
parser.strictEntities = parser.opt.strictEntities
parser.ENTITIES = parser.strictEntities ? Object.create(sax.XML_ENTITIES) : Object.create(sax.ENTITIES)
parser.attribList = []
// namespaces form a prototype chain.
// it always points at the current tag,
// which protos to its parent tag.
if (parser.opt.xmlns) {
parser.ns = Object.create(rootNS)
}
// mostly just for error reporting
parser.trackPosition = parser.opt.position !== false
if (parser.trackPosition) {
parser.position = parser.line = parser.column = 0
}
emit(parser, 'onready')
}
if (!Object.create) {
Object.create = function (o) {
function F () {}
F.prototype = o
var newf = new F()
return newf
}
}
if (!Object.keys) {
Object.keys = function (o) {
var a = []
for (var i in o) if (o.hasOwnProperty(i)) a.push(i)
return a
}
}
function checkBufferLength (parser) {
var maxAllowed = Math.max(sax.MAX_BUFFER_LENGTH, 10)
var maxActual = 0
for (var i = 0, l = buffers.length; i < l; i++) {
var len = parser[buffers[i]].length
if (len > maxAllowed) {
// Text/cdata nodes can get big, and since they're buffered,
// we can get here under normal conditions.
// Avoid issues by emitting the text node now,
// so at least it won't get any bigger.
switch (buffers[i]) {
case 'textNode':
closeText(parser)
break
case 'cdata':
emitNode(parser, 'oncdata', parser.cdata)
parser.cdata = ''
break
case 'script':
emitNode(parser, 'onscript', parser.script)
parser.script = ''
break
default:
error(parser, 'Max buffer length exceeded: ' + buffers[i])
}
}
maxActual = Math.max(maxActual, len)
}
// schedule the next check for the earliest possible buffer overrun.
var m = sax.MAX_BUFFER_LENGTH - maxActual
parser.bufferCheckPosition = m + parser.position
}
function clearBuffers (parser) {
for (var i = 0, l = buffers.length; i < l; i++) {
parser[buffers[i]] = ''
}
}
function flushBuffers (parser) {
closeText(parser)
if (parser.cdata !== '') {
emitNode(parser, 'oncdata', parser.cdata)
parser.cdata = ''
}
if (parser.script !== '') {
emitNode(parser, 'onscript', parser.script)
parser.script = ''
}
}
SAXParser.prototype = {
end: function () { end(this) },
write: write,
resume: function () { this.error = null; return this },
close: function () { return this.write(null) },
flush: function () { flushBuffers(this) }
}
var Stream
try {
Stream = require('stream').Stream
} catch (ex) {
Stream = function () {}
}
var streamWraps = sax.EVENTS.filter(function (ev) {
return ev !== 'error' && ev !== 'end'
})
function createStream (strict, opt) {
return new SAXStream(strict, opt)
}
function SAXStream (strict, opt) {
if (!(this instanceof SAXStream)) {
return new SAXStream(strict, opt)
}
Stream.apply(this)
this._parser = new SAXParser(strict, opt)
this.writable = true
this.readable = true
var me = this
this._parser.onend = function () {
me.emit('end')
}
this._parser.onerror = function (er) {
me.emit('error', er)
// if didn't throw, then means error was handled.
// go ahead and clear error, so we can write again.
me._parser.error = null
}
this._decoder = null
streamWraps.forEach(function (ev) {
Object.defineProperty(me, 'on' + ev, {
get: function () {
return me._parser['on' + ev]
},
set: function (h) {
if (!h) {
me.removeAllListeners(ev)
me._parser['on' + ev] = h
return h
}
me.on(ev, h)
},
enumerable: true,
configurable: false
})
})
}
SAXStream.prototype = Object.create(Stream.prototype, {
constructor: {
value: SAXStream
}
})
SAXStream.prototype.write = function (data) {
if (typeof Buffer === 'function' &&
typeof Buffer.isBuffer === 'function' &&
Buffer.isBuffer(data)) {
if (!this._decoder) {
var SD = require('string_decoder').StringDecoder
this._decoder = new SD('utf8')
}
data = this._decoder.write(data)
}
this._parser.write(data.toString())
this.emit('data', data)
return true
}
SAXStream.prototype.end = function (chunk) {
if (chunk && chunk.length) {
this.write(chunk)
}
this._parser.end()
return true
}
SAXStream.prototype.on = function (ev, handler) {
var me = this
if (!me._parser['on' + ev] && streamWraps.indexOf(ev) !== -1) {
me._parser['on' + ev] = function () {
var args = arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments)
args.splice(0, 0, ev)
me.emit.apply(me, args)
}
}
return Stream.prototype.on.call(me, ev, handler)
}
// character classes and tokens
var whitespace = '\r\n\t '
// this really needs to be replaced with character classes.
// XML allows all manner of ridiculous numbers and digits.
var number = '0124356789'
var letter = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
// (Letter | "_" | ":")
var quote = '\'"'
var attribEnd = whitespace + '>'
var CDATA = '[CDATA['
var DOCTYPE = 'DOCTYPE'
var XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace'
var XMLNS_NAMESPACE = 'http://www.w3.org/2000/xmlns/'
var rootNS = { xml: XML_NAMESPACE, xmlns: XMLNS_NAMESPACE }
// turn all the string character sets into character class objects.
whitespace = charClass(whitespace)
number = charClass(number)
letter = charClass(letter)
// http://www.w3.org/TR/REC-xml/#NT-NameStartChar
// This implementation works on strings, a single character at a time
// as such, it cannot ever support astral-plane characters (10000-EFFFF)
// without a significant breaking change to either this parser, or the
// JavaScript language. Implementation of an emoji-capable xml parser
// is left as an exercise for the reader.
var nameStart = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/
var nameBody = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040\.\d-]/
var entityStart = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/
var entityBody = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040\.\d-]/
quote = charClass(quote)
attribEnd = charClass(attribEnd)
function charClass (str) {
return str.split('').reduce(function (s, c) {
s[c] = true
return s
}, {})
}
function isRegExp (c) {
return Object.prototype.toString.call(c) === '[object RegExp]'
}
function is (charclass, c) {
return isRegExp(charclass) ? !!c.match(charclass) : charclass[c]
}
function not (charclass, c) {
return !is(charclass, c)
}
var S = 0
sax.STATE = {
BEGIN: S++, // leading byte order mark or whitespace
BEGIN_WHITESPACE: S++, // leading whitespace
TEXT: S++, // general stuff
TEXT_ENTITY: S++, // & and such.
OPEN_WAKA: S++, // <
SGML_DECL: S++, // <!BLARG
SGML_DECL_QUOTED: S++, // <!BLARG foo "bar
DOCTYPE: S++, // <!DOCTYPE
DOCTYPE_QUOTED: S++, // <!DOCTYPE "//blah
DOCTYPE_DTD: S++, // <!DOCTYPE "//blah" [ ...
DOCTYPE_DTD_QUOTED: S++, // <!DOCTYPE "//blah" [ "foo
COMMENT_STARTING: S++, // <!-
COMMENT: S++, // <!--
COMMENT_ENDING: S++, // <!-- blah -
COMMENT_ENDED: S++, // <!-- blah --
CDATA: S++, // <![CDATA[ something
CDATA_ENDING: S++, // ]
CDATA_ENDING_2: S++, // ]]
PROC_INST: S++, // <?hi
PROC_INST_BODY: S++, // <?hi there
PROC_INST_ENDING: S++, // <?hi "there" ?
OPEN_TAG: S++, // <strong
OPEN_TAG_SLASH: S++, // <strong /
ATTRIB: S++, // <a
ATTRIB_NAME: S++, // <a foo
ATTRIB_NAME_SAW_WHITE: S++, // <a foo _
ATTRIB_VALUE: S++, // <a foo=
ATTRIB_VALUE_QUOTED: S++, // <a foo="bar
ATTRIB_VALUE_CLOSED: S++, // <a foo="bar"
ATTRIB_VALUE_UNQUOTED: S++, // <a foo=bar
ATTRIB_VALUE_ENTITY_Q: S++, // <foo bar="""
ATTRIB_VALUE_ENTITY_U: S++, // <foo bar="
CLOSE_TAG: S++, // </a
CLOSE_TAG_SAW_WHITE: S++, // </a >
SCRIPT: S++, // <script> ...
SCRIPT_ENDING: S++ // <script> ... <
}
sax.XML_ENTITIES = {
'amp': '&',
'gt': '>',
'lt': '<',
'quot': '"',
'apos': "'"
}
sax.ENTITIES = {
'amp': '&',
'gt': '>',
'lt': '<',
'quot': '"',
'apos': "'",
'AElig': 198,
'Aacute': 193,
'Acirc': 194,
'Agrave': 192,
'Aring': 197,
'Atilde': 195,
'Auml': 196,
'Ccedil': 199,
'ETH': 208,
'Eacute': 201,
'Ecirc': 202,
'Egrave': 200,
'Euml': 203,
'Iacute': 205,
'Icirc': 206,
'Igrave': 204,
'Iuml': 207,
'Ntilde': 209,
'Oacute': 211,
'Ocirc': 212,
'Ograve': 210,
'Oslash': 216,
'Otilde': 213,
'Ouml': 214,
'THORN': 222,
'Uacute': 218,
'Ucirc': 219,
'Ugrave': 217,
'Uuml': 220,
'Yacute': 221,
'aacute': 225,
'acirc': 226,
'aelig': 230,
'agrave': 224,
'aring': 229,
'atilde': 227,
'auml': 228,
'ccedil': 231,
'eacute': 233,
'ecirc': 234,
'egrave': 232,
'eth': 240,
'euml': 235,
'iacute': 237,
'icirc': 238,
'igrave': 236,
'iuml': 239,
'ntilde': 241,
'oacute': 243,
'ocirc': 244,
'ograve': 242,
'oslash': 248,
'otilde': 245,
'ouml': 246,
'szlig': 223,
'thorn': 254,
'uacute': 250,
'ucirc': 251,
'ugrave': 249,
'uuml': 252,
'yacute': 253,
'yuml': 255,
'copy': 169,
'reg': 174,
'nbsp': 160,
'iexcl': 161,
'cent': 162,
'pound': 163,
'curren': 164,
'yen': 165,
'brvbar': 166,
'sect': 167,
'uml': 168,
'ordf': 170,
'laquo': 171,
'not': 172,
'shy': 173,
'macr': 175,
'deg': 176,
'plusmn': 177,
'sup1': 185,
'sup2': 178,
'sup3': 179,
'acute': 180,
'micro': 181,
'para': 182,
'middot': 183,
'cedil': 184,
'ordm': 186,
'raquo': 187,
'frac14': 188,
'frac12': 189,
'frac34': 190,
'iquest': 191,
'times': 215,
'divide': 247,
'OElig': 338,
'oelig': 339,
'Scaron': 352,
'scaron': 353,
'Yuml': 376,
'fnof': 402,
'circ': 710,
'tilde': 732,
'Alpha': 913,
'Beta': 914,
'Gamma': 915,
'Delta': 916,
'Epsilon': 917,
'Zeta': 918,
'Eta': 919,
'Theta': 920,
'Iota': 921,
'Kappa': 922,
'Lambda': 923,
'Mu': 924,
'Nu': 925,
'Xi': 926,
'Omicron': 927,
'Pi': 928,
'Rho': 929,
'Sigma': 931,
'Tau': 932,
'Upsilon': 933,
'Phi': 934,
'Chi': 935,
'Psi': 936,
'Omega': 937,
'alpha': 945,
'beta': 946,
'gamma': 947,
'delta': 948,
'epsilon': 949,
'zeta': 950,
'eta': 951,
'theta': 952,
'iota': 953,
'kappa': 954,
'lambda': 955,
'mu': 956,
'nu': 957,
'xi': 958,
'omicron': 959,
'pi': 960,
'rho': 961,
'sigmaf': 962,
'sigma': 963,
'tau': 964,
'upsilon': 965,
'phi': 966,
'chi': 967,
'psi': 968,
'omega': 969,
'thetasym': 977,
'upsih': 978,
'piv': 982,
'ensp': 8194,
'emsp': 8195,
'thinsp': 8201,
'zwnj': 8204,
'zwj': 8205,
'lrm': 8206,
'rlm': 8207,
'ndash': 8211,
'mdash': 8212,
'lsquo': 8216,
'rsquo': 8217,
'sbquo': 8218,
'ldquo': 8220,
'rdquo': 8221,
'bdquo': 8222,
'dagger': 8224,
'Dagger': 8225,
'bull': 8226,
'hellip': 8230,
'permil': 8240,
'prime': 8242,
'Prime': 8243,
'lsaquo': 8249,
'rsaquo': 8250,
'oline': 8254,
'frasl': 8260,
'euro': 8364,
'image': 8465,
'weierp': 8472,
'real': 8476,
'trade': 8482,
'alefsym': 8501,
'larr': 8592,
'uarr': 8593,
'rarr': 8594,
'darr': 8595,
'harr': 8596,
'crarr': 8629,
'lArr': 8656,
'uArr': 8657,
'rArr': 8658,
'dArr': 8659,
'hArr': 8660,
'forall': 8704,
'part': 8706,
'exist': 8707,
'empty': 8709,
'nabla': 8711,
'isin': 8712,
'notin': 8713,
'ni': 8715,
'prod': 8719,
'sum': 8721,
'minus': 8722,
'lowast': 8727,
'radic': 8730,
'prop': 8733,
'infin': 8734,
'ang': 8736,
'and': 8743,
'or': 8744,
'cap': 8745,
'cup': 8746,
'int': 8747,
'there4': 8756,
'sim': 8764,
'cong': 8773,
'asymp': 8776,
'ne': 8800,
'equiv': 8801,
'le': 8804,
'ge': 8805,
'sub': 8834,
'sup': 8835,
'nsub': 8836,
'sube': 8838,
'supe': 8839,
'oplus': 8853,
'otimes': 8855,
'perp': 8869,
'sdot': 8901,
'lceil': 8968,
'rceil': 8969,
'lfloor': 8970,
'rfloor': 8971,
'lang': 9001,
'rang': 9002,
'loz': 9674,
'spades': 9824,
'clubs': 9827,
'hearts': 9829,
'diams': 9830
}
Object.keys(sax.ENTITIES).forEach(function (key) {
var e = sax.ENTITIES[key]
var s = typeof e === 'number' ? String.fromCharCode(e) : e
sax.ENTITIES[key] = s
})
for (var s in sax.STATE) {
sax.STATE[sax.STATE[s]] = s
}
// shorthand
S = sax.STATE
function emit (parser, event, data) {
parser[event] && parser[event](data)
}
function emitNode (parser, nodeType, data) {
if (parser.textNode) closeText(parser)
emit(parser, nodeType, data)
}
function closeText (parser) {
parser.textNode = textopts(parser.opt, parser.textNode)
if (parser.textNode) emit(parser, 'ontext', parser.textNode)
parser.textNode = ''
}
function textopts (opt, text) {
if (opt.trim) text = text.trim()
if (opt.normalize) text = text.replace(/\s+/g, ' ')
return text
}
function error (parser, er) {
closeText(parser)
if (parser.trackPosition) {
er += '\nLine: ' + parser.line +
'\nColumn: ' + parser.column +
'\nChar: ' + parser.c
}
er = new Error(er)
parser.error = er
emit(parser, 'onerror', er)
return parser
}
function end (parser) {
if (parser.sawRoot && !parser.closedRoot) strictFail(parser, 'Unclosed root tag')
if ((parser.state !== S.BEGIN) &&
(parser.state !== S.BEGIN_WHITESPACE) &&
(parser.state !== S.TEXT)) {
error(parser, 'Unexpected end')
}
closeText(parser)
parser.c = ''
parser.closed = true
emit(parser, 'onend')
SAXParser.call(parser, parser.strict, parser.opt)
return parser
}
function strictFail (parser, message) {
if (typeof parser !== 'object' || !(parser instanceof SAXParser)) {
throw new Error('bad call to strictFail')
}
if (parser.strict) {
error(parser, message)
}
}
function newTag (parser) {
if (!parser.strict) parser.tagName = parser.tagName[parser.looseCase]()
var parent = parser.tags[parser.tags.length - 1] || parser
var tag = parser.tag = { name: parser.tagName, attributes: {} }
// will be overridden if tag contails an xmlns="foo" or xmlns:foo="bar"
if (parser.opt.xmlns) {
tag.ns = parent.ns
}
parser.attribList.length = 0
}
function qname (name, attribute) {
var i = name.indexOf(':')
var qualName = i < 0 ? [ '', name ] : name.split(':')
var prefix = qualName[0]
var local = qualName[1]
// <x "xmlns"="http://foo">
if (attribute && name === 'xmlns') {
prefix = 'xmlns'
local = ''
}
return { prefix: prefix, local: local }
}
function attrib (parser) {
if (!parser.strict) {
parser.attribName = parser.attribName[parser.looseCase]()
}
if (parser.attribList.indexOf(parser.attribName) !== -1 ||
parser.tag.attributes.hasOwnProperty(parser.attribName)) {
parser.attribName = parser.attribValue = ''
return
}
if (parser.opt.xmlns) {
var qn = qname(parser.attribName, true)
var prefix = qn.prefix
var local = qn.local
if (prefix === 'xmlns') {
// namespace binding attribute. push the binding into scope
if (local === 'xml' && parser.attribValue !== XML_NAMESPACE) {
strictFail(parser,
'xml: prefix must be bound to ' + XML_NAMESPACE + '\n' +
'Actual: ' + parser.attribValue)
} else if (local === 'xmlns' && parser.attribValue !== XMLNS_NAMESPACE) {
strictFail(parser,
'xmlns: prefix must be bound to ' + XMLNS_NAMESPACE + '\n' +
'Actual: ' + parser.attribValue)
} else {
var tag = parser.tag
var parent = parser.tags[parser.tags.length - 1] || parser
if (tag.ns === parent.ns) {
tag.ns = Object.create(parent.ns)
}
tag.ns[local] = parser.attribValue
}
}
// defer onattribute events until all attributes have been seen
// so any new bindings can take effect. preserve attribute order
// so deferred events can be emitted in document order
parser.attribList.push([parser.attribName, parser.attribValue])
} else {
// in non-xmlns mode, we can emit the event right away
parser.tag.attributes[parser.attribName] = parser.attribValue
emitNode(parser, 'onattribute', {
name: parser.attribName,
value: parser.attribValue
})
}
parser.attribName = parser.attribValue = ''
}
function openTag (parser, selfClosing) {
if (parser.opt.xmlns) {
// emit namespace binding events
var tag = parser.tag
// add namespace info to tag
var qn = qname(parser.tagName)
tag.prefix = qn.prefix
tag.local = qn.local
tag.uri = tag.ns[qn.prefix] || ''
if (tag.prefix && !tag.uri) {
strictFail(parser, 'Unbound namespace prefix: ' +
JSON.stringify(parser.tagName))
tag.uri = qn.prefix
}
var parent = parser.tags[parser.tags.length - 1] || parser
if (tag.ns && parent.ns !== tag.ns) {
Object.keys(tag.ns).forEach(function (p) {
emitNode(parser, 'onopennamespace', {
prefix: p,
uri: tag.ns[p]
})
})
}
// handle deferred onattribute events
// Note: do not apply default ns to attributes:
// http://www.w3.org/TR/REC-xml-names/#defaulting
for (var i = 0, l = parser.attribList.length; i < l; i++) {
var nv = parser.attribList[i]
var name = nv[0]
var value = nv[1]
var qualName = qname(name, true)
var prefix = qualName.prefix
var local = qualName.local
var uri = prefix === '' ? '' : (tag.ns[prefix] || '')
var a = {
name: name,
value: value,
prefix: prefix,
local: local,
uri: uri
}
// if there's any attributes with an undefined namespace,
// then fail on them now.
if (prefix && prefix !== 'xmlns' && !uri) {
strictFail(parser, 'Unbound namespace prefix: ' +
JSON.stringify(prefix))
a.uri = prefix
}
parser.tag.attributes[name] = a
emitNode(parser, 'onattribute', a)
}
parser.attribList.length = 0
}
parser.tag.isSelfClosing = !!selfClosing
// process the tag
parser.sawRoot = true
parser.tags.push(parser.tag)
emitNode(parser, 'onopentag', parser.tag)
if (!selfClosing) {
// special case for <script> in non-strict mode.
if (!parser.noscript && parser.tagName.toLowerCase() === 'script') {
parser.state = S.SCRIPT
} else {
parser.state = S.TEXT
}
parser.tag = null
parser.tagName = ''
}
parser.attribName = parser.attribValue = ''
parser.attribList.length = 0
}
function closeTag (parser) {
if (!parser.tagName) {
strictFail(parser, 'Weird empty close tag.')
parser.textNode += '</>'
parser.state = S.TEXT
return
}
if (parser.script) {
if (parser.tagName !== 'script') {
parser.script += '</' + parser.tagName + '>'
parser.tagName = ''
parser.state = S.SCRIPT
return
}
emitNode(parser, 'onscript', parser.script)
parser.script = ''
}
// first make sure that the closing tag actually exists.
// <a><b></c></b></a> will close everything, otherwise.
var t = parser.tags.length
var tagName = parser.tagName
if (!parser.strict) {
tagName = tagName[parser.looseCase]()
}
var closeTo = tagName
while (t--) {
var close = parser.tags[t]
if (close.name !== closeTo) {
// fail the first time in strict mode
strictFail(parser, 'Unexpected close tag')
} else {
break
}
}
// didn't find it. we already failed for strict, so just abort.
if (t < 0) {
strictFail(parser, 'Unmatched closing tag: ' + parser.tagName)
parser.textNode += '</' + parser.tagName + '>'
parser.state = S.TEXT
return
}
parser.tagName = tagName
var s = parser.tags.length
while (s-- > t) {
var tag = parser.tag = parser.tags.pop()
parser.tagName = parser.tag.name
emitNode(parser, 'onclosetag', parser.tagName)
var x = {}
for (var i in tag.ns) {
x[i] = tag.ns[i]
}
var parent = parser.tags[parser.tags.length - 1] || parser
if (parser.opt.xmlns && tag.ns !== parent.ns) {
// remove namespace bindings introduced by tag
Object.keys(tag.ns).forEach(function (p) {
var n = tag.ns[p]
emitNode(parser, 'onclosenamespace', { prefix: p, uri: n })
})
}
}
if (t === 0) parser.closedRoot = true
parser.tagName = parser.attribValue = parser.attribName = ''
parser.attribList.length = 0
parser.state = S.TEXT
}
function parseEntity (parser) {
var entity = parser.entity
var entityLC = entity.toLowerCase()
var num
var numStr = ''
if (parser.ENTITIES[entity]) {
return parser.ENTITIES[entity]
}
if (parser.ENTITIES[entityLC]) {
return parser.ENTITIES[entityLC]
}
entity = entityLC
if (entity.charAt(0) === '#') {
if (entity.charAt(1) === 'x') {
entity = entity.slice(2)
num = parseInt(entity, 16)
numStr = num.toString(16)
} else {
entity = entity.slice(1)
num = parseInt(entity, 10)
numStr = num.toString(10)
}
}
entity = entity.replace(/^0+/, '')
if (numStr.toLowerCase() !== entity) {
strictFail(parser, 'Invalid character entity')
return '&' + parser.entity + ';'
}
return String.fromCodePoint(num)
}
function beginWhiteSpace (parser, c) {
if (c === '<') {
parser.state = S.OPEN_WAKA
parser.startTagPosition = parser.position
} else if (not(whitespace, c)) {
// have to process this as a text node.
// weird, but happens.
strictFail(parser, 'Non-whitespace before first tag.')
parser.textNode = c
parser.state = S.TEXT
}
}
function charAt (chunk, i) {
var result = ''
if (i < chunk.length) {
result = chunk.charAt(i)
}
return result
}
function write (chunk) {
var parser = this
if (this.error) {
throw this.error
}
if (parser.closed) {
return error(parser,
'Cannot write after close. Assign an onready handler.')
}
if (chunk === null) {
return end(parser)
}
if (typeof chunk === 'object') {
chunk = chunk.toString()
}
var i = 0
var c = ''
while (true) {
c = charAt(chunk, i++)
parser.c = c
if (!c) {
break
}
if (parser.trackPosition) {
parser.position++
if (c === '\n') {
parser.line++
parser.column = 0
} else {
parser.column++
}
}
switch (parser.state) {
case S.BEGIN:
parser.state = S.BEGIN_WHITESPACE
if (c === '\uFEFF') {
continue
}
beginWhiteSpace(parser, c)
continue
case S.BEGIN_WHITESPACE:
beginWhiteSpace(parser, c)
continue
case S.TEXT:
if (parser.sawRoot && !parser.closedRoot) {
var starti = i - 1
while (c && c !== '<' && c !== '&') {
c = charAt(chunk, i++)
if (c && parser.trackPosition) {
parser.position++
if (c === '\n') {
parser.line++
parser.column = 0
} else {
parser.column++
}
}
}
parser.textNode += chunk.substring(starti, i - 1)
}
if (c === '<' && !(parser.sawRoot && parser.closedRoot && !parser.strict)) {
parser.state = S.OPEN_WAKA
parser.startTagPosition = parser.position
} else {
if (not(whitespace, c) && (!parser.sawRoot || parser.closedRoot)) {
strictFail(parser, 'Text data outside of root node.')
}
if (c === '&') {
parser.state = S.TEXT_ENTITY
} else {
parser.textNode += c
}
}
continue
case S.SCRIPT:
// only non-strict
if (c === '<') {
parser.state = S.SCRIPT_ENDING
} else {
parser.script += c
}
continue
case S.SCRIPT_ENDING:
if (c === '/') {
parser.state = S.CLOSE_TAG
} else {
parser.script += '<' + c
parser.state = S.SCRIPT
}
continue
case S.OPEN_WAKA:
// either a /, ?, !, or text is coming next.
if (c === '!') {
parser.state = S.SGML_DECL
parser.sgmlDecl = ''
} else if (is(whitespace, c)) {
// wait for it...
} else if (is(nameStart, c)) {
parser.state = S.OPEN_TAG
parser.tagName = c
} else if (c === '/') {
parser.state = S.CLOSE_TAG
parser.tagName = ''
} else if (c === '?') {
parser.state = S.PROC_INST
parser.procInstName = parser.procInstBody = ''
} else {
strictFail(parser, 'Unencoded <')
// if there was some whitespace, then add that in.
if (parser.startTagPosition + 1 < parser.position) {
var pad = parser.position - parser.startTagPosition
c = new Array(pad).join(' ') + c
}
parser.textNode += '<' + c
parser.state = S.TEXT
}
continue
case S.SGML_DECL:
if ((parser.sgmlDecl + c).toUpperCase() === CDATA) {
emitNode(parser, 'onopencdata')
parser.state = S.CDATA
parser.sgmlDecl = ''
parser.cdata = ''
} else if (parser.sgmlDecl + c === '--') {
parser.state = S.COMMENT
parser.comment = ''
parser.sgmlDecl = ''
} else if ((parser.sgmlDecl + c).toUpperCase() === DOCTYPE) {
parser.state = S.DOCTYPE
if (parser.doctype || parser.sawRoot) {
strictFail(parser,
'Inappropriately located doctype declaration')
}
parser.doctype = ''
parser.sgmlDecl = ''
} else if (c === '>') {
emitNode(parser, 'onsgmldeclaration', parser.sgmlDecl)
parser.sgmlDecl = ''
parser.state = S.TEXT
} else if (is(quote, c)) {
parser.state = S.SGML_DECL_QUOTED
parser.sgmlDecl += c
} else {
parser.sgmlDecl += c
}
continue
case S.SGML_DECL_QUOTED:
if (c === parser.q) {
parser.state = S.SGML_DECL
parser.q = ''
}
parser.sgmlDecl += c
continue
case S.DOCTYPE:
if (c === '>') {
parser.state = S.TEXT
emitNode(parser, 'ondoctype', parser.doctype)
parser.doctype = true // just remember that we saw it.
} else {
parser.doctype += c
if (c === '[') {
parser.state = S.DOCTYPE_DTD
} else if (is(quote, c)) {
parser.state = S.DOCTYPE_QUOTED
parser.q = c
}
}
continue
case S.DOCTYPE_QUOTED:
parser.doctype += c
if (c === parser.q) {
parser.q = ''
parser.state = S.DOCTYPE
}
continue
case S.DOCTYPE_DTD:
parser.doctype += c
if (c === ']') {
parser.state = S.DOCTYPE
} else if (is(quote, c)) {
parser.state = S.DOCTYPE_DTD_QUOTED
parser.q = c
}
continue
case S.DOCTYPE_DTD_QUOTED:
parser.doctype += c
if (c === parser.q) {
parser.state = S.DOCTYPE_DTD
parser.q = ''
}
continue
case S.COMMENT:
if (c === '-') {
parser.state = S.COMMENT_ENDING
} else {
parser.comment += c
}
continue
case S.COMMENT_ENDING:
if (c === '-') {
parser.state = S.COMMENT_ENDED
parser.comment = textopts(parser.opt, parser.comment)
if (parser.comment) {
emitNode(parser, 'oncomment', parser.comment)
}
parser.comment = ''
} else {
parser.comment += '-' + c
parser.state = S.COMMENT
}
continue
case S.COMMENT_ENDED:
if (c !== '>') {
strictFail(parser, 'Malformed comment')
// allow <!-- blah -- bloo --> in non-strict mode,
// which is a comment of " blah -- bloo "
parser.comment += '--' + c
parser.state = S.COMMENT
} else {
parser.state = S.TEXT
}
continue
case S.CDATA:
if (c === ']') {
parser.state = S.CDATA_ENDING
} else {
parser.cdata += c
}
continue
case S.CDATA_ENDING:
if (c === ']') {
parser.state = S.CDATA_ENDING_2
} else {
parser.cdata += ']' + c
parser.state = S.CDATA
}
continue
case S.CDATA_ENDING_2:
if (c === '>') {
if (parser.cdata) {
emitNode(parser, 'oncdata', parser.cdata)
}
emitNode(parser, 'onclosecdata')
parser.cdata = ''
parser.state = S.TEXT
} else if (c === ']') {
parser.cdata += ']'
} else {
parser.cdata += ']]' + c
parser.state = S.CDATA
}
continue
case S.PROC_INST:
if (c === '?') {
parser.state = S.PROC_INST_ENDING
} else if (is(whitespace, c)) {
parser.state = S.PROC_INST_BODY
} else {
parser.procInstName += c
}
continue
case S.PROC_INST_BODY:
if (!parser.procInstBody && is(whitespace, c)) {
continue
} else if (c === '?') {
parser.state = S.PROC_INST_ENDING
} else {
parser.procInstBody += c
}
continue
case S.PROC_INST_ENDING:
if (c === '>') {
emitNode(parser, 'onprocessinginstruction', {
name: parser.procInstName,
body: parser.procInstBody
})
parser.procInstName = parser.procInstBody = ''
parser.state = S.TEXT
} else {
parser.procInstBody += '?' + c
parser.state = S.PROC_INST_BODY
}
continue
case S.OPEN_TAG:
if (is(nameBody, c)) {
parser.tagName += c
} else {
newTag(parser)
if (c === '>') {
openTag(parser)
} else if (c === '/') {
parser.state = S.OPEN_TAG_SLASH
} else {
if (not(whitespace, c)) {
strictFail(parser, 'Invalid character in tag name')
}
parser.state = S.ATTRIB
}
}
continue
case S.OPEN_TAG_SLASH:
if (c === '>') {
openTag(parser, true)
closeTag(parser)
} else {
strictFail(parser, 'Forward-slash in opening tag not followed by >')
parser.state = S.ATTRIB
}
continue
case S.ATTRIB:
// haven't read the attribute name yet.
if (is(whitespace, c)) {
continue
} else if (c === '>') {
openTag(parser)
} else if (c === '/') {
parser.state = S.OPEN_TAG_SLASH
} else if (is(nameStart, c)) {
parser.attribName = c
parser.attribValue = ''
parser.state = S.ATTRIB_NAME
} else {
strictFail(parser, 'Invalid attribute name')
}
continue
case S.ATTRIB_NAME:
if (c === '=') {
parser.state = S.ATTRIB_VALUE
} else if (c === '>') {
strictFail(parser, 'Attribute without value')
parser.attribValue = parser.attribName
attrib(parser)
openTag(parser)
} else if (is(whitespace, c)) {
parser.state = S.ATTRIB_NAME_SAW_WHITE
} else if (is(nameBody, c)) {
parser.attribName += c
} else {
strictFail(parser, 'Invalid attribute name')
}
continue
case S.ATTRIB_NAME_SAW_WHITE:
if (c === '=') {
parser.state = S.ATTRIB_VALUE
} else if (is(whitespace, c)) {
continue
} else {
strictFail(parser, 'Attribute without value')
parser.tag.attributes[parser.attribName] = ''
parser.attribValue = ''
emitNode(parser, 'onattribute', {
name: parser.attribName,
value: ''
})
parser.attribName = ''
if (c === '>') {
openTag(parser)
} else if (is(nameStart, c)) {
parser.attribName = c
parser.state = S.ATTRIB_NAME
} else {
strictFail(parser, 'Invalid attribute name')
parser.state = S.ATTRIB
}
}
continue
case S.ATTRIB_VALUE:
if (is(whitespace, c)) {
continue
} else if (is(quote, c)) {
parser.q = c
parser.state = S.ATTRIB_VALUE_QUOTED
} else {
strictFail(parser, 'Unquoted attribute value')
parser.state = S.ATTRIB_VALUE_UNQUOTED
parser.attribValue = c
}
continue
case S.ATTRIB_VALUE_QUOTED:
if (c !== parser.q) {
if (c === '&') {
parser.state = S.ATTRIB_VALUE_ENTITY_Q
} else {
parser.attribValue += c
}
continue
}
attrib(parser)
parser.q = ''
parser.state = S.ATTRIB_VALUE_CLOSED
continue
case S.ATTRIB_VALUE_CLOSED:
if (is(whitespace, c)) {
parser.state = S.ATTRIB
} else if (c === '>') {
openTag(parser)
} else if (c === '/') {
parser.state = S.OPEN_TAG_SLASH
} else if (is(nameStart, c)) {
strictFail(parser, 'No whitespace between attributes')
parser.attribName = c
parser.attribValue = ''
parser.state = S.ATTRIB_NAME
} else {
strictFail(parser, 'Invalid attribute name')
}
continue
case S.ATTRIB_VALUE_UNQUOTED:
if (not(attribEnd, c)) {
if (c === '&') {
parser.state = S.ATTRIB_VALUE_ENTITY_U
} else {
parser.attribValue += c
}
continue
}
attrib(parser)
if (c === '>') {
openTag(parser)
} else {
parser.state = S.ATTRIB
}
continue
case S.CLOSE_TAG:
if (!parser.tagName) {
if (is(whitespace, c)) {
continue
} else if (not(nameStart, c)) {
if (parser.script) {
parser.script += '</' + c
parser.state = S.SCRIPT
} else {
strictFail(parser, 'Invalid tagname in closing tag.')
}
} else {
parser.tagName = c
}
} else if (c === '>') {
closeTag(parser)
} else if (is(nameBody, c)) {
parser.tagName += c
} else if (parser.script) {
parser.script += '</' + parser.tagName
parser.tagName = ''
parser.state = S.SCRIPT
} else {
if (not(whitespace, c)) {
strictFail(parser, 'Invalid tagname in closing tag')
}
parser.state = S.CLOSE_TAG_SAW_WHITE
}
continue
case S.CLOSE_TAG_SAW_WHITE:
if (is(whitespace, c)) {
continue
}
if (c === '>') {
closeTag(parser)
} else {
strictFail(parser, 'Invalid characters in closing tag')
}
continue
case S.TEXT_ENTITY:
case S.ATTRIB_VALUE_ENTITY_Q:
case S.ATTRIB_VALUE_ENTITY_U:
var returnState
var buffer
switch (parser.state) {
case S.TEXT_ENTITY:
returnState = S.TEXT
buffer = 'textNode'
break
case S.ATTRIB_VALUE_ENTITY_Q:
returnState = S.ATTRIB_VALUE_QUOTED
buffer = 'attribValue'
break
case S.ATTRIB_VALUE_ENTITY_U:
returnState = S.ATTRIB_VALUE_UNQUOTED
buffer = 'attribValue'
break
}
if (c === ';') {
parser[buffer] += parseEntity(parser)
parser.entity = ''
parser.state = returnState
} else if (is(parser.entity.length ? entityBody : entityStart, c)) {
parser.entity += c
} else {
strictFail(parser, 'Invalid character in entity name')
parser[buffer] += '&' + parser.entity + c
parser.entity = ''
parser.state = returnState
}
continue
default:
throw new Error(parser, 'Unknown state: ' + parser.state)
}
} // while
if (parser.position >= parser.bufferCheckPosition) {
checkBufferLength(parser)
}
return parser
}
/*! http://mths.be/fromcodepoint v0.1.0 by @mathias */
if (!String.fromCodePoint) {
(function () {
var stringFromCharCode = String.fromCharCode
var floor = Math.floor
var fromCodePoint = function () {
var MAX_SIZE = 0x4000
var codeUnits = []
var highSurrogate
var lowSurrogate
var index = -1
var length = arguments.length
if (!length) {
return ''
}
var result = ''
while (++index < length) {
var codePoint = Number(arguments[index])
if (
!isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity`
codePoint < 0 || // not a valid Unicode code point
codePoint > 0x10FFFF || // not a valid Unicode code point
floor(codePoint) !== codePoint // not an integer
) {
throw RangeError('Invalid code point: ' + codePoint)
}
if (codePoint <= 0xFFFF) { // BMP code point
codeUnits.push(codePoint)
} else { // Astral code point; split in surrogate halves
// http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
codePoint -= 0x10000
highSurrogate = (codePoint >> 10) + 0xD800
lowSurrogate = (codePoint % 0x400) + 0xDC00
codeUnits.push(highSurrogate, lowSurrogate)
}
if (index + 1 === length || codeUnits.length > MAX_SIZE) {
result += stringFromCharCode.apply(null, codeUnits)
codeUnits.length = 0
}
}
return result
}
if (Object.defineProperty) {
Object.defineProperty(String, 'fromCodePoint', {
value: fromCodePoint,
configurable: true,
writable: true
})
} else {
String.fromCodePoint = fromCodePoint
}
}())
}
})(typeof exports === 'undefined' ? this.sax = {} : exports)
}).call(this,require("buffer").Buffer)
},{"buffer":75,"stream":99,"string_decoder":100}],156:[function(require,module,exports){
// Underscore.js 1.8.3
// http://underscorejs.org
// (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
// Underscore may be freely distributed under the MIT license.
(function() {
// Baseline setup
// --------------
// Establish the root object, `window` in the browser, or `exports` on the server.
var root = this;
// Save the previous value of the `_` variable.
var previousUnderscore = root._;
// Save bytes in the minified (but not gzipped) version:
var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
// Create quick reference variables for speed access to core prototypes.
var
push = ArrayProto.push,
slice = ArrayProto.slice,
toString = ObjProto.toString,
hasOwnProperty = ObjProto.hasOwnProperty;
// All **ECMAScript 5** native function implementations that we hope to use
// are declared here.
var
nativeIsArray = Array.isArray,
nativeKeys = Object.keys,
nativeBind = FuncProto.bind,
nativeCreate = Object.create;
// Naked function reference for surrogate-prototype-swapping.
var Ctor = function(){};
// Create a safe reference to the Underscore object for use below.
var _ = function(obj) {
if (obj instanceof _) return obj;
if (!(this instanceof _)) return new _(obj);
this._wrapped = obj;
};
// Export the Underscore object for **Node.js**, with
// backwards-compatibility for the old `require()` API. If we're in
// the browser, add `_` as a global object.
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = _;
}
exports._ = _;
} else {
root._ = _;
}
// Current version.
_.VERSION = '1.8.3';
// Internal function that returns an efficient (for current engines) version
// of the passed-in callback, to be repeatedly applied in other Underscore
// functions.
var optimizeCb = function(func, context, argCount) {
if (context === void 0) return func;
switch (argCount == null ? 3 : argCount) {
case 1: return function(value) {
return func.call(context, value);
};
case 2: return function(value, other) {
return func.call(context, value, other);
};
case 3: return function(value, index, collection) {
return func.call(context, value, index, collection);
};
case 4: return function(accumulator, value, index, collection) {
return func.call(context, accumulator, value, index, collection);
};
}
return function() {
return func.apply(context, arguments);
};
};
// A mostly-internal function to generate callbacks that can be applied
// to each element in a collection, returning the desired result — either
// identity, an arbitrary callback, a property matcher, or a property accessor.
var cb = function(value, context, argCount) {
if (value == null) return _.identity;
if (_.isFunction(value)) return optimizeCb(value, context, argCount);
if (_.isObject(value)) return _.matcher(value);
return _.property(value);
};
_.iteratee = function(value, context) {
return cb(value, context, Infinity);
};
// An internal function for creating assigner functions.
var createAssigner = function(keysFunc, undefinedOnly) {
return function(obj) {
var length = arguments.length;
if (length < 2 || obj == null) return obj;
for (var index = 1; index < length; index++) {
var source = arguments[index],
keys = keysFunc(source),
l = keys.length;
for (var i = 0; i < l; i++) {
var key = keys[i];
if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key];
}
}
return obj;
};
};
// An internal function for creating a new object that inherits from another.
var baseCreate = function(prototype) {
if (!_.isObject(prototype)) return {};
if (nativeCreate) return nativeCreate(prototype);
Ctor.prototype = prototype;
var result = new Ctor;
Ctor.prototype = null;
return result;
};
var property = function(key) {
return function(obj) {
return obj == null ? void 0 : obj[key];
};
};
// Helper for collection methods to determine whether a collection
// should be iterated as an array or as an object
// Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
// Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
var getLength = property('length');
var isArrayLike = function(collection) {
var length = getLength(collection);
return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
};
// Collection Functions
// --------------------
// The cornerstone, an `each` implementation, aka `forEach`.
// Handles raw objects in addition to array-likes. Treats all
// sparse array-likes as if they were dense.
_.each = _.forEach = function(obj, iteratee, context) {
iteratee = optimizeCb(iteratee, context);
var i, length;
if (isArrayLike(obj)) {
for (i = 0, length = obj.length; i < length; i++) {
iteratee(obj[i], i, obj);
}
} else {
var keys = _.keys(obj);
for (i = 0, length = keys.length; i < length; i++) {
iteratee(obj[keys[i]], keys[i], obj);
}
}
return obj;
};
// Return the results of applying the iteratee to each element.
_.map = _.collect = function(obj, iteratee, context) {
iteratee = cb(iteratee, context);
var keys = !isArrayLike(obj) && _.keys(obj),
length = (keys || obj).length,
results = Array(length);
for (var index = 0; index < length; index++) {
var currentKey = keys ? keys[index] : index;
results[index] = iteratee(obj[currentKey], currentKey, obj);
}
return results;
};
// Create a reducing function iterating left or right.
function createReduce(dir) {
// Optimized iterator function as using arguments.length
// in the main function will deoptimize the, see #1991.
function iterator(obj, iteratee, memo, keys, index, length) {
for (; index >= 0 && index < length; index += dir) {
var currentKey = keys ? keys[index] : index;
memo = iteratee(memo, obj[currentKey], currentKey, obj);
}
return memo;
}
return function(obj, iteratee, memo, context) {
iteratee = optimizeCb(iteratee, context, 4);
var keys = !isArrayLike(obj) && _.keys(obj),
length = (keys || obj).length,
index = dir > 0 ? 0 : length - 1;
// Determine the initial value if none is provided.
if (arguments.length < 3) {
memo = obj[keys ? keys[index] : index];
index += dir;
}
return iterator(obj, iteratee, memo, keys, index, length);
};
}
// **Reduce** builds up a single result from a list of values, aka `inject`,
// or `foldl`.
_.reduce = _.foldl = _.inject = createReduce(1);
// The right-associative version of reduce, also known as `foldr`.
_.reduceRight = _.foldr = createReduce(-1);
// Return the first value which passes a truth test. Aliased as `detect`.
_.find = _.detect = function(obj, predicate, context) {
var key;
if (isArrayLike(obj)) {
key = _.findIndex(obj, predicate, context);
} else {
key = _.findKey(obj, predicate, context);
}
if (key !== void 0 && key !== -1) return obj[key];
};
// Return all the elements that pass a truth test.
// Aliased as `select`.
_.filter = _.select = function(obj, predicate, context) {
var results = [];
predicate = cb(predicate, context);
_.each(obj, function(value, index, list) {
if (predicate(value, index, list)) results.push(value);
});
return results;
};
// Return all the elements for which a truth test fails.
_.reject = function(obj, predicate, context) {
return _.filter(obj, _.negate(cb(predicate)), context);
};
// Determine whether all of the elements match a truth test.
// Aliased as `all`.
_.every = _.all = function(obj, predicate, context) {
predicate = cb(predicate, context);
var keys = !isArrayLike(obj) && _.keys(obj),
length = (keys || obj).length;
for (var index = 0; index < length; index++) {
var currentKey = keys ? keys[index] : index;
if (!predicate(obj[currentKey], currentKey, obj)) return false;
}
return true;
};
// Determine if at least one element in the object matches a truth test.
// Aliased as `any`.
_.some = _.any = function(obj, predicate, context) {
predicate = cb(predicate, context);
var keys = !isArrayLike(obj) && _.keys(obj),
length = (keys || obj).length;
for (var index = 0; index < length; index++) {
var currentKey = keys ? keys[index] : index;
if (predicate(obj[currentKey], currentKey, obj)) return true;
}
return false;
};
// Determine if the array or object contains a given item (using `===`).
// Aliased as `includes` and `include`.
_.contains = _.includes = _.include = function(obj, item, fromIndex, guard) {
if (!isArrayLike(obj)) obj = _.values(obj);
if (typeof fromIndex != 'number' || guard) fromIndex = 0;
return _.indexOf(obj, item, fromIndex) >= 0;
};
// Invoke a method (with arguments) on every item in a collection.
_.invoke = function(obj, method) {
var args = slice.call(arguments, 2);
var isFunc = _.isFunction(method);
return _.map(obj, function(value) {
var func = isFunc ? method : value[method];
return func == null ? func : func.apply(value, args);
});
};
// Convenience version of a common use case of `map`: fetching a property.
_.pluck = function(obj, key) {
return _.map(obj, _.property(key));
};
// Convenience version of a common use case of `filter`: selecting only objects
// containing specific `key:value` pairs.
_.where = function(obj, attrs) {
return _.filter(obj, _.matcher(attrs));
};
// Convenience version of a common use case of `find`: getting the first object
// containing specific `key:value` pairs.
_.findWhere = function(obj, attrs) {
return _.find(obj, _.matcher(attrs));
};
// Return the maximum element (or element-based computation).
_.max = function(obj, iteratee, context) {
var result = -Infinity, lastComputed = -Infinity,
value, computed;
if (iteratee == null && obj != null) {
obj = isArrayLike(obj) ? obj : _.values(obj);
for (var i = 0, length = obj.length; i < length; i++) {
value = obj[i];
if (value > result) {
result = value;
}
}
} else {
iteratee = cb(iteratee, context);
_.each(obj, function(value, index, list) {
computed = iteratee(value, index, list);
if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
result = value;
lastComputed = computed;
}
});
}
return result;
};
// Return the minimum element (or element-based computation).
_.min = function(obj, iteratee, context) {
var result = Infinity, lastComputed = Infinity,
value, computed;
if (iteratee == null && obj != null) {
obj = isArrayLike(obj) ? obj : _.values(obj);
for (var i = 0, length = obj.length; i < length; i++) {
value = obj[i];
if (value < result) {
result = value;
}
}
} else {
iteratee = cb(iteratee, context);
_.each(obj, function(value, index, list) {
computed = iteratee(value, index, list);
if (computed < lastComputed || computed === Infinity && result === Infinity) {
result = value;
lastComputed = computed;
}
});
}
return result;
};
// Shuffle a collection, using the modern version of the
// [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
_.shuffle = function(obj) {
var set = isArrayLike(obj) ? obj : _.values(obj);
var length = set.length;
var shuffled = Array(length);
for (var index = 0, rand; index < length; index++) {
rand = _.random(0, index);
if (rand !== index) shuffled[index] = shuffled[rand];
shuffled[rand] = set[index];
}
return shuffled;
};
// Sample **n** random values from a collection.
// If **n** is not specified, returns a single random element.
// The internal `guard` argument allows it to work with `map`.
_.sample = function(obj, n, guard) {
if (n == null || guard) {
if (!isArrayLike(obj)) obj = _.values(obj);
return obj[_.random(obj.length - 1)];
}
return _.shuffle(obj).slice(0, Math.max(0, n));
};
// Sort the object's values by a criterion produced by an iteratee.
_.sortBy = function(obj, iteratee, context) {
iteratee = cb(iteratee, context);
return _.pluck(_.map(obj, function(value, index, list) {
return {
value: value,
index: index,
criteria: iteratee(value, index, list)
};
}).sort(function(left, right) {
var a = left.criteria;
var b = right.criteria;
if (a !== b) {
if (a > b || a === void 0) return 1;
if (a < b || b === void 0) return -1;
}
return left.index - right.index;
}), 'value');
};
// An internal function used for aggregate "group by" operations.
var group = function(behavior) {
return function(obj, iteratee, context) {
var result = {};
iteratee = cb(iteratee, context);
_.each(obj, function(value, index) {
var key = iteratee(value, index, obj);
behavior(result, value, key);
});
return result;
};
};
// Groups the object's values by a criterion. Pass either a string attribute
// to group by, or a function that returns the criterion.
_.groupBy = group(function(result, value, key) {
if (_.has(result, key)) result[key].push(value); else result[key] = [value];
});
// Indexes the object's values by a criterion, similar to `groupBy`, but for
// when you know that your index values will be unique.
_.indexBy = group(function(result, value, key) {
result[key] = value;
});
// Counts instances of an object that group by a certain criterion. Pass
// either a string attribute to count by, or a function that returns the
// criterion.
_.countBy = group(function(result, value, key) {
if (_.has(result, key)) result[key]++; else result[key] = 1;
});
// Safely create a real, live array from anything iterable.
_.toArray = function(obj) {
if (!obj) return [];
if (_.isArray(obj)) return slice.call(obj);
if (isArrayLike(obj)) return _.map(obj, _.identity);
return _.values(obj);
};
// Return the number of elements in an object.
_.size = function(obj) {
if (obj == null) return 0;
return isArrayLike(obj) ? obj.length : _.keys(obj).length;
};
// Split a collection into two arrays: one whose elements all satisfy the given
// predicate, and one whose elements all do not satisfy the predicate.
_.partition = function(obj, predicate, context) {
predicate = cb(predicate, context);
var pass = [], fail = [];
_.each(obj, function(value, key, obj) {
(predicate(value, key, obj) ? pass : fail).push(value);
});
return [pass, fail];
};
// Array Functions
// ---------------
// Get the first element of an array. Passing **n** will return the first N
// values in the array. Aliased as `head` and `take`. The **guard** check
// allows it to work with `_.map`.
_.first = _.head = _.take = function(array, n, guard) {
if (array == null) return void 0;
if (n == null || guard) return array[0];
return _.initial(array, array.length - n);
};
// Returns everything but the last entry of the array. Especially useful on
// the arguments object. Passing **n** will return all the values in
// the array, excluding the last N.
_.initial = function(array, n, guard) {
return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
};
// Get the last element of an array. Passing **n** will return the last N
// values in the array.
_.last = function(array, n, guard) {
if (array == null) return void 0;
if (n == null || guard) return array[array.length - 1];
return _.rest(array, Math.max(0, array.length - n));
};
// Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
// Especially useful on the arguments object. Passing an **n** will return
// the rest N values in the array.
_.rest = _.tail = _.drop = function(array, n, guard) {
return slice.call(array, n == null || guard ? 1 : n);
};
// Trim out all falsy values from an array.
_.compact = function(array) {
return _.filter(array, _.identity);
};
// Internal implementation of a recursive `flatten` function.
var flatten = function(input, shallow, strict, startIndex) {
var output = [], idx = 0;
for (var i = startIndex || 0, length = getLength(input); i < length; i++) {
var value = input[i];
if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) {
//flatten current level of array or arguments object
if (!shallow) value = flatten(value, shallow, strict);
var j = 0, len = value.length;
output.length += len;
while (j < len) {
output[idx++] = value[j++];
}
} else if (!strict) {
output[idx++] = value;
}
}
return output;
};
// Flatten out an array, either recursively (by default), or just one level.
_.flatten = function(array, shallow) {
return flatten(array, shallow, false);
};
// Return a version of the array that does not contain the specified value(s).
_.without = function(array) {
return _.difference(array, slice.call(arguments, 1));
};
// Produce a duplicate-free version of the array. If the array has already
// been sorted, you have the option of using a faster algorithm.
// Aliased as `unique`.
_.uniq = _.unique = function(array, isSorted, iteratee, context) {
if (!_.isBoolean(isSorted)) {
context = iteratee;
iteratee = isSorted;
isSorted = false;
}
if (iteratee != null) iteratee = cb(iteratee, context);
var result = [];
var seen = [];
for (var i = 0, length = getLength(array); i < length; i++) {
var value = array[i],
computed = iteratee ? iteratee(value, i, array) : value;
if (isSorted) {
if (!i || seen !== computed) result.push(value);
seen = computed;
} else if (iteratee) {
if (!_.contains(seen, computed)) {
seen.push(computed);
result.push(value);
}
} else if (!_.contains(result, value)) {
result.push(value);
}
}
return result;
};
// Produce an array that contains the union: each distinct element from all of
// the passed-in arrays.
_.union = function() {
return _.uniq(flatten(arguments, true, true));
};
// Produce an array that contains every item shared between all the
// passed-in arrays.
_.intersection = function(array) {
var result = [];
var argsLength = arguments.length;
for (var i = 0, length = getLength(array); i < length; i++) {
var item = array[i];
if (_.contains(result, item)) continue;
for (var j = 1; j < argsLength; j++) {
if (!_.contains(arguments[j], item)) break;
}
if (j === argsLength) result.push(item);
}
return result;
};
// Take the difference between one array and a number of other arrays.
// Only the elements present in just the first array will remain.
_.difference = function(array) {
var rest = flatten(arguments, true, true, 1);
return _.filter(array, function(value){
return !_.contains(rest, value);
});
};
// Zip together multiple lists into a single array -- elements that share
// an index go together.
_.zip = function() {
return _.unzip(arguments);
};
// Complement of _.zip. Unzip accepts an array of arrays and groups
// each array's elements on shared indices
_.unzip = function(array) {
var length = array && _.max(array, getLength).length || 0;
var result = Array(length);
for (var index = 0; index < length; index++) {
result[index] = _.pluck(array, index);
}
return result;
};
// Converts lists into objects. Pass either a single array of `[key, value]`
// pairs, or two parallel arrays of the same length -- one of keys, and one of
// the corresponding values.
_.object = function(list, values) {
var result = {};
for (var i = 0, length = getLength(list); i < length; i++) {
if (values) {
result[list[i]] = values[i];
} else {
result[list[i][0]] = list[i][1];
}
}
return result;
};
// Generator function to create the findIndex and findLastIndex functions
function createPredicateIndexFinder(dir) {
return function(array, predicate, context) {
predicate = cb(predicate, context);
var length = getLength(array);
var index = dir > 0 ? 0 : length - 1;
for (; index >= 0 && index < length; index += dir) {
if (predicate(array[index], index, array)) return index;
}
return -1;
};
}
// Returns the first index on an array-like that passes a predicate test
_.findIndex = createPredicateIndexFinder(1);
_.findLastIndex = createPredicateIndexFinder(-1);
// Use a comparator function to figure out the smallest index at which
// an object should be inserted so as to maintain order. Uses binary search.
_.sortedIndex = function(array, obj, iteratee, context) {
iteratee = cb(iteratee, context, 1);
var value = iteratee(obj);
var low = 0, high = getLength(array);
while (low < high) {
var mid = Math.floor((low + high) / 2);
if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
}
return low;
};
// Generator function to create the indexOf and lastIndexOf functions
function createIndexFinder(dir, predicateFind, sortedIndex) {
return function(array, item, idx) {
var i = 0, length = getLength(array);
if (typeof idx == 'number') {
if (dir > 0) {
i = idx >= 0 ? idx : Math.max(idx + length, i);
} else {
length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
}
} else if (sortedIndex && idx && length) {
idx = sortedIndex(array, item);
return array[idx] === item ? idx : -1;
}
if (item !== item) {
idx = predicateFind(slice.call(array, i, length), _.isNaN);
return idx >= 0 ? idx + i : -1;
}
for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
if (array[idx] === item) return idx;
}
return -1;
};
}
// Return the position of the first occurrence of an item in an array,
// or -1 if the item is not included in the array.
// If the array is large and already in sort order, pass `true`
// for **isSorted** to use binary search.
_.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex);
_.lastIndexOf = createIndexFinder(-1, _.findLastIndex);
// Generate an integer Array containing an arithmetic progression. A port of
// the native Python `range()` function. See
// [the Python documentation](http://docs.python.org/library/functions.html#range).
_.range = function(start, stop, step) {
if (stop == null) {
stop = start || 0;
start = 0;
}
step = step || 1;
var length = Math.max(Math.ceil((stop - start) / step), 0);
var range = Array(length);
for (var idx = 0; idx < length; idx++, start += step) {
range[idx] = start;
}
return range;
};
// Function (ahem) Functions
// ------------------
// Determines whether to execute a function as a constructor
// or a normal function with the provided arguments
var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) {
if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
var self = baseCreate(sourceFunc.prototype);
var result = sourceFunc.apply(self, args);
if (_.isObject(result)) return result;
return self;
};
// Create a function bound to a given object (assigning `this`, and arguments,
// optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
// available.
_.bind = function(func, context) {
if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');
var args = slice.call(arguments, 2);
var bound = function() {
return executeBound(func, bound, context, this, args.concat(slice.call(arguments)));
};
return bound;
};
// Partially apply a function by creating a version that has had some of its
// arguments pre-filled, without changing its dynamic `this` context. _ acts
// as a placeholder, allowing any combination of arguments to be pre-filled.
_.partial = function(func) {
var boundArgs = slice.call(arguments, 1);
var bound = function() {
var position = 0, length = boundArgs.length;
var args = Array(length);
for (var i = 0; i < length; i++) {
args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i];
}
while (position < arguments.length) args.push(arguments[position++]);
return executeBound(func, bound, this, this, args);
};
return bound;
};
// Bind a number of an object's methods to that object. Remaining arguments
// are the method names to be bound. Useful for ensuring that all callbacks
// defined on an object belong to it.
_.bindAll = function(obj) {
var i, length = arguments.length, key;
if (length <= 1) throw new Error('bindAll must be passed function names');
for (i = 1; i < length; i++) {
key = arguments[i];
obj[key] = _.bind(obj[key], obj);
}
return obj;
};
// Memoize an expensive function by storing its results.
_.memoize = function(func, hasher) {
var memoize = function(key) {
var cache = memoize.cache;
var address = '' + (hasher ? hasher.apply(this, arguments) : key);
if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
return cache[address];
};
memoize.cache = {};
return memoize;
};
// Delays a function for the given number of milliseconds, and then calls
// it with the arguments supplied.
_.delay = function(func, wait) {
var args = slice.call(arguments, 2);
return setTimeout(function(){
return func.apply(null, args);
}, wait);
};
// Defers a function, scheduling it to run after the current call stack has
// cleared.
_.defer = _.partial(_.delay, _, 1);
// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time. Normally, the throttled function will run
// as much as it can, without ever going more than once per `wait` duration;
// but if you'd like to disable the execution on the leading edge, pass
// `{leading: false}`. To disable execution on the trailing edge, ditto.
_.throttle = function(func, wait, options) {
var context, args, result;
var timeout = null;
var previous = 0;
if (!options) options = {};
var later = function() {
previous = options.leading === false ? 0 : _.now();
timeout = null;
result = func.apply(context, args);
if (!timeout) context = args = null;
};
return function() {
var now = _.now();
if (!previous && options.leading === false) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
previous = now;
result = func.apply(context, args);
if (!timeout) context = args = null;
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
};
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
_.debounce = function(func, wait, immediate) {
var timeout, args, context, timestamp, result;
var later = function() {
var last = _.now() - timestamp;
if (last < wait && last >= 0) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
if (!timeout) context = args = null;
}
}
};
return function() {
context = this;
args = arguments;
timestamp = _.now();
var callNow = immediate && !timeout;
if (!timeout) timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
context = args = null;
}
return result;
};
};
// Returns the first function passed as an argument to the second,
// allowing you to adjust arguments, run code before and after, and
// conditionally execute the original function.
_.wrap = function(func, wrapper) {
return _.partial(wrapper, func);
};
// Returns a negated version of the passed-in predicate.
_.negate = function(predicate) {
return function() {
return !predicate.apply(this, arguments);
};
};
// Returns a function that is the composition of a list of functions, each
// consuming the return value of the function that follows.
_.compose = function() {
var args = arguments;
var start = args.length - 1;
return function() {
var i = start;
var result = args[start].apply(this, arguments);
while (i--) result = args[i].call(this, result);
return result;
};
};
// Returns a function that will only be executed on and after the Nth call.
_.after = function(times, func) {
return function() {
if (--times < 1) {
return func.apply(this, arguments);
}
};
};
// Returns a function that will only be executed up to (but not including) the Nth call.
_.before = function(times, func) {
var memo;
return function() {
if (--times > 0) {
memo = func.apply(this, arguments);
}
if (times <= 1) func = null;
return memo;
};
};
// Returns a function that will be executed at most one time, no matter how
// often you call it. Useful for lazy initialization.
_.once = _.partial(_.before, 2);
// Object Functions
// ----------------
// Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');
var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];
function collectNonEnumProps(obj, keys) {
var nonEnumIdx = nonEnumerableProps.length;
var constructor = obj.constructor;
var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto;
// Constructor is a special case.
var prop = 'constructor';
if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop);
while (nonEnumIdx--) {
prop = nonEnumerableProps[nonEnumIdx];
if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) {
keys.push(prop);
}
}
}
// Retrieve the names of an object's own properties.
// Delegates to **ECMAScript 5**'s native `Object.keys`
_.keys = function(obj) {
if (!_.isObject(obj)) return [];
if (nativeKeys) return nativeKeys(obj);
var keys = [];
for (var key in obj) if (_.has(obj, key)) keys.push(key);
// Ahem, IE < 9.
if (hasEnumBug) collectNonEnumProps(obj, keys);
return keys;
};
// Retrieve all the property names of an object.
_.allKeys = function(obj) {
if (!_.isObject(obj)) return [];
var keys = [];
for (var key in obj) keys.push(key);
// Ahem, IE < 9.
if (hasEnumBug) collectNonEnumProps(obj, keys);
return keys;
};
// Retrieve the values of an object's properties.
_.values = function(obj) {
var keys = _.keys(obj);
var length = keys.length;
var values = Array(length);
for (var i = 0; i < length; i++) {
values[i] = obj[keys[i]];
}
return values;
};
// Returns the results of applying the iteratee to each element of the object
// In contrast to _.map it returns an object
_.mapObject = function(obj, iteratee, context) {
iteratee = cb(iteratee, context);
var keys = _.keys(obj),
length = keys.length,
results = {},
currentKey;
for (var index = 0; index < length; index++) {
currentKey = keys[index];
results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
}
return results;
};
// Convert an object into a list of `[key, value]` pairs.
_.pairs = function(obj) {
var keys = _.keys(obj);
var length = keys.length;
var pairs = Array(length);
for (var i = 0; i < length; i++) {
pairs[i] = [keys[i], obj[keys[i]]];
}
return pairs;
};
// Invert the keys and values of an object. The values must be serializable.
_.invert = function(obj) {
var result = {};
var keys = _.keys(obj);
for (var i = 0, length = keys.length; i < length; i++) {
result[obj[keys[i]]] = keys[i];
}
return result;
};
// Return a sorted list of the function names available on the object.
// Aliased as `methods`
_.functions = _.methods = function(obj) {
var names = [];
for (var key in obj) {
if (_.isFunction(obj[key])) names.push(key);
}
return names.sort();
};
// Extend a given object with all the properties in passed-in object(s).
_.extend = createAssigner(_.allKeys);
// Assigns a given object with all the own properties in the passed-in object(s)
// (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
_.extendOwn = _.assign = createAssigner(_.keys);
// Returns the first key on an object that passes a predicate test
_.findKey = function(obj, predicate, context) {
predicate = cb(predicate, context);
var keys = _.keys(obj), key;
for (var i = 0, length = keys.length; i < length; i++) {
key = keys[i];
if (predicate(obj[key], key, obj)) return key;
}
};
// Return a copy of the object only containing the whitelisted properties.
_.pick = function(object, oiteratee, context) {
var result = {}, obj = object, iteratee, keys;
if (obj == null) return result;
if (_.isFunction(oiteratee)) {
keys = _.allKeys(obj);
iteratee = optimizeCb(oiteratee, context);
} else {
keys = flatten(arguments, false, false, 1);
iteratee = function(value, key, obj) { return key in obj; };
obj = Object(obj);
}
for (var i = 0, length = keys.length; i < length; i++) {
var key = keys[i];
var value = obj[key];
if (iteratee(value, key, obj)) result[key] = value;
}
return result;
};
// Return a copy of the object without the blacklisted properties.
_.omit = function(obj, iteratee, context) {
if (_.isFunction(iteratee)) {
iteratee = _.negate(iteratee);
} else {
var keys = _.map(flatten(arguments, false, false, 1), String);
iteratee = function(value, key) {
return !_.contains(keys, key);
};
}
return _.pick(obj, iteratee, context);
};
// Fill in a given object with default properties.
_.defaults = createAssigner(_.allKeys, true);
// Creates an object that inherits from the given prototype object.
// If additional properties are provided then they will be added to the
// created object.
_.create = function(prototype, props) {
var result = baseCreate(prototype);
if (props) _.extendOwn(result, props);
return result;
};
// Create a (shallow-cloned) duplicate of an object.
_.clone = function(obj) {
if (!_.isObject(obj)) return obj;
return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
};
// Invokes interceptor with the obj, and then returns obj.
// The primary purpose of this method is to "tap into" a method chain, in
// order to perform operations on intermediate results within the chain.
_.tap = function(obj, interceptor) {
interceptor(obj);
return obj;
};
// Returns whether an object has a given set of `key:value` pairs.
_.isMatch = function(object, attrs) {
var keys = _.keys(attrs), length = keys.length;
if (object == null) return !length;
var obj = Object(object);
for (var i = 0; i < length; i++) {
var key = keys[i];
if (attrs[key] !== obj[key] || !(key in obj)) return false;
}
return true;
};
// Internal recursive comparison function for `isEqual`.
var eq = function(a, b, aStack, bStack) {
// Identical objects are equal. `0 === -0`, but they aren't identical.
// See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
if (a === b) return a !== 0 || 1 / a === 1 / b;
// A strict comparison is necessary because `null == undefined`.
if (a == null || b == null) return a === b;
// Unwrap any wrapped objects.
if (a instanceof _) a = a._wrapped;
if (b instanceof _) b = b._wrapped;
// Compare `[[Class]]` names.
var className = toString.call(a);
if (className !== toString.call(b)) return false;
switch (className) {
// Strings, numbers, regular expressions, dates, and booleans are compared by value.
case '[object RegExp]':
// RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
case '[object String]':
// Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
// equivalent to `new String("5")`.
return '' + a === '' + b;
case '[object Number]':
// `NaN`s are equivalent, but non-reflexive.
// Object(NaN) is equivalent to NaN
if (+a !== +a) return +b !== +b;
// An `egal` comparison is performed for other numeric values.
return +a === 0 ? 1 / +a === 1 / b : +a === +b;
case '[object Date]':
case '[object Boolean]':
// Coerce dates and booleans to numeric primitive values. Dates are compared by their
// millisecond representations. Note that invalid dates with millisecond representations
// of `NaN` are not equivalent.
return +a === +b;
}
var areArrays = className === '[object Array]';
if (!areArrays) {
if (typeof a != 'object' || typeof b != 'object') return false;
// Objects with different constructors are not equivalent, but `Object`s or `Array`s
// from different frames are.
var aCtor = a.constructor, bCtor = b.constructor;
if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor &&
_.isFunction(bCtor) && bCtor instanceof bCtor)
&& ('constructor' in a && 'constructor' in b)) {
return false;
}
}
// Assume equality for cyclic structures. The algorithm for detecting cyclic
// structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
// Initializing stack of traversed objects.
// It's done here since we only need them for objects and arrays comparison.
aStack = aStack || [];
bStack = bStack || [];
var length = aStack.length;
while (length--) {
// Linear search. Performance is inversely proportional to the number of
// unique nested structures.
if (aStack[length] === a) return bStack[length] === b;
}
// Add the first object to the stack of traversed objects.
aStack.push(a);
bStack.push(b);
// Recursively compare objects and arrays.
if (areArrays) {
// Compare array lengths to determine if a deep comparison is necessary.
length = a.length;
if (length !== b.length) return false;
// Deep compare the contents, ignoring non-numeric properties.
while (length--) {
if (!eq(a[length], b[length], aStack, bStack)) return false;
}
} else {
// Deep compare objects.
var keys = _.keys(a), key;
length = keys.length;
// Ensure that both objects contain the same number of properties before comparing deep equality.
if (_.keys(b).length !== length) return false;
while (length--) {
// Deep compare each member
key = keys[length];
if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
}
}
// Remove the first object from the stack of traversed objects.
aStack.pop();
bStack.pop();
return true;
};
// Perform a deep comparison to check if two objects are equal.
_.isEqual = function(a, b) {
return eq(a, b);
};
// Is a given array, string, or object empty?
// An "empty" object has no enumerable own-properties.
_.isEmpty = function(obj) {
if (obj == null) return true;
if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0;
return _.keys(obj).length === 0;
};
// Is a given value a DOM element?
_.isElement = function(obj) {
return !!(obj && obj.nodeType === 1);
};
// Is a given value an array?
// Delegates to ECMA5's native Array.isArray
_.isArray = nativeIsArray || function(obj) {
return toString.call(obj) === '[object Array]';
};
// Is a given variable an object?
_.isObject = function(obj) {
var type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
};
// Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError.
_.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) {
_['is' + name] = function(obj) {
return toString.call(obj) === '[object ' + name + ']';
};
});
// Define a fallback version of the method in browsers (ahem, IE < 9), where
// there isn't any inspectable "Arguments" type.
if (!_.isArguments(arguments)) {
_.isArguments = function(obj) {
return _.has(obj, 'callee');
};
}
// Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8,
// IE 11 (#1621), and in Safari 8 (#1929).
if (typeof /./ != 'function' && typeof Int8Array != 'object') {
_.isFunction = function(obj) {
return typeof obj == 'function' || false;
};
}
// Is a given object a finite number?
_.isFinite = function(obj) {
return isFinite(obj) && !isNaN(parseFloat(obj));
};
// Is the given value `NaN`? (NaN is the only number which does not equal itself).
_.isNaN = function(obj) {
return _.isNumber(obj) && obj !== +obj;
};
// Is a given value a boolean?
_.isBoolean = function(obj) {
return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
};
// Is a given value equal to null?
_.isNull = function(obj) {
return obj === null;
};
// Is a given variable undefined?
_.isUndefined = function(obj) {
return obj === void 0;
};
// Shortcut function for checking if an object has a given property directly
// on itself (in other words, not on a prototype).
_.has = function(obj, key) {
return obj != null && hasOwnProperty.call(obj, key);
};
// Utility Functions
// -----------------
// Run Underscore.js in *noConflict* mode, returning the `_` variable to its
// previous owner. Returns a reference to the Underscore object.
_.noConflict = function() {
root._ = previousUnderscore;
return this;
};
// Keep the identity function around for default iteratees.
_.identity = function(value) {
return value;
};
// Predicate-generating functions. Often useful outside of Underscore.
_.constant = function(value) {
return function() {
return value;
};
};
_.noop = function(){};
_.property = property;
// Generates a function for a given object that returns a given property.
_.propertyOf = function(obj) {
return obj == null ? function(){} : function(key) {
return obj[key];
};
};
// Returns a predicate for checking whether an object has a given set of
// `key:value` pairs.
_.matcher = _.matches = function(attrs) {
attrs = _.extendOwn({}, attrs);
return function(obj) {
return _.isMatch(obj, attrs);
};
};
// Run a function **n** times.
_.times = function(n, iteratee, context) {
var accum = Array(Math.max(0, n));
iteratee = optimizeCb(iteratee, context, 1);
for (var i = 0; i < n; i++) accum[i] = iteratee(i);
return accum;
};
// Return a random integer between min and max (inclusive).
_.random = function(min, max) {
if (max == null) {
max = min;
min = 0;
}
return min + Math.floor(Math.random() * (max - min + 1));
};
// A (possibly faster) way to get the current timestamp as an integer.
_.now = Date.now || function() {
return new Date().getTime();
};
// List of HTML entities for escaping.
var escapeMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'`': '`'
};
var unescapeMap = _.invert(escapeMap);
// Functions for escaping and unescaping strings to/from HTML interpolation.
var createEscaper = function(map) {
var escaper = function(match) {
return map[match];
};
// Regexes for identifying a key that needs to be escaped
var source = '(?:' + _.keys(map).join('|') + ')';
var testRegexp = RegExp(source);
var replaceRegexp = RegExp(source, 'g');
return function(string) {
string = string == null ? '' : '' + string;
return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
};
};
_.escape = createEscaper(escapeMap);
_.unescape = createEscaper(unescapeMap);
// If the value of the named `property` is a function then invoke it with the
// `object` as context; otherwise, return it.
_.result = function(object, property, fallback) {
var value = object == null ? void 0 : object[property];
if (value === void 0) {
value = fallback;
}
return _.isFunction(value) ? value.call(object) : value;
};
// Generate a unique integer id (unique within the entire client session).
// Useful for temporary DOM ids.
var idCounter = 0;
_.uniqueId = function(prefix) {
var id = ++idCounter + '';
return prefix ? prefix + id : id;
};
// By default, Underscore uses ERB-style template delimiters, change the
// following template settings to use alternative delimiters.
_.templateSettings = {
evaluate : /<%([\s\S]+?)%>/g,
interpolate : /<%=([\s\S]+?)%>/g,
escape : /<%-([\s\S]+?)%>/g
};
// When customizing `templateSettings`, if you don't want to define an
// interpolation, evaluation or escaping regex, we need one that is
// guaranteed not to match.
var noMatch = /(.)^/;
// Certain characters need to be escaped so that they can be put into a
// string literal.
var escapes = {
"'": "'",
'\\': '\\',
'\r': 'r',
'\n': 'n',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
var escaper = /\\|'|\r|\n|\u2028|\u2029/g;
var escapeChar = function(match) {
return '\\' + escapes[match];
};
// JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code.
// NB: `oldSettings` only exists for backwards compatibility.
_.template = function(text, settings, oldSettings) {
if (!settings && oldSettings) settings = oldSettings;
settings = _.defaults({}, settings, _.templateSettings);
// Combine delimiters into one regular expression via alternation.
var matcher = RegExp([
(settings.escape || noMatch).source,
(settings.interpolate || noMatch).source,
(settings.evaluate || noMatch).source
].join('|') + '|$', 'g');
// Compile the template source, escaping string literals appropriately.
var index = 0;
var source = "__p+='";
text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
source += text.slice(index, offset).replace(escaper, escapeChar);
index = offset + match.length;
if (escape) {
source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
} else if (interpolate) {
source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
} else if (evaluate) {
source += "';\n" + evaluate + "\n__p+='";
}
// Adobe VMs need the match returned to produce the correct offest.
return match;
});
source += "';\n";
// If a variable is not specified, place data values in local scope.
if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
source = "var __t,__p='',__j=Array.prototype.join," +
"print=function(){__p+=__j.call(arguments,'');};\n" +
source + 'return __p;\n';
try {
var render = new Function(settings.variable || 'obj', '_', source);
} catch (e) {
e.source = source;
throw e;
}
var template = function(data) {
return render.call(this, data, _);
};
// Provide the compiled source as a convenience for precompilation.
var argument = settings.variable || 'obj';
template.source = 'function(' + argument + '){\n' + source + '}';
return template;
};
// Add a "chain" function. Start chaining a wrapped Underscore object.
_.chain = function(obj) {
var instance = _(obj);
instance._chain = true;
return instance;
};
// OOP
// ---------------
// If Underscore is called as a function, it returns a wrapped object that
// can be used OO-style. This wrapper holds altered versions of all the
// underscore functions. Wrapped objects may be chained.
// Helper function to continue chaining intermediate results.
var result = function(instance, obj) {
return instance._chain ? _(obj).chain() : obj;
};
// Add your own custom functions to the Underscore object.
_.mixin = function(obj) {
_.each(_.functions(obj), function(name) {
var func = _[name] = obj[name];
_.prototype[name] = function() {
var args = [this._wrapped];
push.apply(args, arguments);
return result(this, func.apply(_, args));
};
});
};
// Add all of the Underscore functions to the wrapper object.
_.mixin(_);
// Add all mutator Array functions to the wrapper.
_.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
var method = ArrayProto[name];
_.prototype[name] = function() {
var obj = this._wrapped;
method.apply(obj, arguments);
if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];
return result(this, obj);
};
});
// Add all accessor Array functions to the wrapper.
_.each(['concat', 'join', 'slice'], function(name) {
var method = ArrayProto[name];
_.prototype[name] = function() {
return result(this, method.apply(this._wrapped, arguments));
};
});
// Extracts the result from a wrapped and chained object.
_.prototype.value = function() {
return this._wrapped;
};
// Provide unwrapping proxy for some methods used in engine operations
// such as arithmetic and JSON stringification.
_.prototype.valueOf = _.prototype.toJSON = _.prototype.value;
_.prototype.toString = function() {
return '' + this._wrapped;
};
// AMD registration happens at the end for compatibility with AMD loaders
// that may not enforce next-turn semantics on modules. Even though general
// practice for AMD registration is to be anonymous, underscore registers
// as a named module because, like jQuery, it is a base library that is
// popular enough to be bundled in a third party lib, but not be part of
// an AMD load request. Those cases could generate an error when an
// anonymous define() is called outside of a loader request.
if (typeof define === 'function' && define.amd) {
define('underscore', [], function() {
return _;
});
}
}.call(this));
},{}],157:[function(require,module,exports){
// Generated by CoffeeScript 1.9.1
(function() {
var XMLAttribute, create;
create = require('lodash/object/create');
module.exports = XMLAttribute = (function() {
function XMLAttribute(parent, name, value) {
this.stringify = parent.stringify;
if (name == null) {
throw new Error("Missing attribute name of element " + parent.name);
}
if (value == null) {
throw new Error("Missing attribute value for attribute " + name + " of element " + parent.name);
}
this.name = this.stringify.attName(name);
this.value = this.stringify.attValue(value);
}
XMLAttribute.prototype.clone = function() {
return create(XMLAttribute.prototype, this);
};
XMLAttribute.prototype.toString = function(options, level) {
return ' ' + this.name + '="' + this.value + '"';
};
return XMLAttribute;
})();
}).call(this);
},{"lodash/object/create":227}],158:[function(require,module,exports){
// Generated by CoffeeScript 1.9.1
(function() {
var XMLBuilder, XMLDeclaration, XMLDocType, XMLElement, XMLStringifier;
XMLStringifier = require('./XMLStringifier');
XMLDeclaration = require('./XMLDeclaration');
XMLDocType = require('./XMLDocType');
XMLElement = require('./XMLElement');
module.exports = XMLBuilder = (function() {
function XMLBuilder(name, options) {
var root, temp;
if (name == null) {
throw new Error("Root element needs a name");
}
if (options == null) {
options = {};
}
this.options = options;
this.stringify = new XMLStringifier(options);
temp = new XMLElement(this, 'doc');
root = temp.element(name);
root.isRoot = true;
root.documentObject = this;
this.rootObject = root;
if (!options.headless) {
root.declaration(options);
if ((options.pubID != null) || (options.sysID != null)) {
root.doctype(options);
}
}
}
XMLBuilder.prototype.root = function() {
return this.rootObject;
};
XMLBuilder.prototype.end = function(options) {
return this.toString(options);
};
XMLBuilder.prototype.toString = function(options) {
var indent, newline, offset, pretty, r, ref, ref1, ref2;
pretty = (options != null ? options.pretty : void 0) || false;
indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
r = '';
if (this.xmldec != null) {
r += this.xmldec.toString(options);
}
if (this.doctype != null) {
r += this.doctype.toString(options);
}
r += this.rootObject.toString(options);
if (pretty && r.slice(-newline.length) === newline) {
r = r.slice(0, -newline.length);
}
return r;
};
return XMLBuilder;
})();
}).call(this);
},{"./XMLDeclaration":165,"./XMLDocType":166,"./XMLElement":167,"./XMLStringifier":171}],159:[function(require,module,exports){
// Generated by CoffeeScript 1.9.1
(function() {
var XMLCData, XMLNode, create,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
create = require('lodash/object/create');
XMLNode = require('./XMLNode');
module.exports = XMLCData = (function(superClass) {
extend(XMLCData, superClass);
function XMLCData(parent, text) {
XMLCData.__super__.constructor.call(this, parent);
if (text == null) {
throw new Error("Missing CDATA text");
}
this.text = this.stringify.cdata(text);
}
XMLCData.prototype.clone = function() {
return create(XMLCData.prototype, this);
};
XMLCData.prototype.toString = function(options, level) {
var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
pretty = (options != null ? options.pretty : void 0) || false;
indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
level || (level = 0);
space = new Array(level + offset + 1).join(indent);
r = '';
if (pretty) {
r += space;
}
r += '<![CDATA[' + this.text + ']]>';
if (pretty) {
r += newline;
}
return r;
};
return XMLCData;
})(XMLNode);
}).call(this);
},{"./XMLNode":168,"lodash/object/create":227}],160:[function(require,module,exports){
// Generated by CoffeeScript 1.9.1
(function() {
var XMLComment, XMLNode, create,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
create = require('lodash/object/create');
XMLNode = require('./XMLNode');
module.exports = XMLComment = (function(superClass) {
extend(XMLComment, superClass);
function XMLComment(parent, text) {
XMLComment.__super__.constructor.call(this, parent);
if (text == null) {
throw new Error("Missing comment text");
}
this.text = this.stringify.comment(text);
}
XMLComment.prototype.clone = function() {
return create(XMLComment.prototype, this);
};
XMLComment.prototype.toString = function(options, level) {
var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
pretty = (options != null ? options.pretty : void 0) || false;
indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
level || (level = 0);
space = new Array(level + offset + 1).join(indent);
r = '';
if (pretty) {
r += space;
}
r += '<!-- ' + this.text + ' -->';
if (pretty) {
r += newline;
}
return r;
};
return XMLComment;
})(XMLNode);
}).call(this);
},{"./XMLNode":168,"lodash/object/create":227}],161:[function(require,module,exports){
// Generated by CoffeeScript 1.9.1
(function() {
var XMLDTDAttList, create;
create = require('lodash/object/create');
module.exports = XMLDTDAttList = (function() {
function XMLDTDAttList(parent, elementName, attributeName, attributeType, defaultValueType, defaultValue) {
this.stringify = parent.stringify;
if (elementName == null) {
throw new Error("Missing DTD element name");
}
if (attributeName == null) {
throw new Error("Missing DTD attribute name");
}
if (!attributeType) {
throw new Error("Missing DTD attribute type");
}
if (!defaultValueType) {
throw new Error("Missing DTD attribute default");
}
if (defaultValueType.indexOf('#') !== 0) {
defaultValueType = '#' + defaultValueType;
}
if (!defaultValueType.match(/^(#REQUIRED|#IMPLIED|#FIXED|#DEFAULT)$/)) {
throw new Error("Invalid default value type; expected: #REQUIRED, #IMPLIED, #FIXED or #DEFAULT");
}
if (defaultValue && !defaultValueType.match(/^(#FIXED|#DEFAULT)$/)) {
throw new Error("Default value only applies to #FIXED or #DEFAULT");
}
this.elementName = this.stringify.eleName(elementName);
this.attributeName = this.stringify.attName(attributeName);
this.attributeType = this.stringify.dtdAttType(attributeType);
this.defaultValue = this.stringify.dtdAttDefault(defaultValue);
this.defaultValueType = defaultValueType;
}
XMLDTDAttList.prototype.clone = function() {
return create(XMLDTDAttList.prototype, this);
};
XMLDTDAttList.prototype.toString = function(options, level) {
var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
pretty = (options != null ? options.pretty : void 0) || false;
indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
level || (level = 0);
space = new Array(level + offset + 1).join(indent);
r = '';
if (pretty) {
r += space;
}
r += '<!ATTLIST ' + this.elementName + ' ' + this.attributeName + ' ' + this.attributeType;
if (this.defaultValueType !== '#DEFAULT') {
r += ' ' + this.defaultValueType;
}
if (this.defaultValue) {
r += ' "' + this.defaultValue + '"';
}
r += '>';
if (pretty) {
r += newline;
}
return r;
};
return XMLDTDAttList;
})();
}).call(this);
},{"lodash/object/create":227}],162:[function(require,module,exports){
// Generated by CoffeeScript 1.9.1
(function() {
var XMLDTDElement, create;
create = require('lodash/object/create');
module.exports = XMLDTDElement = (function() {
function XMLDTDElement(parent, name, value) {
this.stringify = parent.stringify;
if (name == null) {
throw new Error("Missing DTD element name");
}
if (!value) {
value = '(#PCDATA)';
}
if (Array.isArray(value)) {
value = '(' + value.join(',') + ')';
}
this.name = this.stringify.eleName(name);
this.value = this.stringify.dtdElementValue(value);
}
XMLDTDElement.prototype.clone = function() {
return create(XMLDTDElement.prototype, this);
};
XMLDTDElement.prototype.toString = function(options, level) {
var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
pretty = (options != null ? options.pretty : void 0) || false;
indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
level || (level = 0);
space = new Array(level + offset + 1).join(indent);
r = '';
if (pretty) {
r += space;
}
r += '<!ELEMENT ' + this.name + ' ' + this.value + '>';
if (pretty) {
r += newline;
}
return r;
};
return XMLDTDElement;
})();
}).call(this);
},{"lodash/object/create":227}],163:[function(require,module,exports){
// Generated by CoffeeScript 1.9.1
(function() {
var XMLDTDEntity, create, isObject;
create = require('lodash/object/create');
isObject = require('lodash/lang/isObject');
module.exports = XMLDTDEntity = (function() {
function XMLDTDEntity(parent, pe, name, value) {
this.stringify = parent.stringify;
if (name == null) {
throw new Error("Missing entity name");
}
if (value == null) {
throw new Error("Missing entity value");
}
this.pe = !!pe;
this.name = this.stringify.eleName(name);
if (!isObject(value)) {
this.value = this.stringify.dtdEntityValue(value);
} else {
if (!value.pubID && !value.sysID) {
throw new Error("Public and/or system identifiers are required for an external entity");
}
if (value.pubID && !value.sysID) {
throw new Error("System identifier is required for a public external entity");
}
if (value.pubID != null) {
this.pubID = this.stringify.dtdPubID(value.pubID);
}
if (value.sysID != null) {
this.sysID = this.stringify.dtdSysID(value.sysID);
}
if (value.nData != null) {
this.nData = this.stringify.dtdNData(value.nData);
}
if (this.pe && this.nData) {
throw new Error("Notation declaration is not allowed in a parameter entity");
}
}
}
XMLDTDEntity.prototype.clone = function() {
return create(XMLDTDEntity.prototype, this);
};
XMLDTDEntity.prototype.toString = function(options, level) {
var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
pretty = (options != null ? options.pretty : void 0) || false;
indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
level || (level = 0);
space = new Array(level + offset + 1).join(indent);
r = '';
if (pretty) {
r += space;
}
r += '<!ENTITY';
if (this.pe) {
r += ' %';
}
r += ' ' + this.name;
if (this.value) {
r += ' "' + this.value + '"';
} else {
if (this.pubID && this.sysID) {
r += ' PUBLIC "' + this.pubID + '" "' + this.sysID + '"';
} else if (this.sysID) {
r += ' SYSTEM "' + this.sysID + '"';
}
if (this.nData) {
r += ' NDATA ' + this.nData;
}
}
r += '>';
if (pretty) {
r += newline;
}
return r;
};
return XMLDTDEntity;
})();
}).call(this);
},{"lodash/lang/isObject":223,"lodash/object/create":227}],164:[function(require,module,exports){
// Generated by CoffeeScript 1.9.1
(function() {
var XMLDTDNotation, create;
create = require('lodash/object/create');
module.exports = XMLDTDNotation = (function() {
function XMLDTDNotation(parent, name, value) {
this.stringify = parent.stringify;
if (name == null) {
throw new Error("Missing notation name");
}
if (!value.pubID && !value.sysID) {
throw new Error("Public or system identifiers are required for an external entity");
}
this.name = this.stringify.eleName(name);
if (value.pubID != null) {
this.pubID = this.stringify.dtdPubID(value.pubID);
}
if (value.sysID != null) {
this.sysID = this.stringify.dtdSysID(value.sysID);
}
}
XMLDTDNotation.prototype.clone = function() {
return create(XMLDTDNotation.prototype, this);
};
XMLDTDNotation.prototype.toString = function(options, level) {
var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
pretty = (options != null ? options.pretty : void 0) || false;
indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
level || (level = 0);
space = new Array(level + offset + 1).join(indent);
r = '';
if (pretty) {
r += space;
}
r += '<!NOTATION ' + this.name;
if (this.pubID && this.sysID) {
r += ' PUBLIC "' + this.pubID + '" "' + this.sysID + '"';
} else if (this.pubID) {
r += ' PUBLIC "' + this.pubID + '"';
} else if (this.sysID) {
r += ' SYSTEM "' + this.sysID + '"';
}
r += '>';
if (pretty) {
r += newline;
}
return r;
};
return XMLDTDNotation;
})();
}).call(this);
},{"lodash/object/create":227}],165:[function(require,module,exports){
// Generated by CoffeeScript 1.9.1
(function() {
var XMLDeclaration, XMLNode, create, isObject,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
create = require('lodash/object/create');
isObject = require('lodash/lang/isObject');
XMLNode = require('./XMLNode');
module.exports = XMLDeclaration = (function(superClass) {
extend(XMLDeclaration, superClass);
function XMLDeclaration(parent, version, encoding, standalone) {
var ref;
XMLDeclaration.__super__.constructor.call(this, parent);
if (isObject(version)) {
ref = version, version = ref.version, encoding = ref.encoding, standalone = ref.standalone;
}
if (!version) {
version = '1.0';
}
if (version != null) {
this.version = this.stringify.xmlVersion(version);
}
if (encoding != null) {
this.encoding = this.stringify.xmlEncoding(encoding);
}
if (standalone != null) {
this.standalone = this.stringify.xmlStandalone(standalone);
}
}
XMLDeclaration.prototype.clone = function() {
return create(XMLDeclaration.prototype, this);
};
XMLDeclaration.prototype.toString = function(options, level) {
var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
pretty = (options != null ? options.pretty : void 0) || false;
indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
level || (level = 0);
space = new Array(level + offset + 1).join(indent);
r = '';
if (pretty) {
r += space;
}
r += '<?xml';
if (this.version != null) {
r += ' version="' + this.version + '"';
}
if (this.encoding != null) {
r += ' encoding="' + this.encoding + '"';
}
if (this.standalone != null) {
r += ' standalone="' + this.standalone + '"';
}
r += '?>';
if (pretty) {
r += newline;
}
return r;
};
return XMLDeclaration;
})(XMLNode);
}).call(this);
},{"./XMLNode":168,"lodash/lang/isObject":223,"lodash/object/create":227}],166:[function(require,module,exports){
// Generated by CoffeeScript 1.9.1
(function() {
var XMLCData, XMLComment, XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLDocType, XMLProcessingInstruction, create, isObject;
create = require('lodash/object/create');
isObject = require('lodash/lang/isObject');
XMLCData = require('./XMLCData');
XMLComment = require('./XMLComment');
XMLDTDAttList = require('./XMLDTDAttList');
XMLDTDEntity = require('./XMLDTDEntity');
XMLDTDElement = require('./XMLDTDElement');
XMLDTDNotation = require('./XMLDTDNotation');
XMLProcessingInstruction = require('./XMLProcessingInstruction');
module.exports = XMLDocType = (function() {
function XMLDocType(parent, pubID, sysID) {
var ref, ref1;
this.documentObject = parent;
this.stringify = this.documentObject.stringify;
this.children = [];
if (isObject(pubID)) {
ref = pubID, pubID = ref.pubID, sysID = ref.sysID;
}
if (sysID == null) {
ref1 = [pubID, sysID], sysID = ref1[0], pubID = ref1[1];
}
if (pubID != null) {
this.pubID = this.stringify.dtdPubID(pubID);
}
if (sysID != null) {
this.sysID = this.stringify.dtdSysID(sysID);
}
}
XMLDocType.prototype.clone = function() {
return create(XMLDocType.prototype, this);
};
XMLDocType.prototype.element = function(name, value) {
var child;
child = new XMLDTDElement(this, name, value);
this.children.push(child);
return this;
};
XMLDocType.prototype.attList = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) {
var child;
child = new XMLDTDAttList(this, elementName, attributeName, attributeType, defaultValueType, defaultValue);
this.children.push(child);
return this;
};
XMLDocType.prototype.entity = function(name, value) {
var child;
child = new XMLDTDEntity(this, false, name, value);
this.children.push(child);
return this;
};
XMLDocType.prototype.pEntity = function(name, value) {
var child;
child = new XMLDTDEntity(this, true, name, value);
this.children.push(child);
return this;
};
XMLDocType.prototype.notation = function(name, value) {
var child;
child = new XMLDTDNotation(this, name, value);
this.children.push(child);
return this;
};
XMLDocType.prototype.cdata = function(value) {
var child;
child = new XMLCData(this, value);
this.children.push(child);
return this;
};
XMLDocType.prototype.comment = function(value) {
var child;
child = new XMLComment(this, value);
this.children.push(child);
return this;
};
XMLDocType.prototype.instruction = function(target, value) {
var child;
child = new XMLProcessingInstruction(this, target, value);
this.children.push(child);
return this;
};
XMLDocType.prototype.root = function() {
return this.documentObject.root();
};
XMLDocType.prototype.document = function() {
return this.documentObject;
};
XMLDocType.prototype.toString = function(options, level) {
var child, i, indent, len, newline, offset, pretty, r, ref, ref1, ref2, ref3, space;
pretty = (options != null ? options.pretty : void 0) || false;
indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
level || (level = 0);
space = new Array(level + offset + 1).join(indent);
r = '';
if (pretty) {
r += space;
}
r += '<!DOCTYPE ' + this.root().name;
if (this.pubID && this.sysID) {
r += ' PUBLIC "' + this.pubID + '" "' + this.sysID + '"';
} else if (this.sysID) {
r += ' SYSTEM "' + this.sysID + '"';
}
if (this.children.length > 0) {
r += ' [';
if (pretty) {
r += newline;
}
ref3 = this.children;
for (i = 0, len = ref3.length; i < len; i++) {
child = ref3[i];
r += child.toString(options, level + 1);
}
r += ']';
}
r += '>';
if (pretty) {
r += newline;
}
return r;
};
XMLDocType.prototype.ele = function(name, value) {
return this.element(name, value);
};
XMLDocType.prototype.att = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) {
return this.attList(elementName, attributeName, attributeType, defaultValueType, defaultValue);
};
XMLDocType.prototype.ent = function(name, value) {
return this.entity(name, value);
};
XMLDocType.prototype.pent = function(name, value) {
return this.pEntity(name, value);
};
XMLDocType.prototype.not = function(name, value) {
return this.notation(name, value);
};
XMLDocType.prototype.dat = function(value) {
return this.cdata(value);
};
XMLDocType.prototype.com = function(value) {
return this.comment(value);
};
XMLDocType.prototype.ins = function(target, value) {
return this.instruction(target, value);
};
XMLDocType.prototype.up = function() {
return this.root();
};
XMLDocType.prototype.doc = function() {
return this.document();
};
return XMLDocType;
})();
}).call(this);
},{"./XMLCData":159,"./XMLComment":160,"./XMLDTDAttList":161,"./XMLDTDElement":162,"./XMLDTDEntity":163,"./XMLDTDNotation":164,"./XMLProcessingInstruction":169,"lodash/lang/isObject":223,"lodash/object/create":227}],167:[function(require,module,exports){
// Generated by CoffeeScript 1.9.1
(function() {
var XMLAttribute, XMLElement, XMLNode, XMLProcessingInstruction, create, every, isFunction, isObject,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
create = require('lodash/object/create');
isObject = require('lodash/lang/isObject');
isFunction = require('lodash/lang/isFunction');
every = require('lodash/collection/every');
XMLNode = require('./XMLNode');
XMLAttribute = require('./XMLAttribute');
XMLProcessingInstruction = require('./XMLProcessingInstruction');
module.exports = XMLElement = (function(superClass) {
extend(XMLElement, superClass);
function XMLElement(parent, name, attributes) {
XMLElement.__super__.constructor.call(this, parent);
if (name == null) {
throw new Error("Missing element name");
}
this.name = this.stringify.eleName(name);
this.children = [];
this.instructions = [];
this.attributes = {};
if (attributes != null) {
this.attribute(attributes);
}
}
XMLElement.prototype.clone = function() {
var att, attName, clonedSelf, i, len, pi, ref, ref1;
clonedSelf = create(XMLElement.prototype, this);
if (clonedSelf.isRoot) {
clonedSelf.documentObject = null;
}
clonedSelf.attributes = {};
ref = this.attributes;
for (attName in ref) {
if (!hasProp.call(ref, attName)) continue;
att = ref[attName];
clonedSelf.attributes[attName] = att.clone();
}
clonedSelf.instructions = [];
ref1 = this.instructions;
for (i = 0, len = ref1.length; i < len; i++) {
pi = ref1[i];
clonedSelf.instructions.push(pi.clone());
}
clonedSelf.children = [];
this.children.forEach(function(child) {
var clonedChild;
clonedChild = child.clone();
clonedChild.parent = clonedSelf;
return clonedSelf.children.push(clonedChild);
});
return clonedSelf;
};
XMLElement.prototype.attribute = function(name, value) {
var attName, attValue;
if (name != null) {
name = name.valueOf();
}
if (isObject(name)) {
for (attName in name) {
if (!hasProp.call(name, attName)) continue;
attValue = name[attName];
this.attribute(attName, attValue);
}
} else {
if (isFunction(value)) {
value = value.apply();
}
if (!this.options.skipNullAttributes || (value != null)) {
this.attributes[name] = new XMLAttribute(this, name, value);
}
}
return this;
};
XMLElement.prototype.removeAttribute = function(name) {
var attName, i, len;
if (name == null) {
throw new Error("Missing attribute name");
}
name = name.valueOf();
if (Array.isArray(name)) {
for (i = 0, len = name.length; i < len; i++) {
attName = name[i];
delete this.attributes[attName];
}
} else {
delete this.attributes[name];
}
return this;
};
XMLElement.prototype.instruction = function(target, value) {
var i, insTarget, insValue, instruction, len;
if (target != null) {
target = target.valueOf();
}
if (value != null) {
value = value.valueOf();
}
if (Array.isArray(target)) {
for (i = 0, len = target.length; i < len; i++) {
insTarget = target[i];
this.instruction(insTarget);
}
} else if (isObject(target)) {
for (insTarget in target) {
if (!hasProp.call(target, insTarget)) continue;
insValue = target[insTarget];
this.instruction(insTarget, insValue);
}
} else {
if (isFunction(value)) {
value = value.apply();
}
instruction = new XMLProcessingInstruction(this, target, value);
this.instructions.push(instruction);
}
return this;
};
XMLElement.prototype.toString = function(options, level) {
var att, child, i, indent, instruction, j, len, len1, name, newline, offset, pretty, r, ref, ref1, ref2, ref3, ref4, ref5, space;
pretty = (options != null ? options.pretty : void 0) || false;
indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
level || (level = 0);
space = new Array(level + offset + 1).join(indent);
r = '';
ref3 = this.instructions;
for (i = 0, len = ref3.length; i < len; i++) {
instruction = ref3[i];
r += instruction.toString(options, level);
}
if (pretty) {
r += space;
}
r += '<' + this.name;
ref4 = this.attributes;
for (name in ref4) {
if (!hasProp.call(ref4, name)) continue;
att = ref4[name];
r += att.toString(options);
}
if (this.children.length === 0 || every(this.children, function(e) {
return e.value === '';
})) {
r += '/>';
if (pretty) {
r += newline;
}
} else if (pretty && this.children.length === 1 && (this.children[0].value != null)) {
r += '>';
r += this.children[0].value;
r += '</' + this.name + '>';
r += newline;
} else {
r += '>';
if (pretty) {
r += newline;
}
ref5 = this.children;
for (j = 0, len1 = ref5.length; j < len1; j++) {
child = ref5[j];
r += child.toString(options, level + 1);
}
if (pretty) {
r += space;
}
r += '</' + this.name + '>';
if (pretty) {
r += newline;
}
}
return r;
};
XMLElement.prototype.att = function(name, value) {
return this.attribute(name, value);
};
XMLElement.prototype.ins = function(target, value) {
return this.instruction(target, value);
};
XMLElement.prototype.a = function(name, value) {
return this.attribute(name, value);
};
XMLElement.prototype.i = function(target, value) {
return this.instruction(target, value);
};
return XMLElement;
})(XMLNode);
}).call(this);
},{"./XMLAttribute":157,"./XMLNode":168,"./XMLProcessingInstruction":169,"lodash/collection/every":175,"lodash/lang/isFunction":221,"lodash/lang/isObject":223,"lodash/object/create":227}],168:[function(require,module,exports){
// Generated by CoffeeScript 1.9.1
(function() {
var XMLCData, XMLComment, XMLDeclaration, XMLDocType, XMLElement, XMLNode, XMLRaw, XMLText, isEmpty, isFunction, isObject,
hasProp = {}.hasOwnProperty;
isObject = require('lodash/lang/isObject');
isFunction = require('lodash/lang/isFunction');
isEmpty = require('lodash/lang/isEmpty');
XMLElement = null;
XMLCData = null;
XMLComment = null;
XMLDeclaration = null;
XMLDocType = null;
XMLRaw = null;
XMLText = null;
module.exports = XMLNode = (function() {
function XMLNode(parent) {
this.parent = parent;
this.options = this.parent.options;
this.stringify = this.parent.stringify;
if (XMLElement === null) {
XMLElement = require('./XMLElement');
XMLCData = require('./XMLCData');
XMLComment = require('./XMLComment');
XMLDeclaration = require('./XMLDeclaration');
XMLDocType = require('./XMLDocType');
XMLRaw = require('./XMLRaw');
XMLText = require('./XMLText');
}
}
XMLNode.prototype.clone = function() {
throw new Error("Cannot clone generic XMLNode");
};
XMLNode.prototype.element = function(name, attributes, text) {
var item, j, key, lastChild, len, ref, val;
lastChild = null;
if (attributes == null) {
attributes = {};
}
attributes = attributes.valueOf();
if (!isObject(attributes)) {
ref = [attributes, text], text = ref[0], attributes = ref[1];
}
if (name != null) {
name = name.valueOf();
}
if (Array.isArray(name)) {
for (j = 0, len = name.length; j < len; j++) {
item = name[j];
lastChild = this.element(item);
}
} else if (isFunction(name)) {
lastChild = this.element(name.apply());
} else if (isObject(name)) {
for (key in name) {
if (!hasProp.call(name, key)) continue;
val = name[key];
if (isFunction(val)) {
val = val.apply();
}
if ((isObject(val)) && (isEmpty(val))) {
val = null;
}
if (!this.options.ignoreDecorators && this.stringify.convertAttKey && key.indexOf(this.stringify.convertAttKey) === 0) {
lastChild = this.attribute(key.substr(this.stringify.convertAttKey.length), val);
} else if (!this.options.ignoreDecorators && this.stringify.convertPIKey && key.indexOf(this.stringify.convertPIKey) === 0) {
lastChild = this.instruction(key.substr(this.stringify.convertPIKey.length), val);
} else if (isObject(val)) {
if (!this.options.ignoreDecorators && this.stringify.convertListKey && key.indexOf(this.stringify.convertListKey) === 0 && Array.isArray(val)) {
lastChild = this.element(val);
} else {
lastChild = this.element(key);
lastChild.element(val);
}
} else {
lastChild = this.element(key, val);
}
}
} else {
if (!this.options.ignoreDecorators && this.stringify.convertTextKey && name.indexOf(this.stringify.convertTextKey) === 0) {
lastChild = this.text(text);
} else if (!this.options.ignoreDecorators && this.stringify.convertCDataKey && name.indexOf(this.stringify.convertCDataKey) === 0) {
lastChild = this.cdata(text);
} else if (!this.options.ignoreDecorators && this.stringify.convertCommentKey && name.indexOf(this.stringify.convertCommentKey) === 0) {
lastChild = this.comment(text);
} else if (!this.options.ignoreDecorators && this.stringify.convertRawKey && name.indexOf(this.stringify.convertRawKey) === 0) {
lastChild = this.raw(text);
} else {
lastChild = this.node(name, attributes, text);
}
}
if (lastChild == null) {
throw new Error("Could not create any elements with: " + name);
}
return lastChild;
};
XMLNode.prototype.insertBefore = function(name, attributes, text) {
var child, i, removed;
if (this.isRoot) {
throw new Error("Cannot insert elements at root level");
}
i = this.parent.children.indexOf(this);
removed = this.parent.children.splice(i);
child = this.parent.element(name, attributes, text);
Array.prototype.push.apply(this.parent.children, removed);
return child;
};
XMLNode.prototype.insertAfter = function(name, attributes, text) {
var child, i, removed;
if (this.isRoot) {
throw new Error("Cannot insert elements at root level");
}
i = this.parent.children.indexOf(this);
removed = this.parent.children.splice(i + 1);
child = this.parent.element(name, attributes, text);
Array.prototype.push.apply(this.parent.children, removed);
return child;
};
XMLNode.prototype.remove = function() {
var i, ref;
if (this.isRoot) {
throw new Error("Cannot remove the root element");
}
i = this.parent.children.indexOf(this);
[].splice.apply(this.parent.children, [i, i - i + 1].concat(ref = [])), ref;
return this.parent;
};
XMLNode.prototype.node = function(name, attributes, text) {
var child, ref;
if (name != null) {
name = name.valueOf();
}
if (attributes == null) {
attributes = {};
}
attributes = attributes.valueOf();
if (!isObject(attributes)) {
ref = [attributes, text], text = ref[0], attributes = ref[1];
}
child = new XMLElement(this, name, attributes);
if (text != null) {
child.text(text);
}
this.children.push(child);
return child;
};
XMLNode.prototype.text = function(value) {
var child;
child = new XMLText(this, value);
this.children.push(child);
return this;
};
XMLNode.prototype.cdata = function(value) {
var child;
child = new XMLCData(this, value);
this.children.push(child);
return this;
};
XMLNode.prototype.comment = function(value) {
var child;
child = new XMLComment(this, value);
this.children.push(child);
return this;
};
XMLNode.prototype.raw = function(value) {
var child;
child = new XMLRaw(this, value);
this.children.push(child);
return this;
};
XMLNode.prototype.declaration = function(version, encoding, standalone) {
var doc, xmldec;
doc = this.document();
xmldec = new XMLDeclaration(doc, version, encoding, standalone);
doc.xmldec = xmldec;
return doc.root();
};
XMLNode.prototype.doctype = function(pubID, sysID) {
var doc, doctype;
doc = this.document();
doctype = new XMLDocType(doc, pubID, sysID);
doc.doctype = doctype;
return doctype;
};
XMLNode.prototype.up = function() {
if (this.isRoot) {
throw new Error("The root node has no parent. Use doc() if you need to get the document object.");
}
return this.parent;
};
XMLNode.prototype.root = function() {
var child;
if (this.isRoot) {
return this;
}
child = this.parent;
while (!child.isRoot) {
child = child.parent;
}
return child;
};
XMLNode.prototype.document = function() {
return this.root().documentObject;
};
XMLNode.prototype.end = function(options) {
return this.document().toString(options);
};
XMLNode.prototype.prev = function() {
var i;
if (this.isRoot) {
throw new Error("Root node has no siblings");
}
i = this.parent.children.indexOf(this);
if (i < 1) {
throw new Error("Already at the first node");
}
return this.parent.children[i - 1];
};
XMLNode.prototype.next = function() {
var i;
if (this.isRoot) {
throw new Error("Root node has no siblings");
}
i = this.parent.children.indexOf(this);
if (i === -1 || i === this.parent.children.length - 1) {
throw new Error("Already at the last node");
}
return this.parent.children[i + 1];
};
XMLNode.prototype.importXMLBuilder = function(xmlbuilder) {
var clonedRoot;
clonedRoot = xmlbuilder.root().clone();
clonedRoot.parent = this;
clonedRoot.isRoot = false;
this.children.push(clonedRoot);
return this;
};
XMLNode.prototype.ele = function(name, attributes, text) {
return this.element(name, attributes, text);
};
XMLNode.prototype.nod = function(name, attributes, text) {
return this.node(name, attributes, text);
};
XMLNode.prototype.txt = function(value) {
return this.text(value);
};
XMLNode.prototype.dat = function(value) {
return this.cdata(value);
};
XMLNode.prototype.com = function(value) {
return this.comment(value);
};
XMLNode.prototype.doc = function() {
return this.document();
};
XMLNode.prototype.dec = function(version, encoding, standalone) {
return this.declaration(version, encoding, standalone);
};
XMLNode.prototype.dtd = function(pubID, sysID) {
return this.doctype(pubID, sysID);
};
XMLNode.prototype.e = function(name, attributes, text) {
return this.element(name, attributes, text);
};
XMLNode.prototype.n = function(name, attributes, text) {
return this.node(name, attributes, text);
};
XMLNode.prototype.t = function(value) {
return this.text(value);
};
XMLNode.prototype.d = function(value) {
return this.cdata(value);
};
XMLNode.prototype.c = function(value) {
return this.comment(value);
};
XMLNode.prototype.r = function(value) {
return this.raw(value);
};
XMLNode.prototype.u = function() {
return this.up();
};
return XMLNode;
})();
}).call(this);
},{"./XMLCData":159,"./XMLComment":160,"./XMLDeclaration":165,"./XMLDocType":166,"./XMLElement":167,"./XMLRaw":170,"./XMLText":172,"lodash/lang/isEmpty":220,"lodash/lang/isFunction":221,"lodash/lang/isObject":223}],169:[function(require,module,exports){
// Generated by CoffeeScript 1.9.1
(function() {
var XMLProcessingInstruction, create;
create = require('lodash/object/create');
module.exports = XMLProcessingInstruction = (function() {
function XMLProcessingInstruction(parent, target, value) {
this.stringify = parent.stringify;
if (target == null) {
throw new Error("Missing instruction target");
}
this.target = this.stringify.insTarget(target);
if (value) {
this.value = this.stringify.insValue(value);
}
}
XMLProcessingInstruction.prototype.clone = function() {
return create(XMLProcessingInstruction.prototype, this);
};
XMLProcessingInstruction.prototype.toString = function(options, level) {
var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
pretty = (options != null ? options.pretty : void 0) || false;
indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
level || (level = 0);
space = new Array(level + offset + 1).join(indent);
r = '';
if (pretty) {
r += space;
}
r += '<?';
r += this.target;
if (this.value) {
r += ' ' + this.value;
}
r += '?>';
if (pretty) {
r += newline;
}
return r;
};
return XMLProcessingInstruction;
})();
}).call(this);
},{"lodash/object/create":227}],170:[function(require,module,exports){
// Generated by CoffeeScript 1.9.1
(function() {
var XMLNode, XMLRaw, create,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
create = require('lodash/object/create');
XMLNode = require('./XMLNode');
module.exports = XMLRaw = (function(superClass) {
extend(XMLRaw, superClass);
function XMLRaw(parent, text) {
XMLRaw.__super__.constructor.call(this, parent);
if (text == null) {
throw new Error("Missing raw text");
}
this.value = this.stringify.raw(text);
}
XMLRaw.prototype.clone = function() {
return create(XMLRaw.prototype, this);
};
XMLRaw.prototype.toString = function(options, level) {
var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
pretty = (options != null ? options.pretty : void 0) || false;
indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
level || (level = 0);
space = new Array(level + offset + 1).join(indent);
r = '';
if (pretty) {
r += space;
}
r += this.value;
if (pretty) {
r += newline;
}
return r;
};
return XMLRaw;
})(XMLNode);
}).call(this);
},{"./XMLNode":168,"lodash/object/create":227}],171:[function(require,module,exports){
// Generated by CoffeeScript 1.9.1
(function() {
var XMLStringifier,
bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
hasProp = {}.hasOwnProperty;
module.exports = XMLStringifier = (function() {
function XMLStringifier(options) {
this.assertLegalChar = bind(this.assertLegalChar, this);
var key, ref, value;
this.allowSurrogateChars = options != null ? options.allowSurrogateChars : void 0;
ref = (options != null ? options.stringify : void 0) || {};
for (key in ref) {
if (!hasProp.call(ref, key)) continue;
value = ref[key];
this[key] = value;
}
}
XMLStringifier.prototype.eleName = function(val) {
val = '' + val || '';
return this.assertLegalChar(val);
};
XMLStringifier.prototype.eleText = function(val) {
val = '' + val || '';
return this.assertLegalChar(this.elEscape(val));
};
XMLStringifier.prototype.cdata = function(val) {
val = '' + val || '';
if (val.match(/]]>/)) {
throw new Error("Invalid CDATA text: " + val);
}
return this.assertLegalChar(val);
};
XMLStringifier.prototype.comment = function(val) {
val = '' + val || '';
if (val.match(/--/)) {
throw new Error("Comment text cannot contain double-hypen: " + val);
}
return this.assertLegalChar(val);
};
XMLStringifier.prototype.raw = function(val) {
return '' + val || '';
};
XMLStringifier.prototype.attName = function(val) {
return '' + val || '';
};
XMLStringifier.prototype.attValue = function(val) {
val = '' + val || '';
return this.attEscape(val);
};
XMLStringifier.prototype.insTarget = function(val) {
return '' + val || '';
};
XMLStringifier.prototype.insValue = function(val) {
val = '' + val || '';
if (val.match(/\?>/)) {
throw new Error("Invalid processing instruction value: " + val);
}
return val;
};
XMLStringifier.prototype.xmlVersion = function(val) {
val = '' + val || '';
if (!val.match(/1\.[0-9]+/)) {
throw new Error("Invalid version number: " + val);
}
return val;
};
XMLStringifier.prototype.xmlEncoding = function(val) {
val = '' + val || '';
if (!val.match(/[A-Za-z](?:[A-Za-z0-9._-]|-)*/)) {
throw new Error("Invalid encoding: " + val);
}
return val;
};
XMLStringifier.prototype.xmlStandalone = function(val) {
if (val) {
return "yes";
} else {
return "no";
}
};
XMLStringifier.prototype.dtdPubID = function(val) {
return '' + val || '';
};
XMLStringifier.prototype.dtdSysID = function(val) {
return '' + val || '';
};
XMLStringifier.prototype.dtdElementValue = function(val) {
return '' + val || '';
};
XMLStringifier.prototype.dtdAttType = function(val) {
return '' + val || '';
};
XMLStringifier.prototype.dtdAttDefault = function(val) {
if (val != null) {
return '' + val || '';
} else {
return val;
}
};
XMLStringifier.prototype.dtdEntityValue = function(val) {
return '' + val || '';
};
XMLStringifier.prototype.dtdNData = function(val) {
return '' + val || '';
};
XMLStringifier.prototype.convertAttKey = '@';
XMLStringifier.prototype.convertPIKey = '?';
XMLStringifier.prototype.convertTextKey = '#text';
XMLStringifier.prototype.convertCDataKey = '#cdata';
XMLStringifier.prototype.convertCommentKey = '#comment';
XMLStringifier.prototype.convertRawKey = '#raw';
XMLStringifier.prototype.convertListKey = '#list';
XMLStringifier.prototype.assertLegalChar = function(str) {
var chars, chr;
if (this.allowSurrogateChars) {
chars = /[\u0000-\u0008\u000B-\u000C\u000E-\u001F\uFFFE-\uFFFF]/;
} else {
chars = /[\u0000-\u0008\u000B-\u000C\u000E-\u001F\uD800-\uDFFF\uFFFE-\uFFFF]/;
}
chr = str.match(chars);
if (chr) {
throw new Error("Invalid character (" + chr + ") in string: " + str + " at index " + chr.index);
}
return str;
};
XMLStringifier.prototype.elEscape = function(str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\r/g, '
');
};
XMLStringifier.prototype.attEscape = function(str) {
return str.replace(/&/g, '&').replace(/</g, '<').replace(/"/g, '"').replace(/\t/g, '	').replace(/\n/g, '
').replace(/\r/g, '
');
};
return XMLStringifier;
})();
}).call(this);
},{}],172:[function(require,module,exports){
// Generated by CoffeeScript 1.9.1
(function() {
var XMLNode, XMLText, create,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
create = require('lodash/object/create');
XMLNode = require('./XMLNode');
module.exports = XMLText = (function(superClass) {
extend(XMLText, superClass);
function XMLText(parent, text) {
XMLText.__super__.constructor.call(this, parent);
if (text == null) {
throw new Error("Missing element text");
}
this.value = this.stringify.eleText(text);
}
XMLText.prototype.clone = function() {
return create(XMLText.prototype, this);
};
XMLText.prototype.toString = function(options, level) {
var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
pretty = (options != null ? options.pretty : void 0) || false;
indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
level || (level = 0);
space = new Array(level + offset + 1).join(indent);
r = '';
if (pretty) {
r += space;
}
r += this.value;
if (pretty) {
r += newline;
}
return r;
};
return XMLText;
})(XMLNode);
}).call(this);
},{"./XMLNode":168,"lodash/object/create":227}],173:[function(require,module,exports){
// Generated by CoffeeScript 1.9.1
(function() {
var XMLBuilder, assign;
assign = require('lodash/object/assign');
XMLBuilder = require('./XMLBuilder');
module.exports.create = function(name, xmldec, doctype, options) {
options = assign({}, xmldec, doctype, options);
return new XMLBuilder(name, options).root();
};
}).call(this);
},{"./XMLBuilder":158,"lodash/object/assign":226}],174:[function(require,module,exports){
/**
* Gets the last element of `array`.
*
* @static
* @memberOf _
* @category Array
* @param {Array} array The array to query.
* @returns {*} Returns the last element of `array`.
* @example
*
* _.last([1, 2, 3]);
* // => 3
*/
function last(array) {
var length = array ? array.length : 0;
return length ? array[length - 1] : undefined;
}
module.exports = last;
},{}],175:[function(require,module,exports){
var arrayEvery = require('../internal/arrayEvery'),
baseCallback = require('../internal/baseCallback'),
baseEvery = require('../internal/baseEvery'),
isArray = require('../lang/isArray'),
isIterateeCall = require('../internal/isIterateeCall');
/**
* Checks if `predicate` returns truthy for **all** elements of `collection`.
* The predicate is bound to `thisArg` and invoked with three arguments:
* (value, index|key, collection).
*
* If a property name is provided for `predicate` the created `_.property`
* style callback returns the property value of the given element.
*
* If a value is also provided for `thisArg` the created `_.matchesProperty`
* style callback returns `true` for elements that have a matching property
* value, else `false`.
*
* If an object is provided for `predicate` the created `_.matches` style
* callback returns `true` for elements that have the properties of the given
* object, else `false`.
*
* @static
* @memberOf _
* @alias all
* @category Collection
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [predicate=_.identity] The function invoked
* per iteration.
* @param {*} [thisArg] The `this` binding of `predicate`.
* @returns {boolean} Returns `true` if all elements pass the predicate check,
* else `false`.
* @example
*
* _.every([true, 1, null, 'yes'], Boolean);
* // => false
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false }
* ];
*
* // using the `_.matches` callback shorthand
* _.every(users, { 'user': 'barney', 'active': false });
* // => false
*
* // using the `_.matchesProperty` callback shorthand
* _.every(users, 'active', false);
* // => true
*
* // using the `_.property` callback shorthand
* _.every(users, 'active');
* // => false
*/
function every(collection, predicate, thisArg) {
var func = isArray(collection) ? arrayEvery : baseEvery;
if (thisArg && isIterateeCall(collection, predicate, thisArg)) {
predicate = undefined;
}
if (typeof predicate != 'function' || thisArg !== undefined) {
predicate = baseCallback(predicate, thisArg, 3);
}
return func(collection, predicate);
}
module.exports = every;
},{"../internal/arrayEvery":177,"../internal/baseCallback":181,"../internal/baseEvery":185,"../internal/isIterateeCall":210,"../lang/isArray":219}],176:[function(require,module,exports){
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/* Native method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Creates a function that invokes `func` with the `this` binding of the
* created function and arguments from `start` and beyond provided as an array.
*
* **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/Web/JavaScript/Reference/Functions/rest_parameters).
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @returns {Function} Returns the new function.
* @example
*
* var say = _.restParam(function(what, names) {
* return what + ' ' + _.initial(names).join(', ') +
* (_.size(names) > 1 ? ', & ' : '') + _.last(names);
* });
*
* say('hello', 'fred', 'barney', 'pebbles');
* // => 'hello fred, barney, & pebbles'
*/
function restParam(func, start) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0);
return function() {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
rest = Array(length);
while (++index < length) {
rest[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, rest);
case 1: return func.call(this, args[0], rest);
case 2: return func.call(this, args[0], args[1], rest);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = rest;
return func.apply(this, otherArgs);
};
}
module.exports = restParam;
},{}],177:[function(require,module,exports){
/**
* A specialized version of `_.every` for arrays without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if all elements pass the predicate check,
* else `false`.
*/
function arrayEvery(array, predicate) {
var index = -1,
length = array.length;
while (++index < length) {
if (!predicate(array[index], index, array)) {
return false;
}
}
return true;
}
module.exports = arrayEvery;
},{}],178:[function(require,module,exports){
/**
* A specialized version of `_.some` for arrays without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
*/
function arraySome(array, predicate) {
var index = -1,
length = array.length;
while (++index < length) {
if (predicate(array[index], index, array)) {
return true;
}
}
return false;
}
module.exports = arraySome;
},{}],179:[function(require,module,exports){
var keys = require('../object/keys');
/**
* A specialized version of `_.assign` for customizing assigned values without
* support for argument juggling, multiple sources, and `this` binding `customizer`
* functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {Function} customizer The function to customize assigned values.
* @returns {Object} Returns `object`.
*/
function assignWith(object, source, customizer) {
var index = -1,
props = keys(source),
length = props.length;
while (++index < length) {
var key = props[index],
value = object[key],
result = customizer(value, source[key], key, object, source);
if ((result === result ? (result !== value) : (value === value)) ||
(value === undefined && !(key in object))) {
object[key] = result;
}
}
return object;
}
module.exports = assignWith;
},{"../object/keys":228}],180:[function(require,module,exports){
var baseCopy = require('./baseCopy'),
keys = require('../object/keys');
/**
* The base implementation of `_.assign` without support for argument juggling,
* multiple sources, and `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssign(object, source) {
return source == null
? object
: baseCopy(source, keys(source), object);
}
module.exports = baseAssign;
},{"../object/keys":228,"./baseCopy":182}],181:[function(require,module,exports){
var baseMatches = require('./baseMatches'),
baseMatchesProperty = require('./baseMatchesProperty'),
bindCallback = require('./bindCallback'),
identity = require('../utility/identity'),
property = require('../utility/property');
/**
* The base implementation of `_.callback` which supports specifying the
* number of arguments to provide to `func`.
*
* @private
* @param {*} [func=_.identity] The value to convert to a callback.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {number} [argCount] The number of arguments to provide to `func`.
* @returns {Function} Returns the callback.
*/
function baseCallback(func, thisArg, argCount) {
var type = typeof func;
if (type == 'function') {
return thisArg === undefined
? func
: bindCallback(func, thisArg, argCount);
}
if (func == null) {
return identity;
}
if (type == 'object') {
return baseMatches(func);
}
return thisArg === undefined
? property(func)
: baseMatchesProperty(func, thisArg);
}
module.exports = baseCallback;
},{"../utility/identity":231,"../utility/property":232,"./baseMatches":192,"./baseMatchesProperty":193,"./bindCallback":198}],182:[function(require,module,exports){
/**
* Copies properties of `source` to `object`.
*
* @private
* @param {Object} source The object to copy properties from.
* @param {Array} props The property names to copy.
* @param {Object} [object={}] The object to copy properties to.
* @returns {Object} Returns `object`.
*/
function baseCopy(source, props, object) {
object || (object = {});
var index = -1,
length = props.length;
while (++index < length) {
var key = props[index];
object[key] = source[key];
}
return object;
}
module.exports = baseCopy;
},{}],183:[function(require,module,exports){
var isObject = require('../lang/isObject');
/**
* The base implementation of `_.create` without support for assigning
* properties to the created object.
*
* @private
* @param {Object} prototype The object to inherit from.
* @returns {Object} Returns the new object.
*/
var baseCreate = (function() {
function object() {}
return function(prototype) {
if (isObject(prototype)) {
object.prototype = prototype;
var result = new object;
object.prototype = undefined;
}
return result || {};
};
}());
module.exports = baseCreate;
},{"../lang/isObject":223}],184:[function(require,module,exports){
var baseForOwn = require('./baseForOwn'),
createBaseEach = require('./createBaseEach');
/**
* The base implementation of `_.forEach` without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array|Object|string} Returns `collection`.
*/
var baseEach = createBaseEach(baseForOwn);
module.exports = baseEach;
},{"./baseForOwn":187,"./createBaseEach":200}],185:[function(require,module,exports){
var baseEach = require('./baseEach');
/**
* The base implementation of `_.every` without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if all elements pass the predicate check,
* else `false`
*/
function baseEvery(collection, predicate) {
var result = true;
baseEach(collection, function(value, index, collection) {
result = !!predicate(value, index, collection);
return result;
});
return result;
}
module.exports = baseEvery;
},{"./baseEach":184}],186:[function(require,module,exports){
var createBaseFor = require('./createBaseFor');
/**
* The base implementation of `baseForIn` and `baseForOwn` which iterates
* over `object` properties returned by `keysFunc` invoking `iteratee` for
* each property. Iteratee functions may exit iteration early by explicitly
* returning `false`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {Function} keysFunc The function to get the keys of `object`.
* @returns {Object} Returns `object`.
*/
var baseFor = createBaseFor();
module.exports = baseFor;
},{"./createBaseFor":201}],187:[function(require,module,exports){
var baseFor = require('./baseFor'),
keys = require('../object/keys');
/**
* The base implementation of `_.forOwn` without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function baseForOwn(object, iteratee) {
return baseFor(object, iteratee, keys);
}
module.exports = baseForOwn;
},{"../object/keys":228,"./baseFor":186}],188:[function(require,module,exports){
var toObject = require('./toObject');
/**
* The base implementation of `get` without support for string paths
* and default values.
*
* @private
* @param {Object} object The object to query.
* @param {Array} path The path of the property to get.
* @param {string} [pathKey] The key representation of path.
* @returns {*} Returns the resolved value.
*/
function baseGet(object, path, pathKey) {
if (object == null) {
return;
}
if (pathKey !== undefined && pathKey in toObject(object)) {
path = [pathKey];
}
var index = 0,
length = path.length;
while (object != null && index < length) {
object = object[path[index++]];
}
return (index && index == length) ? object : undefined;
}
module.exports = baseGet;
},{"./toObject":216}],189:[function(require,module,exports){
var baseIsEqualDeep = require('./baseIsEqualDeep'),
isObject = require('../lang/isObject'),
isObjectLike = require('./isObjectLike');
/**
* The base implementation of `_.isEqual` without support for `this` binding
* `customizer` functions.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {Function} [customizer] The function to customize comparing values.
* @param {boolean} [isLoose] Specify performing partial comparisons.
* @param {Array} [stackA] Tracks traversed `value` objects.
* @param {Array} [stackB] Tracks traversed `other` objects.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
*/
function baseIsEqual(value, other, customizer, isLoose, stackA, stackB) {
if (value === other) {
return true;
}
if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) {
return value !== value && other !== other;
}
return baseIsEqualDeep(value, other, baseIsEqual, customizer, isLoose, stackA, stackB);
}
module.exports = baseIsEqual;
},{"../lang/isObject":223,"./baseIsEqualDeep":190,"./isObjectLike":213}],190:[function(require,module,exports){
var equalArrays = require('./equalArrays'),
equalByTag = require('./equalByTag'),
equalObjects = require('./equalObjects'),
isArray = require('../lang/isArray'),
isTypedArray = require('../lang/isTypedArray');
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
objectTag = '[object Object]';
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/**
* A specialized version of `baseIsEqual` for arrays and objects which performs
* deep comparisons and tracks traversed objects enabling objects with circular
* references to be compared.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Function} [customizer] The function to customize comparing objects.
* @param {boolean} [isLoose] Specify performing partial comparisons.
* @param {Array} [stackA=[]] Tracks traversed `value` objects.
* @param {Array} [stackB=[]] Tracks traversed `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function baseIsEqualDeep(object, other, equalFunc, customizer, isLoose, stackA, stackB) {
var objIsArr = isArray(object),
othIsArr = isArray(other),
objTag = arrayTag,
othTag = arrayTag;
if (!objIsArr) {
objTag = objToString.call(object);
if (objTag == argsTag) {
objTag = objectTag;
} else if (objTag != objectTag) {
objIsArr = isTypedArray(object);
}
}
if (!othIsArr) {
othTag = objToString.call(other);
if (othTag == argsTag) {
othTag = objectTag;
} else if (othTag != objectTag) {
othIsArr = isTypedArray(other);
}
}
var objIsObj = objTag == objectTag,
othIsObj = othTag == objectTag,
isSameTag = objTag == othTag;
if (isSameTag && !(objIsArr || objIsObj)) {
return equalByTag(object, other, objTag);
}
if (!isLoose) {
var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
if (objIsWrapped || othIsWrapped) {
return equalFunc(objIsWrapped ? object.value() : object, othIsWrapped ? other.value() : other, customizer, isLoose, stackA, stackB);
}
}
if (!isSameTag) {
return false;
}
// Assume cyclic values are equal.
// For more information on detecting circular references see https://es5.github.io/#JO.
stackA || (stackA = []);
stackB || (stackB = []);
var length = stackA.length;
while (length--) {
if (stackA[length] == object) {
return stackB[length] == other;
}
}
// Add `object` and `other` to the stack of traversed objects.
stackA.push(object);
stackB.push(other);
var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, customizer, isLoose, stackA, stackB);
stackA.pop();
stackB.pop();
return result;
}
module.exports = baseIsEqualDeep;
},{"../lang/isArray":219,"../lang/isTypedArray":225,"./equalArrays":202,"./equalByTag":203,"./equalObjects":204}],191:[function(require,module,exports){
var baseIsEqual = require('./baseIsEqual'),
toObject = require('./toObject');
/**
* The base implementation of `_.isMatch` without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Object} object The object to inspect.
* @param {Array} matchData The propery names, values, and compare flags to match.
* @param {Function} [customizer] The function to customize comparing objects.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
*/
function baseIsMatch(object, matchData, customizer) {
var index = matchData.length,
length = index,
noCustomizer = !customizer;
if (object == null) {
return !length;
}
object = toObject(object);
while (index--) {
var data = matchData[index];
if ((noCustomizer && data[2])
? data[1] !== object[data[0]]
: !(data[0] in object)
) {
return false;
}
}
while (++index < length) {
data = matchData[index];
var key = data[0],
objValue = object[key],
srcValue = data[1];
if (noCustomizer && data[2]) {
if (objValue === undefined && !(key in object)) {
return false;
}
} else {
var result = customizer ? customizer(objValue, srcValue, key) : undefined;
if (!(result === undefined ? baseIsEqual(srcValue, objValue, customizer, true) : result)) {
return false;
}
}
}
return true;
}
module.exports = baseIsMatch;
},{"./baseIsEqual":189,"./toObject":216}],192:[function(require,module,exports){
var baseIsMatch = require('./baseIsMatch'),
getMatchData = require('./getMatchData'),
toObject = require('./toObject');
/**
* The base implementation of `_.matches` which does not clone `source`.
*
* @private
* @param {Object} source The object of property values to match.
* @returns {Function} Returns the new function.
*/
function baseMatches(source) {
var matchData = getMatchData(source);
if (matchData.length == 1 && matchData[0][2]) {
var key = matchData[0][0],
value = matchData[0][1];
return function(object) {
if (object == null) {
return false;
}
return object[key] === value && (value !== undefined || (key in toObject(object)));
};
}
return function(object) {
return baseIsMatch(object, matchData);
};
}
module.exports = baseMatches;
},{"./baseIsMatch":191,"./getMatchData":206,"./toObject":216}],193:[function(require,module,exports){
var baseGet = require('./baseGet'),
baseIsEqual = require('./baseIsEqual'),
baseSlice = require('./baseSlice'),
isArray = require('../lang/isArray'),
isKey = require('./isKey'),
isStrictComparable = require('./isStrictComparable'),
last = require('../array/last'),
toObject = require('./toObject'),
toPath = require('./toPath');
/**
* The base implementation of `_.matchesProperty` which does not clone `srcValue`.
*
* @private
* @param {string} path The path of the property to get.
* @param {*} srcValue The value to compare.
* @returns {Function} Returns the new function.
*/
function baseMatchesProperty(path, srcValue) {
var isArr = isArray(path),
isCommon = isKey(path) && isStrictComparable(srcValue),
pathKey = (path + '');
path = toPath(path);
return function(object) {
if (object == null) {
return false;
}
var key = pathKey;
object = toObject(object);
if ((isArr || !isCommon) && !(key in object)) {
object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1));
if (object == null) {
return false;
}
key = last(path);
object = toObject(object);
}
return object[key] === srcValue
? (srcValue !== undefined || (key in object))
: baseIsEqual(srcValue, object[key], undefined, true);
};
}
module.exports = baseMatchesProperty;
},{"../array/last":174,"../lang/isArray":219,"./baseGet":188,"./baseIsEqual":189,"./baseSlice":196,"./isKey":211,"./isStrictComparable":214,"./toObject":216,"./toPath":217}],194:[function(require,module,exports){
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
module.exports = baseProperty;
},{}],195:[function(require,module,exports){
var baseGet = require('./baseGet'),
toPath = require('./toPath');
/**
* A specialized version of `baseProperty` which supports deep paths.
*
* @private
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new function.
*/
function basePropertyDeep(path) {
var pathKey = (path + '');
path = toPath(path);
return function(object) {
return baseGet(object, path, pathKey);
};
}
module.exports = basePropertyDeep;
},{"./baseGet":188,"./toPath":217}],196:[function(require,module,exports){
/**
* The base implementation of `_.slice` without an iteratee call guard.
*
* @private
* @param {Array} array The array to slice.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the slice of `array`.
*/
function baseSlice(array, start, end) {
var index = -1,
length = array.length;
start = start == null ? 0 : (+start || 0);
if (start < 0) {
start = -start > length ? 0 : (length + start);
}
end = (end === undefined || end > length) ? length : (+end || 0);
if (end < 0) {
end += length;
}
length = start > end ? 0 : ((end - start) >>> 0);
start >>>= 0;
var result = Array(length);
while (++index < length) {
result[index] = array[index + start];
}
return result;
}
module.exports = baseSlice;
},{}],197:[function(require,module,exports){
/**
* Converts `value` to a string if it's not one. An empty string is returned
* for `null` or `undefined` values.
*
* @private
* @param {*} value The value to process.
* @returns {string} Returns the string.
*/
function baseToString(value) {
return value == null ? '' : (value + '');
}
module.exports = baseToString;
},{}],198:[function(require,module,exports){
var identity = require('../utility/identity');
/**
* A specialized version of `baseCallback` which only supports `this` binding
* and specifying the number of arguments to provide to `func`.
*
* @private
* @param {Function} func The function to bind.
* @param {*} thisArg The `this` binding of `func`.
* @param {number} [argCount] The number of arguments to provide to `func`.
* @returns {Function} Returns the callback.
*/
function bindCallback(func, thisArg, argCount) {
if (typeof func != 'function') {
return identity;
}
if (thisArg === undefined) {
return func;
}
switch (argCount) {
case 1: return function(value) {
return func.call(thisArg, value);
};
case 3: return function(value, index, collection) {
return func.call(thisArg, value, index, collection);
};
case 4: return function(accumulator, value, index, collection) {
return func.call(thisArg, accumulator, value, index, collection);
};
case 5: return function(value, other, key, object, source) {
return func.call(thisArg, value, other, key, object, source);
};
}
return function() {
return func.apply(thisArg, arguments);
};
}
module.exports = bindCallback;
},{"../utility/identity":231}],199:[function(require,module,exports){
var bindCallback = require('./bindCallback'),
isIterateeCall = require('./isIterateeCall'),
restParam = require('../function/restParam');
/**
* Creates a `_.assign`, `_.defaults`, or `_.merge` function.
*
* @private
* @param {Function} assigner The function to assign values.
* @returns {Function} Returns the new assigner function.
*/
function createAssigner(assigner) {
return restParam(function(object, sources) {
var index = -1,
length = object == null ? 0 : sources.length,
customizer = length > 2 ? sources[length - 2] : undefined,
guard = length > 2 ? sources[2] : undefined,
thisArg = length > 1 ? sources[length - 1] : undefined;
if (typeof customizer == 'function') {
customizer = bindCallback(customizer, thisArg, 5);
length -= 2;
} else {
customizer = typeof thisArg == 'function' ? thisArg : undefined;
length -= (customizer ? 1 : 0);
}
if (guard && isIterateeCall(sources[0], sources[1], guard)) {
customizer = length < 3 ? undefined : customizer;
length = 1;
}
while (++index < length) {
var source = sources[index];
if (source) {
assigner(object, source, customizer);
}
}
return object;
});
}
module.exports = createAssigner;
},{"../function/restParam":176,"./bindCallback":198,"./isIterateeCall":210}],200:[function(require,module,exports){
var getLength = require('./getLength'),
isLength = require('./isLength'),
toObject = require('./toObject');
/**
* Creates a `baseEach` or `baseEachRight` function.
*
* @private
* @param {Function} eachFunc The function to iterate over a collection.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseEach(eachFunc, fromRight) {
return function(collection, iteratee) {
var length = collection ? getLength(collection) : 0;
if (!isLength(length)) {
return eachFunc(collection, iteratee);
}
var index = fromRight ? length : -1,
iterable = toObject(collection);
while ((fromRight ? index-- : ++index < length)) {
if (iteratee(iterable[index], index, iterable) === false) {
break;
}
}
return collection;
};
}
module.exports = createBaseEach;
},{"./getLength":205,"./isLength":212,"./toObject":216}],201:[function(require,module,exports){
var toObject = require('./toObject');
/**
* Creates a base function for `_.forIn` or `_.forInRight`.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseFor(fromRight) {
return function(object, iteratee, keysFunc) {
var iterable = toObject(object),
props = keysFunc(object),
length = props.length,
index = fromRight ? length : -1;
while ((fromRight ? index-- : ++index < length)) {
var key = props[index];
if (iteratee(iterable[key], key, iterable) === false) {
break;
}
}
return object;
};
}
module.exports = createBaseFor;
},{"./toObject":216}],202:[function(require,module,exports){
var arraySome = require('./arraySome');
/**
* A specialized version of `baseIsEqualDeep` for arrays with support for
* partial deep comparisons.
*
* @private
* @param {Array} array The array to compare.
* @param {Array} other The other array to compare.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Function} [customizer] The function to customize comparing arrays.
* @param {boolean} [isLoose] Specify performing partial comparisons.
* @param {Array} [stackA] Tracks traversed `value` objects.
* @param {Array} [stackB] Tracks traversed `other` objects.
* @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
*/
function equalArrays(array, other, equalFunc, customizer, isLoose, stackA, stackB) {
var index = -1,
arrLength = array.length,
othLength = other.length;
if (arrLength != othLength && !(isLoose && othLength > arrLength)) {
return false;
}
// Ignore non-index properties.
while (++index < arrLength) {
var arrValue = array[index],
othValue = other[index],
result = customizer ? customizer(isLoose ? othValue : arrValue, isLoose ? arrValue : othValue, index) : undefined;
if (result !== undefined) {
if (result) {
continue;
}
return false;
}
// Recursively compare arrays (susceptible to call stack limits).
if (isLoose) {
if (!arraySome(other, function(othValue) {
return arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB);
})) {
return false;
}
} else if (!(arrValue === othValue || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB))) {
return false;
}
}
return true;
}
module.exports = equalArrays;
},{"./arraySome":178}],203:[function(require,module,exports){
/** `Object#toString` result references. */
var boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
numberTag = '[object Number]',
regexpTag = '[object RegExp]',
stringTag = '[object String]';
/**
* A specialized version of `baseIsEqualDeep` for comparing objects of
* the same `toStringTag`.
*
* **Note:** This function only supports comparing values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {string} tag The `toStringTag` of the objects to compare.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalByTag(object, other, tag) {
switch (tag) {
case boolTag:
case dateTag:
// Coerce dates and booleans to numbers, dates to milliseconds and booleans
// to `1` or `0` treating invalid dates coerced to `NaN` as not equal.
return +object == +other;
case errorTag:
return object.name == other.name && object.message == other.message;
case numberTag:
// Treat `NaN` vs. `NaN` as equal.
return (object != +object)
? other != +other
: object == +other;
case regexpTag:
case stringTag:
// Coerce regexes to strings and treat strings primitives and string
// objects as equal. See https://es5.github.io/#x15.10.6.4 for more details.
return object == (other + '');
}
return false;
}
module.exports = equalByTag;
},{}],204:[function(require,module,exports){
var keys = require('../object/keys');
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* A specialized version of `baseIsEqualDeep` for objects with support for
* partial deep comparisons.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Function} [customizer] The function to customize comparing values.
* @param {boolean} [isLoose] Specify performing partial comparisons.
* @param {Array} [stackA] Tracks traversed `value` objects.
* @param {Array} [stackB] Tracks traversed `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function equalObjects(object, other, equalFunc, customizer, isLoose, stackA, stackB) {
var objProps = keys(object),
objLength = objProps.length,
othProps = keys(other),
othLength = othProps.length;
if (objLength != othLength && !isLoose) {
return false;
}
var index = objLength;
while (index--) {
var key = objProps[index];
if (!(isLoose ? key in other : hasOwnProperty.call(other, key))) {
return false;
}
}
var skipCtor = isLoose;
while (++index < objLength) {
key = objProps[index];
var objValue = object[key],
othValue = other[key],
result = customizer ? customizer(isLoose ? othValue : objValue, isLoose? objValue : othValue, key) : undefined;
// Recursively compare objects (susceptible to call stack limits).
if (!(result === undefined ? equalFunc(objValue, othValue, customizer, isLoose, stackA, stackB) : result)) {
return false;
}
skipCtor || (skipCtor = key == 'constructor');
}
if (!skipCtor) {
var objCtor = object.constructor,
othCtor = other.constructor;
// Non `Object` object instances with different constructors are not equal.
if (objCtor != othCtor &&
('constructor' in object && 'constructor' in other) &&
!(typeof objCtor == 'function' && objCtor instanceof objCtor &&
typeof othCtor == 'function' && othCtor instanceof othCtor)) {
return false;
}
}
return true;
}
module.exports = equalObjects;
},{"../object/keys":228}],205:[function(require,module,exports){
var baseProperty = require('./baseProperty');
/**
* Gets the "length" property value of `object`.
*
* **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
* that affects Safari on at least iOS 8.1-8.3 ARM64.
*
* @private
* @param {Object} object The object to query.
* @returns {*} Returns the "length" value.
*/
var getLength = baseProperty('length');
module.exports = getLength;
},{"./baseProperty":194}],206:[function(require,module,exports){
var isStrictComparable = require('./isStrictComparable'),
pairs = require('../object/pairs');
/**
* Gets the propery names, values, and compare flags of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the match data of `object`.
*/
function getMatchData(object) {
var result = pairs(object),
length = result.length;
while (length--) {
result[length][2] = isStrictComparable(result[length][1]);
}
return result;
}
module.exports = getMatchData;
},{"../object/pairs":230,"./isStrictComparable":214}],207:[function(require,module,exports){
var isNative = require('../lang/isNative');
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = object == null ? undefined : object[key];
return isNative(value) ? value : undefined;
}
module.exports = getNative;
},{"../lang/isNative":222}],208:[function(require,module,exports){
var getLength = require('./getLength'),
isLength = require('./isLength');
/**
* Checks if `value` is array-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
*/
function isArrayLike(value) {
return value != null && isLength(getLength(value));
}
module.exports = isArrayLike;
},{"./getLength":205,"./isLength":212}],209:[function(require,module,exports){
/** Used to detect unsigned integer values. */
var reIsUint = /^\d+$/;
/**
* Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer)
* of an array-like value.
*/
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
length = length == null ? MAX_SAFE_INTEGER : length;
return value > -1 && value % 1 == 0 && value < length;
}
module.exports = isIndex;
},{}],210:[function(require,module,exports){
var isArrayLike = require('./isArrayLike'),
isIndex = require('./isIndex'),
isObject = require('../lang/isObject');
/**
* Checks if the provided arguments are from an iteratee call.
*
* @private
* @param {*} value The potential iteratee value argument.
* @param {*} index The potential iteratee index or key argument.
* @param {*} object The potential iteratee object argument.
* @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`.
*/
function isIterateeCall(value, index, object) {
if (!isObject(object)) {
return false;
}
var type = typeof index;
if (type == 'number'
? (isArrayLike(object) && isIndex(index, object.length))
: (type == 'string' && index in object)) {
var other = object[index];
return value === value ? (value === other) : (other !== other);
}
return false;
}
module.exports = isIterateeCall;
},{"../lang/isObject":223,"./isArrayLike":208,"./isIndex":209}],211:[function(require,module,exports){
var isArray = require('../lang/isArray'),
toObject = require('./toObject');
/** Used to match property names within property paths. */
var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\n\\]|\\.)*?\1)\]/,
reIsPlainProp = /^\w*$/;
/**
* Checks if `value` is a property name and not a property path.
*
* @private
* @param {*} value The value to check.
* @param {Object} [object] The object to query keys on.
* @returns {boolean} Returns `true` if `value` is a property name, else `false`.
*/
function isKey(value, object) {
var type = typeof value;
if ((type == 'string' && reIsPlainProp.test(value)) || type == 'number') {
return true;
}
if (isArray(value)) {
return false;
}
var result = !reIsDeepProp.test(value);
return result || (object != null && value in toObject(object));
}
module.exports = isKey;
},{"../lang/isArray":219,"./toObject":216}],212:[function(require,module,exports){
/**
* Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer)
* of an array-like value.
*/
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
*/
function isLength(value) {
return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
module.exports = isLength;
},{}],213:[function(require,module,exports){
/**
* Checks if `value` is object-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
module.exports = isObjectLike;
},{}],214:[function(require,module,exports){
var isObject = require('../lang/isObject');
/**
* Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` if suitable for strict
* equality comparisons, else `false`.
*/
function isStrictComparable(value) {
return value === value && !isObject(value);
}
module.exports = isStrictComparable;
},{"../lang/isObject":223}],215:[function(require,module,exports){
var isArguments = require('../lang/isArguments'),
isArray = require('../lang/isArray'),
isIndex = require('./isIndex'),
isLength = require('./isLength'),
keysIn = require('../object/keysIn');
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* A fallback implementation of `Object.keys` which creates an array of the
* own enumerable property names of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function shimKeys(object) {
var props = keysIn(object),
propsLength = props.length,
length = propsLength && object.length;
var allowIndexes = !!length && isLength(length) &&
(isArray(object) || isArguments(object));
var index = -1,
result = [];
while (++index < propsLength) {
var key = props[index];
if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) {
result.push(key);
}
}
return result;
}
module.exports = shimKeys;
},{"../lang/isArguments":218,"../lang/isArray":219,"../object/keysIn":229,"./isIndex":209,"./isLength":212}],216:[function(require,module,exports){
var isObject = require('../lang/isObject');
/**
* Converts `value` to an object if it's not one.
*
* @private
* @param {*} value The value to process.
* @returns {Object} Returns the object.
*/
function toObject(value) {
return isObject(value) ? value : Object(value);
}
module.exports = toObject;
},{"../lang/isObject":223}],217:[function(require,module,exports){
var baseToString = require('./baseToString'),
isArray = require('../lang/isArray');
/** Used to match property names within property paths. */
var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g;
/** Used to match backslashes in property paths. */
var reEscapeChar = /\\(\\)?/g;
/**
* Converts `value` to property path array if it's not one.
*
* @private
* @param {*} value The value to process.
* @returns {Array} Returns the property path array.
*/
function toPath(value) {
if (isArray(value)) {
return value;
}
var result = [];
baseToString(value).replace(rePropName, function(match, number, quote, string) {
result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match));
});
return result;
}
module.exports = toPath;
},{"../lang/isArray":219,"./baseToString":197}],218:[function(require,module,exports){
var isArrayLike = require('../internal/isArrayLike'),
isObjectLike = require('../internal/isObjectLike');
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Native method references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable;
/**
* Checks if `value` is classified as an `arguments` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
function isArguments(value) {
return isObjectLike(value) && isArrayLike(value) &&
hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee');
}
module.exports = isArguments;
},{"../internal/isArrayLike":208,"../internal/isObjectLike":213}],219:[function(require,module,exports){
var getNative = require('../internal/getNative'),
isLength = require('../internal/isLength'),
isObjectLike = require('../internal/isObjectLike');
/** `Object#toString` result references. */
var arrayTag = '[object Array]';
/** Used for native method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/* Native method references for those with the same name as other `lodash` methods. */
var nativeIsArray = getNative(Array, 'isArray');
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(function() { return arguments; }());
* // => false
*/
var isArray = nativeIsArray || function(value) {
return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag;
};
module.exports = isArray;
},{"../internal/getNative":207,"../internal/isLength":212,"../internal/isObjectLike":213}],220:[function(require,module,exports){
var isArguments = require('./isArguments'),
isArray = require('./isArray'),
isArrayLike = require('../internal/isArrayLike'),
isFunction = require('./isFunction'),
isObjectLike = require('../internal/isObjectLike'),
isString = require('./isString'),
keys = require('../object/keys');
/**
* Checks if `value` is empty. A value is considered empty unless it's an
* `arguments` object, array, string, or jQuery-like collection with a length
* greater than `0` or an object with own enumerable properties.
*
* @static
* @memberOf _
* @category Lang
* @param {Array|Object|string} value The value to inspect.
* @returns {boolean} Returns `true` if `value` is empty, else `false`.
* @example
*
* _.isEmpty(null);
* // => true
*
* _.isEmpty(true);
* // => true
*
* _.isEmpty(1);
* // => true
*
* _.isEmpty([1, 2, 3]);
* // => false
*
* _.isEmpty({ 'a': 1 });
* // => false
*/
function isEmpty(value) {
if (value == null) {
return true;
}
if (isArrayLike(value) && (isArray(value) || isString(value) || isArguments(value) ||
(isObjectLike(value) && isFunction(value.splice)))) {
return !value.length;
}
return !keys(value).length;
}
module.exports = isEmpty;
},{"../internal/isArrayLike":208,"../internal/isObjectLike":213,"../object/keys":228,"./isArguments":218,"./isArray":219,"./isFunction":221,"./isString":224}],221:[function(require,module,exports){
var isObject = require('./isObject');
/** `Object#toString` result references. */
var funcTag = '[object Function]';
/** Used for native method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
// The use of `Object#toString` avoids issues with the `typeof` operator
// in older versions of Chrome and Safari which return 'function' for regexes
// and Safari 8 which returns 'object' for typed array constructors.
return isObject(value) && objToString.call(value) == funcTag;
}
module.exports = isFunction;
},{"./isObject":223}],222:[function(require,module,exports){
var isFunction = require('./isFunction'),
isObjectLike = require('../internal/isObjectLike');
/** Used to detect host constructors (Safari > 5). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var fnToString = Function.prototype.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/**
* Checks if `value` is a native function.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function, else `false`.
* @example
*
* _.isNative(Array.prototype.push);
* // => true
*
* _.isNative(_);
* // => false
*/
function isNative(value) {
if (value == null) {
return false;
}
if (isFunction(value)) {
return reIsNative.test(fnToString.call(value));
}
return isObjectLike(value) && reIsHostCtor.test(value);
}
module.exports = isNative;
},{"../internal/isObjectLike":213,"./isFunction":221}],223:[function(require,module,exports){
/**
* Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// Avoid a V8 JIT bug in Chrome 19-20.
// See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
module.exports = isObject;
},{}],224:[function(require,module,exports){
var isObjectLike = require('../internal/isObjectLike');
/** `Object#toString` result references. */
var stringTag = '[object String]';
/** Used for native method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/**
* Checks if `value` is classified as a `String` primitive or object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isString('abc');
* // => true
*
* _.isString(1);
* // => false
*/
function isString(value) {
return typeof value == 'string' || (isObjectLike(value) && objToString.call(value) == stringTag);
}
module.exports = isString;
},{"../internal/isObjectLike":213}],225:[function(require,module,exports){
var isLength = require('../internal/isLength'),
isObjectLike = require('../internal/isObjectLike');
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag = '[object Object]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
typedArrayTags[dateTag] = typedArrayTags[errorTag] =
typedArrayTags[funcTag] = typedArrayTags[mapTag] =
typedArrayTags[numberTag] = typedArrayTags[objectTag] =
typedArrayTags[regexpTag] = typedArrayTags[setTag] =
typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
/** Used for native method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/**
* Checks if `value` is classified as a typed array.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isTypedArray(new Uint8Array);
* // => true
*
* _.isTypedArray([]);
* // => false
*/
function isTypedArray(value) {
return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)];
}
module.exports = isTypedArray;
},{"../internal/isLength":212,"../internal/isObjectLike":213}],226:[function(require,module,exports){
var assignWith = require('../internal/assignWith'),
baseAssign = require('../internal/baseAssign'),
createAssigner = require('../internal/createAssigner');
/**
* Assigns own enumerable properties of source object(s) to the destination
* object. Subsequent sources overwrite property assignments of previous sources.
* If `customizer` is provided it's invoked to produce the assigned values.
* The `customizer` is bound to `thisArg` and invoked with five arguments:
* (objectValue, sourceValue, key, object, source).
*
* **Note:** This method mutates `object` and is based on
* [`Object.assign`](http://ecma-international.org/ecma-262/6.0/#sec-object.assign).
*
* @static
* @memberOf _
* @alias extend
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @param {Function} [customizer] The function to customize assigned values.
* @param {*} [thisArg] The `this` binding of `customizer`.
* @returns {Object} Returns `object`.
* @example
*
* _.assign({ 'user': 'barney' }, { 'age': 40 }, { 'user': 'fred' });
* // => { 'user': 'fred', 'age': 40 }
*
* // using a customizer callback
* var defaults = _.partialRight(_.assign, function(value, other) {
* return _.isUndefined(value) ? other : value;
* });
*
* defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });
* // => { 'user': 'barney', 'age': 36 }
*/
var assign = createAssigner(function(object, source, customizer) {
return customizer
? assignWith(object, source, customizer)
: baseAssign(object, source);
});
module.exports = assign;
},{"../internal/assignWith":179,"../internal/baseAssign":180,"../internal/createAssigner":199}],227:[function(require,module,exports){
var baseAssign = require('../internal/baseAssign'),
baseCreate = require('../internal/baseCreate'),
isIterateeCall = require('../internal/isIterateeCall');
/**
* Creates an object that inherits from the given `prototype` object. If a
* `properties` object is provided its own enumerable properties are assigned
* to the created object.
*
* @static
* @memberOf _
* @category Object
* @param {Object} prototype The object to inherit from.
* @param {Object} [properties] The properties to assign to the object.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {Object} Returns the new object.
* @example
*
* function Shape() {
* this.x = 0;
* this.y = 0;
* }
*
* function Circle() {
* Shape.call(this);
* }
*
* Circle.prototype = _.create(Shape.prototype, {
* 'constructor': Circle
* });
*
* var circle = new Circle;
* circle instanceof Circle;
* // => true
*
* circle instanceof Shape;
* // => true
*/
function create(prototype, properties, guard) {
var result = baseCreate(prototype);
if (guard && isIterateeCall(prototype, properties, guard)) {
properties = undefined;
}
return properties ? baseAssign(result, properties) : result;
}
module.exports = create;
},{"../internal/baseAssign":180,"../internal/baseCreate":183,"../internal/isIterateeCall":210}],228:[function(require,module,exports){
var getNative = require('../internal/getNative'),
isArrayLike = require('../internal/isArrayLike'),
isObject = require('../lang/isObject'),
shimKeys = require('../internal/shimKeys');
/* Native method references for those with the same name as other `lodash` methods. */
var nativeKeys = getNative(Object, 'keys');
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys)
* for more details.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
var keys = !nativeKeys ? shimKeys : function(object) {
var Ctor = object == null ? undefined : object.constructor;
if ((typeof Ctor == 'function' && Ctor.prototype === object) ||
(typeof object != 'function' && isArrayLike(object))) {
return shimKeys(object);
}
return isObject(object) ? nativeKeys(object) : [];
};
module.exports = keys;
},{"../internal/getNative":207,"../internal/isArrayLike":208,"../internal/shimKeys":215,"../lang/isObject":223}],229:[function(require,module,exports){
var isArguments = require('../lang/isArguments'),
isArray = require('../lang/isArray'),
isIndex = require('../internal/isIndex'),
isLength = require('../internal/isLength'),
isObject = require('../lang/isObject');
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Creates an array of the own and inherited enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keysIn(new Foo);
* // => ['a', 'b', 'c'] (iteration order is not guaranteed)
*/
function keysIn(object) {
if (object == null) {
return [];
}
if (!isObject(object)) {
object = Object(object);
}
var length = object.length;
length = (length && isLength(length) &&
(isArray(object) || isArguments(object)) && length) || 0;
var Ctor = object.constructor,
index = -1,
isProto = typeof Ctor == 'function' && Ctor.prototype === object,
result = Array(length),
skipIndexes = length > 0;
while (++index < length) {
result[index] = (index + '');
}
for (var key in object) {
if (!(skipIndexes && isIndex(key, length)) &&
!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
result.push(key);
}
}
return result;
}
module.exports = keysIn;
},{"../internal/isIndex":209,"../internal/isLength":212,"../lang/isArguments":218,"../lang/isArray":219,"../lang/isObject":223}],230:[function(require,module,exports){
var keys = require('./keys'),
toObject = require('../internal/toObject');
/**
* Creates a two dimensional array of the key-value pairs for `object`,
* e.g. `[[key1, value1], [key2, value2]]`.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the new array of key-value pairs.
* @example
*
* _.pairs({ 'barney': 36, 'fred': 40 });
* // => [['barney', 36], ['fred', 40]] (iteration order is not guaranteed)
*/
function pairs(object) {
object = toObject(object);
var index = -1,
props = keys(object),
length = props.length,
result = Array(length);
while (++index < length) {
var key = props[index];
result[index] = [key, object[key]];
}
return result;
}
module.exports = pairs;
},{"../internal/toObject":216,"./keys":228}],231:[function(require,module,exports){
/**
* This method returns the first argument provided to it.
*
* @static
* @memberOf _
* @category Utility
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'user': 'fred' };
*
* _.identity(object) === object;
* // => true
*/
function identity(value) {
return value;
}
module.exports = identity;
},{}],232:[function(require,module,exports){
var baseProperty = require('../internal/baseProperty'),
basePropertyDeep = require('../internal/basePropertyDeep'),
isKey = require('../internal/isKey');
/**
* Creates a function that returns the property value at `path` on a
* given object.
*
* @static
* @memberOf _
* @category Utility
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new function.
* @example
*
* var objects = [
* { 'a': { 'b': { 'c': 2 } } },
* { 'a': { 'b': { 'c': 1 } } }
* ];
*
* _.map(objects, _.property('a.b.c'));
* // => [2, 1]
*
* _.pluck(_.sortBy(objects, _.property(['a', 'b', 'c'])), 'a.b.c');
* // => [1, 2]
*/
function property(path) {
return isKey(path) ? baseProperty(path) : basePropertyDeep(path);
}
module.exports = property;
},{"../internal/baseProperty":194,"../internal/basePropertyDeep":195,"../internal/isKey":211}]},{},[21])(21)
}); | {
"content_hash": "a566e6ed9f2db80b4cf1af1bb277811b",
"timestamp": "",
"source": "github",
"line_count": 33104,
"max_line_length": 847,
"avg_line_length": 30.819478008699853,
"alnum_prop": 0.5875610635845402,
"repo_name": "seogi1004/cdnjs",
"id": "00a39e7da7e472da51ce1526c6508b0b77454654",
"size": "1020264",
"binary": false,
"copies": "13",
"ref": "refs/heads/master",
"path": "ajax/libs/mammoth/1.4.3/mammoth.browser.js",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package de.kit.sensorlibrary.sensor.weathersensor;
import de.kit.sensorlibrary.sensor.ValueChangedEvent;
/**
* Created by Robert on 11.05.2015.
*/
public class WeatherChangedEvent extends ValueChangedEvent {
/**
* Constructs a new instance of this class.
*
* @param source the object which fired the event.
*/
public WeatherChangedEvent(WeatherSensor source) {
super(source);
}
public double getTemperature() {
return ((WeatherSensor) source).getTemperature();
}
public String getCondition() {
return ((WeatherSensor) source).getCondition();
}
}
| {
"content_hash": "badb32400cedc10289a4e07b04b03ce3",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 60,
"avg_line_length": 24.96,
"alnum_prop": 0.6762820512820513,
"repo_name": "rzetzsche/sensorlibrary",
"id": "b79877d63229fc3642fb4a1ad1aece40a54a5cdd",
"size": "624",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sensorlibrary/src/main/java/de/kit/sensorlibrary/sensor/weathersensor/WeatherChangedEvent.java",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "136161"
}
],
"symlink_target": ""
} |
.. _crystal_interface:
CRYSTAL & phono3py calculation
==============================
CRYSTAL program package has a robust built-in phonon calculation
workflow for harmonic phonon properties. However, combining CRYSTAL
with Phono3py enables convenient access to anharmonic phonon properties.
An example for CRYSTAL is found in the ``example/Si-CRYSTAL`` directory.
To invoke the CRYSTAL interface, ``--crystal`` option has to be always
specified::
% phono3py --crystal [options] [arguments]
When the file name of the unit cell is different from the default one
(see :ref:`default_unit_cell_file_name_for_calculator`), ``-c`` option
is used to specify the file name. CRYSTAL unit cell file parser used in
phono3py is the same as that in phonopy. It reads a limited number of
keywords that are documented in the phonopy web site
(http://phonopy.github.io/phonopy/crystal.html#crystal-interface).
.. _crystal_workflow:
Workflow
---------
In this example (Si-CRYSTAL), the CRYSTAL output file is crystal.o.
This is the default file name for the CRYSTAL interface,
so the -c crystal.o parameter is not needed.
1) Create supercells with displacements
(4x4x4 for 2nd order FC, 2x2x2 for 3rd order FC)
::
% phono3py --crystal --dim="2 2 2" --dim-fc2="4 4 4" -d
57 supercell files (``supercell-xxx.d12/.ext``) for the third order
force constants are created. In addition, one supercell file
(``supercell_fc2-00001.d12/.ext``) is created for the second order
force constants.
2) To make valid CRYSTAL input files, there are two possible options:
a) Manually: modify the generated supercell-xxx.d12 and supercell_fc2-xxxxx.d12
files by replacing the line ``Insert basis sets and parameters here`` with the
basis set and computational parameters.
b) Recommended option: before generating the supercells, include files named
``TEMPLATE`` and ``TEMPLATE3`` in the current directory. These files should
contain the basis sets and computational parameters for CRYSTAL (see the example).
When phono3py finds these files it automatically generates complete
CRYSTAL input files in the step 1.
Note that supercells with displacements must not be relaxed in the
force calculations, because atomic forces induced by a small atomic
displacement are what we need for phonon calculation. To get accurate
forces, TOLDEE parameter should be 10 or higher. Phono3py includes this
parameter and the necessary GRADCAL keyword automatically in the inputs.
Then, CRYSTAL supercell calculations are executed to obtain forces on
atoms, e.g., as follows::
% runcry17 supercell-001.d12
3) Collect forces in ``FORCES_FC3`` and ``FORCES_FC2``::
% phono3py --crystal --cf3 supercell-*o
% phono3py --crystal --cf2 supercell_fc2-*o
``disp_fc3.yaml`` and ``disp_fc2.yaml`` are used to create ``FORCES_FC3`` and
``FORCES_FC2``, therefore they must exist in current directory.
4) Calculate 3rd and 2nd order force constants in files ``fc3.hdf5`` and ``fc2.hdf5``::
% phono3py --crystal --dim="2 2 2" --dim-fc2="4 4 4" --sym-fc
``--sym-fc`` is used to symmetrize second- and third-order force constants.
5) Thermal conductivity calculation::
% phono3py --crystal --fc3 --fc2 --dim="2 2 2" --dim-fc2="4 4 4" --mesh="20 20 20" --br
``--br`` invokes the Relaxation Time Approximation.
Add ``--isotope`` for isotope scattering.
Check the effect of ``--nac`` for polar systems.
Carefully test the convergence with respect to ``--mesh``!
| {
"content_hash": "1fbdee46a1dcb0f37e90833a3e042d89",
"timestamp": "",
"source": "github",
"line_count": 90,
"max_line_length": 92,
"avg_line_length": 39.455555555555556,
"alnum_prop": 0.7200788510278795,
"repo_name": "atztogo/phono3py",
"id": "c7eed8e2e9a09640b78c415ce8651c442eb2dd6f",
"size": "3551",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/crystal.rst",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "246"
},
{
"name": "C",
"bytes": "464971"
},
{
"name": "C++",
"bytes": "10277"
},
{
"name": "Python",
"bytes": "648829"
},
{
"name": "Shell",
"bytes": "1490"
}
],
"symlink_target": ""
} |
"""
Molecule images.
"""
__author__ = "Steven Kearnes"
__copyright__ = "Copyright 2014, Stanford University"
__license__ = "BSD 3-clause"
from rdkit.Chem import Draw
from vs_utils.features import Featurizer
from vs_utils.utils import image_utils, ob_utils
class MolImage(Featurizer):
"""
Molecule images.
Parameters
----------
size : int, optional (default 32)
Size (in any dimension) of generated images.
flatten : bool, optional (default False)
Whether to flatten the pixel array. If False, the features for each
molecule will be a 3D array.
engine : str, optional (default 'obabel')
Which engine to use to generate images. Choose from 'obabel' or
'rdkit'.
"""
name = 'image'
def __init__(self, size=32, flatten=False, engine='obabel'):
self.size = size
if not flatten:
self.topo_view = True
self.flatten = flatten
self.engine = engine
def _featurize(self, mol):
"""
Generate a 2D depiction of a molecule.
Parameters
----------
mol : RDKit Mol
Molecule.
"""
dim = (self.size, self.size)
if self.engine == 'obabel':
image = ob_utils.MolImage(self.size)(mol)
elif self.engine == 'rdkit':
image = Draw.MolToImage(mol, dim, fitImage=True)
image = image.convert('RGB') # drop alpha channel
else:
raise NotImplementedError(self.engine)
pixels = image_utils.get_pixels(image)
if self.flatten:
pixels = pixels.ravel()
return pixels
| {
"content_hash": "f73f15441f4b4d3c8590a025bf703687",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 75,
"avg_line_length": 27.796610169491526,
"alnum_prop": 0.5841463414634146,
"repo_name": "rbharath/pande-gas",
"id": "298b3faab97f255355a47f9439ecdc8cac9e9614",
"size": "1640",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "vs_utils/features/images.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "247790"
},
{
"name": "Shell",
"bytes": "360"
}
],
"symlink_target": ""
} |
package brooklyn.management.internal;
import brooklyn.management.AccessController;
public class NonDeploymentAccessManager implements AccessManager {
private final ManagementContextInternal initialManagementContext;
public NonDeploymentAccessManager(ManagementContextInternal initialManagementContext) {
this.initialManagementContext = initialManagementContext;
}
private boolean isInitialManagementContextReal() {
return (initialManagementContext != null && !(initialManagementContext instanceof NonDeploymentManagementContext));
}
@Override
public AccessController getAccessController() {
if (isInitialManagementContextReal()) {
return initialManagementContext.getAccessManager().getAccessController();
} else {
throw new IllegalStateException("Non-deployment context "+this+" is not valid for this operation");
}
}
@Override
public boolean isLocationProvisioningAllowed() {
if (isInitialManagementContextReal()) {
return initialManagementContext.getAccessManager().isLocationProvisioningAllowed();
} else {
throw new IllegalStateException("Non-deployment context "+this+" is not valid for this operation");
}
}
@Override
public boolean isLocationManagementAllowed() {
if (isInitialManagementContextReal()) {
return initialManagementContext.getAccessManager().isLocationManagementAllowed();
} else {
throw new IllegalStateException("Non-deployment context "+this+" is not valid for this operation");
}
}
@Override
public boolean isEntityManagementAllowed() {
if (isInitialManagementContextReal()) {
return initialManagementContext.getAccessManager().isEntityManagementAllowed();
} else {
throw new IllegalStateException("Non-deployment context "+this+" is not valid for this operation");
}
}
@Override
public void setLocationProvisioningAllowed(boolean allowed) {
if (isInitialManagementContextReal()) {
initialManagementContext.getAccessManager().setLocationProvisioningAllowed(allowed);
} else {
throw new IllegalStateException("Non-deployment context "+this+" is not valid for this operation");
}
}
@Override
public void setLocationManagementAllowed(boolean allowed) {
if (isInitialManagementContextReal()) {
initialManagementContext.getAccessManager().setLocationManagementAllowed(allowed);
} else {
throw new IllegalStateException("Non-deployment context "+this+" is not valid for this operation");
}
}
@Override
public void setEntityManagementAllowed(boolean allowed) {
if (isInitialManagementContextReal()) {
initialManagementContext.getAccessManager().setEntityManagementAllowed(allowed);
} else {
throw new IllegalStateException("Non-deployment context "+this+" is not valid for this operation");
}
}
}
| {
"content_hash": "9769a21c6ff52cf6fbae022fddb082fe",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 123,
"avg_line_length": 38.6375,
"alnum_prop": 0.697508896797153,
"repo_name": "rhodgin/brooklyn",
"id": "95d59ab2108bc7bf05f9520393fca768deae83ba",
"size": "3091",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "core/src/main/java/brooklyn/management/internal/NonDeploymentAccessManager.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
/****
dijit.ProgressBar
****/
.nihilo .dijitProgressBarRtl .dijitProgressBarFull {
border-left-width: 1px;
border-right: 0px;
}
.nihilo .dijitProgressBarIndeterminateRtl .dijitProgressBarTile {
-moz-transform: scaleX(-1);
-o-transform: scaleX(-1);
-webkit-transform: scaleX(-1);
transform: scaleX(-1);
filter: FlipH;
-ms-filter: "FlipH";
}
| {
"content_hash": "f7e387edb0c03783ef84549f9ec4c642",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 65,
"avg_line_length": 18,
"alnum_prop": 0.6587301587301587,
"repo_name": "clorenquecan/geojsonCesium",
"id": "07850ad33954a40468755ad3a6131685c136b91d",
"size": "378",
"binary": false,
"copies": "21",
"ref": "refs/heads/master",
"path": "ThirdParty/dojo-release-1.10.4/dijit/themes/nihilo/ProgressBar_rtl.css",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "680535"
},
{
"name": "GLSL",
"bytes": "210268"
},
{
"name": "HTML",
"bytes": "1534822"
},
{
"name": "JavaScript",
"bytes": "58381248"
},
{
"name": "Shell",
"bytes": "297"
}
],
"symlink_target": ""
} |
function Get-SolutionDir {
if($dte.Solution -and $dte.Solution.IsOpen) {
return Split-Path $dte.Solution.Properties.Item("Path").Value
}
else {
throw "Solution not avaliable"
}
}
function Resolve-ProjectName {
param(
[parameter(ValueFromPipelineByPropertyName = $true)]
[string[]]$ProjectName,
[Switch]
[bool]$All = $true
)
if($ProjectName) {
$projects = Get-Project $ProjectName
}
else {
# All projects by default
$projects = Get-Project -All:$All
}
$projects
}
function Get-MSBuildProject {
param(
[parameter(ValueFromPipelineByPropertyName = $true)]
[string[]]$ProjectName
)
Process {
(Resolve-ProjectName $ProjectName) | % {
$path = $_.FullName
@([Microsoft.Build.Evaluation.ProjectCollection]::GlobalProjectCollection.GetLoadedProjects($path))[0]
}
}
}
function Set-MSBuildProperty {
param(
[parameter(Position = 0, Mandatory = $true)]
$PropertyName,
[parameter(Position = 1, Mandatory = $true)]
$PropertyValue,
[parameter(Position = 2, ValueFromPipelineByPropertyName = $true)]
[string[]]$ProjectName
)
Process {
(Resolve-ProjectName $ProjectName) | %{
$buildProject = $_ | Get-MSBuildProject
$buildProject.SetProperty($PropertyName, $PropertyValue) | Out-Null
$_.Save()
}
}
}
function Get-MSBuildProperty {
param(
[parameter(Position = 0, Mandatory = $true)]
$PropertyName,
[parameter(Position = 2, ValueFromPipelineByPropertyName = $true)]
[string]$ProjectName
)
$buildProject = Get-MSBuildProject $ProjectName
$buildProject.GetProperty($PropertyName)
}
function Install-NuSpec {
param(
[parameter(ValueFromPipelineByPropertyName = $true)]
[string[]]$ProjectName,
[switch]$EnableIntelliSense,
[string]$TemplatePath
)
Process {
$projects = (Resolve-ProjectName $ProjectName)
if(!$projects) {
Write-Error "Unable to locate project. Make sure it isn't unloaded."
return
}
$m = get-module NuSpec
#$profileDirectory = Split-Path $profile -parent
#$profileModulesDirectory = (Join-Path $profileDirectory "Modules")
$moduleDir = split-path -parent $m.Path
if($EnableIntelliSense){
Enable-NuSpecIntelliSense
}
# Add NuSpec file for project(s)
$projects | %{
$project = $_
# Set the nuspec target path
$projectFile = Get-Item $project.FullName
$projectDir = [System.IO.Path]::GetDirectoryName($projectFile)
$projectNuspec = "$($project.Name).nuspec"
$projectNuspecPath = Join-Path $projectDir $projectNuspec
# Get the nuspec template source path
if($TemplatePath) {
$nuspecTemplatePath = $TemplatePath
}
else {
$nuspecTemplatePath = Join-Path $moduleDir NuSpecTemplate.xml
}
write-verbose "creating nuspec at '$projectNuspecPath' from template '$nuspecTemplatePath'"
# Copy the templated nuspec to the project nuspec if it doesn't exist
if(!(Test-Path $projectNuspecPath)) {
Copy-Item $nuspecTemplatePath $projectNuspecPath
}
else {
Write-Warning "Failed to install nuspec '$projectNuspec' into '$($project.Name)' because the file already exists."
}
try {
write-verbose "adding nuspec to project"
# Add nuspec file to the project
add-itemToProject $project $projectNuspecPath
Set-MSBuildProperty NuSpecFile $projectNuspec $project.Name
"Updated '$($project.Name)' to use nuspec '$projectNuspec'"
}
catch {
Write-Warning "Failed to install nuspec '$projectNuspec' into '$($project.Name)': $_"
}
}
}
}
function Enable-NuSpecIntelliSense {
Process {
$profileDirectory = Split-Path $profile -parent
$profileModulesDirectory = (Join-Path $profileDirectory "Modules")
$moduleDir = (Join-Path $profileModulesDirectory "NuSpec")
$solutionDir = Get-SolutionDir
$solution = Get-Interface $dte.Solution ([EnvDTE80.Solution2])
# Set up solution folder "Solution Items"
$solutionItemsProject = $dte.Solution.Projects | Where-Object { $_.ProjectName -eq "Solution Items" }
if(!($solutionItemsProject)) {
$solutionItemsProject = $solution.AddSolutionFolder("Solution Items")
}
# Copy the XSD in the solution directory
try {
$xsdInstallPath = Join-Path $solutionDir 'nuspec.xsd'
$xsdToolsPath = Join-Path $moduleDir 'nuspec.xsd'
if(!(Test-Path $xsdInstallPath)) {
Copy-Item $xsdToolsPath $xsdInstallPath
}
$alreadyAdded = $solutionItemsProject.ProjectItems | Where-Object { $_.Name -eq 'nuspec.xsd' }
if(!($alreadyAdded)) {
$solutionItemsProject.ProjectItems.AddFromFile($xsdInstallPath) | Out-Null
}
}
catch {
Write-Warning "Failed to install nuspec.xsd into 'Solution Items'"
}
$solution.SaveAs($solution.FullName)
}
}
function Pack-Nuget {
param (
[parameter(ValueFromPipelineByPropertyName = $true)]
[string[]]$ProjectName,
[string] $specFile,
[switch][bool] $noProjectRefs
)
Process {
$projects = (Resolve-ProjectName $ProjectName)
if(!$projects) {
Write-Error "Unable to locate project. Make sure it isn't unloaded."
return
}
$profileDirectory = Split-Path $profile -parent
$profileModulesDirectory = (Join-Path $profileDirectory "Modules")
$moduleDir = (Join-Path $profileModulesDirectory "NuSpec")
$projects | % {
Push-Location
try {
$project = $_
# Set the nuspec target path
$projectFile = Get-Item $project.FullName
$projectDir = [System.IO.Path]::GetDirectoryName($projectFile)
$projectNuspec = "$($project.Name).nuspec"
if (![string]::isnullorempty($specFile)) {
$projectNuspec = $specFile
}
$projectNuspecPath = Join-Path $projectDir $projectNuspec
cd $projectDir
$args = @()
if (![string]::isnullorempty($specFile)) {
$args += $projectNuspecPath
} else {
$args += $projectFile
}
if (!$noProjectRefs) {
$args += "-IncludeReferencedProjects"
}
Write-Warning "running command 'nuget pack $args'"
nuget pack @args
}
finally {
Pop-Location
}
}
}
}
function Push-Nuget {
param (
[parameter(ValueFromPipelineByPropertyName = $true)]
[string[]]$ProjectName,
[string] $specFile,
[parameter(Mandatory=$true)]
[string] $Source,
[switch][bool] $Pack = $true,
[switch][bool] $noProjectRefs = $false
)
Process {
$projects = (Resolve-ProjectName $ProjectName)
if(!$projects) {
Write-Error "Unable to locate project. Make sure it isn't unloaded."
return
}
if ($Pack) {
Pack-Nuget -ProjectName $ProjectName -specFile $specFile -noProjectRefs:$noProjectRefs
}
$profileDirectory = Split-Path $profile -parent
$profileModulesDirectory = (Join-Path $profileDirectory "Modules")
$moduleDir = (Join-Path $profileModulesDirectory "NuSpec")
$projects | % {
Push-Location
try {
$project = $_
# Set the nuspec target path
$projectFile = Get-Item $project.FullName
$projectDir = [System.IO.Path]::GetDirectoryName($projectFile)
$projectNuspec = "$($project.Name).nuspec"
if (![string]::isnullorempty($specFile)) {
$projectNuspec = $specFile
}
$projectNuspecPath = Join-Path $projectDir $projectNuspec
cd $projectDir
if (![string]::isnullorempty($specFile)) {
$nupkgs = gci . -Filter "$specFile.*.nupkg" -File
} else {
$nupkgs = gci . -Filter "*.nupkg" -File
}
$nupkgs = $nupkgs | sort -Descending -Property CreationTime
$nupkgs
$pkg = $nupkgs[0]
nuget push $pkg.FullName -source $source
}
finally {
Pop-Location
}
}
}
}
function add-itemToProject($project, $file) {
if ($project.ProjectItems -ne $null) {
$project.ProjectItems.AddFromFile($file) | Out-Null
$project.Save()
} else {
# assume a fallback function 'add-projectItem' exists
add-projectItem $project.FullName $file -Verbose:$($VerbosePreference -eq "Continue")
}
}
# Statement completion for project names
'Install-NuSpec', 'Enable-NuSpecIntelliSense', 'Pack-Nuget', 'Push-Nuget' | %{
#Register-TabExpansion $_ @{
# ProjectName = { Get-Project -All | Select -ExpandProperty Name }
#}
}
Export-ModuleMember Install-NuSpec, Enable-NuSpecIntelliSense, Pack-Nuget, Push-Nuget | {
"content_hash": "68fdfec2e672fb821800b5c157f13d90",
"timestamp": "",
"source": "github",
"line_count": 320,
"max_line_length": 130,
"avg_line_length": 31.678125,
"alnum_prop": 0.5467100720134161,
"repo_name": "qbikez/NuGetPackages",
"id": "b0a870d21d31a713016683174929609df91b55c0",
"size": "10137",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "NuSpec/NuSpec/NuSpec.psm1",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PowerShell",
"bytes": "20879"
}
],
"symlink_target": ""
} |
module Backup
class Manager
def pack
# saving additional informations
s = {}
s[:db_version] = "#{ActiveRecord::Migrator.current_version}"
s[:backup_created_at] = Time.now
s[:gitlab_version] = GitlabCi::VERSION
s[:tar_version] = tar_version
tar_file = "#{s[:backup_created_at].to_i}_gitlab_ci_backup.tar"
Dir.chdir(GitlabCi.config.backup.path) do
File.open("#{GitlabCi.config.backup.path}/backup_information.yml",
"w+") do |file|
file << s.to_yaml.gsub(/^---\n/,'')
end
FileUtils.chmod(0700, ["db", "builds"])
# create archive
$progress.print "Creating backup archive: #{tar_file} ... "
if Kernel.system('tar', '-cf', tar_file, *backup_contents)
$progress.puts "done".green
else
puts "creating archive #{tar_file} failed".red
abort 'Backup failed'
end
upload(tar_file)
end
File.join(GitlabCi.config.backup.path, tar_file)
end
def upload(tar_file)
remote_directory = GitlabCi.config.backup.upload.remote_directory
$progress.print "Uploading backup archive to remote storage #{remote_directory} ... "
connection_settings = GitlabCi.config.backup.upload.connection
if connection_settings.blank?
$progress.puts "skipped".yellow
return
end
connection = ::Fog::Storage.new(connection_settings)
directory = connection.directories.get(remote_directory)
if directory.files.create(key: tar_file, body: File.open(tar_file), public: false,
multipart_chunk_size: GitlabCi.config.backup.upload.multipart_chunk_size)
$progress.puts "done".green
else
puts "uploading backup to #{remote_directory} failed".red
abort 'Backup failed'
end
end
def cleanup
$progress.print "Deleting tmp directories ... "
backup_contents.each do |dir|
next unless File.exist?(File.join(GitlabCi.config.backup.path, dir))
if FileUtils.rm_rf(File.join(GitlabCi.config.backup.path, dir))
$progress.puts "done".green
else
puts "deleting tmp directory '#{dir}' failed".red
abort 'Backup failed'
end
end
end
def remove_old
# delete backups
$progress.print "Deleting old backups ... "
keep_time = GitlabCi.config.backup.keep_time.to_i
if keep_time > 0
removed = 0
Dir.chdir(GitlabCi.config.backup.path) do
file_list = Dir.glob('*_gitlab_ci_backup.tar')
file_list.map! { |f| $1.to_i if f =~ /(\d+)_gitlab_ci_backup.tar/ }
file_list.sort.each do |timestamp|
if Time.at(timestamp) < (Time.now - keep_time)
if Kernel.system(*%W(rm #{timestamp}_gitlab_ci_backup.tar))
removed += 1
end
end
end
end
$progress.puts "done. (#{removed} removed)".green
else
$progress.puts "skipping".yellow
end
end
def unpack
Dir.chdir(GitlabCi.config.backup.path)
# check for existing backups in the backup dir
file_list = Dir.glob("*_gitlab_ci_backup.tar").each.map { |f| f.split(/_/).first.to_i }
puts "no backups found" if file_list.count == 0
if file_list.count > 1 && ENV["BACKUP"].nil?
puts "Found more than one backup, please specify which one you want to restore:"
puts "rake gitlab:backup:restore BACKUP=timestamp_of_backup"
exit 1
end
tar_file = ENV["BACKUP"].nil? ? File.join("#{file_list.first}_gitlab_ci_backup.tar") : File.join(ENV["BACKUP"] + "_gitlab_ci_backup.tar")
unless File.exists?(tar_file)
puts "The specified backup doesn't exist!"
exit 1
end
$progress.print "Unpacking backup ... "
unless Kernel.system(*%W(tar -xf #{tar_file}))
puts "unpacking backup failed".red
exit 1
else
$progress.puts "done".green
end
ENV["VERSION"] = "#{settings[:db_version]}" if settings[:db_version].to_i > 0
# restoring mismatching backups can lead to unexpected problems
if settings[:gitlab_version] != GitlabCi::VERSION
puts "GitLab CI version mismatch:".red
puts " Your current GitLab CI version (#{GitlabCi::VERSION}) differs from the GitLab CI version in the backup!".red
puts " Please switch to the following version and try again:".red
puts " version: #{settings[:gitlab_version]}".red
puts
puts "Hint: git checkout v#{settings[:gitlab_version]}"
exit 1
end
end
def tar_version
tar_version = `tar --version`
tar_version.force_encoding('locale').split("\n").first
end
private
def backup_contents
["db", "builds", "backup_information.yml"]
end
def settings
@settings ||= YAML.load_file("backup_information.yml")
end
end
end
| {
"content_hash": "f7e28f758fa091e0a327696730193804",
"timestamp": "",
"source": "github",
"line_count": 155,
"max_line_length": 143,
"avg_line_length": 32.29677419354839,
"alnum_prop": 0.598881342389133,
"repo_name": "copystudy/gitlab-ci",
"id": "9a4ddab321c47bca8432c0671b913abd5f1f15cf",
"size": "5006",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "lib/backup/manager.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "24271"
},
{
"name": "CoffeeScript",
"bytes": "4046"
},
{
"name": "HTML",
"bytes": "64511"
},
{
"name": "Python",
"bytes": "11005"
},
{
"name": "Ruby",
"bytes": "353569"
},
{
"name": "Shell",
"bytes": "11849"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Phoma hippuridis Staritz
### Remarks
null | {
"content_hash": "b01b18df23315a7610cec74aabfe9905",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 24,
"avg_line_length": 9.923076923076923,
"alnum_prop": 0.7131782945736435,
"repo_name": "mdoering/backbone",
"id": "03f63cb5b582bda3b21d7e7b9161e628db0e7d64",
"size": "177",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Ascomycota/Dothideomycetes/Pleosporales/Phoma/Phoma hippuridis/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (c) 2009-2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>org.wso2.carbon</groupId>
<artifactId>identity</artifactId>
<version>4.3.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.identity.oauth.mediator</artifactId>
<version>4.3.0-SNAPSHOT</version>
<packaging>bundle</packaging>
<name>WSO2 Carbon - Identity OAuth Mediator</name>
<description>A custom wso2 products or solution</description>
<url>http://wso2.org</url>
<dependencies>
<dependency>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2</artifactId>
<!--<version>${axis2.osgi.version}</version>-->
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.core</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
</dependency>
<dependency>
<groupId>org.apache.ws.commons.axiom.wso2</groupId>
<artifactId>axiom</artifactId>
</dependency>
<dependency>
<groupId>org.apache.synapse</groupId>
<artifactId>synapse-core</artifactId>
<!--<version>${synapse.version}</version>-->
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.mediator.service</artifactId>
<!--<version>${wso2carbon.version.identity}</version>-->
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.identity.oauth.stub</artifactId>
<!--<version>4.3.0-SNAPSHOT</version>-->
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
<Bundle-Name>${project.artifactId}</Bundle-Name>
<Export-Package>
org.wso2.carbon.identity.oauth.mediator.*,
</Export-Package>
<Import-Package>
!javax.xml.namespace,
org.apache.commons.logging.*; version="1.0.4",
!org.osgi.framework,
!javax.servlet,
!javax.servlet.http,
!org.apache.axis2.databinding,
!org.apache.axis2.databinding.utils.reader,
!org.pache.axis2.databinding.utils.writer,
!org.wso2.carbon.identity.oauth.mediator.*,
org.wso2.carbon.identity.oauth2.stub.*;version="${carbon.platform.package.import.version.range}",
org.wso2.carbon.identity.oauth.stub.*;version="${carbon.platform.package.import.version.range}",
*; resolution:=optional
</Import-Package>
<Fragment-Host>synapse-core</Fragment-Host>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
</project>
| {
"content_hash": "69e59eedf0356f0b26d9c53c3d0c4dd5",
"timestamp": "",
"source": "github",
"line_count": 110,
"max_line_length": 125,
"avg_line_length": 42.61818181818182,
"alnum_prop": 0.5665529010238908,
"repo_name": "poornan/carbon-identity",
"id": "7579d91bab0f372091ffeece18c75308d402fc37",
"size": "4688",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "components/identity/org.wso2.carbon.identity.oauth.mediator/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "216622"
},
{
"name": "Java",
"bytes": "9048994"
},
{
"name": "JavaScript",
"bytes": "420063"
},
{
"name": "Thrift",
"bytes": "676"
},
{
"name": "XSLT",
"bytes": "951"
}
],
"symlink_target": ""
} |
HOMOTYPIC_SYNONYM
#### According to
Euro+Med Plantbase
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "51c2a3faacf17a82c2c56814fc81edb4",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 18,
"avg_line_length": 9.384615384615385,
"alnum_prop": 0.6967213114754098,
"repo_name": "mdoering/backbone",
"id": "ca62a544b083ac6ad4ec8bd1d21ecc5324c30b93",
"size": "175",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Centaurea/Centaurea aplolepa/ Syn. Acosta aeolica/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package com.github.ljtfreitas.restify.http.client.call.handler.reactor;
import java.util.Collection;
import org.reactivestreams.Publisher;
import com.github.ljtfreitas.restify.http.client.call.async.AsyncEndpointCall;
import com.github.ljtfreitas.restify.http.client.call.handler.EndpointCallHandler;
import com.github.ljtfreitas.restify.http.client.call.handler.async.AsyncEndpointCallHandler;
import com.github.ljtfreitas.restify.http.client.call.handler.async.AsyncEndpointCallHandlerAdapter;
import com.github.ljtfreitas.restify.http.client.call.handler.circuitbreaker.Fallback;
import com.github.ljtfreitas.restify.http.client.call.handler.circuitbreaker.FallbackProvider;
import com.github.ljtfreitas.restify.http.client.call.handler.circuitbreaker.OnCircuitBreaker;
import com.github.ljtfreitas.restify.http.client.call.handler.circuitbreaker.OnCircuitBreakerMetadataResolver;
import com.github.ljtfreitas.restify.http.contract.metadata.EndpointMethod;
import com.github.ljtfreitas.restify.reflection.JavaType;
import com.netflix.hystrix.HystrixObservableCommand;
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Scheduler;
import reactor.core.scheduler.Schedulers;
public class HystrixFluxEndpointCallHandlerAdapter<T, O> implements AsyncEndpointCallHandlerAdapter<Flux<T>, Collection<T>, O> {
private final Scheduler scheduler;
private final FluxEndpointCallHandlerAdapter<T, O> adapterToFlux;
private final HystrixPublisherEndpointCallHandlerAdapter<T, O, Flux<T>> adapterToPublisher;
public HystrixFluxEndpointCallHandlerAdapter() {
this(Schedulers.elastic(), null, null, null);
}
public HystrixFluxEndpointCallHandlerAdapter(HystrixObservableCommand.Setter properties) {
this(Schedulers.elastic(), null, null, null);
}
public HystrixFluxEndpointCallHandlerAdapter(Fallback fallback) {
this((FallbackProvider) m -> fallback);
}
public HystrixFluxEndpointCallHandlerAdapter(FallbackProvider fallback) {
this(Schedulers.elastic(), null, fallback, null);
}
public HystrixFluxEndpointCallHandlerAdapter(OnCircuitBreakerMetadataResolver onCircuitBreakerMetadataResolver) {
this(Schedulers.elastic(), null, null, null);
}
public HystrixFluxEndpointCallHandlerAdapter(Scheduler scheduler, HystrixObservableCommand.Setter properties) {
this(scheduler, properties, null, null);
}
public HystrixFluxEndpointCallHandlerAdapter(Scheduler scheduler, Fallback fallback) {
this(scheduler, (FallbackProvider) m -> fallback);
}
public HystrixFluxEndpointCallHandlerAdapter(Scheduler scheduler, FallbackProvider fallback) {
this(scheduler, null, fallback, null);
}
public HystrixFluxEndpointCallHandlerAdapter(Scheduler scheduler,
OnCircuitBreakerMetadataResolver onCircuitBreakerMetadataResolver) {
this(scheduler, null, null, onCircuitBreakerMetadataResolver);
}
public HystrixFluxEndpointCallHandlerAdapter(HystrixObservableCommand.Setter properties, Fallback fallback) {
this(properties, (FallbackProvider) m -> fallback);
}
public HystrixFluxEndpointCallHandlerAdapter(HystrixObservableCommand.Setter properties,
FallbackProvider fallback) {
this(Schedulers.elastic(), properties, fallback);
}
public HystrixFluxEndpointCallHandlerAdapter(Fallback fallback,
OnCircuitBreakerMetadataResolver onCircuitBreakerMetadataResolver) {
this((FallbackProvider) m -> fallback, onCircuitBreakerMetadataResolver);
}
public HystrixFluxEndpointCallHandlerAdapter(FallbackProvider fallback,
OnCircuitBreakerMetadataResolver onCircuitBreakerMetadataResolver) {
this(Schedulers.elastic(), fallback, onCircuitBreakerMetadataResolver);
}
public HystrixFluxEndpointCallHandlerAdapter(Scheduler scheduler, HystrixObservableCommand.Setter properties,
Fallback fallback) {
this(scheduler, properties, (FallbackProvider) m -> fallback);
}
public HystrixFluxEndpointCallHandlerAdapter(Scheduler scheduler, Fallback fallback,
OnCircuitBreakerMetadataResolver onCircuitBreakerMetadataResolver) {
this(scheduler, (FallbackProvider) m -> fallback, onCircuitBreakerMetadataResolver);
}
public HystrixFluxEndpointCallHandlerAdapter(Scheduler scheduler, HystrixObservableCommand.Setter properties,
FallbackProvider fallback) {
this(Schedulers.elastic(), properties, fallback, null);
}
public HystrixFluxEndpointCallHandlerAdapter(Scheduler scheduler, FallbackProvider fallback,
OnCircuitBreakerMetadataResolver onCircuitBreakerMetadataResolver) {
this(Schedulers.elastic(), null, fallback, onCircuitBreakerMetadataResolver);
}
private HystrixFluxEndpointCallHandlerAdapter(Scheduler scheduler, HystrixObservableCommand.Setter properties,
FallbackProvider fallback, OnCircuitBreakerMetadataResolver onCircuitBreakerMetadataResolver) {
this.scheduler = scheduler;
this.adapterToFlux = new FluxEndpointCallHandlerAdapter<>(scheduler);
this.adapterToPublisher = new HystrixPublisherEndpointCallHandlerAdapter<>(properties, fallback,
onCircuitBreakerMetadataResolver);
}
@Override
public boolean supports(EndpointMethod endpointMethod) {
return endpointMethod.returnType().is(Flux.class)
&& endpointMethod.metadata().contains(OnCircuitBreaker.class);
}
@Override
public JavaType returnType(EndpointMethod endpointMethod) {
return adapterToFlux.returnType(endpointMethod);
}
@Override
public AsyncEndpointCallHandler<Flux<T>, O> adaptAsync(EndpointMethod endpointMethod, EndpointCallHandler<Collection<T>, O> delegate) {
AsyncEndpointCallHandler<Flux<T>, O> handlerToFlux = adapterToFlux.adaptAsync(endpointMethod, delegate);
return new HystrixFluxEndpointCalHandler(adapterToPublisher.adaptAsync(endpointMethod, handlerToFlux));
}
private class HystrixFluxEndpointCalHandler implements AsyncEndpointCallHandler<Flux<T>, O> {
private final AsyncEndpointCallHandler<Publisher<T>, O> delegate;
private HystrixFluxEndpointCalHandler(AsyncEndpointCallHandler<Publisher<T>, O> delegate) {
this.delegate = delegate;
}
@Override
public JavaType returnType() {
return delegate.returnType();
}
@Override
public Flux<T> handleAsync(AsyncEndpointCall<O> call, Object[] args) {
Publisher<T> publisher = delegate.handleAsync(call, args);
return Flux.from(publisher)
.subscribeOn(scheduler);
}
}
}
| {
"content_hash": "359fab129efb931f011761c019f94eee",
"timestamp": "",
"source": "github",
"line_count": 153,
"max_line_length": 136,
"avg_line_length": 40.93464052287582,
"alnum_prop": 0.8258023311512055,
"repo_name": "ljtfreitas/java-restify",
"id": "804c18cce810124cb0ca89c6bf7c7c21dc81e676",
"size": "7568",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "java-restify-reactor-hystrix/src/main/java/com/github/ljtfreitas/restify/http/client/call/handler/reactor/HystrixFluxEndpointCallHandlerAdapter.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "3295925"
}
],
"symlink_target": ""
} |
'use strict';
var
Vaulted = {},
Promise = require('bluebird'),
_ = require('lodash');
/**
* @module init
* @extends Vaulted
* @desc Provides implementation for the Vault Initialization APIs
*
*/
module.exports = function extend(Proto) {
_.extend(Proto, Vaulted);
};
/**
* @method init
* @desc Initializes a remote vault
*
* @param {number} [options.secret_shares=config['secret_shares']] - number of shares to split the master key into
* @param {number} [options.secret_threshold=config['secret_threshold']] - number of shares required to reconstruct the master key
* @resolve {Vaulted} Resolves with keys and token or current instance of Vaulted
* @reject {Error} An error indicating what went wrong
* @return {Promise}
*/
Vaulted.init = Promise.method(function init(options) {
if (this.initialized === true) {
return Promise.resolve(this);
}
options = _.defaults(options || {}, {
secret_shares: this.config.get('secret_shares'),
secret_threshold: this.config.get('secret_threshold')
});
return this.api.getEndpoint('sys/init')
.put({
body: options
})
.promise()
.bind(this).then(function keysAndToken(keys_and_token) {
this.emit('init');
return keys_and_token;
});
});
/**
* @method getInitStatus
* @desc Gets the initialize status of a vault
*
* @resolve {Status} Resolves with the vault initializtion status
* @reject {Error} An error indicating what went wrong
* @return {Promise}
*/
Vaulted.getInitStatus = Promise.method(function getInitStatus() {
return this.api.getEndpoint('sys/init')
.get();
});
| {
"content_hash": "bcc56fc8d59fb792d0fe6dd01b22806c",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 130,
"avg_line_length": 26.8,
"alnum_prop": 0.6766169154228856,
"repo_name": "chiefy/vaulted",
"id": "b03000d9efa7e926aa1c96d9e6ef9123ec3cee5b",
"size": "1608",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/sys/init.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HCL",
"bytes": "624"
},
{
"name": "JavaScript",
"bytes": "305113"
},
{
"name": "Makefile",
"bytes": "1161"
},
{
"name": "Shell",
"bytes": "956"
}
],
"symlink_target": ""
} |
//
// BIM IFC library: this library works with Autodesk(R) Revit(R) to export IFC files containing model geometry.
// Copyright (C) 2011 Autodesk, Inc.
//
// This library 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.1 of the License, 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.IFC;
namespace BIM.IFC.Utility
{
/// <summary>
/// IFC export type.
/// </summary>
enum IFCExportType
{
/// <summary>
/// Don't export.
/// </summary>
DontExport,
/// <summary>
/// Annotation.
/// </summary>
ExportAnnotation,
/// <summary>
/// Beam.
/// </summary>
ExportBeam,
/// <summary>
/// Building element proxy.
/// </summary>
ExportBuildingElementProxy,
/// <summary>
/// Building storey.
/// </summary>
ExportBuildingStorey,
/// <summary>
/// Column type.
/// </summary>
ExportColumnType,
/// <summary>
/// Covering.
/// </summary>
ExportCovering,
/// <summary>
/// Curtain wall.
/// </summary>
ExportCurtainWall,
/// <summary>
/// Door type.
/// </summary>
ExportDoorType,
/// <summary>
/// Footing.
/// </summary>
ExportFooting,
/// <summary>
/// Member type.
/// </summary>
ExportMemberType,
/// <summary>
/// Opening element.
/// </summary>
ExportOpeningElement,
/// <summary>
/// Plate type.
/// </summary>
ExportPlateType,
/// <summary>
/// Railing.
/// </summary>
ExportRailing,
/// <summary>
/// Ramp.
/// </summary>
ExportRamp,
/// <summary>
/// Roof.
/// </summary>
ExportRoof,
/// <summary>
/// Site.
/// </summary>
ExportSite,
/// <summary>
/// Slab.
/// </summary>
ExportSlab,
/// <summary>
/// Space.
/// </summary>
ExportSpace,
/// <summary>
/// Stair.
/// </summary>
ExportStair,
/// <summary>
/// Transport element type.
/// </summary>
ExportTransportElementType,
/// <summary>
/// Wall.
/// </summary>
ExportWall,
/// <summary>
/// Reinforcing bar.
/// </summary>
ExportReinforcingBar,
/// <summary>
/// Reinforcing mesh.
/// </summary>
ExportReinforcingMesh,
/// <summary>
/// Window type.
/// </summary>
ExportWindowType,
/// <summary>
/// Furnishing element and their subclasses.
/// </summary>
ExportFurnishingElement,
/// <summary>
/// Direct subclass of FurnishingElementType.
/// </summary>
ExportFurnitureType,
/// <summary>
/// System furniture element type.
/// </summary>
ExportSystemFurnitureElementType,
/// <summary>
/// Distribution elements and their subclasses.
/// </summary>
ExportDistributionElement,
/// <summary>
/// Direct subclasses of DistributionElement.
/// </summary>
ExportDistributionControlElement,
/// <summary>
/// Distribution flow element.
/// </summary>
ExportDistributionFlowElement,
/// <summary>
/// Direct subclass of DistributionFlowElement.
/// </summary>
ExportDistributionChamberElementType,
/// <summary>
/// Energy conversion device.
/// </summary>
ExportEnergyConversionDevice,
/// <summary>
/// Flow fitting.
/// </summary>
ExportFlowFitting,
/// <summary>
/// Flow moving device.
/// </summary>
ExportFlowMovingDevice,
/// <summary>
/// Flow segment.
/// </summary>
ExportFlowSegment,
/// <summary>
/// Flow storage device.
/// </summary>
ExportFlowStorageDevice,
/// <summary>
/// Flow terminal.
/// </summary>
ExportFlowTerminal,
/// <summary>
/// Flow treatment device.
/// </summary>
ExportFlowTreatmentDevice,
/// <summary>
/// Flow controller.
/// </summary>
ExportFlowController,
// direct subclass of FlowController
//not supported -- ExportElectricDistributionPointType,
// types of DistributionControlElementType
/// <summary>
/// Actuator type.
/// </summary>
ExportActuatorType,
/// <summary>
/// Alarm type.
/// </summary>
ExportAlarmType,
/// <summary>
/// Controller type.
/// </summary>
ExportControllerType,
/// <summary>
/// Flow instrument type.
/// </summary>
ExportFlowInstrumentType,
/// <summary>
/// Sensor type.
/// </summary>
ExportSensorType,
// types of EnergyConversionDeviceType
/// <summary>
/// Air to air heat recovery type.
/// </summary>
ExportAirToAirHeatRecoveryType,
/// <summary>
/// Boiler type.
/// </summary>
ExportBoilerType,
/// <summary>
/// Chiller type.
/// </summary>
ExportChillerType,
/// <summary>
/// Coil type.
/// </summary>
ExportCoilType,
/// <summary>
/// Condenser type.
/// </summary>
ExportCondenserType,
/// <summary>
/// Cooled beam type.
/// </summary>
ExportCooledBeamType,
/// <summary>
/// Cooling tower type.
/// </summary>
ExportCoolingTowerType,
/// <summary>
/// Electric generator type.
/// </summary>
ExportElectricGeneratorType,
/// <summary>
/// Electric motor type.
/// </summary>
ExportElectricMotorType,
/// <summary>
/// Evaporative cooler type.
/// </summary>
ExportEvaporativeCoolerType,
/// <summary>
/// Evaporator type.
/// </summary>
ExportEvaporatorType,
/// <summary>
/// Heat exchanger type.
/// </summary>
ExportHeatExchangerType,
/// <summary>
/// Humidifier type.
/// </summary>
ExportHumidifierType,
/// <summary>
/// Motor connection type.
/// </summary>
ExportMotorConnectionType,
/// <summary>
/// Space heater type.
/// </summary>
ExportSpaceHeaterType,
/// <summary>
/// Transformer type.
/// </summary>
ExportTransformerType,
/// <summary>
/// Tube bundle type.
/// </summary>
ExportTubeBundleType,
/// <summary>
/// Unitary equipment type.
/// </summary>
ExportUnitaryEquipmentType,
// types of FlowControllerType
/// <summary>
/// Air terminal box type.
/// </summary>
ExportAirTerminalBoxType,
/// <summary>
/// Damper type.
/// </summary>
ExportDamperType,
/// <summary>
/// Electric time control type.
/// </summary>
ExportElectricTimeControlType,
/// <summary>
/// Flow meter type.
/// </summary>
ExportFlowMeterType,
/// <summary>
/// Protective device type.
/// </summary>
ExportProtectiveDeviceType,
/// <summary>
/// Switching device type.
/// </summary>
ExportSwitchingDeviceType,
/// <summary>
/// Valve type.
/// </summary>
ExportValveType,
// types of FlowFittingType
/// <summary>
/// Cable carrier fitting type.
/// </summary>
ExportCableCarrierFittingType,
/// <summary>
/// Duct fitting type.
/// </summary>
ExportDuctFittingType,
/// <summary>
/// Junction box type.
/// </summary>
ExportJunctionBoxType,
/// <summary>
/// Pipe fitting type.
/// </summary>
ExportPipeFittingType,
// types of FlowMovingDeviceType
/// <summary>
/// Compressor type.
/// </summary>
ExportCompressorType,
/// <summary>
/// Fan type.
/// </summary>
ExportFanType,
/// <summary>
/// Pump type.
/// </summary>
ExportPumpType,
// types of FlowSegmentType
/// <summary>
/// Cable carrier segment type.
/// </summary>
ExportCableCarrierSegmentType,
/// <summary>
/// Cable segment type.
/// </summary>
ExportCableSegmentType,
/// <summary>
/// Duct segment type.
/// </summary>
ExportDuctSegmentType,
/// <summary>
/// Pipe segment type.
/// </summary>
ExportPipeSegmentType,
// types of FlowStorageDeviceType
/// <summary>
/// Electric flow storage device type.
/// </summary>
ExportElectricFlowStorageDeviceType,
/// <summary>
/// Tank type.
/// </summary>
ExportTankType,
// types of FlowTreatmentDeviceType
/// <summary>
/// Duct silencer type.
/// </summary>
ExportDuctSilencerType,
/// <summary>
/// Filter type.
/// </summary>
ExportFilterType,
// types of FlowTerminalType
/// <summary>
/// Air terminal type.
/// </summary>
ExportAirTerminalType,
/// <summary>
/// Electric appliance type.
/// </summary>
ExportElectricApplianceType,
/// <summary>
/// Electric heater type.
/// </summary>
ExportElectricHeaterType,
/// <summary>
/// Fire suppression terminal type.
/// </summary>
ExportFireSuppressionTerminalType,
/// <summary>
/// Gas terminal type.
/// </summary>
ExportGasTerminalType,
/// <summary>
/// Lamp type.
/// </summary>
ExportLampType,
/// <summary>
/// Light fixture type.
/// </summary>
ExportLightFixtureType,
/// <summary>
/// Outlet type.
/// </summary>
ExportOutletType,
/// <summary>
/// Sanitary terminal type.
/// </summary>
ExportSanitaryTerminalType,
/// <summary>
/// Stack terminal type.
/// </summary>
ExportStackTerminalType,
/// <summary>
/// Waste terminal type.
/// </summary>
ExportWasteTerminalType,
}
/// <summary>
/// Provides static methods for filtering elements.
/// </summary>
class ElementFilteringUtil
{
/// <summary>
/// Gets spatial element filter.
/// </summary>
/// <param name="document">The Revit document.</param>
/// <param name="exporterIFC">The ExporterIFC object.</param>
/// <returns>The element filter.</returns>
public static ElementFilter GetSpatialElementFilter(Document document, ExporterIFC exporterIFC)
{
return GetExportFilter(document, exporterIFC, true);
}
/// <summary>
/// Gets filter for non spatial elements.
/// </summary>
/// <param name="document">The Revit document.</param>
/// <param name="exporterIFC">The ExporterIFC object.</param>
/// <returns>The Element filter.</returns>
public static ElementFilter GetNonSpatialElementFilter(Document document, ExporterIFC exporterIFC)
{
return GetExportFilter(document, exporterIFC, false);
}
/// <summary>
/// Gets element filter for export.
/// </summary>
/// <param name="document">The Revit document.</param>
/// <param name="exporterIFC">The ExporterIFC object.</param>
/// <param name="forSpatialElements">True to get spatial element filter, false for non spatial elements filter.</param>
/// <returns>The element filter.</returns>
private static ElementFilter GetExportFilter(Document document, ExporterIFC exporterIFC, bool forSpatialElements)
{
List<ElementFilter> filters = new List<ElementFilter>();
// Class types & categories
ElementFilter classFilter = GetClassFilter(forSpatialElements, exporterIFC.ExportAs2x2);
// Special handling for family instances and view specific elements
if (!forSpatialElements)
{
ElementFilter familyInstanceFilter = GetFamilyInstanceFilter(exporterIFC);
List<ElementFilter> classFilters = new List<ElementFilter>();
classFilters.Add(classFilter);
classFilters.Add(familyInstanceFilter);
if (!exporterIFC.ExportAs2x2)
{
ElementFilter ownerViewFilter = GetViewSpecificTypesFilter(exporterIFC);
classFilters.Add(ownerViewFilter);
}
classFilter = new LogicalOrFilter(classFilters);
}
filters.Add(classFilter);
// Design options
filters.Add(GetDesignOptionFilter());
// Phases
filters.Add(GetPhaseStatusFilter(document));
return new LogicalAndFilter(filters);
}
/// <summary>
/// Gets element filter for family instance.
/// </summary>
/// <param name="exporter">The ExporterIFC object.</param>
/// <returns>The element filter.</returns>
private static ElementFilter GetFamilyInstanceFilter(ExporterIFC exporter)
{
List<ElementFilter> filters = new List<ElementFilter>();
filters.Add(new ElementOwnerViewFilter(ElementId.InvalidElementId));
filters.Add(new ElementClassFilter(typeof(FamilyInstance)));
LogicalAndFilter andFilter = new LogicalAndFilter(filters);
return andFilter;
}
/// <summary>
/// Gets element filter meeting design option requirements.
/// </summary>
/// <returns>The element filter.</returns>
private static ElementFilter GetDesignOptionFilter()
{
ElementFilter dOptionFilter = new ElementDesignOptionFilter(ElementId.InvalidElementId);
ElementFilter primaryOptionsFilter = new PrimaryDesignOptionMemberFilter();
return new LogicalOrFilter(dOptionFilter, primaryOptionsFilter);
}
/// <summary>
/// Checks if element in certain category should be exported.
/// </summary>
/// <param name="exporterIFC">The ExporterIFC object.</param>
/// <param name="element">The element.</param>
/// <returns>True if the element should be exported, false otherwise.</returns>
public static bool ShouldCategoryBeExported(ExporterIFC exporterIFC, Element element)
{
IFCExportType exportType = IFCExportType.DontExport;
String ifcClassName = ExporterIFCUtils.GetIFCClassName(element, exporterIFC);
if (ifcClassName == "")
return false;
bool foundName = String.Compare(ifcClassName, "Default", true) != 0;
if (foundName)
exportType = GetExportTypeFromClassName(ifcClassName);
// We don't export openings directly, only via the element they are opening.
if (!foundName || (exportType != IFCExportType.DontExport && exportType != IFCExportType.ExportOpeningElement))
return true;
return false;
}
/// <summary>
/// Checks if name is equal to base or its type name.
/// </summary>
/// <param name="name">The object type name.</param>
/// <param name="baseName">The IFC base name.</param>
/// <returns>True if equal, false otherwise.</returns>
private static bool IsEqualToTypeName(String name, String baseName)
{
if (String.Compare(name, baseName, true) == 0)
return true;
String typeName = baseName + "Type";
return (String.Compare(name, typeName, true) == 0);
}
/// <summary>
/// Gets export type from IFC class name.
/// </summary>
/// <param name="ifcClassName">The IFC class name.</param>
/// <returns>The export type.</returns>
public static IFCExportType GetExportTypeFromClassName(String ifcClassName)
{
if (String.Compare(ifcClassName, "IfcAnnotation", true) == 0)
{
// Used to mark curves, text, and filled regions for export.
return IFCExportType.ExportAnnotation;
}
else if (String.Compare(ifcClassName, "IfcBeam", true) == 0)
return IFCExportType.ExportBeam;
else if (String.Compare(ifcClassName, "IfcBuildingElementProxy", true) == 0)
return IFCExportType.ExportBuildingElementProxy;
else if (String.Compare(ifcClassName, "IfcBuildingStorey", true) == 0)
return IFCExportType.ExportBuildingStorey; // Only to be used for exporting level information!
else if (IsEqualToTypeName(ifcClassName, ("IfcColumn")))
return IFCExportType.ExportColumnType;
else if (String.Compare(ifcClassName, "IfcCovering", true) == 0)
return IFCExportType.ExportCovering;
else if (String.Compare(ifcClassName, "IfcCurtainWall", true) == 0)
return IFCExportType.ExportCurtainWall;
else if (IsEqualToTypeName(ifcClassName, ("IfcDoor")))
return IFCExportType.ExportDoorType;
else if (String.Compare(ifcClassName, "IfcFloor", true) == 0)
{
// IfcFloor is not a real type, but is being kept for backwards compatibility as a typo.
return IFCExportType.ExportSlab;
}
else if (IsEqualToTypeName(ifcClassName, ("IfcFooting")))
return IFCExportType.ExportFooting;
else if (String.Compare(ifcClassName, "IfcMember", true) == 0)
return IFCExportType.ExportMemberType;
else if (String.Compare(ifcClassName, "IfcOpeningElement", true) == 0)
{
// Used to mark reveals for export.
return IFCExportType.ExportOpeningElement;
}
else if (String.Compare(ifcClassName, "IfcPlate", true) == 0)
return IFCExportType.ExportPlateType;
else if (String.Compare(ifcClassName, "IfcRailing", true) == 0)
return IFCExportType.ExportRailing;
else if (String.Compare(ifcClassName, "IfcRamp", true) == 0)
return IFCExportType.ExportRamp;
else if (String.Compare(ifcClassName, "IfcRoof", true) == 0)
return IFCExportType.ExportRoof;
else if (String.Compare(ifcClassName, "IfcSite", true) == 0)
return IFCExportType.ExportSite;
else if (String.Compare(ifcClassName, "IfcSlab", true) == 0)
return IFCExportType.ExportSlab;
else if (String.Compare(ifcClassName, "IfcSpace", true) == 0)
{
// Not a real type; used to mark rooms for export.
return IFCExportType.ExportSpace;
}
else if (String.Compare(ifcClassName, "IfcStair", true) == 0)
return IFCExportType.ExportStair;
else if (IsEqualToTypeName(ifcClassName, ("IfcTransportElement")))
return IFCExportType.ExportTransportElementType;
else if (String.Compare(ifcClassName, "IfcWall", true) == 0)
return IFCExportType.ExportWall;
else if (IsEqualToTypeName(ifcClassName, ("IfcWindow")))
return IFCExportType.ExportWindowType;
// furnishing type(s) to be exported as geometry, not mapped item
else if (IsEqualToTypeName(ifcClassName, ("IfcFurnishingElement")))
return IFCExportType.ExportFurnishingElement;
// furnishing types to be exported as mapped item
else if (IsEqualToTypeName(ifcClassName, ("IfcFurniture")))
return IFCExportType.ExportFurnitureType;
else if (IsEqualToTypeName(ifcClassName, ("IfcSystemFurnitureElement")))
return IFCExportType.ExportSystemFurnitureElementType;
// distribution types to be exported as geometry, not mapped item
else if (IsEqualToTypeName(ifcClassName, ("IfcDistributionElement")))
return IFCExportType.ExportDistributionElement;
else if (IsEqualToTypeName(ifcClassName, ("IfcDistributionControlElement")))
return IFCExportType.ExportDistributionControlElement;
else if (IsEqualToTypeName(ifcClassName, ("IfcDistributionFlowElement")))
return IFCExportType.ExportDistributionFlowElement;
else if (IsEqualToTypeName(ifcClassName, ("IfcEnergyConversionDevice")))
return IFCExportType.ExportEnergyConversionDevice;
else if (IsEqualToTypeName(ifcClassName, ("IfcFlowFitting")))
return IFCExportType.ExportFlowFitting;
else if (IsEqualToTypeName(ifcClassName, ("IfcFlowMovingDevice")))
return IFCExportType.ExportFlowMovingDevice;
else if (IsEqualToTypeName(ifcClassName, ("IfcFlowSegment")))
return IFCExportType.ExportFlowSegment;
else if (IsEqualToTypeName(ifcClassName, ("IfcFlowSegmentStorageDevice")))
return IFCExportType.ExportFlowStorageDevice;
else if (IsEqualToTypeName(ifcClassName, ("IfcFlowTerminal")))
return IFCExportType.ExportFlowTerminal;
else if (IsEqualToTypeName(ifcClassName, ("IfcFlowTreatmentDevice")))
return IFCExportType.ExportFlowTreatmentDevice;
else if (IsEqualToTypeName(ifcClassName, ("IfcFlowController")))
return IFCExportType.ExportFlowController;
// distribution types to be exported as mapped item
else if (IsEqualToTypeName(ifcClassName, ("IfcActuator")))
return IFCExportType.ExportActuatorType;
else if (IsEqualToTypeName(ifcClassName, ("IfcAirTerminalBox")))
return IFCExportType.ExportAirTerminalBoxType;
else if (IsEqualToTypeName(ifcClassName, ("IfcAirTerminal")))
return IFCExportType.ExportAirTerminalType;
else if (IsEqualToTypeName(ifcClassName, ("IfcAirToAirHeatRecovery")))
return IFCExportType.ExportAirToAirHeatRecoveryType;
else if (IsEqualToTypeName(ifcClassName, ("IfcAlarm")))
return IFCExportType.ExportAlarmType;
else if (IsEqualToTypeName(ifcClassName, ("IfcBoiler")))
return IFCExportType.ExportBoilerType;
else if (IsEqualToTypeName(ifcClassName, ("IfcCableCarrierFitting")))
return IFCExportType.ExportCableCarrierFittingType;
else if (IsEqualToTypeName(ifcClassName, ("IfcCableCarrierSegment")))
return IFCExportType.ExportCableCarrierSegmentType;
else if (IsEqualToTypeName(ifcClassName, ("IfcCableSegment")))
return IFCExportType.ExportCableSegmentType;
else if (IsEqualToTypeName(ifcClassName, ("IfcChiller")))
return IFCExportType.ExportChillerType;
else if (IsEqualToTypeName(ifcClassName, ("IfcCoil")))
return IFCExportType.ExportCoilType;
else if (IsEqualToTypeName(ifcClassName, ("IfcCompressor")))
return IFCExportType.ExportCompressorType;
else if (IsEqualToTypeName(ifcClassName, ("IfcCondenser")))
return IFCExportType.ExportCondenserType;
else if (IsEqualToTypeName(ifcClassName, ("IfcController")))
return IFCExportType.ExportControllerType;
else if (IsEqualToTypeName(ifcClassName, ("IfcCooledBeam")))
return IFCExportType.ExportCooledBeamType;
else if (IsEqualToTypeName(ifcClassName, ("IfcCoolingTower")))
return IFCExportType.ExportCoolingTowerType;
else if (IsEqualToTypeName(ifcClassName, ("IfcDamper")))
return IFCExportType.ExportDamperType;
else if (IsEqualToTypeName(ifcClassName, ("IfcDistributionChamberElement")))
return IFCExportType.ExportDistributionChamberElementType;
else if (IsEqualToTypeName(ifcClassName, ("IfcDuctFitting")))
return IFCExportType.ExportDuctFittingType;
else if (IsEqualToTypeName(ifcClassName, ("IfcDuctSegment")))
return IFCExportType.ExportDuctSegmentType;
else if (IsEqualToTypeName(ifcClassName, ("IfcDuctSilencer")))
return IFCExportType.ExportDuctSilencerType;
else if (IsEqualToTypeName(ifcClassName, ("IfcElectricAppliance")))
return IFCExportType.ExportElectricApplianceType;
//else if (IsEqualToTypeName(ifcClassName, ("IfcElectricDistributionPoint")))
//return IFCExportType.ExportElectricDistributionPointType;
else if (IsEqualToTypeName(ifcClassName, ("IfcElectricFlowStorageDevice")))
return IFCExportType.ExportElectricFlowStorageDeviceType;
else if (IsEqualToTypeName(ifcClassName, ("IfcElectricGenerator")))
return IFCExportType.ExportElectricGeneratorType;
else if (IsEqualToTypeName(ifcClassName, ("IfcElectricHeater")))
return IFCExportType.ExportElectricHeaterType;
else if (IsEqualToTypeName(ifcClassName, ("IfcElectricMotor")))
return IFCExportType.ExportElectricMotorType;
else if (IsEqualToTypeName(ifcClassName, ("IfcElectricTimeControl")))
return IFCExportType.ExportElectricTimeControlType;
else if (IsEqualToTypeName(ifcClassName, ("IfcEnergyConversionDevice")))
return IFCExportType.ExportEnergyConversionDevice;
else if (IsEqualToTypeName(ifcClassName, ("IfcEvaporativeCooler")))
return IFCExportType.ExportEvaporativeCoolerType;
else if (IsEqualToTypeName(ifcClassName, ("IfcEvaporator")))
return IFCExportType.ExportEvaporatorType;
else if (IsEqualToTypeName(ifcClassName, ("IfcFan")))
return IFCExportType.ExportFanType;
else if (IsEqualToTypeName(ifcClassName, ("IfcFilter")))
return IFCExportType.ExportFilterType;
else if (IsEqualToTypeName(ifcClassName, ("IfcFireSuppressionTerminal")))
return IFCExportType.ExportFireSuppressionTerminalType;
else if (IsEqualToTypeName(ifcClassName, ("IfcFlowController")))
return IFCExportType.ExportFlowController;
else if (IsEqualToTypeName(ifcClassName, ("IfcFlowFitting")))
return IFCExportType.ExportFlowFitting;
else if (IsEqualToTypeName(ifcClassName, ("IfcFlowInstrument")))
return IFCExportType.ExportFlowInstrumentType;
else if (IsEqualToTypeName(ifcClassName, ("IfcFlowMeter")))
return IFCExportType.ExportFlowMeterType;
else if (IsEqualToTypeName(ifcClassName, ("IfcFlowMovingDevice")))
return IFCExportType.ExportFlowMovingDevice;
else if (IsEqualToTypeName(ifcClassName, ("IfcFlowSegment")))
return IFCExportType.ExportFlowSegment;
else if (IsEqualToTypeName(ifcClassName, ("IfcFlowStorageDevice")))
return IFCExportType.ExportFlowStorageDevice;
else if (IsEqualToTypeName(ifcClassName, ("IfcFlowTerminal")))
return IFCExportType.ExportFlowTerminal;
else if (IsEqualToTypeName(ifcClassName, ("IfcFlowTreatmentDevice")))
return IFCExportType.ExportFlowTreatmentDevice;
else if (IsEqualToTypeName(ifcClassName, ("IfcGasTerminal")))
return IFCExportType.ExportGasTerminalType;
else if (IsEqualToTypeName(ifcClassName, ("IfcHeatExchanger")))
return IFCExportType.ExportHeatExchangerType;
else if (IsEqualToTypeName(ifcClassName, ("IfcHumidifier")))
return IFCExportType.ExportHumidifierType;
else if (IsEqualToTypeName(ifcClassName, ("IfcJunctionBox")))
return IFCExportType.ExportJunctionBoxType;
else if (IsEqualToTypeName(ifcClassName, ("IfcLamp")))
return IFCExportType.ExportLampType;
else if (IsEqualToTypeName(ifcClassName, ("IfcLightFixture")))
return IFCExportType.ExportLightFixtureType;
else if (IsEqualToTypeName(ifcClassName, ("IfcMotorConnection")))
return IFCExportType.ExportMotorConnectionType;
else if (IsEqualToTypeName(ifcClassName, ("IfcOutlet")))
return IFCExportType.ExportOutletType;
else if (IsEqualToTypeName(ifcClassName, ("IfcPipeFitting")))
return IFCExportType.ExportPipeFittingType;
else if (IsEqualToTypeName(ifcClassName, ("IfcPipeSegment")))
return IFCExportType.ExportPipeSegmentType;
else if (IsEqualToTypeName(ifcClassName, ("IfcProtectiveDevice")))
return IFCExportType.ExportProtectiveDeviceType;
else if (IsEqualToTypeName(ifcClassName, ("IfcPump")))
return IFCExportType.ExportPumpType;
else if (IsEqualToTypeName(ifcClassName, ("IfcReinforcingBar")))
return IFCExportType.ExportReinforcingBar;
else if (IsEqualToTypeName(ifcClassName, ("IfcReinforcingMesh")))
return IFCExportType.ExportReinforcingMesh;
else if (IsEqualToTypeName(ifcClassName, ("IfcSanitaryTerminal")))
return IFCExportType.ExportSanitaryTerminalType;
else if (IsEqualToTypeName(ifcClassName, ("IfcSensor")))
return IFCExportType.ExportSensorType;
else if (IsEqualToTypeName(ifcClassName, ("IfcSpaceHeater")))
return IFCExportType.ExportSpaceHeaterType;
else if (IsEqualToTypeName(ifcClassName, ("IfcStackTerminal")))
return IFCExportType.ExportStackTerminalType;
else if (IsEqualToTypeName(ifcClassName, ("IfcSwitchingDevice")))
return IFCExportType.ExportSwitchingDeviceType;
else if (IsEqualToTypeName(ifcClassName, ("IfcTank")))
return IFCExportType.ExportTankType;
else if (IsEqualToTypeName(ifcClassName, ("IfcTransformer")))
return IFCExportType.ExportTransformerType;
else if (IsEqualToTypeName(ifcClassName, ("IfcTubeBundle")))
return IFCExportType.ExportTubeBundleType;
else if (IsEqualToTypeName(ifcClassName, ("IfcUnitaryEquipment")))
return IFCExportType.ExportUnitaryEquipmentType;
else if (IsEqualToTypeName(ifcClassName, ("IfcValve")))
return IFCExportType.ExportValveType;
else if (IsEqualToTypeName(ifcClassName, ("IfcWasteTerminal")))
return IFCExportType.ExportWasteTerminalType;
else if (ifcClassName.StartsWith("Ifc"))
{
throw new Exception("IFC: Unknown IFC type in getExportTypeFromClassName: " + ifcClassName);
}
return IFCExportType.DontExport;
}
// TODO: implement out bool exportSeparately
/// <summary>
/// Gets export type from category id.
/// </summary>
/// <param name="categoryId">The category id.</param>
/// <param name="ifcEnumType">The string value represents the IFC type.</param>
/// <returns>The export type.</returns>
public static IFCExportType GetExportTypeFromCategoryId(ElementId categoryId, out string ifcEnumType /*, out bool exportSeparately*/)
{
ifcEnumType = "";
//exportSeparately = true;
if (categoryId == new ElementId(BuiltInCategory.OST_Cornices))
return IFCExportType.ExportBeam;
else if (categoryId == new ElementId(BuiltInCategory.OST_Ceilings))
return IFCExportType.ExportCovering;
else if (categoryId == new ElementId(BuiltInCategory.OST_CurtainWallPanels))
{
ifcEnumType = "CURTAIN_PANEL";
//exportSeparately = false;
return IFCExportType.ExportPlateType;
}
else if (categoryId == new ElementId(BuiltInCategory.OST_Doors))
return IFCExportType.ExportDoorType;
else if (categoryId == new ElementId(BuiltInCategory.OST_Furniture))
return IFCExportType.ExportFurnitureType;
else if (categoryId == new ElementId(BuiltInCategory.OST_Floors))
{
ifcEnumType = "FLOOR";
return IFCExportType.ExportSlab;
}
else if (categoryId == new ElementId(BuiltInCategory.OST_Mass))
return IFCExportType.ExportBuildingElementProxy;
else if (categoryId == new ElementId(BuiltInCategory.OST_CurtainWallMullions))
{
ifcEnumType = "MULLION";
//exportSeparately = false;
return IFCExportType.ExportMemberType;
}
else if (categoryId == new ElementId(BuiltInCategory.OST_Railings))
return IFCExportType.ExportRailing;
else if (categoryId == new ElementId(BuiltInCategory.OST_Ramps))
return IFCExportType.ExportRamp;
else if (categoryId == new ElementId(BuiltInCategory.OST_Roofs))
return IFCExportType.ExportRoof;
else if (categoryId == new ElementId(BuiltInCategory.OST_Site))
return IFCExportType.ExportSite;
else if (categoryId == new ElementId(BuiltInCategory.OST_Stairs))
return IFCExportType.ExportStair;
else if (categoryId == new ElementId(BuiltInCategory.OST_Walls))
return IFCExportType.ExportWall;
else if (categoryId == new ElementId(BuiltInCategory.OST_Windows))
return IFCExportType.ExportWindowType;
return IFCExportType.DontExport;
}
/// <summary>
/// Gets element filter for specific views.
/// </summary>
/// <param name="exporter">The ExporterIFC object.</param>
/// <returns>The element filter.</returns>
private static ElementFilter GetViewSpecificTypesFilter(ExporterIFC exporter)
{
ElementFilter ownerViewFilter = GetOwnerViewFilter(exporter);
List<Type> viewSpecificTypes = new List<Type>();
viewSpecificTypes.Add(typeof(TextNote));
viewSpecificTypes.Add(typeof(FilledRegion));
ElementMulticlassFilter classFilter = new ElementMulticlassFilter(viewSpecificTypes);
LogicalAndFilter viewSpecificTypesFilter = new LogicalAndFilter(ownerViewFilter, classFilter);
return viewSpecificTypesFilter;
}
/// <summary>
/// Gets element filter to match elements which are owned by a particular view.
/// </summary>
/// <param name="exporter">The exporter.</param>
/// <returns>The element filter.</returns>
private static ElementFilter GetOwnerViewFilter(ExporterIFC exporter)
{
List<ElementFilter> filters = new List<ElementFilter>();
ICollection<ElementId> viewIds = exporter.GetViewIdsToExport();
foreach (ElementId id in viewIds)
{
filters.Add(new ElementOwnerViewFilter(id));
}
filters.Add(new ElementOwnerViewFilter(ElementId.InvalidElementId));
LogicalOrFilter viewFilters = new LogicalOrFilter(filters);
return viewFilters;
}
/// <summary>
/// Gets element filter that match certain types.
/// </summary>
/// <param name="forSpatialElements">True if to get filter for spatial element, false for other elements.</param>
/// <param name="exportAs2x2">True if it is to export IFC 2x2 version.</param>
/// <returns>The element filter.</returns>
private static ElementFilter GetClassFilter(bool forSpatialElements, bool exportAs2x2)
{
if (forSpatialElements)
{
return new ElementClassFilter(typeof(SpatialElement));
}
else
{
List<Type> excludedTypes = new List<Type>();
// FamilyInstances are handled in separate filter.
excludedTypes.Add(typeof(FamilyInstance));
excludedTypes.Add(typeof(SpatialElement));
if (exportAs2x2)
excludedTypes.Add(typeof(CurveElement));
excludedTypes.Add(typeof(ElementType));
excludedTypes.Add(typeof(Group));
excludedTypes.Add(typeof(BaseArray));
excludedTypes.Add(typeof(FillPatternElement));
excludedTypes.Add(typeof(LinePatternElement));
excludedTypes.Add(typeof(Material));
excludedTypes.Add(typeof(GraphicsStyle));
excludedTypes.Add(typeof(Family));
excludedTypes.Add(typeof(SketchPlane));
excludedTypes.Add(typeof(View));
excludedTypes.Add(typeof(Autodesk.Revit.DB.Structure.LoadBase));
excludedTypes.Add(typeof(BeamSystem));
// curtain wall sub-types we are ignoring.
excludedTypes.Add(typeof(CurtainGridLine));
// excludedTypes.Add(typeof(Mullion));
// this will be gotten from the element(s) it cuts.
excludedTypes.Add(typeof(Opening));
// 2D types we are ignoring
excludedTypes.Add(typeof(SketchBase));
excludedTypes.Add(typeof(FaceSplitter));
// 2D types covered by the element owner view filter
excludedTypes.Add(typeof(TextNote));
excludedTypes.Add(typeof(FilledRegion));
// exclude analytical models
excludedTypes.Add(typeof(Autodesk.Revit.DB.Structure.AnalyticalModel));
ElementFilter excludedClassFilter = new ElementMulticlassFilter(excludedTypes, true);
List<BuiltInCategory> excludedCategories = new List<BuiltInCategory>();
// Native Revit types without match in API
excludedCategories.Add(BuiltInCategory.OST_Property);
excludedCategories.Add(BuiltInCategory.OST_SiteProperty);
excludedCategories.Add(BuiltInCategory.OST_SitePropertyLineSegment);
excludedCategories.Add(BuiltInCategory.OST_Viewports);
excludedCategories.Add(BuiltInCategory.OST_Views);
excludedCategories.Add(BuiltInCategory.OST_IOS_GeoLocations);
excludedCategories.Add(BuiltInCategory.OST_RvtLinks);
excludedCategories.Add(BuiltInCategory.OST_DecalElement);
excludedCategories.Add(BuiltInCategory.OST_Parts);
ElementMulticategoryFilter excludedCategoryFilter = new ElementMulticategoryFilter(excludedCategories, true);
LogicalAndFilter exclusionFilter = new LogicalAndFilter(excludedClassFilter, excludedCategoryFilter);
ElementOwnerViewFilter ownerViewFilter = new ElementOwnerViewFilter(ElementId.InvalidElementId);
LogicalAndFilter returnedFilter = new LogicalAndFilter(exclusionFilter, ownerViewFilter);
return returnedFilter;
}
}
/// <summary>
/// Gets element filter that match certain phases.
/// </summary>
/// <param name="document">The Revit document.</param>
/// <returns>The element filter.</returns>
private static ElementFilter GetPhaseStatusFilter(Document document)
{
List<ElementOnPhaseStatus> phaseStatuses = new List<ElementOnPhaseStatus>();
phaseStatuses.Add(ElementOnPhaseStatus.None); //include "none" because we might want to export phaseless elements.
phaseStatuses.Add(ElementOnPhaseStatus.Existing);
phaseStatuses.Add(ElementOnPhaseStatus.New);
PhaseArray phaseArray = document.Phases;
Phase lastPhase = phaseArray.get_Item(phaseArray.Size - 1);
return new ElementPhaseStatusFilter(lastPhase.Id, phaseStatuses);
}
/// <summary>
/// Checks if element is visible for certain view.
/// </summary>
/// <param name="filterView">The view.</param>
/// <param name="element">The element.</param>
/// <returns>True if the element is visible, false otherwise.</returns>
public static bool IsElementVisible(View filterView, Element element)
{
Document doc = element.Document;
bool hidden = element.IsHidden(filterView);
if (hidden)
return false;
Category category = element.Category;
if (category != null && category.get_AllowsVisibilityControl(filterView) && !category.get_Visible(filterView))
return false;
bool temporaryVisible = filterView.IsElementVisibleInTemporaryViewMode(TemporaryViewMode.TemporaryHideIsolate, element.Id);
return temporaryVisible;
}
}
}
| {
"content_hash": "fdb7ca530b2a676f9872e0472ca3effa",
"timestamp": "",
"source": "github",
"line_count": 1032,
"max_line_length": 141,
"avg_line_length": 41.89728682170543,
"alnum_prop": 0.5982469124381331,
"repo_name": "ivanifan/RevitCustomIFCexporter",
"id": "00f8ef2a1880a36f2c7246a297c189cc8e498260",
"size": "43240",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tags/Release2012_1.0.4/Source/Utility/ElementFilteringUtil.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "4565"
},
{
"name": "C#",
"bytes": "20848566"
},
{
"name": "HTML",
"bytes": "185362"
}
],
"symlink_target": ""
} |
package com.google.gapid.widgets;
import com.google.gapid.util.BigPoint;
import com.google.gapid.util.MouseAdapter;
import com.google.gapid.widgets.CopyPaste.CopySource;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.internal.DPIUtil;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.ScrollBar;
import java.math.BigInteger;
import java.util.function.IntConsumer;
/**
* A {@link ScrolledComposite} where the contents can be too large in one or both dimensions to use
* a standard scrollbar. The scrollbar thumb will jump back to the center position when let go,
* while scrolling through the middle of the bulk of the scroll range.
*/
public class InfiniteScrolledComposite extends ScrolledComposite {
private static final BigInteger MAX_NON_INFINTE =
BigInteger.valueOf(DPIUtil.autoScaleDown((1 << 15)) - 1);
private final Scrollable contents;
private final Canvas canvas;
private final ScrollHandler xHandler, yHandler;
public InfiniteScrolledComposite(Composite parent, int style, Scrollable contents) {
super(parent, style);
this.contents = contents;
canvas = new Canvas(this, SWT.DOUBLE_BUFFERED);
this.xHandler = new ScrollHandler(getHorizontalBar(), x -> {
canvas.setLocation(x, canvas.getLocation().y);
canvas.redraw();
});
this.yHandler = new ScrollHandler(getVerticalBar(), y -> {
canvas.setLocation(canvas.getLocation().x, y);
canvas.redraw();
});
setContent(canvas);
setExpandVertical(true);
setExpandHorizontal(true);
updateMinSize();
addListener(SWT.Resize, e -> updateMinSize());
canvas.addListener(SWT.Paint, e -> contents.paint(xHandler.offset, yHandler.offset, e.gc));
}
public BigPoint getLocation(Event e) {
return new BigPoint(
xHandler.offset.add(BigInteger.valueOf(e.x)),
yHandler.offset.add(BigInteger.valueOf(e.y)));
}
public BigPoint getLocation(MouseEvent e) {
return new BigPoint(
xHandler.offset.add(BigInteger.valueOf(e.x)),
yHandler.offset.add(BigInteger.valueOf(e.y)));
}
public BigPoint getMouseLocation() {
Display disp = getDisplay();
Point mouse = disp.map(null, canvas, disp.getCursorLocation());
return new BigPoint(
xHandler.offset.add(BigInteger.valueOf(mouse.x)),
yHandler.offset.add(BigInteger.valueOf(mouse.y)));
}
public BigPoint getScrollLocation() {
return new BigPoint(
xHandler.offset.add(BigInteger.valueOf(xHandler.bar.getSelection())),
yHandler.offset.add(BigInteger.valueOf(yHandler.bar.getSelection())));
}
public void scrollTo(BigInteger x, BigInteger y) {
xHandler.scrollTo(x);
yHandler.scrollTo(y);
Widgets.scheduleIfNotDisposed(canvas, canvas::redraw);
}
@Override
public void redraw() {
super.redraw();
canvas.redraw();
}
public void addContentListener(int type, Listener listener) {
canvas.addListener(type, listener);
}
/**
* Registers the given listener on the contents. Note that the selection events are not included.
*/
public void addContentListener(MouseAdapter listener) {
canvas.addMouseListener(listener);
canvas.addMouseMoveListener(listener);
canvas.addMouseWheelListener(listener);
canvas.addMouseTrackListener(listener);
xHandler.bar.addSelectionListener(listener);
yHandler.bar.addSelectionListener(listener);
}
public void registerContentAsCopySource(CopyPaste copyPaste, CopySource source) {
copyPaste.registerCopySource(canvas, source);
}
public void updateMinSize() {
BigInteger w = contents.getWidth(), h = contents.getHeight();
Rectangle size = getClientArea();
xHandler.setEnabled(w.compareTo(MAX_NON_INFINTE) > 0);
yHandler.setEnabled(h.compareTo(MAX_NON_INFINTE) > 0);
xHandler.max = w.subtract(BigInteger.valueOf(size.width));
yHandler.max = h.subtract(BigInteger.valueOf(size.height));
int mw = (xHandler.enabled ? MAX_NON_INFINTE : w).intValueExact();
int mh = (yHandler.enabled ? MAX_NON_INFINTE : h).intValueExact();
setMinSize(mw, mh);
}
/**
* Contents to be scrolled.
*/
public static interface Scrollable {
/**
* @return the height of the scrolling contents in SWT points.
*/
public BigInteger getHeight();
/**
* @return the width of the scrolling contents in SWT points.
*/
public BigInteger getWidth();
/**
* Paints the contents at the given location using the given graphics context.
*/
public void paint(BigInteger xOffset, BigInteger yOffset, GC gc);
}
/**
* Hanldes the scroll events of an infinite scrollbar.
*/
private static class ScrollHandler extends SelectionAdapter {
public final ScrollBar bar;
private final IntConsumer updateLocation;
public BigInteger offset = BigInteger.ZERO;
public BigInteger max = BigInteger.ONE;
public boolean enabled = false;
public ScrollHandler(ScrollBar bar, IntConsumer updateLocation) {
this.bar = bar;
this.updateLocation = updateLocation;
bar.addSelectionListener(this);
}
public void setEnabled(boolean enabled) {
if (enabled != this.enabled) {
this.enabled = enabled;
this.offset = BigInteger.ZERO;
this.max = BigInteger.ONE;
}
}
public void scrollTo(BigInteger pos) {
if (enabled) {
int mid = getMidpoint(bar); BigInteger bigMid = BigInteger.valueOf(mid);
if (pos.compareTo(bigMid) <= 0) {
// Going to the top.
offset = BigInteger.ZERO;
bar.setSelection(pos.intValue());
updateLocation.accept(-pos.intValue());
} else if (pos.compareTo(max.subtract(bigMid)) >= 0) {
// Going to the bottom.
offset = max.subtract(bigMid).subtract(bigMid);
int selection = pos.min(max).subtract(offset).intValue();
bar.setSelection(selection);
updateLocation.accept(-selection);
} else {
// Going somewhere in the middle.
offset = pos.subtract(bigMid);
bar.setSelection(mid);
updateLocation.accept(-mid);
}
} else {
if (pos.compareTo(BigInteger.valueOf(bar.getMaximum() - bar.getThumb())) <= 0) {
int selection = pos.intValue();
bar.setSelection(selection);
updateLocation.accept(-selection);
}
}
}
@Override
public void widgetSelected(SelectionEvent e) {
if (enabled) {
int selection = bar.getSelection();
if ((e.stateMask & SWT.BUTTON1) != 0 &&
(e.detail == SWT.NONE || e.detail == SWT.DRAG)) {
// The user is scrolling by dragging the thumb thingie. Don't do anything.
} else {
// User has released the mouse or is scrolling in another fashion.
updateLocation.accept(-update(selection));
}
}
}
private int update(int selection) {
int mid = getMidpoint(bar);
BigInteger maxOffset = max.subtract(BigInteger.valueOf(2 * mid));
if (selection < mid && offset.equals(BigInteger.ZERO)) {
// We're scrolling near the top. Don't do anything.
} else if (selection > mid && offset.compareTo(maxOffset) >= 0) {
// We're scrolling near the bottom. Don't do anything.
} else if (selection == mid) {
// Don't do anything. Since the bar hasn't moved.
} else {
offset = offset.add(BigInteger.valueOf(selection - mid))
.max(BigInteger.ZERO).min(maxOffset);
bar.setSelection(mid);
selection = mid;
}
return selection;
}
private static int getMidpoint(ScrollBar bar) {
int min = bar.getMinimum(), max = bar.getMaximum(), thumb = bar.getThumb();
return (max - thumb - min) / 2 + min;
}
}
}
| {
"content_hash": "bcec13ef00a93be63463383e3a5b4ad7",
"timestamp": "",
"source": "github",
"line_count": 242,
"max_line_length": 99,
"avg_line_length": 34.21487603305785,
"alnum_prop": 0.6745169082125604,
"repo_name": "ek9852/gapid",
"id": "16432fbd1a227207e7ea65af80996320b9c5c852",
"size": "8879",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "gapic/src/main/com/google/gapid/widgets/InfiniteScrolledComposite.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "7873"
},
{
"name": "C",
"bytes": "227802"
},
{
"name": "C++",
"bytes": "1158948"
},
{
"name": "CMake",
"bytes": "402027"
},
{
"name": "GLSL",
"bytes": "24812"
},
{
"name": "Go",
"bytes": "4685920"
},
{
"name": "HTML",
"bytes": "128711"
},
{
"name": "Java",
"bytes": "1008429"
},
{
"name": "JavaScript",
"bytes": "13177"
},
{
"name": "Objective-C++",
"bytes": "12872"
},
{
"name": "Protocol Buffer",
"bytes": "127967"
},
{
"name": "Python",
"bytes": "917"
},
{
"name": "Shell",
"bytes": "13371"
}
],
"symlink_target": ""
} |
package org.cmuchimps.gort.modules.crowdanalysis.samples.helloworld;
import com.amazonaws.mturk.service.axis.RequesterService;
import com.amazonaws.mturk.service.exception.ServiceException;
import com.amazonaws.mturk.util.PropertiesClientConfig;
import com.amazonaws.mturk.requester.HIT;
/**
* The MTurk Hello World sample application creates a simple HIT via the Mechanical Turk
* Java SDK. mturk.properties must be found in the current file path.
*/
public class MTurkHelloWorld {
private RequesterService service;
// Defining the attributes of the HIT to be created
private String title = "Answer a question";
private String description =
"This is a HIT created by the Mechanical Turk SDK. Please answer the provided question.";
private int numAssignments = 1;
private double reward = 0.05;
/**
* Constructor
*
*/
public MTurkHelloWorld() {
service = new RequesterService(new PropertiesClientConfig("../mturk.properties"));
}
/**
* Check if there are enough funds in your account in order to create the HIT
* on Mechanical Turk
*
* @return true if there are sufficient funds. False if not.
*/
public boolean hasEnoughFund() {
double balance = service.getAccountBalance();
System.out.println("Got account balance: " + RequesterService.formatCurrency(balance));
return balance > reward;
}
/**
* Creates the simple HIT.
*
*/
public void createHelloWorld() {
try {
// The createHIT method is called using a convenience static method of
// RequesterService.getBasicFreeTextQuestion that generates the QAP for
// the HIT.
HIT hit = service.createHIT(
title,
description,
reward,
RequesterService.getBasicFreeTextQuestion(
"What is the weather like right now in Seattle, WA?"),
numAssignments);
System.out.println("Created HIT: " + hit.getHITId());
System.out.println("You may see your HIT with HITTypeId '"
+ hit.getHITTypeId() + "' here: ");
System.out.println(service.getWebsiteURL()
+ "/mturk/preview?groupId=" + hit.getHITTypeId());
} catch (ServiceException e) {
System.err.println(e.getLocalizedMessage());
}
}
/**
* Main method
*
* @param args
*/
public static void main(String[] args) {
MTurkHelloWorld app = new MTurkHelloWorld();
if (app.hasEnoughFund()) {
app.createHelloWorld();
System.out.println("Success.");
} else {
System.out.println("You do not have enough funds to create the HIT.");
}
}
}
| {
"content_hash": "f784f4da5baa8a1b77c72a91408130ec",
"timestamp": "",
"source": "github",
"line_count": 92,
"max_line_length": 94,
"avg_line_length": 28.684782608695652,
"alnum_prop": 0.665403561955286,
"repo_name": "samini/gort-public",
"id": "152c28bdc26cf394f16410e595cd6ffe313a3621",
"size": "3150",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Source/GortGUIv2/Gort/crowdanalysis/src/org/cmuchimps/gort/modules/crowdanalysis/samples/helloworld/MTurkHelloWorld.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "36395"
},
{
"name": "Groff",
"bytes": "1577"
},
{
"name": "HTML",
"bytes": "15840"
},
{
"name": "Java",
"bytes": "1292597"
},
{
"name": "Makefile",
"bytes": "4963"
},
{
"name": "Python",
"bytes": "532008"
},
{
"name": "Shell",
"bytes": "118901"
},
{
"name": "XSLT",
"bytes": "221100"
}
],
"symlink_target": ""
} |
layout: mitradgelegenheit
title: "Critical Mass Stuttgart"
date: 2015-03-06 17:30:00
categories: mitradgelegenheit
facebook-event: https://www.facebook.com/events/1413453822288842/
redirect_from: "/critical-mass/2015/02/17/erste-mitradgelegenheit.html"
---
Die MitRadGelegenheit zur [Critical Mass Stuttgart][CM-Stuttgart]{:target="_blank"} am 06. März 2015 wird die Erste in der Geschichte von MitRadStuttgart sein. Bei der Auswahl der Strecke haben wir auf folgende Punkte geachtet:
<div class="row">
<div class="col-xs-12 col-md-4" markdown='1'>
* Wir sind die Strecke bei einer Testfahrt Mitte Februar abgefahren. Dabei wurde darauf geachtet, dass sowohl die Beschaffenheit der Wege als auch die notwendige Geschwindigkeit (< 15 km/h) es allen Altersgruppen ermöglicht teilzunehmen.
</div>
<div class="col-xs-12 col-md-4" markdown='1'>
* Entlang des Wegs gibt es einige Zustiegsmöglichkeiten. Diese sind aufeinander abgestimmt und erlauben es die Wege dazwischen in angemessener Geschwindigkeit zu absolvieren.
</div>
<div class="col-xs-12 col-md-4" markdown='1'>
* An den Zustiegspunkten Böblingen und Vaihingen gibt es die Möglichkeit per S-Bahn dazuzustoßen. Das eignet sich beispielsweise, wenn man aus Renningen kommt oder in Herrenberg noch nicht um 15:30 Uhr losradeln kann. Angegeben sind jeweils die S-Bahn-Anschlüsse mit Fahrtrichtung Hauptbahnhof.
</div>
</div>
### Zustiegsmöglichkeiten
<div class="row">
<div class="col-md-6">
<h4>Bis Stuttgart</h4>
<div class="panel-group" id="accordionLeft" role="tablist" aria-multiselectable="true">
{% include meeting-point-open.html group="Left" id="Herrenberg" place="Herrenberg" point="Auf dem Graben" time="15:30 Uhr" expanded="true" %}
Um halb vier Uhr findet sich eine kleine Gruppe am Startpunkt der
Herrenberger Critical Mass ein. Doch, wie jeden ersten Freitag im
Monat, wird es nicht durch die Kleinstadt, sondern Richtung Stuttgart
zur dortigen Critical Mass gehen.
Weitere Informationen gibt es auf der Seite der <a href="https://criticalmassherrenberg.wordpress.com/" target="_blank">Critical Mass Herrenberg</a>.
{% include meeting-point-close.html %}
{% include meeting-point-open.html group="Left" id="Nufringen" place="Nufringen" point="Bahnhof" time="bei Bedarf" %}
Wer möchte, kann sich hier der MitRadGelegenheit anschließen. Damit
nicht ewig gewartet werden muss, empfiehlt es sich, sich mit der
Herrenberger Gruppe in Verbindung zu setzen. Dafür eignen sich unter
anderem deren Blog oder Twitter.
{% include meeting-point-close.html %}
{% include meeting-point-open.html group="Left" id="Gaertringen" place="Gärtringen" point="Bahnhof" time="bei Bedarf" %}
Wer möchte, kann sich hier der MitRadGelegenheit anschließen. Damit
nicht ewig gewartet werden muss, empfiehlt es sich, sich mit der
Herrenberger Gruppe in Verbindung zu setzen. Dafür eignen sich unter
anderem deren Blog oder Twitter.
{% include meeting-point-close.html %}
{% include meeting-point-open.html group="Left" id="Ehningen" place="Ehningen" point="Alter Friedhof" time="bei Bedarf" %}
Wer möchte, kann sich hier der MitRadGelegenheit anschließen. Damit
nicht ewig gewartet werden muss, empfiehlt es sich, sich mit der
Herrenberger Gruppe in Verbindung zu setzen. Dafür eignen sich unter
anderem deren Blog oder Twitter.
{% include meeting-point-close.html %}
{% include meeting-point-open.html group="Left" id="Boeblingen" place="Böblingen" point="Elbenplatz" time="16:40 Uhr" %}
Vermutlich trifft die Gruppe aus Herrenberg ein paar Minuten später
ein. Sollten sie aber schon früher da sein, geht es pünktlich weiter
Richtung Stuttgart-Vaihingen.
Die Route über die Kreisstraße K 1055 ist flacher als über die
Panzerstraße. Dafür befahren einige Autos die Strecke. Obwohl die
Strecke außerorts liegt und über keine Radinfrastruktur verfügt, gilt
sie als sicher. Sie wird von vielen FahrradfahrerInnen befahren.
<table class="table table-striped table-condensed">
<thead>
<tr>
<th>S-Bahn</th>
<th>Aus</th>
<th>Ankunft</th>
</tr>
</thead>
<tbody>
<tr>
<td><span class="fa fa-train"></span> S 1</td>
<td>Herrenberg</td>
<td><span class="fa fa-clock-o"></span> 16:30 Uhr</td>
</tr>
<tr>
<td><span class="fa fa-train"></span> S 60</td>
<td>Renningen</td>
<td><span class="fa fa-clock-o"></span> 16:26 Uhr</td>
</tr>
</tbody>
</table>
{% include meeting-point-close.html %}
</div>
</div>
<div class="col-md-6">
<h4>In Stuttgart</h4>
<div class="panel-group" id="accordionRight" role="tablist" aria-multiselectable="true">
{% include meeting-point-open.html group="Right" id="Vaihingen" place="S-Vaihingen" point="Reisezentrum Bahnhof" time="17:30 Uhr" %}
Schon deutlich vor halb sechs werden die ersten FahradfahrerInnen am
Reisezentrum am Bahnhof Vaihingen eintreffen und Werbung für die
Critical Mass Stuttgart machen.
Wenn die Gruppe aus Herrenberg rechtzeitig eintrifft, geht es
pünktlich um halb sechs Uhr weiter. Richtung Möhringen nutzen wir,
gemäß der Stuttgarter Hauptradroutenplanung, die Möhringer
Landstraße/Vaihinger Straße (HRR 10.2) um schließlich in
Möhringen durch die Leinenweberstraße und Balinger Straße zur
Nordseite des Bahnhofs zu gelangen.
<table class="table table-striped table-condensed">
<thead>
<tr>
<th>S-Bahn</th>
<th>Aus</th>
<th>Ankunft</th>
</tr>
</thead>
<tbody>
<tr>
<td><span class="fa fa-train"></span> S 1</td>
<td>Herrenberg</td>
<td><span class="fa fa-clock-o"></span> 17:25 Uhr</td>
</tr>
<tr>
<td><span class="fa fa-train"></span> S 2</td>
<td>Filderstadt</td>
<td><span class="fa fa-clock-o"></span> 17:20 Uhr</td>
</tr>
<tr>
<td><span class="fa fa-train"></span> S 3</td>
<td>Flughafen/Messe</td>
<td><span class="fa fa-clock-o"></span> 17:15 Uhr</td>
</tr>
</tbody>
</table>
{% include meeting-point-image.html url="/images/vaihingen-bahnhof-small.jpg" alt="Treffpunkt Reisezentrum Bahnhof in Stuttgart-Vaihingen" %}
{% include meeting-point-close.html %}
{% include meeting-point-open.html group="Right" id="Moehringen" place="S-Möhringen" point="Nordseite Bahnhof" time="17:45 Uhr" %}
Wenn wir am Bahnhof Möhringen eintreffen, werden wir uns gespannt
umsehen, ob jemand auf uns wartet. Auf jeden Fall werden 1–2 unserer
Gruppe eine kleine Runde zur Südseite des Bahnhofs drehen und für die
Critical Mass werben.
Pünktlich um dreiviertel sechs müssen wir weiter, damit auf dem Weg
nach Degerloch möglichst viele RadlerInnen angesprochen werden können.
Über die Probststraße (HRR 10.1) geht es Richtung Sonnenberg.
Dort wäre auch eine gute Möglichkeit in die MitRadGelegenheit
einzusteigen. Nach Degerloch führt uns schließlich der Höhenrandweg
(HRR 10).
{% include meeting-point-image.html url="/images/moehringen-bahnhof-small.jpg" alt="Treffpunkt Möhringen Bahnhof" %}
{% include meeting-point-close.html %}
{% include meeting-point-open.html group="Right" id="Degerloch" place="S-Degerloch" point="Bahnhof Zacke" time="18:00 Uhr" %}
Der Bahnhof der Zacke ist leider nicht legal mit dem Fahrrad zu
erreichen. Somit wird die Gruppe die B 27 (Löffelstraße)
überqueren und in der Josefstraße (Nordeingang U-Bahnhof) warten,
während sich ein kleiner Teil zum Treffpunkt begibt und die Wartenden
abholt.
Ab Degerloch müssen wir leider das Hauptradroutennetz verlassen und
nutzen den Schießbahn- und Lerchenrainweg ins Tal. Da die Ausleitung
in die Karl-Kloß-Straße erst im Zuge der Downhillstrecke gebaut wird,
fahren wir über die Eierstraße zur Matthäuskirche am
Erwin-Schoettle-Platz.
Es gibt neben der gewählten Strecke zahlreiche weitere Wege in den
Stuttgarter Talkessel. Das Ziel Feuersee vor Augen scheint die
gewählte Route am geeignetsten was Befahrbarkeit (Kinder, Anhänger, …)
und Distanz betrifft.
{% include meeting-point-image.html url="/images/degerloch-bahnhof-small.jpg" alt="Treffpunkt Bahnhof der Zacke in Degerloch" %}
{% include meeting-point-close.html %}
{% include meeting-point-open.html group="Right" id="Schoettle" place="Stuttgart-Süd" point="Erwin-Schoettle-Platz" time="bei Bedarf" %}
Der Erwin-Schoettle-Platz wird nur gestreift. Wer hier zusteigen
möchte wartet am besten an der Ostseite der Matthäuskirche (Kreuzung
Eierstraße/Möhringer Straße) am Tallängsweg (HRR 1). Es ist
ratsam sich um 18:10 Uhr an besagter Stelle einzufinden.
Im weiteren Verlauf geht es entlang des Tallängswegs über die
Möhringer Straße und die Böblinger Straße zum Marienplatz. Der
Schwenk in die Böblinger Straße ist notwendig, da der Tallängsweg auf
den freigegebenen Bürgersteig führt. Dort ist es selbst für einzelne
Fahrradfahrer zu eng.
<div style="width:100%; text-align:center;">
<em>Photo folgt</em>
</div>
{% include meeting-point-close.html %}
{% include meeting-point-open.html group="Right" id="Marienplatz" place="Stuttgart-Süd" point="Marienplatz" time="18:20 Uhr" %}
Am Marienplatz, im Bereich des Beginns der Tübinger Straße, befindet
sich der letzte Halt der MitRadGelegenheit vor der Critical Mass.
Für alle, die die MitRadGelegenheit unterstützen wollen, aber nicht
entlang der Strecke wohnen oder arbeiten, ist hier der passende
Einstieg. Wir freuen uns über jede moralische Unterstützung beim
bevorstehenden Anstieg die Hohenstaufenstraße entlang.
Bevor wir den Treffpunkt der Critical Mass Stuttgart erreichen, fahren
wir erst auf der Rotebühlstraße daran vorbei. Dabei hoffen wir auf
entsprechende Begrüßung durch die wartende Masse.
{% include meeting-point-image.html url="/images/marienplatz-small.jpg" alt="Treffpunkt Marienplatz" %}
{% include meeting-point-close.html %}
{% include meeting-point-open.html group="Right" id="Feuersee" place="Stuttgart" point="Feuersee" time="18:30 Uhr" %}
Hier liegt das Ziel der MitRadGelegenheit. Gegen halb sieben, und
somit rechtzeitig zum Start, werden wir eintreffen. Da es in der
Regel erst ein paar Minuten später losgeht, bleibt auch noch die
Gelegenheit sich zu unterhalten.
Wer hier wartet fühle sich hiermit dazu aufgefordert die
MitRadGelegenheit bei ihrer Vorbeifahrt entlang der Rotebühlstraße
entsprechend zu begrüßen. ;)
{% include meeting-point-close.html %}
</div>
</div>
</div>
### Karte
{% include map.html %}
<div id="mitradmap" style="width:100%; height: 100px;"></div>
<script>
$(document).ready(function(){
makeMap(
"/maps/critical-mass/stuttgart-2015-03-06.geojson",
"mitradmap",
["Herrenberg", "Böblingen", "S-Vaihingen", "Critical Mass Stuttgart"]
);
});
</script>
[CM-Stuttgart]: https://criticalmassstuttgart.wordpress.com/
| {
"content_hash": "6dd14d91fb291fc37d030a364e5cbcf6",
"timestamp": "",
"source": "github",
"line_count": 250,
"max_line_length": 296,
"avg_line_length": 42.876,
"alnum_prop": 0.7494169232204496,
"repo_name": "mitradstuttgart/test",
"id": "dbfa0c3c68132a2666be7490b3bbec1b773c619e",
"size": "10838",
"binary": false,
"copies": "2",
"ref": "refs/heads/gh-pages",
"path": "_posts/mrg/2015-03-06-cm-stuttgart.markdown",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "11234"
},
{
"name": "HTML",
"bytes": "15900"
},
{
"name": "JavaScript",
"bytes": "8155"
},
{
"name": "Ruby",
"bytes": "3086"
}
],
"symlink_target": ""
} |
package Mar2021Leetcode;
import java.util.Arrays;
public class _0322CoinChange {
public static void main(String[] args) {
System.out.println(coinChange(new int[] { 1, 2, 5 }, 11));
System.out.println(coinChange(new int[] { 2 }, 3));
System.out.println(coinChange(new int[] { 1 }, 0));
System.out.println(coinChange(new int[] { 1 }, 1));
System.out.println(coinChange(new int[] { 1 }, 2));
System.out.println(coinChange(new int[] { 2, 5, 10, 1 }, 27));
System.out.println(coinChange(new int[] { 186, 419, 83, 408 }, 6249));
}
public static int coinChange(int[] coins, int amount) {
}
}
| {
"content_hash": "053577b27e42626976562105bea496d5",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 72,
"avg_line_length": 27.818181818181817,
"alnum_prop": 0.6503267973856209,
"repo_name": "darshanhs90/Java-InterviewPrep",
"id": "bd9ec1cb6cb64a6533440ce4f5b8dbea8251daed",
"size": "612",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Mar2021Leetcode/_0322CoinChange.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "1870066"
}
],
"symlink_target": ""
} |
package i5.las2peer.services.fileService;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
public class MIMEMapper
{
public static final String DEFAULT_MIME = "text/plain";
private static HashMap<String, String> typeMapping = new HashMap<String, String>();
private static MIMEMapper mapper;
private MIMEMapper()
{
initMapping();
}
private void initMapping()
{
String mimeTypes = null;
try {
mimeTypes = new String(LocalFileManager.getFile(new File("./etc/MIME.txt")), "UTF-8");
} catch (UnsupportedEncodingException e) {
mimeTypes = null;
}
if (mimeTypes == null)// backup plan if no file
{
typeMapping.put("html", "text/html");
typeMapping.put("js", "text/javascript");
typeMapping.put("css", "text/css");
typeMapping.put("txt", "text/plain");
}
else
{
String[] mimeLines = mimeTypes.split("\n");
for (int i = 0; i < mimeLines.length; i++)
{
String[] lineParts = mimeLines[i].trim().split(" ");
if (lineParts.length > 1)
{
String mime = lineParts[0];
for (int j = lineParts.length - 1; j > 0; j--)
{
typeMapping.put(lineParts[j].trim(), mime);
}
}
}
}
}
private static MIMEMapper getMapper()
{
if (mapper == null)
mapper = new MIMEMapper();
return mapper;
}
public static String getMIME(String path)
{
getMapper();
int lastDot = path.indexOf('.');
if (lastDot > 0)// file
{
String extension = path.substring(lastDot + 1).trim().toLowerCase();
String mime = typeMapping.get(extension);
if (mime != null)
{
return mime;
}
else
{
return DEFAULT_MIME;
}
}
else
return null;
}
}
| {
"content_hash": "ef42d5f96d4250260b0930640f22633c",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 89,
"avg_line_length": 20.154761904761905,
"alnum_prop": 0.6337861783815711,
"repo_name": "rwth-acis/LAS2peer-File-Service",
"id": "60915f305aa46d4df6fc8370b02aaf581e51b8ef",
"size": "1693",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/i5/las2peer/services/fileService/MIMEMapper.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "559"
},
{
"name": "HTML",
"bytes": "139"
},
{
"name": "Java",
"bytes": "15149"
},
{
"name": "Shell",
"bytes": "713"
}
],
"symlink_target": ""
} |
This document explains where and how to get help with most of my projects.
Please ensure you read through it thoroughly.
> :point_right: **Note**: before participating in the community, please read our
> [Code of Conduct][coc].
> By interacting with this repository, organization, or community you agree to
> abide by its terms.
## :grey_question: Asking quality questions
Questions can go to [Github Discussions][discussions] or feel free to join
the Discord [here][chat].
Help me help you! Spend time framing questions and add links and resources.
Spending the extra time up front can help save everyone time in the long run.
Here are some tips:
* Don't fall for the [XY problem][xy].
* Search to find out if a similar question has been asked or if a similar
issue/bug has been reported.
* Try to define what you need help with:
* Is there something in particular you want to do?
* What problem are you encountering and what steps have you taken to try
and fix it?
* Is there a concept you don't understand?
* Provide sample code, such as a [CodeSandbox][cs] or a simple snippet, if
possible.
* Screenshots can help, but if there's important text such as code or error
messages in them, please also provide those.
* The more time you put into asking your question, the better I and others
can help you.
## :old_key: Security
For any security or vulnerability related disclosure, please follow the
guidelines outlined in our [security policy][security].
## :handshake: Contributions
See [`CONTRIBUTING.md`][contributing] on how to contribute.
<!-- definitions -->
[coc]: https://github.com/lrstanley/girc/blob/master/.github/CODE_OF_CONDUCT.md
[contributing]: https://github.com/lrstanley/girc/blob/master/.github/CONTRIBUTING.md
[discussions]: https://github.com/lrstanley/girc/discussions/categories/q-a
[issues]: https://github.com/lrstanley/girc/issues/new/choose
[license]: https://github.com/lrstanley/girc/blob/master/LICENSE
[pull-requests]: https://github.com/lrstanley/girc/issues/new/choose
[security]: https://github.com/lrstanley/girc/security/policy
[support]: https://github.com/lrstanley/girc/blob/master/.github/SUPPORT.md
[xy]: https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem/66378#66378
[chat]: https://liam.sh/chat
[cs]: https://codesandbox.io
| {
"content_hash": "21a60fb4399407500be38671bc40a362",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 87,
"avg_line_length": 43.074074074074076,
"alnum_prop": 0.7566638005159071,
"repo_name": "lrstanley/girc",
"id": "026a796e5f9c7ca1dd3ab480d9a69324fd14b1af",
"size": "2356",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": ".github/SUPPORT.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "235499"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="ApiGen 2.8.0" />
<title>Namespace Symfony\Component\Security\Tests | seip</title>
<script type="text/javascript" src="resources/combined.js?784181472"></script>
<script type="text/javascript" src="elementlist.js?3927760630"></script>
<link rel="stylesheet" type="text/css" media="all" href="resources/style.css?3505392360" />
</head>
<body>
<div id="left">
<div id="menu">
<a href="index.html" title="Overview"><span>Overview</span></a>
<div id="groups">
<h3>Namespaces</h3>
<ul>
<li><a href="namespace-Acme.html">Acme<span></span></a>
<ul>
<li><a href="namespace-Acme.DemoBundle.html">DemoBundle<span></span></a>
<ul>
<li><a href="namespace-Acme.DemoBundle.Command.html">Command</a>
</li>
<li><a href="namespace-Acme.DemoBundle.Controller.html">Controller</a>
</li>
<li><a href="namespace-Acme.DemoBundle.DependencyInjection.html">DependencyInjection</a>
</li>
<li><a href="namespace-Acme.DemoBundle.EventListener.html">EventListener</a>
</li>
<li><a href="namespace-Acme.DemoBundle.Form.html">Form</a>
</li>
<li><a href="namespace-Acme.DemoBundle.Proxy.html">Proxy<span></span></a>
<ul>
<li><a href="namespace-Acme.DemoBundle.Proxy.__CG__.html">__CG__<span></span></a>
<ul>
<li><a href="namespace-Acme.DemoBundle.Proxy.__CG__.Symfony.html">Symfony<span></span></a>
<ul>
<li><a href="namespace-Acme.DemoBundle.Proxy.__CG__.Symfony.Component.html">Component<span></span></a>
<ul>
<li><a href="namespace-Acme.DemoBundle.Proxy.__CG__.Symfony.Component.Security.html">Security<span></span></a>
<ul>
<li><a href="namespace-Acme.DemoBundle.Proxy.__CG__.Symfony.Component.Security.Acl.html">Acl<span></span></a>
<ul>
<li><a href="namespace-Acme.DemoBundle.Proxy.__CG__.Symfony.Component.Security.Acl.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Acme.DemoBundle.Proxy.__CG__.Symfony.Component.Security.Acl.Tests.Domain.html">Domain</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Acme.DemoBundle.Proxy.__CG__.Symfony.Component.Security.Core.html">Core<span></span></a>
<ul>
<li><a href="namespace-Acme.DemoBundle.Proxy.__CG__.Symfony.Component.Security.Core.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Acme.DemoBundle.Proxy.__CG__.Symfony.Component.Security.Core.Tests.Util.html">Util</a>
</li>
</ul></li></ul></li></ul></li></ul></li></ul></li></ul></li></ul></li>
<li><a href="namespace-Acme.DemoBundle.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Acme.DemoBundle.Tests.Controller.html">Controller</a>
</li>
</ul></li>
<li><a href="namespace-Acme.DemoBundle.Twig.html">Twig<span></span></a>
<ul>
<li><a href="namespace-Acme.DemoBundle.Twig.Extension.html">Extension</a>
</li>
</ul></li></ul></li></ul></li>
<li><a href="namespace-Alpha.html">Alpha</a>
</li>
<li><a href="namespace-Apc.html">Apc<span></span></a>
<ul>
<li><a href="namespace-Apc.NamespaceCollision.html">NamespaceCollision<span></span></a>
<ul>
<li><a href="namespace-Apc.NamespaceCollision.A.html">A<span></span></a>
<ul>
<li><a href="namespace-Apc.NamespaceCollision.A.B.html">B</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Apc.Namespaced.html">Namespaced</a>
</li>
</ul></li>
<li><a href="namespace-Assetic.html">Assetic<span></span></a>
<ul>
<li><a href="namespace-Assetic.Asset.html">Asset<span></span></a>
<ul>
<li><a href="namespace-Assetic.Asset.Iterator.html">Iterator</a>
</li>
</ul></li>
<li><a href="namespace-Assetic.Cache.html">Cache</a>
</li>
<li><a href="namespace-Assetic.Exception.html">Exception</a>
</li>
<li><a href="namespace-Assetic.Extension.html">Extension<span></span></a>
<ul>
<li><a href="namespace-Assetic.Extension.Twig.html">Twig</a>
</li>
</ul></li>
<li><a href="namespace-Assetic.Factory.html">Factory<span></span></a>
<ul>
<li><a href="namespace-Assetic.Factory.Loader.html">Loader</a>
</li>
<li><a href="namespace-Assetic.Factory.Resource.html">Resource</a>
</li>
<li><a href="namespace-Assetic.Factory.Worker.html">Worker</a>
</li>
</ul></li>
<li><a href="namespace-Assetic.Filter.html">Filter<span></span></a>
<ul>
<li><a href="namespace-Assetic.Filter.GoogleClosure.html">GoogleClosure</a>
</li>
<li><a href="namespace-Assetic.Filter.Sass.html">Sass</a>
</li>
<li><a href="namespace-Assetic.Filter.Yui.html">Yui</a>
</li>
</ul></li>
<li><a href="namespace-Assetic.Util.html">Util</a>
</li>
</ul></li>
<li><a href="namespace-Bazinga.html">Bazinga<span></span></a>
<ul>
<li><a href="namespace-Bazinga.Bundle.html">Bundle<span></span></a>
<ul>
<li><a href="namespace-Bazinga.Bundle.JsTranslationBundle.html">JsTranslationBundle<span></span></a>
<ul>
<li><a href="namespace-Bazinga.Bundle.JsTranslationBundle.Command.html">Command</a>
</li>
<li><a href="namespace-Bazinga.Bundle.JsTranslationBundle.Controller.html">Controller</a>
</li>
<li><a href="namespace-Bazinga.Bundle.JsTranslationBundle.DependencyInjection.html">DependencyInjection<span></span></a>
<ul>
<li><a href="namespace-Bazinga.Bundle.JsTranslationBundle.DependencyInjection.Compiler.html">Compiler</a>
</li>
</ul></li>
<li><a href="namespace-Bazinga.Bundle.JsTranslationBundle.Dumper.html">Dumper</a>
</li>
<li><a href="namespace-Bazinga.Bundle.JsTranslationBundle.Finder.html">Finder</a>
</li>
<li><a href="namespace-Bazinga.Bundle.JsTranslationBundle.Tests.html">Tests</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Bazinga.JsTranslationBundle.html">JsTranslationBundle<span></span></a>
<ul>
<li><a href="namespace-Bazinga.JsTranslationBundle.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Bazinga.JsTranslationBundle.Tests.Controller.html">Controller</a>
</li>
<li><a href="namespace-Bazinga.JsTranslationBundle.Tests.Finder.html">Finder</a>
</li>
</ul></li></ul></li></ul></li>
<li><a href="namespace-Beta.html">Beta</a>
</li>
<li><a href="namespace-Blameable.html">Blameable<span></span></a>
<ul>
<li><a href="namespace-Blameable.Fixture.html">Fixture<span></span></a>
<ul>
<li><a href="namespace-Blameable.Fixture.Document.html">Document</a>
</li>
<li><a href="namespace-Blameable.Fixture.Entity.html">Entity</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-ClassesWithParents.html">ClassesWithParents</a>
</li>
<li><a href="namespace-ClassLoaderTest.html">ClassLoaderTest</a>
</li>
<li><a href="namespace-ClassMap.html">ClassMap</a>
</li>
<li><a href="namespace-Composer.html">Composer<span></span></a>
<ul>
<li><a href="namespace-Composer.Autoload.html">Autoload</a>
</li>
</ul></li>
<li><a href="namespace-Container14.html">Container14</a>
</li>
<li><a href="namespace-Doctrine.html">Doctrine<span></span></a>
<ul>
<li><a href="namespace-Doctrine.Bundle.html">Bundle<span></span></a>
<ul>
<li><a href="namespace-Doctrine.Bundle.DoctrineBundle.html">DoctrineBundle<span></span></a>
<ul>
<li><a href="namespace-Doctrine.Bundle.DoctrineBundle.Command.html">Command<span></span></a>
<ul>
<li><a href="namespace-Doctrine.Bundle.DoctrineBundle.Command.Proxy.html">Proxy</a>
</li>
</ul></li>
<li><a href="namespace-Doctrine.Bundle.DoctrineBundle.Controller.html">Controller</a>
</li>
<li><a href="namespace-Doctrine.Bundle.DoctrineBundle.DataCollector.html">DataCollector</a>
</li>
<li><a href="namespace-Doctrine.Bundle.DoctrineBundle.DependencyInjection.html">DependencyInjection</a>
</li>
<li><a href="namespace-Doctrine.Bundle.DoctrineBundle.Mapping.html">Mapping</a>
</li>
<li><a href="namespace-Doctrine.Bundle.DoctrineBundle.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Doctrine.Bundle.DoctrineBundle.Tests.DependencyInjection.html">DependencyInjection</a>
</li>
</ul></li>
<li><a href="namespace-Doctrine.Bundle.DoctrineBundle.Twig.html">Twig</a>
</li>
</ul></li>
<li><a href="namespace-Doctrine.Bundle.FixturesBundle.html">FixturesBundle<span></span></a>
<ul>
<li><a href="namespace-Doctrine.Bundle.FixturesBundle.Command.html">Command</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Doctrine.Common.html">Common<span></span></a>
<ul>
<li><a href="namespace-Doctrine.Common.Annotations.html">Annotations<span></span></a>
<ul>
<li><a href="namespace-Doctrine.Common.Annotations.Annotation.html">Annotation</a>
</li>
</ul></li>
<li><a href="namespace-Doctrine.Common.Cache.html">Cache</a>
</li>
<li><a href="namespace-Doctrine.Common.Collections.html">Collections<span></span></a>
<ul>
<li><a href="namespace-Doctrine.Common.Collections.Expr.html">Expr</a>
</li>
</ul></li>
<li><a href="namespace-Doctrine.Common.DataFixtures.html">DataFixtures<span></span></a>
<ul>
<li><a href="namespace-Doctrine.Common.DataFixtures.Event.html">Event<span></span></a>
<ul>
<li><a href="namespace-Doctrine.Common.DataFixtures.Event.Listener.html">Listener</a>
</li>
</ul></li>
<li><a href="namespace-Doctrine.Common.DataFixtures.Exception.html">Exception</a>
</li>
<li><a href="namespace-Doctrine.Common.DataFixtures.Executor.html">Executor</a>
</li>
<li><a href="namespace-Doctrine.Common.DataFixtures.Purger.html">Purger</a>
</li>
</ul></li>
<li><a href="namespace-Doctrine.Common.Inflector.html">Inflector</a>
</li>
<li><a href="namespace-Doctrine.Common.Lexer.html">Lexer</a>
</li>
<li><a href="namespace-Doctrine.Common.Persistence.html">Persistence<span></span></a>
<ul>
<li><a href="namespace-Doctrine.Common.Persistence.Event.html">Event</a>
</li>
<li><a href="namespace-Doctrine.Common.Persistence.Mapping.html">Mapping<span></span></a>
<ul>
<li><a href="namespace-Doctrine.Common.Persistence.Mapping.Driver.html">Driver</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Doctrine.Common.Proxy.html">Proxy<span></span></a>
<ul>
<li><a href="namespace-Doctrine.Common.Proxy.Exception.html">Exception</a>
</li>
</ul></li>
<li><a href="namespace-Doctrine.Common.Reflection.html">Reflection</a>
</li>
<li><a href="namespace-Doctrine.Common.Util.html">Util</a>
</li>
</ul></li>
<li><a href="namespace-Doctrine.DBAL.html">DBAL<span></span></a>
<ul>
<li><a href="namespace-Doctrine.DBAL.Cache.html">Cache</a>
</li>
<li><a href="namespace-Doctrine.DBAL.Connections.html">Connections</a>
</li>
<li><a href="namespace-Doctrine.DBAL.Driver.html">Driver<span></span></a>
<ul>
<li><a href="namespace-Doctrine.DBAL.Driver.DrizzlePDOMySql.html">DrizzlePDOMySql</a>
</li>
<li><a href="namespace-Doctrine.DBAL.Driver.IBMDB2.html">IBMDB2</a>
</li>
<li><a href="namespace-Doctrine.DBAL.Driver.Mysqli.html">Mysqli</a>
</li>
<li><a href="namespace-Doctrine.DBAL.Driver.OCI8.html">OCI8</a>
</li>
<li><a href="namespace-Doctrine.DBAL.Driver.PDOIbm.html">PDOIbm</a>
</li>
<li><a href="namespace-Doctrine.DBAL.Driver.PDOMySql.html">PDOMySql</a>
</li>
<li><a href="namespace-Doctrine.DBAL.Driver.PDOOracle.html">PDOOracle</a>
</li>
<li><a href="namespace-Doctrine.DBAL.Driver.PDOPgSql.html">PDOPgSql</a>
</li>
<li><a href="namespace-Doctrine.DBAL.Driver.PDOSqlite.html">PDOSqlite</a>
</li>
<li><a href="namespace-Doctrine.DBAL.Driver.PDOSqlsrv.html">PDOSqlsrv</a>
</li>
<li><a href="namespace-Doctrine.DBAL.Driver.SQLSrv.html">SQLSrv</a>
</li>
</ul></li>
<li><a href="namespace-Doctrine.DBAL.Event.html">Event<span></span></a>
<ul>
<li><a href="namespace-Doctrine.DBAL.Event.Listeners.html">Listeners</a>
</li>
</ul></li>
<li><a href="namespace-Doctrine.DBAL.Id.html">Id</a>
</li>
<li><a href="namespace-Doctrine.DBAL.Logging.html">Logging</a>
</li>
<li><a href="namespace-Doctrine.DBAL.Platforms.html">Platforms<span></span></a>
<ul>
<li><a href="namespace-Doctrine.DBAL.Platforms.Keywords.html">Keywords</a>
</li>
</ul></li>
<li><a href="namespace-Doctrine.DBAL.Portability.html">Portability</a>
</li>
<li><a href="namespace-Doctrine.DBAL.Query.html">Query<span></span></a>
<ul>
<li><a href="namespace-Doctrine.DBAL.Query.Expression.html">Expression</a>
</li>
</ul></li>
<li><a href="namespace-Doctrine.DBAL.Schema.html">Schema<span></span></a>
<ul>
<li><a href="namespace-Doctrine.DBAL.Schema.Synchronizer.html">Synchronizer</a>
</li>
<li><a href="namespace-Doctrine.DBAL.Schema.Visitor.html">Visitor</a>
</li>
</ul></li>
<li><a href="namespace-Doctrine.DBAL.Sharding.html">Sharding<span></span></a>
<ul>
<li><a href="namespace-Doctrine.DBAL.Sharding.ShardChoser.html">ShardChoser</a>
</li>
<li><a href="namespace-Doctrine.DBAL.Sharding.SQLAzure.html">SQLAzure<span></span></a>
<ul>
<li><a href="namespace-Doctrine.DBAL.Sharding.SQLAzure.Schema.html">Schema</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Doctrine.DBAL.Tools.html">Tools<span></span></a>
<ul>
<li><a href="namespace-Doctrine.DBAL.Tools.Console.html">Console<span></span></a>
<ul>
<li><a href="namespace-Doctrine.DBAL.Tools.Console.Command.html">Command</a>
</li>
<li><a href="namespace-Doctrine.DBAL.Tools.Console.Helper.html">Helper</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Doctrine.DBAL.Types.html">Types</a>
</li>
</ul></li>
<li><a href="namespace-Doctrine.ORM.html">ORM<span></span></a>
<ul>
<li><a href="namespace-Doctrine.ORM.Decorator.html">Decorator</a>
</li>
<li><a href="namespace-Doctrine.ORM.Event.html">Event</a>
</li>
<li><a href="namespace-Doctrine.ORM.Id.html">Id</a>
</li>
<li><a href="namespace-Doctrine.ORM.Internal.html">Internal<span></span></a>
<ul>
<li><a href="namespace-Doctrine.ORM.Internal.Hydration.html">Hydration</a>
</li>
</ul></li>
<li><a href="namespace-Doctrine.ORM.Mapping.html">Mapping<span></span></a>
<ul>
<li><a href="namespace-Doctrine.ORM.Mapping.Builder.html">Builder</a>
</li>
<li><a href="namespace-Doctrine.ORM.Mapping.Driver.html">Driver</a>
</li>
</ul></li>
<li><a href="namespace-Doctrine.ORM.Persisters.html">Persisters</a>
</li>
<li><a href="namespace-Doctrine.ORM.Proxy.html">Proxy</a>
</li>
<li><a href="namespace-Doctrine.ORM.Query.html">Query<span></span></a>
<ul>
<li><a href="namespace-Doctrine.ORM.Query.AST.html">AST<span></span></a>
<ul>
<li><a href="namespace-Doctrine.ORM.Query.AST.Functions.html">Functions</a>
</li>
</ul></li>
<li><a href="namespace-Doctrine.ORM.Query.Exec.html">Exec</a>
</li>
<li><a href="namespace-Doctrine.ORM.Query.Expr.html">Expr</a>
</li>
<li><a href="namespace-Doctrine.ORM.Query.Filter.html">Filter</a>
</li>
</ul></li>
<li><a href="namespace-Doctrine.ORM.Repository.html">Repository</a>
</li>
<li><a href="namespace-Doctrine.ORM.Tools.html">Tools<span></span></a>
<ul>
<li><a href="namespace-Doctrine.ORM.Tools.Console.html">Console<span></span></a>
<ul>
<li><a href="namespace-Doctrine.ORM.Tools.Console.Command.html">Command<span></span></a>
<ul>
<li><a href="namespace-Doctrine.ORM.Tools.Console.Command.ClearCache.html">ClearCache</a>
</li>
<li><a href="namespace-Doctrine.ORM.Tools.Console.Command.SchemaTool.html">SchemaTool</a>
</li>
</ul></li>
<li><a href="namespace-Doctrine.ORM.Tools.Console.Helper.html">Helper</a>
</li>
</ul></li>
<li><a href="namespace-Doctrine.ORM.Tools.Event.html">Event</a>
</li>
<li><a href="namespace-Doctrine.ORM.Tools.Export.html">Export<span></span></a>
<ul>
<li><a href="namespace-Doctrine.ORM.Tools.Export.Driver.html">Driver</a>
</li>
</ul></li>
<li><a href="namespace-Doctrine.ORM.Tools.Pagination.html">Pagination</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Doctrine.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Doctrine.Tests.Common.html">Common<span></span></a>
<ul>
<li><a href="namespace-Doctrine.Tests.Common.Annotations.html">Annotations<span></span></a>
<ul>
<li><a href="namespace-Doctrine.Tests.Common.Annotations.Bar.html">Bar</a>
</li>
<li><a href="namespace-Doctrine.Tests.Common.Annotations.Fixtures.html">Fixtures<span></span></a>
<ul>
<li><a href="namespace-Doctrine.Tests.Common.Annotations.Fixtures.Annotation.html">Annotation</a>
</li>
</ul></li>
<li><a href="namespace-Doctrine.Tests.Common.Annotations.Foo.html">Foo</a>
</li>
<li><a href="namespace-Doctrine.Tests.Common.Annotations.FooBar.html">FooBar</a>
</li>
<li><a href="namespace-Doctrine.Tests.Common.Annotations.Ticket.html">Ticket<span></span></a>
<ul>
<li><a href="namespace-Doctrine.Tests.Common.Annotations.Ticket.Doctrine.html">Doctrine<span></span></a>
<ul>
<li><a href="namespace-Doctrine.Tests.Common.Annotations.Ticket.Doctrine.ORM.html">ORM<span></span></a>
<ul>
<li><a href="namespace-Doctrine.Tests.Common.Annotations.Ticket.Doctrine.ORM.Mapping.html">Mapping</a>
</li>
</ul></li></ul></li></ul></li></ul></li>
<li><a href="namespace-Doctrine.Tests.Common.Cache.html">Cache</a>
</li>
<li><a href="namespace-Doctrine.Tests.Common.Collections.html">Collections</a>
</li>
<li><a href="namespace-Doctrine.Tests.Common.DataFixtures.html">DataFixtures<span></span></a>
<ul>
<li><a href="namespace-Doctrine.Tests.Common.DataFixtures.Executor.html">Executor</a>
</li>
<li><a href="namespace-Doctrine.Tests.Common.DataFixtures.TestEntity.html">TestEntity</a>
</li>
<li><a href="namespace-Doctrine.Tests.Common.DataFixtures.TestFixtures.html">TestFixtures</a>
</li>
</ul></li>
<li><a href="namespace-Doctrine.Tests.Common.Inflector.html">Inflector</a>
</li>
<li><a href="namespace-Doctrine.Tests.Common.Persistence.html">Persistence<span></span></a>
<ul>
<li><a href="namespace-Doctrine.Tests.Common.Persistence.Mapping.html">Mapping</a>
</li>
</ul></li>
<li><a href="namespace-Doctrine.Tests.Common.Proxy.html">Proxy</a>
</li>
<li><a href="namespace-Doctrine.Tests.Common.Reflection.html">Reflection<span></span></a>
<ul>
<li><a href="namespace-Doctrine.Tests.Common.Reflection.Dummies.html">Dummies</a>
</li>
</ul></li>
<li><a href="namespace-Doctrine.Tests.Common.Util.html">Util</a>
</li>
</ul></li></ul></li></ul></li>
<li><a href="namespace-Entity.html">Entity<span></span></a>
<ul>
<li><a href="namespace-Entity.Repository.html">Repository</a>
</li>
</ul></li>
<li><a href="namespace-Fixtures.html">Fixtures<span></span></a>
<ul>
<li><a href="namespace-Fixtures.Bundles.html">Bundles<span></span></a>
<ul>
<li><a href="namespace-Fixtures.Bundles.AnnotationsBundle.html">AnnotationsBundle<span></span></a>
<ul>
<li><a href="namespace-Fixtures.Bundles.AnnotationsBundle.Entity.html">Entity</a>
</li>
</ul></li>
<li><a href="namespace-Fixtures.Bundles.Vendor.html">Vendor<span></span></a>
<ul>
<li><a href="namespace-Fixtures.Bundles.Vendor.AnnotationsBundle.html">AnnotationsBundle<span></span></a>
<ul>
<li><a href="namespace-Fixtures.Bundles.Vendor.AnnotationsBundle.Entity.html">Entity</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Fixtures.Bundles.XmlBundle.html">XmlBundle<span></span></a>
<ul>
<li><a href="namespace-Fixtures.Bundles.XmlBundle.Entity.html">Entity</a>
</li>
</ul></li>
<li><a href="namespace-Fixtures.Bundles.YamlBundle.html">YamlBundle<span></span></a>
<ul>
<li><a href="namespace-Fixtures.Bundles.YamlBundle.Entity.html">Entity</a>
</li>
</ul></li></ul></li></ul></li>
<li><a href="namespace-Foo.html">Foo<span></span></a>
<ul>
<li><a href="namespace-Foo.Bar.html">Bar</a>
</li>
</ul></li>
<li><a href="namespace-FOS.html">FOS<span></span></a>
<ul>
<li><a href="namespace-FOS.RestBundle.html">RestBundle<span></span></a>
<ul>
<li><a href="namespace-FOS.RestBundle.Controller.html">Controller<span></span></a>
<ul>
<li><a href="namespace-FOS.RestBundle.Controller.Annotations.html">Annotations</a>
</li>
</ul></li>
<li><a href="namespace-FOS.RestBundle.Decoder.html">Decoder</a>
</li>
<li><a href="namespace-FOS.RestBundle.DependencyInjection.html">DependencyInjection<span></span></a>
<ul>
<li><a href="namespace-FOS.RestBundle.DependencyInjection.Compiler.html">Compiler</a>
</li>
</ul></li>
<li><a href="namespace-FOS.RestBundle.EventListener.html">EventListener</a>
</li>
<li><a href="namespace-FOS.RestBundle.Examples.html">Examples</a>
</li>
<li><a href="namespace-FOS.RestBundle.Form.html">Form<span></span></a>
<ul>
<li><a href="namespace-FOS.RestBundle.Form.Extension.html">Extension</a>
</li>
</ul></li>
<li><a href="namespace-FOS.RestBundle.Normalizer.html">Normalizer<span></span></a>
<ul>
<li><a href="namespace-FOS.RestBundle.Normalizer.Exception.html">Exception</a>
</li>
</ul></li>
<li><a href="namespace-FOS.RestBundle.Request.html">Request</a>
</li>
<li><a href="namespace-FOS.RestBundle.Response.html">Response<span></span></a>
<ul>
<li><a href="namespace-FOS.RestBundle.Response.AllowedMethodsLoader.html">AllowedMethodsLoader</a>
</li>
</ul></li>
<li><a href="namespace-FOS.RestBundle.Routing.html">Routing<span></span></a>
<ul>
<li><a href="namespace-FOS.RestBundle.Routing.Loader.html">Loader<span></span></a>
<ul>
<li><a href="namespace-FOS.RestBundle.Routing.Loader.Reader.html">Reader</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-FOS.RestBundle.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-FOS.RestBundle.Tests.Controller.html">Controller<span></span></a>
<ul>
<li><a href="namespace-FOS.RestBundle.Tests.Controller.Annotations.html">Annotations</a>
</li>
</ul></li>
<li><a href="namespace-FOS.RestBundle.Tests.Decoder.html">Decoder</a>
</li>
<li><a href="namespace-FOS.RestBundle.Tests.DependencyInjection.html">DependencyInjection<span></span></a>
<ul>
<li><a href="namespace-FOS.RestBundle.Tests.DependencyInjection.Compiler.html">Compiler</a>
</li>
</ul></li>
<li><a href="namespace-FOS.RestBundle.Tests.EventListener.html">EventListener</a>
</li>
<li><a href="namespace-FOS.RestBundle.Tests.Fixtures.html">Fixtures<span></span></a>
<ul>
<li><a href="namespace-FOS.RestBundle.Tests.Fixtures.Controller.html">Controller</a>
</li>
</ul></li>
<li><a href="namespace-FOS.RestBundle.Tests.Normalizer.html">Normalizer</a>
</li>
<li><a href="namespace-FOS.RestBundle.Tests.Request.html">Request</a>
</li>
<li><a href="namespace-FOS.RestBundle.Tests.Routing.html">Routing<span></span></a>
<ul>
<li><a href="namespace-FOS.RestBundle.Tests.Routing.Loader.html">Loader</a>
</li>
</ul></li>
<li><a href="namespace-FOS.RestBundle.Tests.Util.html">Util</a>
</li>
<li><a href="namespace-FOS.RestBundle.Tests.View.html">View</a>
</li>
</ul></li>
<li><a href="namespace-FOS.RestBundle.Util.html">Util<span></span></a>
<ul>
<li><a href="namespace-FOS.RestBundle.Util.Inflector.html">Inflector</a>
</li>
</ul></li>
<li><a href="namespace-FOS.RestBundle.View.html">View</a>
</li>
</ul></li>
<li><a href="namespace-FOS.UserBundle.html">UserBundle<span></span></a>
<ul>
<li><a href="namespace-FOS.UserBundle.Command.html">Command</a>
</li>
<li><a href="namespace-FOS.UserBundle.Controller.html">Controller</a>
</li>
<li><a href="namespace-FOS.UserBundle.CouchDocument.html">CouchDocument</a>
</li>
<li><a href="namespace-FOS.UserBundle.DependencyInjection.html">DependencyInjection<span></span></a>
<ul>
<li><a href="namespace-FOS.UserBundle.DependencyInjection.Compiler.html">Compiler</a>
</li>
</ul></li>
<li><a href="namespace-FOS.UserBundle.Doctrine.html">Doctrine</a>
</li>
<li><a href="namespace-FOS.UserBundle.Document.html">Document</a>
</li>
<li><a href="namespace-FOS.UserBundle.Entity.html">Entity</a>
</li>
<li><a href="namespace-FOS.UserBundle.Form.html">Form<span></span></a>
<ul>
<li><a href="namespace-FOS.UserBundle.Form.DataTransformer.html">DataTransformer</a>
</li>
<li><a href="namespace-FOS.UserBundle.Form.Handler.html">Handler</a>
</li>
<li><a href="namespace-FOS.UserBundle.Form.Model.html">Model</a>
</li>
<li><a href="namespace-FOS.UserBundle.Form.Type.html">Type</a>
</li>
</ul></li>
<li><a href="namespace-FOS.UserBundle.Mailer.html">Mailer</a>
</li>
<li><a href="namespace-FOS.UserBundle.Model.html">Model</a>
</li>
<li><a href="namespace-FOS.UserBundle.Propel.html">Propel</a>
</li>
<li><a href="namespace-FOS.UserBundle.Security.html">Security</a>
</li>
<li><a href="namespace-FOS.UserBundle.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-FOS.UserBundle.Tests.DependencyInjection.html">DependencyInjection</a>
</li>
<li><a href="namespace-FOS.UserBundle.Tests.Doctrine.html">Doctrine</a>
</li>
<li><a href="namespace-FOS.UserBundle.Tests.Model.html">Model</a>
</li>
<li><a href="namespace-FOS.UserBundle.Tests.Security.html">Security</a>
</li>
<li><a href="namespace-FOS.UserBundle.Tests.Util.html">Util</a>
</li>
</ul></li>
<li><a href="namespace-FOS.UserBundle.Util.html">Util</a>
</li>
<li><a href="namespace-FOS.UserBundle.Validator.html">Validator</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Gedmo.html">Gedmo<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Blameable.html">Blameable<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Blameable.Mapping.html">Mapping<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Blameable.Mapping.Driver.html">Driver</a>
</li>
<li><a href="namespace-Gedmo.Blameable.Mapping.Event.html">Event<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Blameable.Mapping.Event.Adapter.html">Adapter</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Gedmo.Blameable.Traits.html">Traits</a>
</li>
</ul></li>
<li><a href="namespace-Gedmo.Exception.html">Exception</a>
</li>
<li><a href="namespace-Gedmo.IpTraceable.html">IpTraceable<span></span></a>
<ul>
<li><a href="namespace-Gedmo.IpTraceable.Mapping.html">Mapping<span></span></a>
<ul>
<li><a href="namespace-Gedmo.IpTraceable.Mapping.Driver.html">Driver</a>
</li>
<li><a href="namespace-Gedmo.IpTraceable.Mapping.Event.html">Event<span></span></a>
<ul>
<li><a href="namespace-Gedmo.IpTraceable.Mapping.Event.Adapter.html">Adapter</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Gedmo.IpTraceable.Traits.html">Traits</a>
</li>
</ul></li>
<li><a href="namespace-Gedmo.Loggable.html">Loggable<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Loggable.Document.html">Document<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Loggable.Document.MappedSuperclass.html">MappedSuperclass</a>
</li>
<li><a href="namespace-Gedmo.Loggable.Document.Repository.html">Repository</a>
</li>
</ul></li>
<li><a href="namespace-Gedmo.Loggable.Entity.html">Entity<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Loggable.Entity.MappedSuperclass.html">MappedSuperclass</a>
</li>
<li><a href="namespace-Gedmo.Loggable.Entity.Repository.html">Repository</a>
</li>
</ul></li>
<li><a href="namespace-Gedmo.Loggable.Mapping.html">Mapping<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Loggable.Mapping.Driver.html">Driver</a>
</li>
<li><a href="namespace-Gedmo.Loggable.Mapping.Event.html">Event<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Loggable.Mapping.Event.Adapter.html">Adapter</a>
</li>
</ul></li></ul></li></ul></li>
<li><a href="namespace-Gedmo.Mapping.html">Mapping<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Mapping.Annotation.html">Annotation</a>
</li>
<li><a href="namespace-Gedmo.Mapping.Driver.html">Driver</a>
</li>
<li><a href="namespace-Gedmo.Mapping.Event.html">Event<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Mapping.Event.Adapter.html">Adapter</a>
</li>
</ul></li>
<li><a href="namespace-Gedmo.Mapping.Mock.html">Mock<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Mapping.Mock.Extension.html">Extension<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Mapping.Mock.Extension.Encoder.html">Encoder<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Mapping.Mock.Extension.Encoder.Mapping.html">Mapping<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Mapping.Mock.Extension.Encoder.Mapping.Driver.html">Driver</a>
</li>
<li><a href="namespace-Gedmo.Mapping.Mock.Extension.Encoder.Mapping.Event.html">Event<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Mapping.Mock.Extension.Encoder.Mapping.Event.Adapter.html">Adapter</a>
</li>
</ul></li></ul></li></ul></li></ul></li>
<li><a href="namespace-Gedmo.Mapping.Mock.Mapping.html">Mapping<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Mapping.Mock.Mapping.Event.html">Event<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Mapping.Mock.Mapping.Event.Adapter.html">Adapter</a>
</li>
</ul></li></ul></li></ul></li>
<li><a href="namespace-Gedmo.Mapping.Xml.html">Xml</a>
</li>
</ul></li>
<li><a href="namespace-Gedmo.ReferenceIntegrity.html">ReferenceIntegrity<span></span></a>
<ul>
<li><a href="namespace-Gedmo.ReferenceIntegrity.Mapping.html">Mapping<span></span></a>
<ul>
<li><a href="namespace-Gedmo.ReferenceIntegrity.Mapping.Driver.html">Driver</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Gedmo.References.html">References<span></span></a>
<ul>
<li><a href="namespace-Gedmo.References.Mapping.html">Mapping<span></span></a>
<ul>
<li><a href="namespace-Gedmo.References.Mapping.Driver.html">Driver</a>
</li>
<li><a href="namespace-Gedmo.References.Mapping.Event.html">Event<span></span></a>
<ul>
<li><a href="namespace-Gedmo.References.Mapping.Event.Adapter.html">Adapter</a>
</li>
</ul></li></ul></li></ul></li>
<li><a href="namespace-Gedmo.Sluggable.html">Sluggable<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Sluggable.Handler.html">Handler</a>
</li>
<li><a href="namespace-Gedmo.Sluggable.Mapping.html">Mapping<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Sluggable.Mapping.Driver.html">Driver</a>
</li>
<li><a href="namespace-Gedmo.Sluggable.Mapping.Event.html">Event<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Sluggable.Mapping.Event.Adapter.html">Adapter</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Gedmo.Sluggable.Util.html">Util</a>
</li>
</ul></li>
<li><a href="namespace-Gedmo.SoftDeleteable.html">SoftDeleteable<span></span></a>
<ul>
<li><a href="namespace-Gedmo.SoftDeleteable.Filter.html">Filter<span></span></a>
<ul>
<li><a href="namespace-Gedmo.SoftDeleteable.Filter.ODM.html">ODM</a>
</li>
</ul></li>
<li><a href="namespace-Gedmo.SoftDeleteable.Mapping.html">Mapping<span></span></a>
<ul>
<li><a href="namespace-Gedmo.SoftDeleteable.Mapping.Driver.html">Driver</a>
</li>
<li><a href="namespace-Gedmo.SoftDeleteable.Mapping.Event.html">Event<span></span></a>
<ul>
<li><a href="namespace-Gedmo.SoftDeleteable.Mapping.Event.Adapter.html">Adapter</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Gedmo.SoftDeleteable.Query.html">Query<span></span></a>
<ul>
<li><a href="namespace-Gedmo.SoftDeleteable.Query.TreeWalker.html">TreeWalker<span></span></a>
<ul>
<li><a href="namespace-Gedmo.SoftDeleteable.Query.TreeWalker.Exec.html">Exec</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Gedmo.SoftDeleteable.Traits.html">Traits</a>
</li>
</ul></li>
<li><a href="namespace-Gedmo.Sortable.html">Sortable<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Sortable.Entity.html">Entity<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Sortable.Entity.Repository.html">Repository</a>
</li>
</ul></li>
<li><a href="namespace-Gedmo.Sortable.Mapping.html">Mapping<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Sortable.Mapping.Driver.html">Driver</a>
</li>
<li><a href="namespace-Gedmo.Sortable.Mapping.Event.html">Event<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Sortable.Mapping.Event.Adapter.html">Adapter</a>
</li>
</ul></li></ul></li></ul></li>
<li><a href="namespace-Gedmo.Timestampable.html">Timestampable<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Timestampable.Mapping.html">Mapping<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Timestampable.Mapping.Driver.html">Driver</a>
</li>
<li><a href="namespace-Gedmo.Timestampable.Mapping.Event.html">Event<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Timestampable.Mapping.Event.Adapter.html">Adapter</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Gedmo.Timestampable.Traits.html">Traits</a>
</li>
</ul></li>
<li><a href="namespace-Gedmo.Tool.html">Tool<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Tool.Logging.html">Logging<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Tool.Logging.DBAL.html">DBAL</a>
</li>
</ul></li>
<li><a href="namespace-Gedmo.Tool.Wrapper.html">Wrapper</a>
</li>
</ul></li>
<li><a href="namespace-Gedmo.Translatable.html">Translatable<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Translatable.Document.html">Document<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Translatable.Document.MappedSuperclass.html">MappedSuperclass</a>
</li>
<li><a href="namespace-Gedmo.Translatable.Document.Repository.html">Repository</a>
</li>
</ul></li>
<li><a href="namespace-Gedmo.Translatable.Entity.html">Entity<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Translatable.Entity.MappedSuperclass.html">MappedSuperclass</a>
</li>
<li><a href="namespace-Gedmo.Translatable.Entity.Repository.html">Repository</a>
</li>
</ul></li>
<li><a href="namespace-Gedmo.Translatable.Hydrator.html">Hydrator<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Translatable.Hydrator.ORM.html">ORM</a>
</li>
</ul></li>
<li><a href="namespace-Gedmo.Translatable.Mapping.html">Mapping<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Translatable.Mapping.Driver.html">Driver</a>
</li>
<li><a href="namespace-Gedmo.Translatable.Mapping.Event.html">Event<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Translatable.Mapping.Event.Adapter.html">Adapter</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Gedmo.Translatable.Query.html">Query<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Translatable.Query.TreeWalker.html">TreeWalker</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Gedmo.Translator.html">Translator<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Translator.Document.html">Document</a>
</li>
<li><a href="namespace-Gedmo.Translator.Entity.html">Entity</a>
</li>
</ul></li>
<li><a href="namespace-Gedmo.Tree.html">Tree<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Tree.Document.html">Document<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Tree.Document.MongoDB.html">MongoDB<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Tree.Document.MongoDB.Repository.html">Repository</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Gedmo.Tree.Entity.html">Entity<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Tree.Entity.MappedSuperclass.html">MappedSuperclass</a>
</li>
<li><a href="namespace-Gedmo.Tree.Entity.Repository.html">Repository</a>
</li>
</ul></li>
<li><a href="namespace-Gedmo.Tree.Mapping.html">Mapping<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Tree.Mapping.Driver.html">Driver</a>
</li>
<li><a href="namespace-Gedmo.Tree.Mapping.Event.html">Event<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Tree.Mapping.Event.Adapter.html">Adapter</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Gedmo.Tree.Strategy.html">Strategy<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Tree.Strategy.ODM.html">ODM<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Tree.Strategy.ODM.MongoDB.html">MongoDB</a>
</li>
</ul></li>
<li><a href="namespace-Gedmo.Tree.Strategy.ORM.html">ORM</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Gedmo.Uploadable.html">Uploadable<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Uploadable.Event.html">Event</a>
</li>
<li><a href="namespace-Gedmo.Uploadable.FileInfo.html">FileInfo</a>
</li>
<li><a href="namespace-Gedmo.Uploadable.FilenameGenerator.html">FilenameGenerator</a>
</li>
<li><a href="namespace-Gedmo.Uploadable.Mapping.html">Mapping<span></span></a>
<ul>
<li><a href="namespace-Gedmo.Uploadable.Mapping.Driver.html">Driver</a>
</li>
</ul></li>
<li><a href="namespace-Gedmo.Uploadable.MimeType.html">MimeType</a>
</li>
<li><a href="namespace-Gedmo.Uploadable.Stub.html">Stub</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Incenteev.html">Incenteev<span></span></a>
<ul>
<li><a href="namespace-Incenteev.ParameterHandler.html">ParameterHandler<span></span></a>
<ul>
<li><a href="namespace-Incenteev.ParameterHandler.Tests.html">Tests</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-IpTraceable.html">IpTraceable<span></span></a>
<ul>
<li><a href="namespace-IpTraceable.Fixture.html">Fixture<span></span></a>
<ul>
<li><a href="namespace-IpTraceable.Fixture.Document.html">Document</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-JMS.html">JMS<span></span></a>
<ul>
<li><a href="namespace-JMS.Parser.html">Parser<span></span></a>
<ul>
<li><a href="namespace-JMS.Parser.Tests.html">Tests</a>
</li>
</ul></li>
<li><a href="namespace-JMS.Serializer.html">Serializer<span></span></a>
<ul>
<li><a href="namespace-JMS.Serializer.Annotation.html">Annotation</a>
</li>
<li><a href="namespace-JMS.Serializer.Builder.html">Builder</a>
</li>
<li><a href="namespace-JMS.Serializer.Construction.html">Construction</a>
</li>
<li><a href="namespace-JMS.Serializer.EventDispatcher.html">EventDispatcher<span></span></a>
<ul>
<li><a href="namespace-JMS.Serializer.EventDispatcher.Subscriber.html">Subscriber</a>
</li>
</ul></li>
<li><a href="namespace-JMS.Serializer.Exception.html">Exception</a>
</li>
<li><a href="namespace-JMS.Serializer.Exclusion.html">Exclusion</a>
</li>
<li><a href="namespace-JMS.Serializer.Handler.html">Handler</a>
</li>
<li><a href="namespace-JMS.Serializer.Metadata.html">Metadata<span></span></a>
<ul>
<li><a href="namespace-JMS.Serializer.Metadata.Driver.html">Driver</a>
</li>
</ul></li>
<li><a href="namespace-JMS.Serializer.Naming.html">Naming</a>
</li>
<li><a href="namespace-JMS.Serializer.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-JMS.Serializer.Tests.Exclusion.html">Exclusion</a>
</li>
<li><a href="namespace-JMS.Serializer.Tests.Fixtures.html">Fixtures<span></span></a>
<ul>
<li><a href="namespace-JMS.Serializer.Tests.Fixtures.Discriminator.html">Discriminator</a>
</li>
<li><a href="namespace-JMS.Serializer.Tests.Fixtures.Doctrine.html">Doctrine</a>
</li>
<li><a href="namespace-JMS.Serializer.Tests.Fixtures.DoctrinePHPCR.html">DoctrinePHPCR</a>
</li>
</ul></li>
<li><a href="namespace-JMS.Serializer.Tests.Handler.html">Handler</a>
</li>
<li><a href="namespace-JMS.Serializer.Tests.Metadata.html">Metadata<span></span></a>
<ul>
<li><a href="namespace-JMS.Serializer.Tests.Metadata.Driver.html">Driver</a>
</li>
</ul></li>
<li><a href="namespace-JMS.Serializer.Tests.Serializer.html">Serializer<span></span></a>
<ul>
<li><a href="namespace-JMS.Serializer.Tests.Serializer.EventDispatcher.html">EventDispatcher<span></span></a>
<ul>
<li><a href="namespace-JMS.Serializer.Tests.Serializer.EventDispatcher.Subscriber.html">Subscriber</a>
</li>
</ul></li>
<li><a href="namespace-JMS.Serializer.Tests.Serializer.Naming.html">Naming</a>
</li>
</ul></li>
<li><a href="namespace-JMS.Serializer.Tests.Twig.html">Twig</a>
</li>
</ul></li>
<li><a href="namespace-JMS.Serializer.Twig.html">Twig</a>
</li>
<li><a href="namespace-JMS.Serializer.Util.html">Util</a>
</li>
</ul></li>
<li><a href="namespace-JMS.SerializerBundle.html">SerializerBundle<span></span></a>
<ul>
<li><a href="namespace-JMS.SerializerBundle.DependencyInjection.html">DependencyInjection<span></span></a>
<ul>
<li><a href="namespace-JMS.SerializerBundle.DependencyInjection.Compiler.html">Compiler</a>
</li>
</ul></li>
<li><a href="namespace-JMS.SerializerBundle.Serializer.html">Serializer</a>
</li>
<li><a href="namespace-JMS.SerializerBundle.Templating.html">Templating</a>
</li>
<li><a href="namespace-JMS.SerializerBundle.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-JMS.SerializerBundle.Tests.DependencyInjection.html">DependencyInjection<span></span></a>
<ul>
<li><a href="namespace-JMS.SerializerBundle.Tests.DependencyInjection.Fixture.html">Fixture</a>
</li>
</ul></li></ul></li></ul></li>
<li><a href="namespace-JMS.TranslationBundle.html">TranslationBundle<span></span></a>
<ul>
<li><a href="namespace-JMS.TranslationBundle.Annotation.html">Annotation</a>
</li>
<li><a href="namespace-JMS.TranslationBundle.Command.html">Command</a>
</li>
<li><a href="namespace-JMS.TranslationBundle.Controller.html">Controller</a>
</li>
<li><a href="namespace-JMS.TranslationBundle.DependencyInjection.html">DependencyInjection<span></span></a>
<ul>
<li><a href="namespace-JMS.TranslationBundle.DependencyInjection.Compiler.html">Compiler</a>
</li>
</ul></li>
<li><a href="namespace-JMS.TranslationBundle.Exception.html">Exception</a>
</li>
<li><a href="namespace-JMS.TranslationBundle.Logger.html">Logger</a>
</li>
<li><a href="namespace-JMS.TranslationBundle.Model.html">Model</a>
</li>
<li><a href="namespace-JMS.TranslationBundle.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-JMS.TranslationBundle.Tests.Functional.html">Functional<span></span></a>
<ul>
<li><a href="namespace-JMS.TranslationBundle.Tests.Functional.TestBundle.html">TestBundle<span></span></a>
<ul>
<li><a href="namespace-JMS.TranslationBundle.Tests.Functional.TestBundle.Controller.html">Controller</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-JMS.TranslationBundle.Tests.Model.html">Model</a>
</li>
<li><a href="namespace-JMS.TranslationBundle.Tests.Translation.html">Translation<span></span></a>
<ul>
<li><a href="namespace-JMS.TranslationBundle.Tests.Translation.Comparison.html">Comparison</a>
</li>
<li><a href="namespace-JMS.TranslationBundle.Tests.Translation.Dumper.html">Dumper</a>
</li>
<li><a href="namespace-JMS.TranslationBundle.Tests.Translation.Extractor.html">Extractor<span></span></a>
<ul>
<li><a href="namespace-JMS.TranslationBundle.Tests.Translation.Extractor.File.html">File<span></span></a>
<ul>
<li><a href="namespace-JMS.TranslationBundle.Tests.Translation.Extractor.File.Fixture.html">Fixture</a>
</li>
</ul></li>
<li><a href="namespace-JMS.TranslationBundle.Tests.Translation.Extractor.Fixture.html">Fixture<span></span></a>
<ul>
<li><a href="namespace-JMS.TranslationBundle.Tests.Translation.Extractor.Fixture.SimpleTest.html">SimpleTest<span></span></a>
<ul>
<li><a href="namespace-JMS.TranslationBundle.Tests.Translation.Extractor.Fixture.SimpleTest.Controller.html">Controller</a>
</li>
<li><a href="namespace-JMS.TranslationBundle.Tests.Translation.Extractor.Fixture.SimpleTest.Form.html">Form</a>
</li>
</ul></li></ul></li></ul></li>
<li><a href="namespace-JMS.TranslationBundle.Tests.Translation.Loader.html">Loader<span></span></a>
<ul>
<li><a href="namespace-JMS.TranslationBundle.Tests.Translation.Loader.Symfony.html">Symfony</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-JMS.TranslationBundle.Tests.Twig.html">Twig</a>
</li>
</ul></li>
<li><a href="namespace-JMS.TranslationBundle.Translation.html">Translation<span></span></a>
<ul>
<li><a href="namespace-JMS.TranslationBundle.Translation.Comparison.html">Comparison</a>
</li>
<li><a href="namespace-JMS.TranslationBundle.Translation.Dumper.html">Dumper</a>
</li>
<li><a href="namespace-JMS.TranslationBundle.Translation.Extractor.html">Extractor<span></span></a>
<ul>
<li><a href="namespace-JMS.TranslationBundle.Translation.Extractor.File.html">File</a>
</li>
</ul></li>
<li><a href="namespace-JMS.TranslationBundle.Translation.Loader.html">Loader<span></span></a>
<ul>
<li><a href="namespace-JMS.TranslationBundle.Translation.Loader.Symfony.html">Symfony</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-JMS.TranslationBundle.Twig.html">Twig</a>
</li>
<li><a href="namespace-JMS.TranslationBundle.Util.html">Util</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Knp.html">Knp<span></span></a>
<ul>
<li><a href="namespace-Knp.Bundle.html">Bundle<span></span></a>
<ul>
<li><a href="namespace-Knp.Bundle.MenuBundle.html">MenuBundle<span></span></a>
<ul>
<li><a href="namespace-Knp.Bundle.MenuBundle.DependencyInjection.html">DependencyInjection<span></span></a>
<ul>
<li><a href="namespace-Knp.Bundle.MenuBundle.DependencyInjection.Compiler.html">Compiler</a>
</li>
</ul></li>
<li><a href="namespace-Knp.Bundle.MenuBundle.EventListener.html">EventListener</a>
</li>
<li><a href="namespace-Knp.Bundle.MenuBundle.Provider.html">Provider</a>
</li>
<li><a href="namespace-Knp.Bundle.MenuBundle.Renderer.html">Renderer</a>
</li>
<li><a href="namespace-Knp.Bundle.MenuBundle.Templating.html">Templating<span></span></a>
<ul>
<li><a href="namespace-Knp.Bundle.MenuBundle.Templating.Helper.html">Helper</a>
</li>
</ul></li>
<li><a href="namespace-Knp.Bundle.MenuBundle.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Knp.Bundle.MenuBundle.Tests.DependencyInjection.html">DependencyInjection<span></span></a>
<ul>
<li><a href="namespace-Knp.Bundle.MenuBundle.Tests.DependencyInjection.Compiler.html">Compiler</a>
</li>
</ul></li>
<li><a href="namespace-Knp.Bundle.MenuBundle.Tests.EventListener.html">EventListener</a>
</li>
<li><a href="namespace-Knp.Bundle.MenuBundle.Tests.Provider.html">Provider</a>
</li>
<li><a href="namespace-Knp.Bundle.MenuBundle.Tests.Renderer.html">Renderer</a>
</li>
<li><a href="namespace-Knp.Bundle.MenuBundle.Tests.Stubs.html">Stubs<span></span></a>
<ul>
<li><a href="namespace-Knp.Bundle.MenuBundle.Tests.Stubs.Child.html">Child<span></span></a>
<ul>
<li><a href="namespace-Knp.Bundle.MenuBundle.Tests.Stubs.Child.Menu.html">Menu</a>
</li>
</ul></li>
<li><a href="namespace-Knp.Bundle.MenuBundle.Tests.Stubs.Menu.html">Menu</a>
</li>
</ul></li>
<li><a href="namespace-Knp.Bundle.MenuBundle.Tests.Templating.html">Templating</a>
</li>
</ul></li></ul></li></ul></li>
<li><a href="namespace-Knp.Menu.html">Menu<span></span></a>
<ul>
<li><a href="namespace-Knp.Menu.Factory.html">Factory</a>
</li>
<li><a href="namespace-Knp.Menu.Integration.html">Integration<span></span></a>
<ul>
<li><a href="namespace-Knp.Menu.Integration.Silex.html">Silex</a>
</li>
<li><a href="namespace-Knp.Menu.Integration.Symfony.html">Symfony</a>
</li>
</ul></li>
<li><a href="namespace-Knp.Menu.Iterator.html">Iterator</a>
</li>
<li><a href="namespace-Knp.Menu.Loader.html">Loader</a>
</li>
<li><a href="namespace-Knp.Menu.Matcher.html">Matcher<span></span></a>
<ul>
<li><a href="namespace-Knp.Menu.Matcher.Voter.html">Voter</a>
</li>
</ul></li>
<li><a href="namespace-Knp.Menu.Provider.html">Provider</a>
</li>
<li><a href="namespace-Knp.Menu.Renderer.html">Renderer</a>
</li>
<li><a href="namespace-Knp.Menu.Silex.html">Silex<span></span></a>
<ul>
<li><a href="namespace-Knp.Menu.Silex.Voter.html">Voter</a>
</li>
</ul></li>
<li><a href="namespace-Knp.Menu.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Knp.Menu.Tests.Factory.html">Factory</a>
</li>
<li><a href="namespace-Knp.Menu.Tests.Integration.html">Integration<span></span></a>
<ul>
<li><a href="namespace-Knp.Menu.Tests.Integration.Silex.html">Silex</a>
</li>
</ul></li>
<li><a href="namespace-Knp.Menu.Tests.Iterator.html">Iterator</a>
</li>
<li><a href="namespace-Knp.Menu.Tests.Loader.html">Loader</a>
</li>
<li><a href="namespace-Knp.Menu.Tests.Matcher.html">Matcher<span></span></a>
<ul>
<li><a href="namespace-Knp.Menu.Tests.Matcher.Voter.html">Voter</a>
</li>
</ul></li>
<li><a href="namespace-Knp.Menu.Tests.Provider.html">Provider</a>
</li>
<li><a href="namespace-Knp.Menu.Tests.Renderer.html">Renderer</a>
</li>
<li><a href="namespace-Knp.Menu.Tests.Silex.html">Silex</a>
</li>
<li><a href="namespace-Knp.Menu.Tests.Twig.html">Twig</a>
</li>
<li><a href="namespace-Knp.Menu.Tests.Util.html">Util</a>
</li>
</ul></li>
<li><a href="namespace-Knp.Menu.Twig.html">Twig</a>
</li>
<li><a href="namespace-Knp.Menu.Util.html">Util</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Loggable.html">Loggable<span></span></a>
<ul>
<li><a href="namespace-Loggable.Fixture.html">Fixture<span></span></a>
<ul>
<li><a href="namespace-Loggable.Fixture.Document.html">Document<span></span></a>
<ul>
<li><a href="namespace-Loggable.Fixture.Document.Log.html">Log</a>
</li>
</ul></li>
<li><a href="namespace-Loggable.Fixture.Entity.html">Entity<span></span></a>
<ul>
<li><a href="namespace-Loggable.Fixture.Entity.Log.html">Log</a>
</li>
</ul></li></ul></li></ul></li>
<li><a href="namespace-Lunetics.html">Lunetics<span></span></a>
<ul>
<li><a href="namespace-Lunetics.LocaleBundle.html">LocaleBundle<span></span></a>
<ul>
<li><a href="namespace-Lunetics.LocaleBundle.Controller.html">Controller</a>
</li>
<li><a href="namespace-Lunetics.LocaleBundle.Cookie.html">Cookie</a>
</li>
<li><a href="namespace-Lunetics.LocaleBundle.DependencyInjection.html">DependencyInjection<span></span></a>
<ul>
<li><a href="namespace-Lunetics.LocaleBundle.DependencyInjection.Compiler.html">Compiler</a>
</li>
</ul></li>
<li><a href="namespace-Lunetics.LocaleBundle.Event.html">Event</a>
</li>
<li><a href="namespace-Lunetics.LocaleBundle.EventListener.html">EventListener</a>
</li>
<li><a href="namespace-Lunetics.LocaleBundle.Form.html">Form<span></span></a>
<ul>
<li><a href="namespace-Lunetics.LocaleBundle.Form.Extension.html">Extension<span></span></a>
<ul>
<li><a href="namespace-Lunetics.LocaleBundle.Form.Extension.ChoiceList.html">ChoiceList</a>
</li>
<li><a href="namespace-Lunetics.LocaleBundle.Form.Extension.Type.html">Type</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Lunetics.LocaleBundle.LocaleGuesser.html">LocaleGuesser</a>
</li>
<li><a href="namespace-Lunetics.LocaleBundle.LocaleInformation.html">LocaleInformation</a>
</li>
<li><a href="namespace-Lunetics.LocaleBundle.Matcher.html">Matcher</a>
</li>
<li><a href="namespace-Lunetics.LocaleBundle.Session.html">Session</a>
</li>
<li><a href="namespace-Lunetics.LocaleBundle.Switcher.html">Switcher</a>
</li>
<li><a href="namespace-Lunetics.LocaleBundle.Templating.html">Templating<span></span></a>
<ul>
<li><a href="namespace-Lunetics.LocaleBundle.Templating.Helper.html">Helper</a>
</li>
</ul></li>
<li><a href="namespace-Lunetics.LocaleBundle.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Lunetics.LocaleBundle.Tests.Controller.html">Controller</a>
</li>
<li><a href="namespace-Lunetics.LocaleBundle.Tests.DependencyInjection.html">DependencyInjection<span></span></a>
<ul>
<li><a href="namespace-Lunetics.LocaleBundle.Tests.DependencyInjection.Compiler.html">Compiler</a>
</li>
</ul></li>
<li><a href="namespace-Lunetics.LocaleBundle.Tests.Event.html">Event</a>
</li>
<li><a href="namespace-Lunetics.LocaleBundle.Tests.EventListener.html">EventListener</a>
</li>
<li><a href="namespace-Lunetics.LocaleBundle.Tests.Form.html">Form<span></span></a>
<ul>
<li><a href="namespace-Lunetics.LocaleBundle.Tests.Form.Extension.html">Extension<span></span></a>
<ul>
<li><a href="namespace-Lunetics.LocaleBundle.Tests.Form.Extension.ChoiceList.html">ChoiceList</a>
</li>
<li><a href="namespace-Lunetics.LocaleBundle.Tests.Form.Extension.Type.html">Type</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Lunetics.LocaleBundle.Tests.LocaleGuesser.html">LocaleGuesser</a>
</li>
<li><a href="namespace-Lunetics.LocaleBundle.Tests.LocaleInformation.html">LocaleInformation</a>
</li>
<li><a href="namespace-Lunetics.LocaleBundle.Tests.Templating.html">Templating<span></span></a>
<ul>
<li><a href="namespace-Lunetics.LocaleBundle.Tests.Templating.Helper.html">Helper</a>
</li>
</ul></li>
<li><a href="namespace-Lunetics.LocaleBundle.Tests.Twig.html">Twig<span></span></a>
<ul>
<li><a href="namespace-Lunetics.LocaleBundle.Tests.Twig.Extension.html">Extension</a>
</li>
</ul></li>
<li><a href="namespace-Lunetics.LocaleBundle.Tests.Validator.html">Validator</a>
</li>
</ul></li>
<li><a href="namespace-Lunetics.LocaleBundle.Twig.html">Twig<span></span></a>
<ul>
<li><a href="namespace-Lunetics.LocaleBundle.Twig.Extension.html">Extension</a>
</li>
</ul></li>
<li><a href="namespace-Lunetics.LocaleBundle.Validator.html">Validator</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Mapping.html">Mapping<span></span></a>
<ul>
<li><a href="namespace-Mapping.Fixture.html">Fixture<span></span></a>
<ul>
<li><a href="namespace-Mapping.Fixture.Compatibility.html">Compatibility</a>
</li>
<li><a href="namespace-Mapping.Fixture.Document.html">Document</a>
</li>
<li><a href="namespace-Mapping.Fixture.Unmapped.html">Unmapped</a>
</li>
<li><a href="namespace-Mapping.Fixture.Xml.html">Xml</a>
</li>
<li><a href="namespace-Mapping.Fixture.Yaml.html">Yaml</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Metadata.html">Metadata<span></span></a>
<ul>
<li><a href="namespace-Metadata.Cache.html">Cache</a>
</li>
<li><a href="namespace-Metadata.Driver.html">Driver</a>
</li>
<li><a href="namespace-Metadata.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Metadata.Tests.Cache.html">Cache</a>
</li>
<li><a href="namespace-Metadata.Tests.Driver.html">Driver<span></span></a>
<ul>
<li><a href="namespace-Metadata.Tests.Driver.Fixture.html">Fixture<span></span></a>
<ul>
<li><a href="namespace-Metadata.Tests.Driver.Fixture.A.html">A</a>
</li>
<li><a href="namespace-Metadata.Tests.Driver.Fixture.B.html">B</a>
</li>
<li><a href="namespace-Metadata.Tests.Driver.Fixture.C.html">C<span></span></a>
<ul>
<li><a href="namespace-Metadata.Tests.Driver.Fixture.C.SubDir.html">SubDir</a>
</li>
</ul></li>
<li><a href="namespace-Metadata.Tests.Driver.Fixture.T.html">T</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Metadata.Tests.Fixtures.html">Fixtures<span></span></a>
<ul>
<li><a href="namespace-Metadata.Tests.Fixtures.ComplexHierarchy.html">ComplexHierarchy</a>
</li>
</ul></li></ul></li></ul></li>
<li><a href="namespace-Monolog.html">Monolog<span></span></a>
<ul>
<li><a href="namespace-Monolog.Formatter.html">Formatter</a>
</li>
<li><a href="namespace-Monolog.Handler.html">Handler<span></span></a>
<ul>
<li><a href="namespace-Monolog.Handler.FingersCrossed.html">FingersCrossed</a>
</li>
<li><a href="namespace-Monolog.Handler.SyslogUdp.html">SyslogUdp</a>
</li>
</ul></li>
<li><a href="namespace-Monolog.Processor.html">Processor</a>
</li>
</ul></li>
<li><a href="namespace-MyProject.html">MyProject<span></span></a>
<ul>
<li><a href="namespace-MyProject.Proxies.html">Proxies<span></span></a>
<ul>
<li><a href="namespace-MyProject.Proxies.__CG__.html">__CG__<span></span></a>
<ul>
<li><a href="namespace-MyProject.Proxies.__CG__.Doctrine.html">Doctrine<span></span></a>
<ul>
<li><a href="namespace-MyProject.Proxies.__CG__.Doctrine.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-MyProject.Proxies.__CG__.Doctrine.Tests.Common.html">Common<span></span></a>
<ul>
<li><a href="namespace-MyProject.Proxies.__CG__.Doctrine.Tests.Common.Util.html">Util</a>
</li>
</ul></li></ul></li></ul></li>
<li><a href="namespace-MyProject.Proxies.__CG__.OtherProject.html">OtherProject<span></span></a>
<ul>
<li><a href="namespace-MyProject.Proxies.__CG__.OtherProject.Proxies.html">Proxies<span></span></a>
<ul>
<li><a href="namespace-MyProject.Proxies.__CG__.OtherProject.Proxies.__CG__.html">__CG__<span></span></a>
<ul>
<li><a href="namespace-MyProject.Proxies.__CG__.OtherProject.Proxies.__CG__.Doctrine.html">Doctrine<span></span></a>
<ul>
<li><a href="namespace-MyProject.Proxies.__CG__.OtherProject.Proxies.__CG__.Doctrine.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-MyProject.Proxies.__CG__.OtherProject.Proxies.__CG__.Doctrine.Tests.Common.html">Common<span></span></a>
<ul>
<li><a href="namespace-MyProject.Proxies.__CG__.OtherProject.Proxies.__CG__.Doctrine.Tests.Common.Util.html">Util</a>
</li>
</ul></li></ul></li></ul></li></ul></li></ul></li></ul></li></ul></li></ul></li></ul></li>
<li><a href="namespace-NamespaceCollision.html">NamespaceCollision<span></span></a>
<ul>
<li><a href="namespace-NamespaceCollision.A.html">A<span></span></a>
<ul>
<li><a href="namespace-NamespaceCollision.A.B.html">B</a>
</li>
</ul></li>
<li><a href="namespace-NamespaceCollision.C.html">C<span></span></a>
<ul>
<li><a href="namespace-NamespaceCollision.C.B.html">B</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Namespaced.html">Namespaced</a>
</li>
<li><a href="namespace-Namespaced2.html">Namespaced2</a>
</li>
<li><a href="namespace-Negotiation.html">Negotiation<span></span></a>
<ul>
<li><a href="namespace-Negotiation.Tests.html">Tests</a>
</li>
</ul></li>
<li><a href="namespace-None.html">None</a>
</li>
<li><a href="namespace-Pequiven.html">Pequiven<span></span></a>
<ul>
<li><a href="namespace-Pequiven.SEIPBundle.html">SEIPBundle<span></span></a>
<ul>
<li><a href="namespace-Pequiven.SEIPBundle.Controller.html">Controller</a>
</li>
<li><a href="namespace-Pequiven.SEIPBundle.DataFixtures.html">DataFixtures</a>
</li>
<li><a href="namespace-Pequiven.SEIPBundle.DependencyInjection.html">DependencyInjection</a>
</li>
<li><a href="namespace-Pequiven.SEIPBundle.Entity.html">Entity</a>
</li>
<li><a href="namespace-Pequiven.SEIPBundle.EventListener.html">EventListener</a>
</li>
<li><a href="namespace-Pequiven.SEIPBundle.Form.html">Form<span></span></a>
<ul>
<li><a href="namespace-Pequiven.SEIPBundle.Form.Type.html">Type</a>
</li>
</ul></li>
<li><a href="namespace-Pequiven.SEIPBundle.Menu.html">Menu<span></span></a>
<ul>
<li><a href="namespace-Pequiven.SEIPBundle.Menu.Template.html">Template<span></span></a>
<ul>
<li><a href="namespace-Pequiven.SEIPBundle.Menu.Template.Developer.html">Developer</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Pequiven.SEIPBundle.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Pequiven.SEIPBundle.Tests.Controller.html">Controller</a>
</li>
</ul></li></ul></li></ul></li>
<li><a href="namespace-PHP.html">PHP</a>
</li>
<li><a href="namespace-PhpCollection.html">PhpCollection<span></span></a>
<ul>
<li><a href="namespace-PhpCollection.Tests.html">Tests</a>
</li>
</ul></li>
<li><a href="namespace-PhpOption.html">PhpOption<span></span></a>
<ul>
<li><a href="namespace-PhpOption.Tests.html">Tests</a>
</li>
</ul></li>
<li><a href="namespace-Proxies.html">Proxies<span></span></a>
<ul>
<li><a href="namespace-Proxies.__CG__.html">__CG__<span></span></a>
<ul>
<li><a href="namespace-Proxies.__CG__.Pequiven.html">Pequiven<span></span></a>
<ul>
<li><a href="namespace-Proxies.__CG__.Pequiven.SEIPBundle.html">SEIPBundle<span></span></a>
<ul>
<li><a href="namespace-Proxies.__CG__.Pequiven.SEIPBundle.Entity.html">Entity</a>
</li>
</ul></li></ul></li></ul></li></ul></li>
<li><a href="namespace-Psr.html">Psr<span></span></a>
<ul>
<li><a href="namespace-Psr.Log.html">Log<span></span></a>
<ul>
<li><a href="namespace-Psr.Log.Test.html">Test</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-ReferenceIntegrity.html">ReferenceIntegrity<span></span></a>
<ul>
<li><a href="namespace-ReferenceIntegrity.Fixture.html">Fixture<span></span></a>
<ul>
<li><a href="namespace-ReferenceIntegrity.Fixture.Document.html">Document<span></span></a>
<ul>
<li><a href="namespace-ReferenceIntegrity.Fixture.Document.ManyNullify.html">ManyNullify</a>
</li>
<li><a href="namespace-ReferenceIntegrity.Fixture.Document.ManyRestrict.html">ManyRestrict</a>
</li>
<li><a href="namespace-ReferenceIntegrity.Fixture.Document.OneNullify.html">OneNullify</a>
</li>
<li><a href="namespace-ReferenceIntegrity.Fixture.Document.OneRestrict.html">OneRestrict</a>
</li>
</ul></li></ul></li></ul></li>
<li><a href="namespace-References.html">References<span></span></a>
<ul>
<li><a href="namespace-References.Fixture.html">Fixture<span></span></a>
<ul>
<li><a href="namespace-References.Fixture.ODM.html">ODM<span></span></a>
<ul>
<li><a href="namespace-References.Fixture.ODM.MongoDB.html">MongoDB</a>
</li>
</ul></li>
<li><a href="namespace-References.Fixture.ORM.html">ORM</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Sensio.html">Sensio<span></span></a>
<ul>
<li><a href="namespace-Sensio.Bundle.html">Bundle<span></span></a>
<ul>
<li><a href="namespace-Sensio.Bundle.DistributionBundle.html">DistributionBundle<span></span></a>
<ul>
<li><a href="namespace-Sensio.Bundle.DistributionBundle.Composer.html">Composer</a>
</li>
<li><a href="namespace-Sensio.Bundle.DistributionBundle.Configurator.html">Configurator<span></span></a>
<ul>
<li><a href="namespace-Sensio.Bundle.DistributionBundle.Configurator.Form.html">Form</a>
</li>
<li><a href="namespace-Sensio.Bundle.DistributionBundle.Configurator.Step.html">Step</a>
</li>
</ul></li>
<li><a href="namespace-Sensio.Bundle.DistributionBundle.Controller.html">Controller</a>
</li>
<li><a href="namespace-Sensio.Bundle.DistributionBundle.DependencyInjection.html">DependencyInjection</a>
</li>
</ul></li>
<li><a href="namespace-Sensio.Bundle.FrameworkExtraBundle.html">FrameworkExtraBundle<span></span></a>
<ul>
<li><a href="namespace-Sensio.Bundle.FrameworkExtraBundle.Configuration.html">Configuration</a>
</li>
<li><a href="namespace-Sensio.Bundle.FrameworkExtraBundle.DependencyInjection.html">DependencyInjection<span></span></a>
<ul>
<li><a href="namespace-Sensio.Bundle.FrameworkExtraBundle.DependencyInjection.Compiler.html">Compiler</a>
</li>
</ul></li>
<li><a href="namespace-Sensio.Bundle.FrameworkExtraBundle.EventListener.html">EventListener</a>
</li>
<li><a href="namespace-Sensio.Bundle.FrameworkExtraBundle.Request.html">Request<span></span></a>
<ul>
<li><a href="namespace-Sensio.Bundle.FrameworkExtraBundle.Request.ParamConverter.html">ParamConverter</a>
</li>
</ul></li>
<li><a href="namespace-Sensio.Bundle.FrameworkExtraBundle.Routing.html">Routing</a>
</li>
<li><a href="namespace-Sensio.Bundle.FrameworkExtraBundle.Security.html">Security</a>
</li>
<li><a href="namespace-Sensio.Bundle.FrameworkExtraBundle.Templating.html">Templating</a>
</li>
<li><a href="namespace-Sensio.Bundle.FrameworkExtraBundle.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Sensio.Bundle.FrameworkExtraBundle.Tests.Configuration.html">Configuration</a>
</li>
<li><a href="namespace-Sensio.Bundle.FrameworkExtraBundle.Tests.EventListener.html">EventListener<span></span></a>
<ul>
<li><a href="namespace-Sensio.Bundle.FrameworkExtraBundle.Tests.EventListener.Fixture.html">Fixture</a>
</li>
</ul></li>
<li><a href="namespace-Sensio.Bundle.FrameworkExtraBundle.Tests.Request.html">Request<span></span></a>
<ul>
<li><a href="namespace-Sensio.Bundle.FrameworkExtraBundle.Tests.Request.ParamConverter.html">ParamConverter</a>
</li>
</ul></li>
<li><a href="namespace-Sensio.Bundle.FrameworkExtraBundle.Tests.Routing.html">Routing</a>
</li>
<li><a href="namespace-Sensio.Bundle.FrameworkExtraBundle.Tests.Templating.html">Templating<span></span></a>
<ul>
<li><a href="namespace-Sensio.Bundle.FrameworkExtraBundle.Tests.Templating.Fixture.html">Fixture<span></span></a>
<ul>
<li><a href="namespace-Sensio.Bundle.FrameworkExtraBundle.Tests.Templating.Fixture.BarBundle.html">BarBundle<span></span></a>
<ul>
<li><a href="namespace-Sensio.Bundle.FrameworkExtraBundle.Tests.Templating.Fixture.BarBundle.Controller.html">Controller</a>
</li>
</ul></li>
<li><a href="namespace-Sensio.Bundle.FrameworkExtraBundle.Tests.Templating.Fixture.FooBarBundle.html">FooBarBundle<span></span></a>
<ul>
<li><a href="namespace-Sensio.Bundle.FrameworkExtraBundle.Tests.Templating.Fixture.FooBarBundle.Controller.html">Controller</a>
</li>
</ul></li>
<li><a href="namespace-Sensio.Bundle.FrameworkExtraBundle.Tests.Templating.Fixture.FooBundle.html">FooBundle<span></span></a>
<ul>
<li><a href="namespace-Sensio.Bundle.FrameworkExtraBundle.Tests.Templating.Fixture.FooBundle.Controller.html">Controller</a>
</li>
</ul></li></ul></li></ul></li></ul></li></ul></li>
<li><a href="namespace-Sensio.Bundle.GeneratorBundle.html">GeneratorBundle<span></span></a>
<ul>
<li><a href="namespace-Sensio.Bundle.GeneratorBundle.Command.html">Command<span></span></a>
<ul>
<li><a href="namespace-Sensio.Bundle.GeneratorBundle.Command.Helper.html">Helper</a>
</li>
</ul></li>
<li><a href="namespace-Sensio.Bundle.GeneratorBundle.Generator.html">Generator</a>
</li>
<li><a href="namespace-Sensio.Bundle.GeneratorBundle.Manipulator.html">Manipulator</a>
</li>
<li><a href="namespace-Sensio.Bundle.GeneratorBundle.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Sensio.Bundle.GeneratorBundle.Tests.Command.html">Command</a>
</li>
<li><a href="namespace-Sensio.Bundle.GeneratorBundle.Tests.Generator.html">Generator</a>
</li>
</ul></li></ul></li></ul></li></ul></li>
<li><a href="namespace-Sluggable.html">Sluggable<span></span></a>
<ul>
<li><a href="namespace-Sluggable.Fixture.html">Fixture<span></span></a>
<ul>
<li><a href="namespace-Sluggable.Fixture.Doctrine.html">Doctrine</a>
</li>
<li><a href="namespace-Sluggable.Fixture.Document.html">Document<span></span></a>
<ul>
<li><a href="namespace-Sluggable.Fixture.Document.Handler.html">Handler</a>
</li>
</ul></li>
<li><a href="namespace-Sluggable.Fixture.Handler.html">Handler<span></span></a>
<ul>
<li><a href="namespace-Sluggable.Fixture.Handler.People.html">People</a>
</li>
</ul></li>
<li><a href="namespace-Sluggable.Fixture.Inheritance.html">Inheritance</a>
</li>
<li><a href="namespace-Sluggable.Fixture.Inheritance2.html">Inheritance2</a>
</li>
<li><a href="namespace-Sluggable.Fixture.Issue104.html">Issue104</a>
</li>
<li><a href="namespace-Sluggable.Fixture.Issue116.html">Issue116</a>
</li>
<li><a href="namespace-Sluggable.Fixture.Issue131.html">Issue131</a>
</li>
<li><a href="namespace-Sluggable.Fixture.Issue449.html">Issue449</a>
</li>
<li><a href="namespace-Sluggable.Fixture.Issue633.html">Issue633</a>
</li>
<li><a href="namespace-Sluggable.Fixture.Issue827.html">Issue827</a>
</li>
<li><a href="namespace-Sluggable.Fixture.Issue939.html">Issue939</a>
</li>
<li><a href="namespace-Sluggable.Fixture.MappedSuperclass.html">MappedSuperclass</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-SoftDeleteable.html">SoftDeleteable<span></span></a>
<ul>
<li><a href="namespace-SoftDeleteable.Fixture.html">Fixture<span></span></a>
<ul>
<li><a href="namespace-SoftDeleteable.Fixture.Document.html">Document</a>
</li>
<li><a href="namespace-SoftDeleteable.Fixture.Entity.html">Entity</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Sortable.html">Sortable<span></span></a>
<ul>
<li><a href="namespace-Sortable.Fixture.html">Fixture<span></span></a>
<ul>
<li><a href="namespace-Sortable.Fixture.Transport.html">Transport</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Stof.html">Stof<span></span></a>
<ul>
<li><a href="namespace-Stof.DoctrineExtensionsBundle.html">DoctrineExtensionsBundle<span></span></a>
<ul>
<li><a href="namespace-Stof.DoctrineExtensionsBundle.DependencyInjection.html">DependencyInjection<span></span></a>
<ul>
<li><a href="namespace-Stof.DoctrineExtensionsBundle.DependencyInjection.Compiler.html">Compiler</a>
</li>
</ul></li>
<li><a href="namespace-Stof.DoctrineExtensionsBundle.EventListener.html">EventListener</a>
</li>
<li><a href="namespace-Stof.DoctrineExtensionsBundle.Uploadable.html">Uploadable</a>
</li>
</ul></li></ul></li>
<li class="active"><a href="namespace-Symfony.html">Symfony<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bridge.html">Bridge<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bridge.Doctrine.html">Doctrine<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bridge.Doctrine.CacheWarmer.html">CacheWarmer</a>
</li>
<li><a href="namespace-Symfony.Bridge.Doctrine.DataCollector.html">DataCollector</a>
</li>
<li><a href="namespace-Symfony.Bridge.Doctrine.DataFixtures.html">DataFixtures</a>
</li>
<li><a href="namespace-Symfony.Bridge.Doctrine.DependencyInjection.html">DependencyInjection<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bridge.Doctrine.DependencyInjection.CompilerPass.html">CompilerPass</a>
</li>
<li><a href="namespace-Symfony.Bridge.Doctrine.DependencyInjection.Security.html">Security<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bridge.Doctrine.DependencyInjection.Security.UserProvider.html">UserProvider</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Symfony.Bridge.Doctrine.ExpressionLanguage.html">ExpressionLanguage</a>
</li>
<li><a href="namespace-Symfony.Bridge.Doctrine.Form.html">Form<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bridge.Doctrine.Form.ChoiceList.html">ChoiceList</a>
</li>
<li><a href="namespace-Symfony.Bridge.Doctrine.Form.DataTransformer.html">DataTransformer</a>
</li>
<li><a href="namespace-Symfony.Bridge.Doctrine.Form.EventListener.html">EventListener</a>
</li>
<li><a href="namespace-Symfony.Bridge.Doctrine.Form.Type.html">Type</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Bridge.Doctrine.HttpFoundation.html">HttpFoundation</a>
</li>
<li><a href="namespace-Symfony.Bridge.Doctrine.Logger.html">Logger</a>
</li>
<li><a href="namespace-Symfony.Bridge.Doctrine.Security.html">Security<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bridge.Doctrine.Security.RememberMe.html">RememberMe</a>
</li>
<li><a href="namespace-Symfony.Bridge.Doctrine.Security.User.html">User</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Bridge.Doctrine.Test.html">Test</a>
</li>
<li><a href="namespace-Symfony.Bridge.Doctrine.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bridge.Doctrine.Tests.DataCollector.html">DataCollector</a>
</li>
<li><a href="namespace-Symfony.Bridge.Doctrine.Tests.DataFixtures.html">DataFixtures</a>
</li>
<li><a href="namespace-Symfony.Bridge.Doctrine.Tests.DependencyInjection.html">DependencyInjection<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bridge.Doctrine.Tests.DependencyInjection.CompilerPass.html">CompilerPass</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Bridge.Doctrine.Tests.ExpressionLanguage.html">ExpressionLanguage</a>
</li>
<li><a href="namespace-Symfony.Bridge.Doctrine.Tests.Fixtures.html">Fixtures</a>
</li>
<li><a href="namespace-Symfony.Bridge.Doctrine.Tests.Form.html">Form<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bridge.Doctrine.Tests.Form.ChoiceList.html">ChoiceList</a>
</li>
<li><a href="namespace-Symfony.Bridge.Doctrine.Tests.Form.DataTransformer.html">DataTransformer</a>
</li>
<li><a href="namespace-Symfony.Bridge.Doctrine.Tests.Form.Type.html">Type</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Bridge.Doctrine.Tests.HttpFoundation.html">HttpFoundation</a>
</li>
<li><a href="namespace-Symfony.Bridge.Doctrine.Tests.Logger.html">Logger</a>
</li>
<li><a href="namespace-Symfony.Bridge.Doctrine.Tests.Security.html">Security<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bridge.Doctrine.Tests.Security.User.html">User</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Bridge.Doctrine.Tests.Validator.html">Validator<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bridge.Doctrine.Tests.Validator.Constraints.html">Constraints</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Symfony.Bridge.Doctrine.Validator.html">Validator<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bridge.Doctrine.Validator.Constraints.html">Constraints</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Symfony.Bridge.Monolog.html">Monolog<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bridge.Monolog.Formatter.html">Formatter</a>
</li>
<li><a href="namespace-Symfony.Bridge.Monolog.Handler.html">Handler</a>
</li>
<li><a href="namespace-Symfony.Bridge.Monolog.Processor.html">Processor</a>
</li>
<li><a href="namespace-Symfony.Bridge.Monolog.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bridge.Monolog.Tests.Handler.html">Handler</a>
</li>
<li><a href="namespace-Symfony.Bridge.Monolog.Tests.Processor.html">Processor</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Symfony.Bridge.Propel1.html">Propel1<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bridge.Propel1.DataCollector.html">DataCollector</a>
</li>
<li><a href="namespace-Symfony.Bridge.Propel1.DependencyInjection.html">DependencyInjection<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bridge.Propel1.DependencyInjection.Security.html">Security<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bridge.Propel1.DependencyInjection.Security.UserProvider.html">UserProvider</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Symfony.Bridge.Propel1.Form.html">Form<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bridge.Propel1.Form.ChoiceList.html">ChoiceList</a>
</li>
<li><a href="namespace-Symfony.Bridge.Propel1.Form.DataTransformer.html">DataTransformer</a>
</li>
<li><a href="namespace-Symfony.Bridge.Propel1.Form.EventListener.html">EventListener</a>
</li>
<li><a href="namespace-Symfony.Bridge.Propel1.Form.Type.html">Type</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Bridge.Propel1.Logger.html">Logger</a>
</li>
<li><a href="namespace-Symfony.Bridge.Propel1.Security.html">Security<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bridge.Propel1.Security.User.html">User</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Bridge.Propel1.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bridge.Propel1.Tests.DataCollector.html">DataCollector</a>
</li>
<li><a href="namespace-Symfony.Bridge.Propel1.Tests.Fixtures.html">Fixtures</a>
</li>
<li><a href="namespace-Symfony.Bridge.Propel1.Tests.Form.html">Form<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bridge.Propel1.Tests.Form.ChoiceList.html">ChoiceList</a>
</li>
<li><a href="namespace-Symfony.Bridge.Propel1.Tests.Form.DataTransformer.html">DataTransformer</a>
</li>
</ul></li></ul></li></ul></li>
<li><a href="namespace-Symfony.Bridge.ProxyManager.html">ProxyManager<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bridge.ProxyManager.LazyProxy.html">LazyProxy<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bridge.ProxyManager.LazyProxy.Instantiator.html">Instantiator</a>
</li>
<li><a href="namespace-Symfony.Bridge.ProxyManager.LazyProxy.PhpDumper.html">PhpDumper</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Bridge.ProxyManager.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bridge.ProxyManager.Tests.LazyProxy.html">LazyProxy<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bridge.ProxyManager.Tests.LazyProxy.Dumper.html">Dumper</a>
</li>
<li><a href="namespace-Symfony.Bridge.ProxyManager.Tests.LazyProxy.Instantiator.html">Instantiator</a>
</li>
<li><a href="namespace-Symfony.Bridge.ProxyManager.Tests.LazyProxy.PhpDumper.html">PhpDumper</a>
</li>
</ul></li></ul></li></ul></li>
<li><a href="namespace-Symfony.Bridge.Twig.html">Twig<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bridge.Twig.Extension.html">Extension</a>
</li>
<li><a href="namespace-Symfony.Bridge.Twig.Form.html">Form</a>
</li>
<li><a href="namespace-Symfony.Bridge.Twig.Node.html">Node</a>
</li>
<li><a href="namespace-Symfony.Bridge.Twig.NodeVisitor.html">NodeVisitor</a>
</li>
<li><a href="namespace-Symfony.Bridge.Twig.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bridge.Twig.Tests.Extension.html">Extension<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bridge.Twig.Tests.Extension.Fixtures.html">Fixtures</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Bridge.Twig.Tests.Node.html">Node</a>
</li>
<li><a href="namespace-Symfony.Bridge.Twig.Tests.NodeVisitor.html">NodeVisitor</a>
</li>
<li><a href="namespace-Symfony.Bridge.Twig.Tests.TokenParser.html">TokenParser</a>
</li>
<li><a href="namespace-Symfony.Bridge.Twig.Tests.Translation.html">Translation</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Bridge.Twig.TokenParser.html">TokenParser</a>
</li>
<li><a href="namespace-Symfony.Bridge.Twig.Translation.html">Translation</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Symfony.Bundle.html">Bundle<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.AsseticBundle.html">AsseticBundle<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.AsseticBundle.CacheWarmer.html">CacheWarmer</a>
</li>
<li><a href="namespace-Symfony.Bundle.AsseticBundle.Command.html">Command</a>
</li>
<li><a href="namespace-Symfony.Bundle.AsseticBundle.Config.html">Config</a>
</li>
<li><a href="namespace-Symfony.Bundle.AsseticBundle.Controller.html">Controller</a>
</li>
<li><a href="namespace-Symfony.Bundle.AsseticBundle.DependencyInjection.html">DependencyInjection<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.AsseticBundle.DependencyInjection.Compiler.html">Compiler</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Bundle.AsseticBundle.EventListener.html">EventListener</a>
</li>
<li><a href="namespace-Symfony.Bundle.AsseticBundle.Exception.html">Exception</a>
</li>
<li><a href="namespace-Symfony.Bundle.AsseticBundle.Factory.html">Factory<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.AsseticBundle.Factory.Loader.html">Loader</a>
</li>
<li><a href="namespace-Symfony.Bundle.AsseticBundle.Factory.Resource.html">Resource</a>
</li>
<li><a href="namespace-Symfony.Bundle.AsseticBundle.Factory.Worker.html">Worker</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Bundle.AsseticBundle.Routing.html">Routing</a>
</li>
<li><a href="namespace-Symfony.Bundle.AsseticBundle.Templating.html">Templating</a>
</li>
<li><a href="namespace-Symfony.Bundle.AsseticBundle.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.AsseticBundle.Tests.CacheWarmer.html">CacheWarmer</a>
</li>
<li><a href="namespace-Symfony.Bundle.AsseticBundle.Tests.Command.html">Command</a>
</li>
<li><a href="namespace-Symfony.Bundle.AsseticBundle.Tests.Controller.html">Controller</a>
</li>
<li><a href="namespace-Symfony.Bundle.AsseticBundle.Tests.DependencyInjection.html">DependencyInjection</a>
</li>
<li><a href="namespace-Symfony.Bundle.AsseticBundle.Tests.Factory.html">Factory<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.AsseticBundle.Tests.Factory.Resource.html">Resource</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Bundle.AsseticBundle.Tests.Templating.html">Templating</a>
</li>
<li><a href="namespace-Symfony.Bundle.AsseticBundle.Tests.TestBundle.html">TestBundle</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Bundle.AsseticBundle.Twig.html">Twig</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.html">FrameworkBundle<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.CacheWarmer.html">CacheWarmer</a>
</li>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.Command.html">Command</a>
</li>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.Console.html">Console<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.Console.Descriptor.html">Descriptor</a>
</li>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.Console.Helper.html">Helper</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.Controller.html">Controller</a>
</li>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.DataCollector.html">DataCollector</a>
</li>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.DependencyInjection.html">DependencyInjection<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.DependencyInjection.Compiler.html">Compiler</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.EventListener.html">EventListener</a>
</li>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.Fragment.html">Fragment</a>
</li>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.HttpCache.html">HttpCache</a>
</li>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.Routing.html">Routing</a>
</li>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.Templating.html">Templating<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.Templating.Asset.html">Asset</a>
</li>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.Templating.Helper.html">Helper</a>
</li>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.Templating.Loader.html">Loader</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.Test.html">Test</a>
</li>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.Tests.CacheWarmer.html">CacheWarmer</a>
</li>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.Tests.Console.html">Console<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.Tests.Console.Descriptor.html">Descriptor</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.Tests.Controller.html">Controller</a>
</li>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.Tests.DependencyInjection.html">DependencyInjection<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.Tests.DependencyInjection.Compiler.html">Compiler</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.Tests.Fixtures.html">Fixtures<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.Tests.Fixtures.BaseBundle.html">BaseBundle</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.Tests.Fragment.html">Fragment</a>
</li>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.Tests.Functional.html">Functional<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.Tests.Functional.app.html">app</a>
</li>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.Tests.Functional.Bundle.html">Bundle<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.Tests.Functional.Bundle.TestBundle.html">TestBundle<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.Tests.Functional.Bundle.TestBundle.Controller.html">Controller</a>
</li>
</ul></li></ul></li></ul></li>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.Tests.Routing.html">Routing</a>
</li>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.Tests.Templating.html">Templating<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.Tests.Templating.Helper.html">Helper<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.Tests.Templating.Helper.Fixtures.html">Fixtures</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.Tests.Templating.Loader.html">Loader</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.Tests.Translation.html">Translation</a>
</li>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.Tests.Validator.html">Validator</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.Translation.html">Translation</a>
</li>
<li><a href="namespace-Symfony.Bundle.FrameworkBundle.Validator.html">Validator</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Bundle.MonologBundle.html">MonologBundle<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.MonologBundle.DependencyInjection.html">DependencyInjection<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.MonologBundle.DependencyInjection.Compiler.html">Compiler</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Bundle.MonologBundle.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.MonologBundle.Tests.DependencyInjection.html">DependencyInjection<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.MonologBundle.Tests.DependencyInjection.Compiler.html">Compiler</a>
</li>
</ul></li></ul></li></ul></li>
<li><a href="namespace-Symfony.Bundle.SecurityBundle.html">SecurityBundle<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.SecurityBundle.Command.html">Command</a>
</li>
<li><a href="namespace-Symfony.Bundle.SecurityBundle.DataCollector.html">DataCollector</a>
</li>
<li><a href="namespace-Symfony.Bundle.SecurityBundle.DependencyInjection.html">DependencyInjection<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.SecurityBundle.DependencyInjection.Compiler.html">Compiler</a>
</li>
<li><a href="namespace-Symfony.Bundle.SecurityBundle.DependencyInjection.Security.html">Security<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.SecurityBundle.DependencyInjection.Security.Factory.html">Factory</a>
</li>
<li><a href="namespace-Symfony.Bundle.SecurityBundle.DependencyInjection.Security.UserProvider.html">UserProvider</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Symfony.Bundle.SecurityBundle.EventListener.html">EventListener</a>
</li>
<li><a href="namespace-Symfony.Bundle.SecurityBundle.Security.html">Security</a>
</li>
<li><a href="namespace-Symfony.Bundle.SecurityBundle.Templating.html">Templating<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.SecurityBundle.Templating.Helper.html">Helper</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Bundle.SecurityBundle.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.SecurityBundle.Tests.DependencyInjection.html">DependencyInjection<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.SecurityBundle.Tests.DependencyInjection.Security.html">Security<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.SecurityBundle.Tests.DependencyInjection.Security.Factory.html">Factory</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Symfony.Bundle.SecurityBundle.Tests.Functional.html">Functional<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.SecurityBundle.Tests.Functional.app.html">app</a>
</li>
<li><a href="namespace-Symfony.Bundle.SecurityBundle.Tests.Functional.Bundle.html">Bundle<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.SecurityBundle.Tests.Functional.Bundle.CsrfFormLoginBundle.html">CsrfFormLoginBundle<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.SecurityBundle.Tests.Functional.Bundle.CsrfFormLoginBundle.Controller.html">Controller</a>
</li>
<li><a href="namespace-Symfony.Bundle.SecurityBundle.Tests.Functional.Bundle.CsrfFormLoginBundle.Form.html">Form</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Bundle.SecurityBundle.Tests.Functional.Bundle.FormLoginBundle.html">FormLoginBundle<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.SecurityBundle.Tests.Functional.Bundle.FormLoginBundle.Controller.html">Controller</a>
</li>
<li><a href="namespace-Symfony.Bundle.SecurityBundle.Tests.Functional.Bundle.FormLoginBundle.DependencyInjection.html">DependencyInjection</a>
</li>
<li><a href="namespace-Symfony.Bundle.SecurityBundle.Tests.Functional.Bundle.FormLoginBundle.Security.html">Security</a>
</li>
</ul></li></ul></li></ul></li></ul></li>
<li><a href="namespace-Symfony.Bundle.SecurityBundle.Twig.html">Twig<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.SecurityBundle.Twig.Extension.html">Extension</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Symfony.Bundle.SwiftmailerBundle.html">SwiftmailerBundle<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.SwiftmailerBundle.Command.html">Command</a>
</li>
<li><a href="namespace-Symfony.Bundle.SwiftmailerBundle.DataCollector.html">DataCollector</a>
</li>
<li><a href="namespace-Symfony.Bundle.SwiftmailerBundle.DependencyInjection.html">DependencyInjection<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.SwiftmailerBundle.DependencyInjection.Compiler.html">Compiler</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Bundle.SwiftmailerBundle.EventListener.html">EventListener</a>
</li>
<li><a href="namespace-Symfony.Bundle.SwiftmailerBundle.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.SwiftmailerBundle.Tests.DependencyInjection.html">DependencyInjection</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Symfony.Bundle.TwigBundle.html">TwigBundle<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.TwigBundle.CacheWarmer.html">CacheWarmer</a>
</li>
<li><a href="namespace-Symfony.Bundle.TwigBundle.Command.html">Command</a>
</li>
<li><a href="namespace-Symfony.Bundle.TwigBundle.Controller.html">Controller</a>
</li>
<li><a href="namespace-Symfony.Bundle.TwigBundle.Debug.html">Debug</a>
</li>
<li><a href="namespace-Symfony.Bundle.TwigBundle.DependencyInjection.html">DependencyInjection<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.TwigBundle.DependencyInjection.Compiler.html">Compiler</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Bundle.TwigBundle.Extension.html">Extension</a>
</li>
<li><a href="namespace-Symfony.Bundle.TwigBundle.Loader.html">Loader</a>
</li>
<li><a href="namespace-Symfony.Bundle.TwigBundle.Node.html">Node</a>
</li>
<li><a href="namespace-Symfony.Bundle.TwigBundle.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.TwigBundle.Tests.Controller.html">Controller</a>
</li>
<li><a href="namespace-Symfony.Bundle.TwigBundle.Tests.DependencyInjection.html">DependencyInjection<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.TwigBundle.Tests.DependencyInjection.Compiler.html">Compiler</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Bundle.TwigBundle.Tests.Loader.html">Loader</a>
</li>
<li><a href="namespace-Symfony.Bundle.TwigBundle.Tests.TokenParser.html">TokenParser</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Bundle.TwigBundle.TokenParser.html">TokenParser</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Bundle.WebProfilerBundle.html">WebProfilerBundle<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.WebProfilerBundle.Controller.html">Controller</a>
</li>
<li><a href="namespace-Symfony.Bundle.WebProfilerBundle.DependencyInjection.html">DependencyInjection</a>
</li>
<li><a href="namespace-Symfony.Bundle.WebProfilerBundle.EventListener.html">EventListener</a>
</li>
<li><a href="namespace-Symfony.Bundle.WebProfilerBundle.Profiler.html">Profiler</a>
</li>
<li><a href="namespace-Symfony.Bundle.WebProfilerBundle.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Symfony.Bundle.WebProfilerBundle.Tests.Controller.html">Controller</a>
</li>
<li><a href="namespace-Symfony.Bundle.WebProfilerBundle.Tests.DependencyInjection.html">DependencyInjection</a>
</li>
<li><a href="namespace-Symfony.Bundle.WebProfilerBundle.Tests.EventListener.html">EventListener</a>
</li>
<li><a href="namespace-Symfony.Bundle.WebProfilerBundle.Tests.Profiler.html">Profiler</a>
</li>
</ul></li></ul></li></ul></li>
<li class="active"><a href="namespace-Symfony.Component.html">Component<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.BrowserKit.html">BrowserKit<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.BrowserKit.Tests.html">Tests</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.ClassLoader.html">ClassLoader<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.ClassLoader.Tests.html">Tests</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Config.html">Config<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Config.Definition.html">Definition<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Config.Definition.Builder.html">Builder</a>
</li>
<li><a href="namespace-Symfony.Component.Config.Definition.Dumper.html">Dumper</a>
</li>
<li><a href="namespace-Symfony.Component.Config.Definition.Exception.html">Exception</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Config.Exception.html">Exception</a>
</li>
<li><a href="namespace-Symfony.Component.Config.Loader.html">Loader</a>
</li>
<li><a href="namespace-Symfony.Component.Config.Resource.html">Resource</a>
</li>
<li><a href="namespace-Symfony.Component.Config.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Config.Tests.Definition.html">Definition<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Config.Tests.Definition.Builder.html">Builder</a>
</li>
<li><a href="namespace-Symfony.Component.Config.Tests.Definition.Dumper.html">Dumper</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Config.Tests.Fixtures.html">Fixtures<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Config.Tests.Fixtures.Configuration.html">Configuration</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Config.Tests.Loader.html">Loader</a>
</li>
<li><a href="namespace-Symfony.Component.Config.Tests.Resource.html">Resource</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Config.Util.html">Util</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Console.html">Console<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Console.Command.html">Command</a>
</li>
<li><a href="namespace-Symfony.Component.Console.Descriptor.html">Descriptor</a>
</li>
<li><a href="namespace-Symfony.Component.Console.Event.html">Event</a>
</li>
<li><a href="namespace-Symfony.Component.Console.Formatter.html">Formatter</a>
</li>
<li><a href="namespace-Symfony.Component.Console.Helper.html">Helper</a>
</li>
<li><a href="namespace-Symfony.Component.Console.Input.html">Input</a>
</li>
<li><a href="namespace-Symfony.Component.Console.Output.html">Output</a>
</li>
<li><a href="namespace-Symfony.Component.Console.Tester.html">Tester</a>
</li>
<li><a href="namespace-Symfony.Component.Console.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Console.Tests.Command.html">Command</a>
</li>
<li><a href="namespace-Symfony.Component.Console.Tests.Descriptor.html">Descriptor</a>
</li>
<li><a href="namespace-Symfony.Component.Console.Tests.Fixtures.html">Fixtures</a>
</li>
<li><a href="namespace-Symfony.Component.Console.Tests.Formatter.html">Formatter</a>
</li>
<li><a href="namespace-Symfony.Component.Console.Tests.Helper.html">Helper</a>
</li>
<li><a href="namespace-Symfony.Component.Console.Tests.Input.html">Input</a>
</li>
<li><a href="namespace-Symfony.Component.Console.Tests.Output.html">Output</a>
</li>
<li><a href="namespace-Symfony.Component.Console.Tests.Tester.html">Tester</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Symfony.Component.CssSelector.html">CssSelector<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.CssSelector.Exception.html">Exception</a>
</li>
<li><a href="namespace-Symfony.Component.CssSelector.Node.html">Node</a>
</li>
<li><a href="namespace-Symfony.Component.CssSelector.Parser.html">Parser<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.CssSelector.Parser.Handler.html">Handler</a>
</li>
<li><a href="namespace-Symfony.Component.CssSelector.Parser.Shortcut.html">Shortcut</a>
</li>
<li><a href="namespace-Symfony.Component.CssSelector.Parser.Tokenizer.html">Tokenizer</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.CssSelector.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.CssSelector.Tests.Node.html">Node</a>
</li>
<li><a href="namespace-Symfony.Component.CssSelector.Tests.Parser.html">Parser<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.CssSelector.Tests.Parser.Handler.html">Handler</a>
</li>
<li><a href="namespace-Symfony.Component.CssSelector.Tests.Parser.Shortcut.html">Shortcut</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.CssSelector.Tests.XPath.html">XPath</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.CssSelector.XPath.html">XPath<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.CssSelector.XPath.Extension.html">Extension</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Symfony.Component.Debug.html">Debug<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Debug.Exception.html">Exception</a>
</li>
<li><a href="namespace-Symfony.Component.Debug.FatalErrorHandler.html">FatalErrorHandler</a>
</li>
<li><a href="namespace-Symfony.Component.Debug.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Debug.Tests.Exception.html">Exception</a>
</li>
<li><a href="namespace-Symfony.Component.Debug.Tests.FatalErrorHandler.html">FatalErrorHandler</a>
</li>
<li><a href="namespace-Symfony.Component.Debug.Tests.Fixtures.html">Fixtures</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Symfony.Component.DependencyInjection.html">DependencyInjection<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.DependencyInjection.Compiler.html">Compiler</a>
</li>
<li><a href="namespace-Symfony.Component.DependencyInjection.Dump.html">Dump</a>
</li>
<li><a href="namespace-Symfony.Component.DependencyInjection.Dumper.html">Dumper</a>
</li>
<li><a href="namespace-Symfony.Component.DependencyInjection.Exception.html">Exception</a>
</li>
<li><a href="namespace-Symfony.Component.DependencyInjection.Extension.html">Extension</a>
</li>
<li><a href="namespace-Symfony.Component.DependencyInjection.LazyProxy.html">LazyProxy<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.DependencyInjection.LazyProxy.Instantiator.html">Instantiator</a>
</li>
<li><a href="namespace-Symfony.Component.DependencyInjection.LazyProxy.PhpDumper.html">PhpDumper</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.DependencyInjection.Loader.html">Loader</a>
</li>
<li><a href="namespace-Symfony.Component.DependencyInjection.ParameterBag.html">ParameterBag</a>
</li>
<li><a href="namespace-Symfony.Component.DependencyInjection.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.DependencyInjection.Tests.Compiler.html">Compiler</a>
</li>
<li><a href="namespace-Symfony.Component.DependencyInjection.Tests.Dumper.html">Dumper</a>
</li>
<li><a href="namespace-Symfony.Component.DependencyInjection.Tests.Extension.html">Extension</a>
</li>
<li><a href="namespace-Symfony.Component.DependencyInjection.Tests.LazyProxy.html">LazyProxy<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.DependencyInjection.Tests.LazyProxy.Instantiator.html">Instantiator</a>
</li>
<li><a href="namespace-Symfony.Component.DependencyInjection.Tests.LazyProxy.PhpDumper.html">PhpDumper</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.DependencyInjection.Tests.Loader.html">Loader</a>
</li>
<li><a href="namespace-Symfony.Component.DependencyInjection.Tests.ParameterBag.html">ParameterBag</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Symfony.Component.DomCrawler.html">DomCrawler<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.DomCrawler.Field.html">Field</a>
</li>
<li><a href="namespace-Symfony.Component.DomCrawler.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.DomCrawler.Tests.Field.html">Field</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Symfony.Component.EventDispatcher.html">EventDispatcher<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.EventDispatcher.Debug.html">Debug</a>
</li>
<li><a href="namespace-Symfony.Component.EventDispatcher.Tests.html">Tests</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.ExpressionLanguage.html">ExpressionLanguage<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.ExpressionLanguage.Node.html">Node</a>
</li>
<li><a href="namespace-Symfony.Component.ExpressionLanguage.ParserCache.html">ParserCache</a>
</li>
<li><a href="namespace-Symfony.Component.ExpressionLanguage.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.ExpressionLanguage.Tests.Node.html">Node</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Symfony.Component.Filesystem.html">Filesystem<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Filesystem.Exception.html">Exception</a>
</li>
<li><a href="namespace-Symfony.Component.Filesystem.Tests.html">Tests</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Finder.html">Finder<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Finder.Adapter.html">Adapter</a>
</li>
<li><a href="namespace-Symfony.Component.Finder.Comparator.html">Comparator</a>
</li>
<li><a href="namespace-Symfony.Component.Finder.Exception.html">Exception</a>
</li>
<li><a href="namespace-Symfony.Component.Finder.Expression.html">Expression</a>
</li>
<li><a href="namespace-Symfony.Component.Finder.Iterator.html">Iterator</a>
</li>
<li><a href="namespace-Symfony.Component.Finder.Shell.html">Shell</a>
</li>
<li><a href="namespace-Symfony.Component.Finder.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Finder.Tests.Comparator.html">Comparator</a>
</li>
<li><a href="namespace-Symfony.Component.Finder.Tests.Expression.html">Expression</a>
</li>
<li><a href="namespace-Symfony.Component.Finder.Tests.FakeAdapter.html">FakeAdapter</a>
</li>
<li><a href="namespace-Symfony.Component.Finder.Tests.Iterator.html">Iterator</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Symfony.Component.Form.html">Form<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Form.Exception.html">Exception</a>
</li>
<li><a href="namespace-Symfony.Component.Form.Extension.html">Extension<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Form.Extension.Core.html">Core<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Form.Extension.Core.ChoiceList.html">ChoiceList</a>
</li>
<li><a href="namespace-Symfony.Component.Form.Extension.Core.DataMapper.html">DataMapper</a>
</li>
<li><a href="namespace-Symfony.Component.Form.Extension.Core.DataTransformer.html">DataTransformer</a>
</li>
<li><a href="namespace-Symfony.Component.Form.Extension.Core.EventListener.html">EventListener</a>
</li>
<li><a href="namespace-Symfony.Component.Form.Extension.Core.Type.html">Type</a>
</li>
<li><a href="namespace-Symfony.Component.Form.Extension.Core.View.html">View</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Form.Extension.Csrf.html">Csrf<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Form.Extension.Csrf.EventListener.html">EventListener</a>
</li>
<li><a href="namespace-Symfony.Component.Form.Extension.Csrf.Type.html">Type</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Form.Extension.DataCollector.html">DataCollector<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Form.Extension.DataCollector.EventListener.html">EventListener</a>
</li>
<li><a href="namespace-Symfony.Component.Form.Extension.DataCollector.Proxy.html">Proxy</a>
</li>
<li><a href="namespace-Symfony.Component.Form.Extension.DataCollector.Type.html">Type</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Form.Extension.DependencyInjection.html">DependencyInjection</a>
</li>
<li><a href="namespace-Symfony.Component.Form.Extension.HttpFoundation.html">HttpFoundation<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Form.Extension.HttpFoundation.Type.html">Type</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Form.Extension.Templating.html">Templating</a>
</li>
<li><a href="namespace-Symfony.Component.Form.Extension.Validator.html">Validator<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Form.Extension.Validator.Constraints.html">Constraints</a>
</li>
<li><a href="namespace-Symfony.Component.Form.Extension.Validator.EventListener.html">EventListener</a>
</li>
<li><a href="namespace-Symfony.Component.Form.Extension.Validator.Type.html">Type</a>
</li>
<li><a href="namespace-Symfony.Component.Form.Extension.Validator.Util.html">Util</a>
</li>
<li><a href="namespace-Symfony.Component.Form.Extension.Validator.ViolationMapper.html">ViolationMapper</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Symfony.Component.Form.Guess.html">Guess</a>
</li>
<li><a href="namespace-Symfony.Component.Form.Test.html">Test</a>
</li>
<li><a href="namespace-Symfony.Component.Form.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Form.Tests.Extension.html">Extension<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Form.Tests.Extension.Core.html">Core<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Form.Tests.Extension.Core.ChoiceList.html">ChoiceList</a>
</li>
<li><a href="namespace-Symfony.Component.Form.Tests.Extension.Core.DataMapper.html">DataMapper</a>
</li>
<li><a href="namespace-Symfony.Component.Form.Tests.Extension.Core.DataTransformer.html">DataTransformer</a>
</li>
<li><a href="namespace-Symfony.Component.Form.Tests.Extension.Core.EventListener.html">EventListener</a>
</li>
<li><a href="namespace-Symfony.Component.Form.Tests.Extension.Core.Type.html">Type</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Form.Tests.Extension.Csrf.html">Csrf<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Form.Tests.Extension.Csrf.CsrfProvider.html">CsrfProvider</a>
</li>
<li><a href="namespace-Symfony.Component.Form.Tests.Extension.Csrf.EventListener.html">EventListener</a>
</li>
<li><a href="namespace-Symfony.Component.Form.Tests.Extension.Csrf.Type.html">Type</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Form.Tests.Extension.DataCollector.html">DataCollector<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Form.Tests.Extension.DataCollector.Type.html">Type</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Form.Tests.Extension.HttpFoundation.html">HttpFoundation<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Form.Tests.Extension.HttpFoundation.EventListener.html">EventListener</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Form.Tests.Extension.Validator.html">Validator<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Form.Tests.Extension.Validator.Constraints.html">Constraints</a>
</li>
<li><a href="namespace-Symfony.Component.Form.Tests.Extension.Validator.EventListener.html">EventListener</a>
</li>
<li><a href="namespace-Symfony.Component.Form.Tests.Extension.Validator.Type.html">Type</a>
</li>
<li><a href="namespace-Symfony.Component.Form.Tests.Extension.Validator.Util.html">Util</a>
</li>
<li><a href="namespace-Symfony.Component.Form.Tests.Extension.Validator.ViolationMapper.html">ViolationMapper</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Symfony.Component.Form.Tests.Fixtures.html">Fixtures</a>
</li>
<li><a href="namespace-Symfony.Component.Form.Tests.Guess.html">Guess</a>
</li>
<li><a href="namespace-Symfony.Component.Form.Tests.Util.html">Util</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Form.Util.html">Util</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.HttpFoundation.html">HttpFoundation<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.HttpFoundation.File.html">File<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.HttpFoundation.File.Exception.html">Exception</a>
</li>
<li><a href="namespace-Symfony.Component.HttpFoundation.File.MimeType.html">MimeType</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.HttpFoundation.Session.html">Session<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.HttpFoundation.Session.Attribute.html">Attribute</a>
</li>
<li><a href="namespace-Symfony.Component.HttpFoundation.Session.Flash.html">Flash</a>
</li>
<li><a href="namespace-Symfony.Component.HttpFoundation.Session.Storage.html">Storage<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.HttpFoundation.Session.Storage.Handler.html">Handler</a>
</li>
<li><a href="namespace-Symfony.Component.HttpFoundation.Session.Storage.Proxy.html">Proxy</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Symfony.Component.HttpFoundation.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.HttpFoundation.Tests.File.html">File<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.HttpFoundation.Tests.File.MimeType.html">MimeType</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.HttpFoundation.Tests.Session.html">Session<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.HttpFoundation.Tests.Session.Attribute.html">Attribute</a>
</li>
<li><a href="namespace-Symfony.Component.HttpFoundation.Tests.Session.Flash.html">Flash</a>
</li>
<li><a href="namespace-Symfony.Component.HttpFoundation.Tests.Session.Storage.html">Storage<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.HttpFoundation.Tests.Session.Storage.Handler.html">Handler</a>
</li>
<li><a href="namespace-Symfony.Component.HttpFoundation.Tests.Session.Storage.Proxy.html">Proxy</a>
</li>
</ul></li></ul></li></ul></li></ul></li>
<li><a href="namespace-Symfony.Component.HttpKernel.html">HttpKernel<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.HttpKernel.Bundle.html">Bundle</a>
</li>
<li><a href="namespace-Symfony.Component.HttpKernel.CacheClearer.html">CacheClearer</a>
</li>
<li><a href="namespace-Symfony.Component.HttpKernel.CacheWarmer.html">CacheWarmer</a>
</li>
<li><a href="namespace-Symfony.Component.HttpKernel.Config.html">Config</a>
</li>
<li><a href="namespace-Symfony.Component.HttpKernel.Controller.html">Controller</a>
</li>
<li><a href="namespace-Symfony.Component.HttpKernel.DataCollector.html">DataCollector<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.HttpKernel.DataCollector.Util.html">Util</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.HttpKernel.Debug.html">Debug</a>
</li>
<li><a href="namespace-Symfony.Component.HttpKernel.DependencyInjection.html">DependencyInjection</a>
</li>
<li><a href="namespace-Symfony.Component.HttpKernel.Event.html">Event</a>
</li>
<li><a href="namespace-Symfony.Component.HttpKernel.EventListener.html">EventListener</a>
</li>
<li><a href="namespace-Symfony.Component.HttpKernel.Exception.html">Exception</a>
</li>
<li><a href="namespace-Symfony.Component.HttpKernel.Fragment.html">Fragment</a>
</li>
<li><a href="namespace-Symfony.Component.HttpKernel.HttpCache.html">HttpCache</a>
</li>
<li><a href="namespace-Symfony.Component.HttpKernel.Log.html">Log</a>
</li>
<li><a href="namespace-Symfony.Component.HttpKernel.Profiler.html">Profiler</a>
</li>
<li><a href="namespace-Symfony.Component.HttpKernel.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.HttpKernel.Tests.Bundle.html">Bundle</a>
</li>
<li><a href="namespace-Symfony.Component.HttpKernel.Tests.CacheClearer.html">CacheClearer</a>
</li>
<li><a href="namespace-Symfony.Component.HttpKernel.Tests.CacheWarmer.html">CacheWarmer</a>
</li>
<li><a href="namespace-Symfony.Component.HttpKernel.Tests.Config.html">Config</a>
</li>
<li><a href="namespace-Symfony.Component.HttpKernel.Tests.Controller.html">Controller</a>
</li>
<li><a href="namespace-Symfony.Component.HttpKernel.Tests.DataCollector.html">DataCollector</a>
</li>
<li><a href="namespace-Symfony.Component.HttpKernel.Tests.Debug.html">Debug</a>
</li>
<li><a href="namespace-Symfony.Component.HttpKernel.Tests.DependencyInjection.html">DependencyInjection</a>
</li>
<li><a href="namespace-Symfony.Component.HttpKernel.Tests.EventListener.html">EventListener</a>
</li>
<li><a href="namespace-Symfony.Component.HttpKernel.Tests.Fixtures.html">Fixtures<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.HttpKernel.Tests.Fixtures.ExtensionAbsentBundle.html">ExtensionAbsentBundle</a>
</li>
<li><a href="namespace-Symfony.Component.HttpKernel.Tests.Fixtures.ExtensionLoadedBundle.html">ExtensionLoadedBundle<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.HttpKernel.Tests.Fixtures.ExtensionLoadedBundle.DependencyInjection.html">DependencyInjection</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.HttpKernel.Tests.Fixtures.ExtensionPresentBundle.html">ExtensionPresentBundle<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.HttpKernel.Tests.Fixtures.ExtensionPresentBundle.Command.html">Command</a>
</li>
<li><a href="namespace-Symfony.Component.HttpKernel.Tests.Fixtures.ExtensionPresentBundle.DependencyInjection.html">DependencyInjection</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Symfony.Component.HttpKernel.Tests.Fragment.html">Fragment</a>
</li>
<li><a href="namespace-Symfony.Component.HttpKernel.Tests.HttpCache.html">HttpCache</a>
</li>
<li><a href="namespace-Symfony.Component.HttpKernel.Tests.Profiler.html">Profiler<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.HttpKernel.Tests.Profiler.Mock.html">Mock</a>
</li>
</ul></li></ul></li></ul></li>
<li><a href="namespace-Symfony.Component.Icu.html">Icu<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Icu.Tests.html">Tests</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Intl.html">Intl<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Intl.Collator.html">Collator</a>
</li>
<li><a href="namespace-Symfony.Component.Intl.DateFormatter.html">DateFormatter<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Intl.DateFormatter.DateFormat.html">DateFormat</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Intl.Exception.html">Exception</a>
</li>
<li><a href="namespace-Symfony.Component.Intl.Globals.html">Globals</a>
</li>
<li><a href="namespace-Symfony.Component.Intl.Locale.html">Locale</a>
</li>
<li><a href="namespace-Symfony.Component.Intl.NumberFormatter.html">NumberFormatter</a>
</li>
<li><a href="namespace-Symfony.Component.Intl.ResourceBundle.html">ResourceBundle<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Intl.ResourceBundle.Compiler.html">Compiler</a>
</li>
<li><a href="namespace-Symfony.Component.Intl.ResourceBundle.Reader.html">Reader</a>
</li>
<li><a href="namespace-Symfony.Component.Intl.ResourceBundle.Transformer.html">Transformer<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Intl.ResourceBundle.Transformer.Rule.html">Rule</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Intl.ResourceBundle.Util.html">Util</a>
</li>
<li><a href="namespace-Symfony.Component.Intl.ResourceBundle.Writer.html">Writer</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Intl.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Intl.Tests.Collator.html">Collator<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Intl.Tests.Collator.Verification.html">Verification</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Intl.Tests.DateFormatter.html">DateFormatter<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Intl.Tests.DateFormatter.Verification.html">Verification</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Intl.Tests.Globals.html">Globals<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Intl.Tests.Globals.Verification.html">Verification</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Intl.Tests.Locale.html">Locale<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Intl.Tests.Locale.Verification.html">Verification</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Intl.Tests.NumberFormatter.html">NumberFormatter<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Intl.Tests.NumberFormatter.Verification.html">Verification</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Intl.Tests.ResourceBundle.html">ResourceBundle<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Intl.Tests.ResourceBundle.Reader.html">Reader</a>
</li>
<li><a href="namespace-Symfony.Component.Intl.Tests.ResourceBundle.Util.html">Util</a>
</li>
<li><a href="namespace-Symfony.Component.Intl.Tests.ResourceBundle.Writer.html">Writer</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Intl.Tests.Util.html">Util</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Intl.Util.html">Util</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Locale.html">Locale<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Locale.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Locale.Tests.Stub.html">Stub</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Symfony.Component.OptionsResolver.html">OptionsResolver<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.OptionsResolver.Exception.html">Exception</a>
</li>
<li><a href="namespace-Symfony.Component.OptionsResolver.Tests.html">Tests</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Process.html">Process<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Process.Exception.html">Exception</a>
</li>
<li><a href="namespace-Symfony.Component.Process.Tests.html">Tests</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.PropertyAccess.html">PropertyAccess<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.PropertyAccess.Exception.html">Exception</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Routing.html">Routing<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Routing.Annotation.html">Annotation</a>
</li>
<li><a href="namespace-Symfony.Component.Routing.Exception.html">Exception</a>
</li>
<li><a href="namespace-Symfony.Component.Routing.Generator.html">Generator<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Routing.Generator.Dumper.html">Dumper</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Routing.Loader.html">Loader</a>
</li>
<li><a href="namespace-Symfony.Component.Routing.Matcher.html">Matcher<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Routing.Matcher.Dumper.html">Dumper</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Routing.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Routing.Tests.Annotation.html">Annotation</a>
</li>
<li><a href="namespace-Symfony.Component.Routing.Tests.Fixtures.html">Fixtures<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Routing.Tests.Fixtures.AnnotatedClasses.html">AnnotatedClasses</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Routing.Tests.Generator.html">Generator<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Routing.Tests.Generator.Dumper.html">Dumper</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Routing.Tests.Loader.html">Loader</a>
</li>
<li><a href="namespace-Symfony.Component.Routing.Tests.Matcher.html">Matcher<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Routing.Tests.Matcher.Dumper.html">Dumper</a>
</li>
</ul></li></ul></li></ul></li>
<li class="active"><a href="namespace-Symfony.Component.Security.html">Security<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Security.Acl.html">Acl<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Security.Acl.Dbal.html">Dbal</a>
</li>
<li><a href="namespace-Symfony.Component.Security.Acl.Domain.html">Domain</a>
</li>
<li><a href="namespace-Symfony.Component.Security.Acl.Exception.html">Exception</a>
</li>
<li><a href="namespace-Symfony.Component.Security.Acl.Model.html">Model</a>
</li>
<li><a href="namespace-Symfony.Component.Security.Acl.Permission.html">Permission</a>
</li>
<li><a href="namespace-Symfony.Component.Security.Acl.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Security.Acl.Tests.Dbal.html">Dbal</a>
</li>
<li><a href="namespace-Symfony.Component.Security.Acl.Tests.Domain.html">Domain</a>
</li>
<li><a href="namespace-Symfony.Component.Security.Acl.Tests.Permission.html">Permission</a>
</li>
<li><a href="namespace-Symfony.Component.Security.Acl.Tests.Voter.html">Voter</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Security.Acl.Voter.html">Voter</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Security.Core.html">Core<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Security.Core.Authentication.html">Authentication<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Security.Core.Authentication.Provider.html">Provider</a>
</li>
<li><a href="namespace-Symfony.Component.Security.Core.Authentication.RememberMe.html">RememberMe</a>
</li>
<li><a href="namespace-Symfony.Component.Security.Core.Authentication.Token.html">Token</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Security.Core.Authorization.html">Authorization<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Security.Core.Authorization.Voter.html">Voter</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Security.Core.Encoder.html">Encoder</a>
</li>
<li><a href="namespace-Symfony.Component.Security.Core.Event.html">Event</a>
</li>
<li><a href="namespace-Symfony.Component.Security.Core.Exception.html">Exception</a>
</li>
<li><a href="namespace-Symfony.Component.Security.Core.Role.html">Role</a>
</li>
<li><a href="namespace-Symfony.Component.Security.Core.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Security.Core.Tests.Authentication.html">Authentication<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Security.Core.Tests.Authentication.Provider.html">Provider</a>
</li>
<li><a href="namespace-Symfony.Component.Security.Core.Tests.Authentication.RememberMe.html">RememberMe</a>
</li>
<li><a href="namespace-Symfony.Component.Security.Core.Tests.Authentication.Token.html">Token</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Security.Core.Tests.Authorization.html">Authorization<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Security.Core.Tests.Authorization.Voter.html">Voter</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Security.Core.Tests.Encoder.html">Encoder</a>
</li>
<li><a href="namespace-Symfony.Component.Security.Core.Tests.Role.html">Role</a>
</li>
<li><a href="namespace-Symfony.Component.Security.Core.Tests.User.html">User</a>
</li>
<li><a href="namespace-Symfony.Component.Security.Core.Tests.Util.html">Util</a>
</li>
<li><a href="namespace-Symfony.Component.Security.Core.Tests.Validator.html">Validator<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Security.Core.Tests.Validator.Constraints.html">Constraints</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Symfony.Component.Security.Core.User.html">User</a>
</li>
<li><a href="namespace-Symfony.Component.Security.Core.Util.html">Util</a>
</li>
<li><a href="namespace-Symfony.Component.Security.Core.Validator.html">Validator<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Security.Core.Validator.Constraints.html">Constraints</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Symfony.Component.Security.Csrf.html">Csrf<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Security.Csrf.Exception.html">Exception</a>
</li>
<li><a href="namespace-Symfony.Component.Security.Csrf.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Security.Csrf.Tests.TokenGenerator.html">TokenGenerator</a>
</li>
<li><a href="namespace-Symfony.Component.Security.Csrf.Tests.TokenStorage.html">TokenStorage</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Security.Csrf.TokenGenerator.html">TokenGenerator</a>
</li>
<li><a href="namespace-Symfony.Component.Security.Csrf.TokenStorage.html">TokenStorage</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Security.Http.html">Http<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Security.Http.Authentication.html">Authentication</a>
</li>
<li><a href="namespace-Symfony.Component.Security.Http.Authorization.html">Authorization</a>
</li>
<li><a href="namespace-Symfony.Component.Security.Http.EntryPoint.html">EntryPoint</a>
</li>
<li><a href="namespace-Symfony.Component.Security.Http.Event.html">Event</a>
</li>
<li><a href="namespace-Symfony.Component.Security.Http.Firewall.html">Firewall</a>
</li>
<li><a href="namespace-Symfony.Component.Security.Http.Logout.html">Logout</a>
</li>
<li><a href="namespace-Symfony.Component.Security.Http.RememberMe.html">RememberMe</a>
</li>
<li><a href="namespace-Symfony.Component.Security.Http.Session.html">Session</a>
</li>
<li><a href="namespace-Symfony.Component.Security.Http.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Security.Http.Tests.Authentication.html">Authentication</a>
</li>
<li><a href="namespace-Symfony.Component.Security.Http.Tests.EntryPoint.html">EntryPoint</a>
</li>
<li><a href="namespace-Symfony.Component.Security.Http.Tests.Firewall.html">Firewall</a>
</li>
<li><a href="namespace-Symfony.Component.Security.Http.Tests.Logout.html">Logout</a>
</li>
<li><a href="namespace-Symfony.Component.Security.Http.Tests.RememberMe.html">RememberMe</a>
</li>
<li><a href="namespace-Symfony.Component.Security.Http.Tests.Session.html">Session</a>
</li>
</ul></li></ul></li>
<li class="active"><a href="namespace-Symfony.Component.Security.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Security.Tests.Core.html">Core<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Security.Tests.Core.Authentication.html">Authentication<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Security.Tests.Core.Authentication.Token.html">Token</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Security.Tests.Core.User.html">User</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Security.Tests.Http.html">Http<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Security.Tests.Http.Firewall.html">Firewall</a>
</li>
</ul></li></ul></li></ul></li>
<li><a href="namespace-Symfony.Component.Serializer.html">Serializer<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Serializer.Encoder.html">Encoder</a>
</li>
<li><a href="namespace-Symfony.Component.Serializer.Exception.html">Exception</a>
</li>
<li><a href="namespace-Symfony.Component.Serializer.Normalizer.html">Normalizer</a>
</li>
<li><a href="namespace-Symfony.Component.Serializer.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Serializer.Tests.Encoder.html">Encoder</a>
</li>
<li><a href="namespace-Symfony.Component.Serializer.Tests.Fixtures.html">Fixtures</a>
</li>
<li><a href="namespace-Symfony.Component.Serializer.Tests.Normalizer.html">Normalizer</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Symfony.Component.Stopwatch.html">Stopwatch</a>
</li>
<li><a href="namespace-Symfony.Component.Templating.html">Templating<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Templating.Asset.html">Asset</a>
</li>
<li><a href="namespace-Symfony.Component.Templating.Helper.html">Helper</a>
</li>
<li><a href="namespace-Symfony.Component.Templating.Loader.html">Loader</a>
</li>
<li><a href="namespace-Symfony.Component.Templating.Storage.html">Storage</a>
</li>
<li><a href="namespace-Symfony.Component.Templating.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Templating.Tests.Fixtures.html">Fixtures</a>
</li>
<li><a href="namespace-Symfony.Component.Templating.Tests.Helper.html">Helper</a>
</li>
<li><a href="namespace-Symfony.Component.Templating.Tests.Loader.html">Loader</a>
</li>
<li><a href="namespace-Symfony.Component.Templating.Tests.Storage.html">Storage</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Symfony.Component.Translation.html">Translation<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Translation.Catalogue.html">Catalogue</a>
</li>
<li><a href="namespace-Symfony.Component.Translation.Dumper.html">Dumper</a>
</li>
<li><a href="namespace-Symfony.Component.Translation.Exception.html">Exception</a>
</li>
<li><a href="namespace-Symfony.Component.Translation.Extractor.html">Extractor</a>
</li>
<li><a href="namespace-Symfony.Component.Translation.Loader.html">Loader</a>
</li>
<li><a href="namespace-Symfony.Component.Translation.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Translation.Tests.Catalogue.html">Catalogue</a>
</li>
<li><a href="namespace-Symfony.Component.Translation.Tests.Dumper.html">Dumper</a>
</li>
<li><a href="namespace-Symfony.Component.Translation.Tests.Loader.html">Loader</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Translation.Writer.html">Writer</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Validator.html">Validator<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Validator.Constraints.html">Constraints</a>
</li>
<li><a href="namespace-Symfony.Component.Validator.Exception.html">Exception</a>
</li>
<li><a href="namespace-Symfony.Component.Validator.Mapping.html">Mapping<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Validator.Mapping.Cache.html">Cache</a>
</li>
<li><a href="namespace-Symfony.Component.Validator.Mapping.Loader.html">Loader</a>
</li>
</ul></li>
<li><a href="namespace-Symfony.Component.Validator.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Validator.Tests.Constraints.html">Constraints</a>
</li>
<li><a href="namespace-Symfony.Component.Validator.Tests.Fixtures.html">Fixtures</a>
</li>
<li><a href="namespace-Symfony.Component.Validator.Tests.Mapping.html">Mapping<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Validator.Tests.Mapping.Cache.html">Cache</a>
</li>
<li><a href="namespace-Symfony.Component.Validator.Tests.Mapping.Loader.html">Loader</a>
</li>
</ul></li></ul></li></ul></li>
<li><a href="namespace-Symfony.Component.Yaml.html">Yaml<span></span></a>
<ul>
<li><a href="namespace-Symfony.Component.Yaml.Exception.html">Exception</a>
</li>
<li><a href="namespace-Symfony.Component.Yaml.Tests.html">Tests</a>
</li>
</ul></li></ul></li></ul></li>
<li><a href="namespace-Tecnocreaciones.html">Tecnocreaciones<span></span></a>
<ul>
<li><a href="namespace-Tecnocreaciones.Bundle.html">Bundle<span></span></a>
<ul>
<li><a href="namespace-Tecnocreaciones.Bundle.AjaxFOSUserBundle.html">AjaxFOSUserBundle<span></span></a>
<ul>
<li><a href="namespace-Tecnocreaciones.Bundle.AjaxFOSUserBundle.Controller.html">Controller</a>
</li>
<li><a href="namespace-Tecnocreaciones.Bundle.AjaxFOSUserBundle.DependencyInjection.html">DependencyInjection<span></span></a>
<ul>
<li><a href="namespace-Tecnocreaciones.Bundle.AjaxFOSUserBundle.DependencyInjection.Compiler.html">Compiler</a>
</li>
</ul></li>
<li><a href="namespace-Tecnocreaciones.Bundle.AjaxFOSUserBundle.Event.html">Event</a>
</li>
<li><a href="namespace-Tecnocreaciones.Bundle.AjaxFOSUserBundle.EventListener.html">EventListener</a>
</li>
<li><a href="namespace-Tecnocreaciones.Bundle.AjaxFOSUserBundle.Handler.html">Handler</a>
</li>
<li><a href="namespace-Tecnocreaciones.Bundle.AjaxFOSUserBundle.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Tecnocreaciones.Bundle.AjaxFOSUserBundle.Tests.Controller.html">Controller</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Tecnocreaciones.Bundle.InstallBundle.html">InstallBundle<span></span></a>
<ul>
<li><a href="namespace-Tecnocreaciones.Bundle.InstallBundle.Command.html">Command</a>
</li>
<li><a href="namespace-Tecnocreaciones.Bundle.InstallBundle.DependencyInjection.html">DependencyInjection</a>
</li>
<li><a href="namespace-Tecnocreaciones.Bundle.InstallBundle.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Tecnocreaciones.Bundle.InstallBundle.Tests.Controller.html">Controller</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Tecnocreaciones.Bundle.TemplateBundle.html">TemplateBundle<span></span></a>
<ul>
<li><a href="namespace-Tecnocreaciones.Bundle.TemplateBundle.Controller.html">Controller</a>
</li>
<li><a href="namespace-Tecnocreaciones.Bundle.TemplateBundle.DependencyInjection.html">DependencyInjection</a>
</li>
<li><a href="namespace-Tecnocreaciones.Bundle.TemplateBundle.Menu.html">Menu<span></span></a>
<ul>
<li><a href="namespace-Tecnocreaciones.Bundle.TemplateBundle.Menu.Template.html">Template<span></span></a>
<ul>
<li><a href="namespace-Tecnocreaciones.Bundle.TemplateBundle.Menu.Template.Developer.html">Developer</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Tecnocreaciones.Bundle.TemplateBundle.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Tecnocreaciones.Bundle.TemplateBundle.Tests.Controller.html">Controller</a>
</li>
</ul></li></ul></li></ul></li>
<li><a href="namespace-Tecnocreaciones.Vzla.html">Vzla<span></span></a>
<ul>
<li><a href="namespace-Tecnocreaciones.Vzla.GovernmentBundle.html">GovernmentBundle<span></span></a>
<ul>
<li><a href="namespace-Tecnocreaciones.Vzla.GovernmentBundle.DependencyInjection.html">DependencyInjection</a>
</li>
<li><a href="namespace-Tecnocreaciones.Vzla.GovernmentBundle.Form.html">Form<span></span></a>
<ul>
<li><a href="namespace-Tecnocreaciones.Vzla.GovernmentBundle.Form.Type.html">Type</a>
</li>
</ul></li>
<li><a href="namespace-Tecnocreaciones.Vzla.GovernmentBundle.Menu.html">Menu<span></span></a>
<ul>
<li><a href="namespace-Tecnocreaciones.Vzla.GovernmentBundle.Menu.Template.html">Template<span></span></a>
<ul>
<li><a href="namespace-Tecnocreaciones.Vzla.GovernmentBundle.Menu.Template.Developer.html">Developer</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Tecnocreaciones.Vzla.GovernmentBundle.Model.html">Model</a>
</li>
<li><a href="namespace-Tecnocreaciones.Vzla.GovernmentBundle.Tests.html">Tests<span></span></a>
<ul>
<li><a href="namespace-Tecnocreaciones.Vzla.GovernmentBundle.Tests.Controller.html">Controller</a>
</li>
</ul></li>
<li><a href="namespace-Tecnocreaciones.Vzla.GovernmentBundle.Twig.html">Twig<span></span></a>
<ul>
<li><a href="namespace-Tecnocreaciones.Vzla.GovernmentBundle.Twig.Extension.html">Extension</a>
</li>
</ul></li></ul></li></ul></li></ul></li>
<li><a href="namespace-TestBundle.html">TestBundle<span></span></a>
<ul>
<li><a href="namespace-TestBundle.Fabpot.html">Fabpot<span></span></a>
<ul>
<li><a href="namespace-TestBundle.Fabpot.FooBundle.html">FooBundle<span></span></a>
<ul>
<li><a href="namespace-TestBundle.Fabpot.FooBundle.Controller.html">Controller</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-TestBundle.FooBundle.html">FooBundle<span></span></a>
<ul>
<li><a href="namespace-TestBundle.FooBundle.Controller.html">Controller<span></span></a>
<ul>
<li><a href="namespace-TestBundle.FooBundle.Controller.Sub.html">Sub</a>
</li>
<li><a href="namespace-TestBundle.FooBundle.Controller.Test.html">Test</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-TestBundle.Sensio.html">Sensio<span></span></a>
<ul>
<li><a href="namespace-TestBundle.Sensio.Cms.html">Cms<span></span></a>
<ul>
<li><a href="namespace-TestBundle.Sensio.Cms.FooBundle.html">FooBundle<span></span></a>
<ul>
<li><a href="namespace-TestBundle.Sensio.Cms.FooBundle.Controller.html">Controller</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-TestBundle.Sensio.FooBundle.html">FooBundle<span></span></a>
<ul>
<li><a href="namespace-TestBundle.Sensio.FooBundle.Controller.html">Controller</a>
</li>
</ul></li></ul></li></ul></li>
<li><a href="namespace-TestFixtures.html">TestFixtures</a>
</li>
<li><a href="namespace-Timestampable.html">Timestampable<span></span></a>
<ul>
<li><a href="namespace-Timestampable.Fixture.html">Fixture<span></span></a>
<ul>
<li><a href="namespace-Timestampable.Fixture.Document.html">Document</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Tool.html">Tool</a>
</li>
<li><a href="namespace-Translatable.html">Translatable<span></span></a>
<ul>
<li><a href="namespace-Translatable.Fixture.html">Fixture<span></span></a>
<ul>
<li><a href="namespace-Translatable.Fixture.Document.html">Document<span></span></a>
<ul>
<li><a href="namespace-Translatable.Fixture.Document.Personal.html">Personal</a>
</li>
</ul></li>
<li><a href="namespace-Translatable.Fixture.Issue114.html">Issue114</a>
</li>
<li><a href="namespace-Translatable.Fixture.Issue138.html">Issue138</a>
</li>
<li><a href="namespace-Translatable.Fixture.Issue165.html">Issue165</a>
</li>
<li><a href="namespace-Translatable.Fixture.Issue173.html">Issue173</a>
</li>
<li><a href="namespace-Translatable.Fixture.Issue75.html">Issue75</a>
</li>
<li><a href="namespace-Translatable.Fixture.Issue922.html">Issue922</a>
</li>
<li><a href="namespace-Translatable.Fixture.Personal.html">Personal</a>
</li>
<li><a href="namespace-Translatable.Fixture.Template.html">Template</a>
</li>
<li><a href="namespace-Translatable.Fixture.Type.html">Type</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Translator.html">Translator<span></span></a>
<ul>
<li><a href="namespace-Translator.Fixture.html">Fixture</a>
</li>
</ul></li>
<li><a href="namespace-Tree.html">Tree<span></span></a>
<ul>
<li><a href="namespace-Tree.Fixture.html">Fixture<span></span></a>
<ul>
<li><a href="namespace-Tree.Fixture.Closure.html">Closure</a>
</li>
<li><a href="namespace-Tree.Fixture.Document.html">Document</a>
</li>
<li><a href="namespace-Tree.Fixture.Genealogy.html">Genealogy</a>
</li>
<li><a href="namespace-Tree.Fixture.Mock.html">Mock</a>
</li>
<li><a href="namespace-Tree.Fixture.Repository.html">Repository</a>
</li>
<li><a href="namespace-Tree.Fixture.Transport.html">Transport</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Uploadable.html">Uploadable<span></span></a>
<ul>
<li><a href="namespace-Uploadable.Fixture.html">Fixture<span></span></a>
<ul>
<li><a href="namespace-Uploadable.Fixture.Entity.html">Entity</a>
</li>
</ul></li></ul></li>
<li><a href="namespace-Wrapper.html">Wrapper<span></span></a>
<ul>
<li><a href="namespace-Wrapper.Fixture.html">Fixture<span></span></a>
<ul>
<li><a href="namespace-Wrapper.Fixture.Document.html">Document</a>
</li>
<li><a href="namespace-Wrapper.Fixture.Entity.html">Entity</a>
</li>
</ul></li></ul></li>
</ul>
</div>
<div id="elements">
</div>
</div>
</div>
<div id="splitter"></div>
<div id="right">
<div id="rightInner">
<form id="search">
<input type="hidden" name="cx" value="" />
<input type="hidden" name="ie" value="UTF-8" />
<input type="text" name="q" class="text" />
<input type="submit" value="Search" />
</form>
<div id="navigation">
<ul>
<li>
<a href="index.html" title="Overview"><span>Overview</span></a>
</li>
<li class="active">
<span>Namespace</span> </li>
<li>
<span>Class</span> </li>
</ul>
<ul>
<li>
<a href="tree.html" title="Tree view of classes, interfaces, traits and exceptions"><span>Tree</span></a>
</li>
</ul>
<ul>
</ul>
</div>
<div id="content" class="namespace">
<h1>Namespace <a href="namespace-Symfony.html">Symfony</a>\<a href="namespace-Symfony.Component.html">Component</a>\<a href="namespace-Symfony.Component.Security.html">Security</a>\Tests</h1>
<table class="summary" id="namespaces">
<caption>Namespaces summary</caption>
<tr>
<td class="name"><a href="namespace-Symfony.Component.Security.Tests.Core.html">Symfony\Component\Security\Tests\Core</a></td>
</tr>
<tr>
<td class="name"><a href="namespace-Symfony.Component.Security.Tests.Http.html">Symfony\Component\Security\Tests\Http</a></td>
</tr>
</table>
</div>
<div id="footer">
seip API documentation generated by <a href="http://apigen.org">ApiGen 2.8.0</a>
</div>
</div>
</div>
</body>
</html>
| {
"content_hash": "f38c0e9e69ecdba260570cd80741ecd9",
"timestamp": "",
"source": "github",
"line_count": 3338,
"max_line_length": 192,
"avg_line_length": 46.07819053325345,
"alnum_prop": 0.6489672255849788,
"repo_name": "Tecnocreaciones/VzlaGovernmentTemplateDeveloperSeed",
"id": "736b3aee7cb97c8444930560a0032f497c52dcfb",
"size": "153809",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "api/namespace-Symfony.Component.Security.Tests.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "10864"
},
{
"name": "JavaScript",
"bytes": "131316"
},
{
"name": "PHP",
"bytes": "211008"
},
{
"name": "Perl",
"bytes": "2621"
}
],
"symlink_target": ""
} |
from django.db import models
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
import uuid
import os
class Entry(models.Model):
def get_file_path(instance, filename):
ext = filename.split('.')[-1]
filename = "%s.%s" % (uuid.uuid4(), ext)
return os.path.join('licitacao', filename)
created = models.DateTimeField(_(u'Data de Criação'), auto_now_add=True)
modified = models.DateTimeField(_(u'Data de Modificação'), auto_now=True)
description = models.TextField(_(u'Objeto da Licitação'))
process = models.CharField(_(u'Processo Licitatório Nº'), max_length=20)
price = models.CharField(_(u'Tomada de Preços Nº'), max_length=20)
attach = models.FileField(_(u'Arquivo'), upload_to=get_file_path,
help_text='Selecione um arquivo')
def admin_attach(self):
if self.attach:
return "<a href='%s'>Baixar</a>" % self.attach.url
else:
return "Nenhum arquivo encontrado"
admin_attach.allow_tags = True
admin_attach.short_description = _(u'Arquivo')
def __unicode__(self):
return unicode(self.process)
class Meta:
verbose_name = _(u'Licitação')
verbose_name_plural = _(u'Licitações')
ordering = ['-created', 'description', 'process', 'price']
| {
"content_hash": "b73466ec25183bb31845c1bdff0aefe0",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 77,
"avg_line_length": 36.78378378378378,
"alnum_prop": 0.6385011021307861,
"repo_name": "klebercode/pmsal",
"id": "e5b8e866e930c18a142b42916b67ae5f4a0a4f0e",
"size": "1391",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pmsal/bid/models.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "129165"
},
{
"name": "HTML",
"bytes": "78095"
},
{
"name": "JavaScript",
"bytes": "204743"
},
{
"name": "Python",
"bytes": "52737"
}
],
"symlink_target": ""
} |
#ifndef BOOST_RANDOM_RANLUX_HPP
#define BOOST_RANDOM_RANLUX_HPP
#include <boost/config.hpp>
#include <boost/random/subtract_with_carry.hpp>
#include <boost/random/discard_block.hpp>
namespace boost {
namespace random {
namespace detail {
/**
* The ranlux family of generators are described in
*
* @blockquote
* "A portable high-quality random number generator for lattice field theory
* calculations", M. Luescher, Computer Physics Communications, 79 (1994)
* pp 100-110.
* @endblockquote
*
* The levels are given in
*
* @blockquote
* "RANLUX: A Fortran implementation of the high-quality
* pseudorandom number generator of Luescher", F. James,
* Computer Physics Communications 79 (1994) 111-114
* @endblockquote
*/
class ranlux_documentation {};
}
typedef subtract_with_carry_engine<uint32_t, 24, 10, 24> ranlux_base;
typedef subtract_with_carry_01_engine<float, 24, 10, 24> ranlux_base_01;
typedef subtract_with_carry_01_engine<double, 48, 10, 24> ranlux64_base_01;
/** @copydoc boost::random::detail::ranlux_documentation */
typedef discard_block_engine<ranlux_base, 223, 24> ranlux3;
/** @copydoc boost::random::detail::ranlux_documentation */
typedef discard_block_engine<ranlux_base, 389, 24> ranlux4;
/** @copydoc boost::random::detail::ranlux_documentation */
typedef discard_block_engine<ranlux_base_01, 223, 24> ranlux3_01;
/** @copydoc boost::random::detail::ranlux_documentation */
typedef discard_block_engine<ranlux_base_01, 389, 24> ranlux4_01;
/** @copydoc boost::random::detail::ranlux_documentation */
typedef discard_block_engine<ranlux64_base_01, 223, 24> ranlux64_3_01;
/** @copydoc boost::random::detail::ranlux_documentation */
typedef discard_block_engine<ranlux64_base_01, 389, 24> ranlux64_4_01;
#if !defined(BOOST_NO_INT64_T) && !defined(BOOST_NO_INTEGRAL_INT64_T)
typedef subtract_with_carry_engine<uint64_t, 48, 10, 24> ranlux64_base;
/** @copydoc boost::random::detail::ranlux_documentation */
typedef discard_block_engine<ranlux64_base, 223, 24> ranlux64_3;
/** @copydoc boost::random::detail::ranlux_documentation */
typedef discard_block_engine<ranlux64_base, 389, 24> ranlux64_4;
#endif /* !BOOST_NO_INT64_T && !BOOST_NO_INTEGRAL_INT64_T */
typedef subtract_with_carry_engine<uint32_t, 24, 10, 24> ranlux24_base;
typedef subtract_with_carry_engine<uint64_t, 48, 5, 12> ranlux48_base;
typedef discard_block_engine<ranlux24_base, 223, 23> ranlux24;
#if !defined(BOOST_NO_INT64_T) && !defined(BOOST_NO_INTEGRAL_INT64_T)
typedef discard_block_engine<ranlux48_base, 389, 11> ranlux48;
#endif
}
using random::ranlux3;
using random::ranlux4;
using random::ranlux3_01;
using random::ranlux4_01;
using random::ranlux64_3_01;
using random::ranlux64_4_01;
#if !defined(BOOST_NO_INT64_T) && !defined(BOOST_NO_INTEGRAL_INT64_T)
using random::ranlux64_3;
using random::ranlux64_4;
#endif
} // namespace boost
#endif // BOOST_RANDOM_LINEAR_CONGRUENTIAL_HPP
| {
"content_hash": "b976ea37f4a76c8770930e9b5546225e",
"timestamp": "",
"source": "github",
"line_count": 86,
"max_line_length": 77,
"avg_line_length": 33.98837209302326,
"alnum_prop": 0.7403352719808416,
"repo_name": "darklost/darkforce",
"id": "f960e9837546a667b39aa004799b47702ea7f248",
"size": "3348",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "third_party/boost/boost/random/ranlux.hpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "1920"
},
{
"name": "C#",
"bytes": "12787"
},
{
"name": "C++",
"bytes": "186310"
},
{
"name": "CMake",
"bytes": "10698"
},
{
"name": "Python",
"bytes": "22561"
}
],
"symlink_target": ""
} |
var dispatcher = new WebSocketRails('localhost:3000/websocket');
channel = dispatcher.subscribe('orders'); | {
"content_hash": "65cdd9e1fbd4967b8512c7ea71d9b1d8",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 64,
"avg_line_length": 35.666666666666664,
"alnum_prop": 0.7850467289719626,
"repo_name": "gczh/websockets-sample",
"id": "fe315dab2bc92e0247860bc2cac451f427c5a2a7",
"size": "805",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/assets/javascripts/application.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1750"
},
{
"name": "CoffeeScript",
"bytes": "211"
},
{
"name": "JavaScript",
"bytes": "805"
},
{
"name": "Ruby",
"bytes": "29449"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html class="t-blue">
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS-MML_HTMLorMML" type="text/javascript"></script>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Solving The Schrodinger Equation Using Chebfun!</title>
<meta name="description" content="My first introduction to scientific computing was working with Jared L. Aurentz.Over the summer of 2014 we worked on developing an algorithm in C, Python, an...">
<link href='https://fonts.googleapis.com/css?family=Roboto:400,400italic,700|Roboto+Mono:400,500' rel='stylesheet' type='text/css'>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="/css/main.css">
<link rel="canonical" href="http://localhost:4000/2014/09/solving-the-schrodinger-equation-using-chebfun">
<link rel="alternate" type="application/rss+xml" title="Johnny Devriese" href="http://localhost:4000/feed.xml">
</head>
<body>
<nav class="c-navigation is-fixed">
<div class="c-navigation__container u-container">
<a class="c-navigation__item " href="/">Home</a>
<a class="c-navigation__item " href="/articles/">Articles</a>
<a class="c-navigation__item " href="/resources/">Resources</a>
<a class="c-navigation__item " href="/about/">About</a>
</div>
</nav>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS-MML_HTMLorMML" type="text/javascript"></script>
<article class="c-article">
<header class="c-header c-article__header">
<div class="u-container">
<h1 class="c-header__title">Solving The Schrodinger Equation Using Chebfun!</h1>
</div>
</header>
<div class="c-article__main">
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS-MML_HTMLorMML" type="text/javascript"></script>
<p>My first introduction to scientific computing was working with <a href="http://jaurentz.github.io/">Jared L. Aurentz</a>.
Over the summer of 2014 we worked on developing an algorithm in C, Python, and eventually Matlab
to solve the Schrodinger and then calculate the hyperpolerizatbility of with the given potential.</p>
<p>You can read through Jared’s write brief write-up through Oxford’s research group <a href="http://www.chebfun.org/examples/ode-eig/OpticalResponse.html">Chebfun website</a>.</p>
<p>I hope to put my significantly longer write up along with all of the code on GitHub soon!</p>
<p>Here’s a plot from Wikipedia of the first five chebyshev polynomials.
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/5c/Chebyshev_Polynomials_of_the_First_Kind.svg/640px-Chebyshev_Polynomials_of_the_First_Kind.svg.png?1498838992669" alt="Chebyshev Polynomials are fun" title="Chebyshev polynomials are fun!" /></p>
<!--
You’ll find this post in your `_posts` directory. Go ahead and edit it and re-build the site to see your changes. You can rebuild the site in many different ways, but the most common way is to run `jekyll serve`, which launches a web server and auto-regenerates your site when a file is updated.
To add new posts, simply add a file in the `_posts` directory that follows the convention `YYYY-MM-DD-name-of-post.ext` and includes the necessary front matter. Take a look at the source for this post to get an idea about how it works.
Jekyll also offers powerful support for code snippets:
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="k">def</span> <span class="nf">print_hi</span><span class="p">(</span><span class="nb">name</span><span class="p">)</span>
<span class="nb">puts</span> <span class="s2">"Hi, </span><span class="si">#{</span><span class="nb">name</span><span class="si">}</span><span class="s2">"</span>
<span class="k">end</span>
<span class="n">print_hi</span><span class="p">(</span><span class="s1">'Tom'</span><span class="p">)</span>
<span class="c1">#=> prints 'Hi, Tom' to STDOUT.</span></code></pre></figure>
Check out the [Jekyll docs][jekyll-docs] for more info on how to get the most out of Jekyll. File all bugs/feature requests at [Jekyll’s GitHub repo][jekyll-gh]. If you have questions, you can ask them on [Jekyll Talk][jekyll-talk].
[jekyll-docs]: http://jekyllrb.com/docs/home
[jekyll-gh]: https://github.com/jekyll/jekyll
[jekyll-talk]: https://talk.jekyllrb.com/
-->
</div>
</article>
<footer class="c-footer">
<div class="u-container c-footer__container">
<p>© Johnny Devriese 2020</p>
<p>
<a href="https://github.com/johnnydevriese">GitHub</a>
<a href="https://instagram.com/johnnydevriese">Instagram</a>
<a href="https://twitter.com/johnnydevriese">Twitter</a>
<a href="https://500px.com/johnminor07">500px</a>
</p>
</div>
</footer>
</body>
</html>
| {
"content_hash": "e332519f0ed8596f1033747023c058d4",
"timestamp": "",
"source": "github",
"line_count": 94,
"max_line_length": 295,
"avg_line_length": 52.9468085106383,
"alnum_prop": 0.7086598352421137,
"repo_name": "johnnydevriese/johnnydevriese.github.io",
"id": "f036c57181f9b01e11525672ad4b6ff7bb89caba",
"size": "4987",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_site/2014/09/solving-the-schrodinger-equation-using-chebfun.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "10811"
},
{
"name": "HTML",
"bytes": "145345"
},
{
"name": "Ruby",
"bytes": "15388"
}
],
"symlink_target": ""
} |
define( 'Todos/Controls',
[ 'Olives/OObject', 'Olives/Event-plugin', 'Olives/Model-plugin', 'Olives/LocalStore', 'Todos/Tools' ],
// The Controls UI
function Controls( OObject, EventPlugin, ModelPlugin, Store, Tools ) {
return function ControlsInit( view, model, stats ) {
// The OObject (the controller) inits with a default model which is a simple store
// But it can be init'ed with any other store, like the LocalStore
var controls = new OObject(model),
// A function to get the completed tasks
getCompleted = function () {
var completed = [];
model.loop(function ( value, id ) {
if ( value.completed ) {
completed.push(id);
}
});
return completed;
},
// Update all stats
updateStats = function () {
var nbCompleted = getCompleted().length;
stats.set( 'nbItems', model.getNbItems() );
stats.set( 'nbLeft', stats.get('nbItems') - nbCompleted );
stats.set( 'nbCompleted', nbCompleted );
stats.set( 'plural', stats.get('nbLeft') === 1 ? 'item' : 'items' );
};
// Add plugins to the UI.
controls.plugins.addAll({
'event': new EventPlugin( controls ),
'stats': new ModelPlugin( stats, {
'toggleClass': Tools.toggleClass
})
});
// Alive applies the plugins to the HTML view
controls.alive( view );
// Delete all tasks
controls.delAll = function () {
model.delAll( getCompleted() );
};
// Update stats when the tasks list is modified
model.watch( 'added', updateStats );
model.watch( 'deleted', updateStats );
model.watch( 'updated', updateStats );
// I could either update stats at init or save them in a localStore
updateStats();
};
});
| {
"content_hash": "4eed06613240177abea8ecf49e59df2d",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 103,
"avg_line_length": 28,
"alnum_prop": 0.6567796610169492,
"repo_name": "1manStartup/todomvc",
"id": "81df75615628e928807e9210b036d7c6605618b2",
"size": "1652",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "labs/architecture-examples/olives/js/uis/Controls.js",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Trans. Br. mycol. Soc. 43(2): 217 (1960)
#### Original name
Cortinarius pseudocrassus Joss. ex P.D. Orton, 1960
### Remarks
null | {
"content_hash": "5eabd6c703251f6f48c7ea9b749ae190",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 51,
"avg_line_length": 16.615384615384617,
"alnum_prop": 0.6944444444444444,
"repo_name": "mdoering/backbone",
"id": "64bcf9bd7dbc8fc385a26cdf0237b45a72282563",
"size": "291",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Cortinariaceae/Cortinarius/Cortinarius crassus/ Syn. Cortinarius pseudocrassus/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
import argparse
import numpy as np
import sys
import queue
import uuid
import tritonclient.grpc as grpcclient
from tritonclient.utils import InferenceServerException
FLAGS = None
class UserData:
def __init__(self):
self._completed_requests = queue.Queue()
def sync_send(triton_client, result_list, values, batch_size, sequence_id,
model_name, model_version):
count = 1
for value in values:
# Create the tensor for INPUT
value_data = np.full(shape=[batch_size, 1],
fill_value=value,
dtype=np.int32)
inputs = []
inputs.append(grpcclient.InferInput('INPUT', value_data.shape, "INT32"))
# Initialize the data
inputs[0].set_data_from_numpy(value_data)
outputs = []
outputs.append(grpcclient.InferRequestedOutput('OUTPUT'))
# Issue the synchronous sequence inference.
result = triton_client.infer(model_name=model_name,
inputs=inputs,
outputs=outputs,
sequence_id=sequence_id,
sequence_start=(count == 1),
sequence_end=(count == len(values)))
result_list.append(result.as_numpy('OUTPUT'))
count = count + 1
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-v',
'--verbose',
action="store_true",
required=False,
default=False,
help='Enable verbose output')
parser.add_argument(
'-u',
'--url',
type=str,
required=False,
default='localhost:8001',
help='Inference server URL and it gRPC port. Default is localhost:8001.'
)
parser.add_argument('-d',
'--dyna',
action="store_true",
required=False,
default=False,
help='Assume dynamic sequence model')
parser.add_argument('-o',
'--offset',
type=int,
required=False,
default=0,
help='Add offset to sequence ID used')
FLAGS = parser.parse_args()
try:
triton_client = grpcclient.InferenceServerClient(url=FLAGS.url,
verbose=FLAGS.verbose)
except Exception as e:
print("context creation failed: " + str(e))
sys.exit()
# We use custom "sequence" models which take 1 input
# value. The output is the accumulated value of the inputs. See
# src/custom/sequence.
int_sequence_model_name = "simple_dyna_sequence" if FLAGS.dyna else "simple_sequence"
string_sequence_model_name = "simple_string_dyna_sequence" if FLAGS.dyna else "simple_sequence"
model_version = ""
batch_size = 1
values = [11, 7, 5, 3, 2, 0, 1]
# Will use two sequences and send them synchronously. Note the
# sequence IDs should be non-zero because zero is reserved for
# non-sequence requests.
int_sequence_id0 = 1000 + FLAGS.offset * 2
int_sequence_id1 = 1001 + FLAGS.offset * 2
# For string sequence IDs, the dyna backend requires that the
# sequence id be decodable into an integer, otherwise we'll use
# a UUID4 sequence id and a model that doesn't require corrid
# control.
string_sequence_id0 = str(1002) if FLAGS.dyna else str(uuid.uuid4())
int_result0_list = []
int_result1_list = []
string_result0_list = []
user_data = UserData()
try:
sync_send(triton_client, int_result0_list, [0] + values, batch_size,
int_sequence_id0, int_sequence_model_name, model_version)
sync_send(triton_client, int_result1_list,
[100] + [-1 * val for val in values], batch_size,
int_sequence_id1, int_sequence_model_name, model_version)
sync_send(triton_client, string_result0_list,
[20] + [-1 * val for val in values], batch_size,
string_sequence_id0, string_sequence_model_name,
model_version)
except InferenceServerException as error:
print(error)
sys.exit(1)
for i in range(len(int_result0_list)):
int_seq0_expected = 1 if (i == 0) else values[i - 1]
int_seq1_expected = 101 if (i == 0) else values[i - 1] * -1
# For string sequence ID we are testing two different backends
if i == 0 and FLAGS.dyna:
string_seq0_expected = 20
elif i == 0 and not FLAGS.dyna:
string_seq0_expected = 21
elif i != 0 and FLAGS.dyna:
string_seq0_expected = values[i - 1] * -1 + int(
string_result0_list[i - 1][0][0])
else:
string_seq0_expected = values[i - 1] * -1
# The dyna_sequence custom backend adds the correlation ID
# to the last request in a sequence.
if FLAGS.dyna and (i != 0) and (values[i - 1] == 1):
int_seq0_expected += int_sequence_id0
int_seq1_expected += int_sequence_id1
string_seq0_expected += int(string_sequence_id0)
print("[" + str(i) + "] " + str(int_result0_list[i][0][0]) + " : " +
str(int_result1_list[i][0][0]) + " : " +
str(string_result0_list[i][0][0]))
if ((int_seq0_expected != int_result0_list[i][0][0]) or
(int_seq1_expected != int_result1_list[i][0][0]) or
(string_seq0_expected != string_result0_list[i][0][0])):
print("[ expected ] " + str(int_seq0_expected) + " : " +
str(int_seq1_expected) + " : " + str(string_seq0_expected))
sys.exit(1)
print("PASS: Sequence")
| {
"content_hash": "622185862e6bb254c29d73d6f4835719",
"timestamp": "",
"source": "github",
"line_count": 159,
"max_line_length": 99,
"avg_line_length": 37.522012578616355,
"alnum_prop": 0.5439155212872947,
"repo_name": "triton-inference-server/client",
"id": "68bd15f1b09797748e2a313536e1614d25a0872f",
"size": "7522",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/python/examples/simple_grpc_sequence_sync_infer_client.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "12998"
},
{
"name": "C++",
"bytes": "1722864"
},
{
"name": "CMake",
"bytes": "90419"
},
{
"name": "Go",
"bytes": "8979"
},
{
"name": "Java",
"bytes": "99082"
},
{
"name": "JavaScript",
"bytes": "5249"
},
{
"name": "Python",
"bytes": "552945"
},
{
"name": "Scala",
"bytes": "8330"
},
{
"name": "Shell",
"bytes": "7084"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<title>LOOP: Component Models</title>
<style type="text/css" media="all"><!--
@import "../loop.css";
@import "../layout1.css";
--></style>
</head>
<body>
<div id="Header">Class Models for Lua</div>
<div id="Logo"><img alt="small (1K)" src="../small.gif" height="70"></div>
<div id="Menu">
<div class="outside"><div class="inside"><ul>
<li><a href="../index.html", title="">Home</a></li>
<li><a href="../release/index.html", title="Installation">Install</a></li>
<li><a href="index.html", title="User Manual">Manual</a>
<div class="outside"><div class="inside"><ul>
<li><a href="intro.html", title="Introduction">Intro</a></li>
<li><a href="basics.html", title="Basic Concepts">Basics</a></li>
<li><a href="models.html", title="Class Models">Models</a></li>
<li><a href="classops.html", title="Class Features">Classes</a></li>
<li><strong>Comps</strong></li>
</ul></div></div>
</li>
<li><a href="../library/index.html", title="Class Library">Library</a></li>
<li><a href="../contact.html", title="Contact People">Contact</a></li>
<li><a href="http://luaforge.net/projects/oil/", title="Project at LuaForge">LuaForge</a></li>
</ul></div></div>
</div>
<div class="content">
<h1>Component Models</h1>
<p>The LOOP project extends the Lua programming language to support popular object-oriented programming features combined with adaptive and reflection mechanisms. Additionally, it also supports other programming paradigms related to the object concept like component-based development. Similar to the class models, the component model also provides dynamic features like reflection support.</p>
<h2><a name="general">General Model</a></h2>
<p>Similarly to the class model, the component model is also provided by a set of packages that present different features.
Basically, the component model is implemented by two kinds of packages: component and port packages.
A component package provides means to define and create components with different features and the port packages provides different implementations of ports used to link components together.
In the examples below, we assume that a component package is loaded in variable <code>component</code> and a port package is loaded in variable <code>port</code>.
The packages provided by LOOP that implement the model described in this section are listed below.</p>
<dl>
<dt>Component packages:</dt>
<dd>
<ul>
<li><code>loop.component.base</code></li>
<li><code>loop.component.wrapped</code></li>
<li><code>loop.component.contained</code></li>
<li><code>loop.component.dynamic</code></li>
</ul>
</dd>
<dt>Port packages:</dt>
<dd>
<ul>
<li><code>loop.component.base</code></li>
<li><code>loop.component.intercepted</code></li>
</ul>
</dd>
</dl>
<h3><a name="ports">Ports</a></h3>
<p>The LOOP component model defines only two kinds of ports, called facets and receptacles.
Each port is identified by a unique name on the component.
Component systems are assembled connecting facets to receptacles.</p>
<p>A facet is a port that provides some functionality by means of an interface, <i>i.e.</i> values and methods.
Facet represents the functionalities provided by the component.
In LOOP, a facet is realized by an object that provides the values and methods of the facet.
A component can have multiple facets and even facets providing the same service with different features, <i>e.g.</i> performance.</p>
<p>On the other hand, a receptacle is a port that requires some functionality through an interface.
Receptacles defines the explicit dependencies of the component.
A receptacle is realized as a table field that holds a reference to the object that provides the required functionality, <i>i.e.</i> the object connected to the receptacle.
LOOP also defines the concept of multiple receptacles, <i>i.e.</i> receptacles that can hold multiple references simultaneously.
Multiple receptacles are realized as a table containing the references to all objects connected to the receptacle.
Multiple receptacles provides the following operations that may be used to access the objects connected.</p>
<dl>
<dt><code>receptacle:__bind(object [, id])</code></dt>
<dd>Binds <code>bind</code> to the receptacle using the optional parameter <code>id</code> as the connection identifier and returns the connection identifier used.</dd>
<dt><code>receptacle:__unbind(id)</code></dt>
<dd>Removes de connection identified by parameter <code>id</code>.</dd>
<dt><code>receptacle:__hasany()</code></dt>
<dd>Returns a non-nil value if there is any object connected to the receptacle.</dd>
<dt><code>receptacle:__get(id)</code></dt>
<dd>Returns the object connected to the receptacle with identifier <code>id</code>.</dd>
<dt><code>receptacle:__all()</code></dt>
<dd>Returns an iterator that can be used in a <code>for</code> statement to iterate over all objects connected to the receptacle with the following construction<br>
<code>for conn_id, object in receptacle:__all() do ... end</code></dd>
</dl>
<p>There are three different types of multiple receptacles, as described below.</p>
<dl>
<dt><code>ListReceptacle</code></dt>
<dd>Accepts connections and automatically generates identifiers, therefore it ignores the identifier provided to <code>__bind</code> method.</dd>
<dt><code>HashReceptacle</code></dt>
<dd>Accepts connections with application-defined identifiers, therefore it is necessary to provide an identifier to the <code>__bind</code> method.</dd>
<dt><code>SetReceptacle</code></dt>
<dd>Accepts only one connection for each object and uses the object as the connection identifier, therefore it also ignores the identifier provided to <code>__bind</code> method.</dd>
</dl>
<h3><a name="templates">Templates</a></h3>
<p>A component is a computational element that provides a set of ports that can be connected to other components or objects in order to assemble a computational system.
The set of ports provided by a component is defined by a template.
A component template is realized as an object that maps port names to a specific port type.
The code below illustrates the definition of a component template.</p>
<pre>
local DispatcherTemplate = component.Template{
requester = port.Facet,
scheduler = port.Receptacle,
objectmap = port.HashReceptacle,
}
</pre>
<p>Component templates are responsible to create all the infrastructure necessary for the execution of a component implementation.</p>
<h3><a name="factories">Factories</a></h3>
<p>Once a component template is defined we can create factories of components that follow that template.
For example, consider the following class that is used as the constructor of implementations of components of the template defined above.</p>
<a name="implexample"></a>
<pre>
-- implementation
Requester = oo.class{ context = false }
function Requester:push(request)
local object = self.context.objectmap[request.object_key]
if object then
local operation = object[request.operation] or
self.defaultops and self.defaultops[request.operation]
if operation then
self.context.scheduler:start(operation, object, unpack(request.params))
end
end
end
-- factory
DispatcherFactory = DispatcherTemplate{ requester = Requester }
-- component
local dispatcher = DispatcherFactory()
</pre>
<p>To create a factory, we use a component template as the factory constructor.
Such constructor gets as parameter the factory definition, <i>i.e.</i> a table containing the constructor of each facet defined by the template.
The constructor of each facet must be a callable object (<i>e.g.</i> function or class) that returns a new implementation for the facet of each new component created by the factory.
In the example above, we create a factory of components that follow the template <code>DispatcherTemplate</code> and each facet <code>requester</code> is an instance of class <code>Requester</code>.</p>
<p>Alternatively, a factory may also define a constructor for the component itself aside from the constructor of its facets.
The component constructor is defined by index 1 or using the special name <code>__component</code> in the factory definition.
If a constructor is provided for the component then all facets that do not have a specific constructor defined are implemented by the implementation returned by the component constructor.
For example, we can create a factory of dispatcher components similar to the one described above using the following code:</p>
<pre>
-- factory with component implementation that also implement all facets
OtherDispatcherFactory = DispatcherTemplate{ Requester }
</pre>
<p>When a component is created, the component implementation's constructor is executed first if it is provided.
This constructor receives as parameter all the values passed to the factory.
After that, the constructor of each facet is executed.
The facet constructors receive as parameter the field of the component implementation that matches the name of the facet plus a reference to this component implementation.
Therefore, the component implementation may provide an initialization object to the provided the facet constructor.
For example, the following code will create a component which the <code>requester</code> facet has the field <code>defaultops</code> defined.</p>
<pre>
-- component
local dispatcher = DispatcherFactory{
requester = { -- object passed to class 'Requester'
defaultops = {
getid = function(self)
return self.id
end,
}
}
}
</pre>
A similar approach may be used to define initial values for the receptacles, like in the example below.
<pre>
-- component
local dispatcher = DispatcherFactory{
objectmap = _G, -- allow disptach to global objects.
}
</pre>
<h3><a name="implementation">Implementation</a></h3>
<p>A single component instance may be made of different objects that are responsible to implement different facets.
In addition to that, the component is also made of its receptacles that contains references to its dependencies.
All this information if provided to the component by the context object.
The context object is a table that maps the name of each port to its implementation, in case of facets, or to the objects connected in case of receptacles.
Additionally, the context object also contains the factory that created the object and the component implementation at indexes <code>__factory</code> and <code>__component</code>, respectively.</p>
<p>The context object is provided to the component's implementation and each facet implementation by field <code>context</code>.
If the implementation object provides the field context with a value different from <code>nil</code>, then this field is changed to hold the context object, like in the <a href="#implexample">example of the section above</a>.</p>
<p>Alternatively, if the field <code>context</code> is a function then this function is called as a method of the implementation object that receives the context object as a parameter.
The invocation of the <code>context</code> function also signals that all implementation objects are created, so it is useful if some part of the component needs to perform some initialization only when the whole component's implementation is created.
Since the order in which the implementation objects are created is not defined, the <code>context</code> method may also be used to initialize some state of the object that is dependable of the others component's implementation objects, like in the example below.</p>
<pre>
-- facet 'requester' implementation
Requester = oo.class()
function Requester:context(context)
self.context = context
-- check if the 'defaultops' are defined in the component's implementation
self.defaultops = self.defaultops or context.__component.defaultops
end
</pre>
<h3><a name="assembly">Assembly</a></h3>
<p>Once components are created they shall be assembled by connection of their ports.
Connections are typically established by setting a facet of a component to the receptacle of another.
However, in case of multiple receptacles, this is done by operation <code>__bind</code> provided by this kind receptacles.
The following example is extracted from the basic kernel architecture of the <a href="http://oil.luaforge.net/">OiL</a> ORB.</p>
<pre>
-- CLIENT SIDE
ClientBroker = component.Template{
broker = port.Facet,
proxies = port.Receptacle,
references = port.Receptacle,
}
ObjectProxies = component.Template{
proxies = port.Facet,
invoker = port.Receptacle,
}
OperationInvoker = component.Template{
invoker = port.Facet,
requester = port.Receptacle,
}
-- SERVER SIDE
ServerBroker = component.Template{
broker = port.Facet,
objects = port.Receptacle,
acceptor = port.Receptacle,
references = port.Receptacle,
}
RequestDispatcher = component.Template{
objects = port.Facet,
dispatcher = port.Facet,
}
RequestReceiver = component.Template{
acceptor = port.Facet,
dispatcher = port.Receptacle,
listener = port.Receptacle,
}
function assemble(components)
setfenv(1, components) -- to avoid the 'components.' prefix.
-- Client side
OperationInvoker.requester = OperationRequester.requests
ObjectProxies.invoker = OperationInvoker.invoker
ClientBroker.proxies = ObjectProxies.proxies
ClientBroker.references = ObjectReferrer.references
-- Server side
RequestReceiver.listener = RequestListener.listener
RequestReceiver.dispatcher = RequestDispatcher.dispatcher
ServerBroker.objects = RequestDispatcher.objects
ServerBroker.acceptor = RequestReceiver.acceptor
ServerBroker.references = ObjectReferrer.references
end
</pre>
<h3><a name="instrospection">Introspection</a></h3>
<p>All LOOP component packages provide some introspection functions that are used to retrieve information about the structure of the components like the type of their ports or their implementations, like is listed below.</p>
<dl>
<dt><code>factoryof(component)</code></dt>
<dd>Returns the factory object that was used to create the component <code>component</code>.</dd>
<dt><code>templateof(component|factory)</code></dt>
<dd>Returns the template of a component or the template used by a component factory.</dd>
<dt><code>ports(template)</code></dt>
<dd>Returns an iterator for all ports defined by a component template.
The iteration variables get the name of the current port and the kind of the port that is one of the field of the port package like <code>port.Facet</code> or <code>port.HashReceptacle</code>.</dd>
<dt><code>segmentof(component, portname)</code></dt>
<dd>Returns the implementation of the port with name <code>portname</code> of component <code>component</code>.</dd>
</dl>
<!--
<p>Additionally, each port package maps port kinds to their names, therefore to print the ports of a component you can use the following code:</p>
<pre>
for name, kind in component.ports(component.templateof(MyComp)) do
print("port "..name.." is a "..port[kind])
end
</pre>
-->
<h2><a name="packages">Component Packages</a></h2>
<p>The component package that implements the standard model is <code>loop.component.contained</code>.
This package makes no assumption about the component's implementation objects, therefore these objects may be userdata or even non-indexable values like functions or threads.
This is because the template provided by this package creates additional objects to represent the component's external interface, which is provided to clients to access the component ports, and also the context object, which is the component's internal interface.
The figure bellow illustrates the schema of components created with templates of package <code>loop.component.contained</code>.</p>
<div align="center"><img src="contained.jpg"></div>
<p>Alternatively, LOOP also provides other component packages that provide templates that avoid creation of additional objects for each component like <code>loop.component.wrapped</code> that creates only one additional object to represent the component external interface, but uses the component's implementation itself as the context object and therefore stores all ports values (facet implementation and receptacle connections) and the factory in the component's implementation object.
This results that the component's implementation object can access all ports using the <code>self</code> parameter and avoid an additional table index to get the context object.
The only advantage of providing an additional object for the external interface of the component is to be able to provide an alternative external view like is used by ports with support for interception like is described in section <a href="#intercept">Interception</a>.</p>
<p>The component package <code>loop.component.base</code> provides the lightest template implementation.
Such templates use the component's object implementation both as the external and internal interface of the component, and therefore are very similar to ordinary objects, however they provide all the features described in the <a href="#general">first section</a>.</p>
<h2><a name="intercept">Port Interception</a></h2>
<p>Package <code>loop.component.intercepted</code> is a port package that provides implementation of component ports with support for interception.
When a component template is created with ports from this package, interceptors may be registered in the component to be executed whenever an access is performed on its ports.</p>
<p>Interceptors may be defined for each component, or for all components created from a given factory, or even for all components of a given template.
The interceptors are registered by the use of the following function provided by the <code>loop.component.intercepted</code> package.</p>
<dl>
<dt><code>intercept(component|factory|template, portname, event [, interceptor])</code></dt>
<dd>Sets <code>interceptor</code> as the interceptor to be invoked when event <code>event</code> is triggered in port with name <code>portname</code> of the component or components defined by the first parameter.
If the <code>interceptor</code> is omitted or is <code>nil</code> then the interceptor registered for that event is removed.
The possible values for <code>event</code> are:
<ul>
<li><code>"method"</code>: a port's method is invoked.</li>
<li><code>"call"</code>: the port is invoked like a function.</li>
<li><code>"index"</code>: a port's field is indexed (this event always precede the <code>"method"</code> event).</li>
<li><code>"newindex"</code>: a port's field is set.</li>
</ul></dd>
</dl>
<p><strong>WARNING:</strong>
There is a current limitation that intercepted ports cannot provide fields that contains function values. Such fields can only be methods, <i>i.e.</i> functions that are invoked immediately after they are indexed and take the <code>self</code> parameter.</p>
<h3><a name="interceptors">Interceptors</a></h3>
<p>Interceptors are ordinary objects that may provide methods <code>before</code> and <code>after</code>.
The semantics provided by these methods (the <code>self</code> parameter is implict) are described below.</p>
<dl>
<dt><code>before(request, ...)</code></dt>
<dd>Receives the <code>request</code> table that contains the following fields:
<ul>
<li><code>context</code>: context object of the component.</li>
<li><code>port</code>: name of the port being intercepted.</li>
<li><code>object</code>: implementation object of the facet or object connected to the receptacle.</li>
<li><code>event</code>: kind of the event that triggered the interception (<code>"method"</code>, <code>"call"</code>, <code>"index"</code>, or <code>"newindex"</code>).</li>
<li><code>method</code>: if <code>event</code> is <code>"method"</code> then this field is provided with the function that implements the method being invoked.</li>
<li><code>field</code>: if <code>event</code> is <code>"index"</code> or <code>"newindex"</code> then this field is provided with the name of the field being accessed.</li>
</ul>
In addition to the <code>request</code> table this method also receive additional parameters that differ depending on the event that triggered the interception.
In case of <code>"method"</code> and <code>"call"</code> these parameters are the parameters of the call, including the <code>self</code> parameter in case of method invocations.
In case of <code>"index"</code> these parameters are only the name of the indexed field.
In case of <code>"newindex"</code> these parameters are the name of the indexed field and the new value being set to it.
<br>
This method must always return the values that must be used as the parameters of the actual event being intercepted.
Therefore, to allow that the event be performed with unchanged parameters the method must return the additional parameters provided (<i>i.e.</i> the expression <code>...</code>)
<br>
Finally, this method may cancel the event so it is not delegated to the component implementation.
This is done by definition of field <code>cancel</code> of table <code>request</code> provided as the first parameter of the method.
In this case, the values returned by this method are used as the return values passed to the client of the event intercepted. </dd>
<dt><code>after(request, ...)</code></dt>
<dd>Receives the same <code>request</code> table that was provided to the <code>before</code> method for the this triggered event.
Therefore, if some value is stored in the <code>request</code> table in the execution of the <code>before</code> method, such value is available in this table as well.
The additional parameters are the return values of the triggered event.
In case of <code>"method"</code> and <code>"call"</code> these parameters are the return values of the call.
In case of <code>"index"</code> these parameters are only the value of the indexed field.
In case of <code>"newindex"</code> no additional parameters are provided.
<br>
Similar to the <code>before</code> method, this method must always return the values that must be used as the return values of the actual event being intercepted.
Therefore, to allow that the event be performed with unchanged return values the method must return the additional parameters provided (<i>i.e.</i> the expression <code>...</code>) </dd>
</dl>
<h3>Example</h3>
<pre>
ProfilerInterceptor = {}
function ProfilerInterceptor:before(request, ...)
if request.event == "index" then
local field = ...
self.lastindexed = field
elseif request.event == "method" then
-- should work because method index and invocation are atomic
request.name = self.lastindexed
request.start = os.time()
end
return ...
end
function ProfilerInterceptor:after(request, ...)
if request.event == "method" then
print(string.format("operation %s.%s(...) spent at least %d seconds.",
request.port,
request.name,
os.difftime(os.time(), request.start)
))
end
return ...
end
local component = require "loop.component.base"
local port = require "loop.component.intercepted"
local MyTemplate = component.Template{
myfacet = port.Facet,
myreceptacle = port.Receptacle,
}
port.intercept(MyTemplate, "myfacet", "index", ProfilerInterceptor)
port.intercept(MyTemplate, "myfacet", "method", ProfilerInterceptor)
port.intercept(MyTemplate, "myreceptacle", "index", ProfilerInterceptor)
port.intercept(MyTemplate, "myreceptacle", "method", ProfilerInterceptor)
</pre>
<h2><a name="dynamic">Dynamic Changes</a></h2>
<p>Package <code>loop.component.dynamic</code> is a component package that provides templates that can be changed dynamically and reflect such changes on all its instances.
This package provides operations to add and remove ports of all components of a given template or factory or also from a single instance.
When a new facet is added, it is possible to define the implementation of that facet that will be instantiated for each component instance on demand following the same implementation protocol used for ordinary facet implementations.
The functions provided by the <code>loop.component.dynamic</code> package are described below.</p>
<h3>Functions</h3>
<dl>
<dt><code>addport(component|factory|template, portname, portkind [, constructor])</code></dt>
<dd>Defines a dynamic port with name <code>portname</code> of the kind specified by parameter <code>portkind</code> that may be any port kind provided by packages <code>loop.component.base</code> or <code>loop.component.intercepted</code>.
The parameter <code>constructor</code> is used in addition of facets to define the constructor of their implementation objects.</dd>
<dt><code>removeport(component|factory|template, portname)</code></dt>
<dd>Removes a dynamic port that was added by function <code>addport</code> described above.
It is not possible to remove ports that were not added dynamically.</dd>
</dl>
<h3>Example</h3>
<pre>
local component = require "loop.component.dynamic"
local port = require "loop.component.base"
local iport = require "loop.component.intercepted"
local MyTemplate = component.Template()
component.addport(MyTemplate, "inspector", port.Facet, oo.class{
context = function(self, context)
self.context = context
end,
getfieldof = function(self, port, field)
self.context[port][field]
end,
})
</pre>
</div>
<div class="content">
<p><small><strong>Copyright (C) 2004-2008 Tecgraf, PUC-Rio</strong></small></p>
<small>This project is currently being maintained by <a href="http://www.tecgraf.puc-rio.br">Tecgraf</a> at <a href="http://www.puc-rio.br">PUC-Rio</a>.</small>
</div>
</body>
</html>
| {
"content_hash": "08029b18928c273f7dff90faa59e34a4",
"timestamp": "",
"source": "github",
"line_count": 484,
"max_line_length": 488,
"avg_line_length": 53.675619834710744,
"alnum_prop": 0.7539936102236422,
"repo_name": "ld-test/loop",
"id": "7bf0e8776503d654e68f6870f50afd8d28dba544",
"size": "25979",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "doc/manual/components.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Lua",
"bytes": "219862"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DataSourceManagerImpl" format="xml" multifile-model="true">
<data-source source="LOCAL" name="@localhost" uuid="1d0d17c8-a95c-41db-9064-73eabfac72ad">
<driver-ref>mysql</driver-ref>
<synchronize>true</synchronize>
<jdbc-driver>com.mysql.jdbc.Driver</jdbc-driver>
<jdbc-url>jdbc:mysql://localhost:3306</jdbc-url>
<driver-properties>
<property name="autoReconnect" value="true" />
<property name="zeroDateTimeBehavior" value="convertToNull" />
<property name="tinyInt1isBit" value="false" />
<property name="characterEncoding" value="utf8" />
<property name="characterSetResults" value="utf8" />
<property name="yearIsDateType" value="false" />
</driver-properties>
</data-source>
</component>
</project> | {
"content_hash": "ba0d269d4afb5ea2d5fb9b330a2d43cc",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 94,
"avg_line_length": 46.10526315789474,
"alnum_prop": 0.6666666666666666,
"repo_name": "TorettoLong/financeP2p",
"id": "e292fe05c9375e35c6162f0e00adb141f18ea415",
"size": "876",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": ".idea/dataSources.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "36"
},
{
"name": "CSS",
"bytes": "72199"
},
{
"name": "HTML",
"bytes": "126255"
},
{
"name": "Java",
"bytes": "74195"
},
{
"name": "JavaScript",
"bytes": "217707"
},
{
"name": "PHP",
"bytes": "6746"
}
],
"symlink_target": ""
} |
<?php if(!defined('IN_PHPVMS') && IN_PHPVMS !== true) { die(); } ?>
<h3>Thank you!</h3>
<p>Your registration is now complete! You may log-in now</p> | {
"content_hash": "ced4c080a56ba85457c2f90b2adf65cb",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 67,
"avg_line_length": 49.333333333333336,
"alnum_prop": 0.6216216216216216,
"repo_name": "DavidJClark/phpvms_5.5.x",
"id": "a12058a3330a9374d8528c6078c2bef65a161a95",
"size": "148",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "core/templates/registration_complete.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "1347"
},
{
"name": "CSS",
"bytes": "34906"
},
{
"name": "Groff",
"bytes": "405"
},
{
"name": "HTML",
"bytes": "26114"
},
{
"name": "JavaScript",
"bytes": "93601"
},
{
"name": "PHP",
"bytes": "1606596"
}
],
"symlink_target": ""
} |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.api.ads.admanager.jaxws.v202205;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
*
* Returns an insite preview URL that references the specified site URL with
* the specified creative from the association served to it. For Creative Set
* previewing you may specify the master creative Id.
*
*
* <p>Java class for getPreviewUrl element declaration.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <element name="getPreviewUrl">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="lineItemId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/>
* <element name="creativeId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/>
* <element name="siteUrl" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"lineItemId",
"creativeId",
"siteUrl"
})
@XmlRootElement(name = "getPreviewUrl")
public class LineItemCreativeAssociationServiceInterfacegetPreviewUrl {
protected Long lineItemId;
protected Long creativeId;
protected String siteUrl;
/**
* Gets the value of the lineItemId property.
*
* @return
* possible object is
* {@link Long }
*
*/
public Long getLineItemId() {
return lineItemId;
}
/**
* Sets the value of the lineItemId property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setLineItemId(Long value) {
this.lineItemId = value;
}
/**
* Gets the value of the creativeId property.
*
* @return
* possible object is
* {@link Long }
*
*/
public Long getCreativeId() {
return creativeId;
}
/**
* Sets the value of the creativeId property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setCreativeId(Long value) {
this.creativeId = value;
}
/**
* Gets the value of the siteUrl property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSiteUrl() {
return siteUrl;
}
/**
* Sets the value of the siteUrl property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSiteUrl(String value) {
this.siteUrl = value;
}
}
| {
"content_hash": "9fd7a685b821fdaa4d9660f681db344c",
"timestamp": "",
"source": "github",
"line_count": 138,
"max_line_length": 104,
"avg_line_length": 26.369565217391305,
"alnum_prop": 0.6081341027754877,
"repo_name": "googleads/googleads-java-lib",
"id": "7dd0f556ab3a8b6a8c9a9ae11ca7b247149f4335",
"size": "3639",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/dfp_appengine/src/main/java/com/google/api/ads/admanager/jaxws/v202205/LineItemCreativeAssociationServiceInterfacegetPreviewUrl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "81068791"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html><head><title></title>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<link rel="stylesheet" type="text/css" href="search.css"/>
<script type="text/javascript" src="all_c.js"></script>
<script type="text/javascript" src="search.js"></script>
</head>
<body class="SRPage">
<div id="SRIndex">
<div class="SRStatus" id="Loading">Loading...</div>
<div id="SRResults"></div>
<script type="text/javascript"><!--
createResults();
--></script>
<div class="SRStatus" id="Searching">Searching...</div>
<div class="SRStatus" id="NoMatches">No Matches</div>
<script type="text/javascript"><!--
document.getElementById("Loading").style.display="none";
document.getElementById("NoMatches").style.display="none";
var searchResults = new SearchResults("searchResults");
searchResults.Search();
--></script>
</div>
<!-- Google Analytics -->
<script type="text/javascript">
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-75289145-1', 'auto');
ga('send', 'pageview');
</script>
<!-- End Google Analytics -->
</body>
</html>
| {
"content_hash": "022de8ecef5bc98a01f14ecb08530f43",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 121,
"avg_line_length": 38.53846153846154,
"alnum_prop": 0.6819693945442449,
"repo_name": "mike-jumper/incubator-guacamole-website",
"id": "ade398cf4da3391d1870581f2bc9c53245c2e4df",
"size": "1503",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "doc/0.9.9/libguac/search/all_c.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "12886"
},
{
"name": "HTML",
"bytes": "37702"
},
{
"name": "JavaScript",
"bytes": "439018"
},
{
"name": "Perl",
"bytes": "2217"
},
{
"name": "Ruby",
"bytes": "660"
},
{
"name": "Shell",
"bytes": "4849"
}
],
"symlink_target": ""
} |
describe RSpotify::Category do
# Keys generated specifically for the tests. Should be removed in the future
let(:client_id) { '5ac1cda2ad354aeaa1ad2693d33bb98c' }
let(:client_secret) { '155fc038a85840679b55a1822ef36b9b' }
before do
authenticate_client
end
describe 'Category::find' do
it 'should find right category' do
category = VCR.use_cassette('category:find:party') do
RSpotify::Category.find('party')
end
expect(category.href) .to eq 'https://api.spotify.com/v1/browse/categories/party'
expect(category.icons.first['url']) .to eq 'https://datsnxq1rwndn.cloudfront.net/media/derived/party-274x274_73d1907a7371c3bb96a288390a96ee27_0_0_274_274.jpg'
expect(category.id) .to eq 'party'
expect(category.name) .to eq 'Party'
end
it 'should find right category with additional attributes' do
category = VCR.use_cassette('category:find:party:country:BR') do
RSpotify::Category.find('party', country: 'BR')
end
expect(category.href) .to eq 'https://api.spotify.com/v1/browse/categories/party'
expect(category.name) .to eq 'Party'
category = VCR.use_cassette('category:find:party:locale:es_MX') do
RSpotify::Category.find('party', locale: 'es_MX')
end
expect(category.href) .to eq 'https://api.spotify.com/v1/browse/categories/party'
expect(category.name) .to eq 'Party'
end
end
describe 'Category::list' do
it 'should get the right categories' do
categories = VCR.use_cassette('category:list') do
RSpotify::Category.list
end
expect(categories.size) .to eq 20
expect(categories.map(&:name)) .to include('Top Lists', 'Country', 'Decades')
end
it 'should get the right categories with additional attributes' do
categories = VCR.use_cassette('category:list:locale:es_MX:limit:10') do
RSpotify::Category.list(locale: 'es_MX', limit: 10)
end
expect(categories.size) .to eq 10
expect(categories.map(&:name)) .to include('Dance', 'Pop', 'Chill')
categories = VCR.use_cassette('category:list:country:BR') do
RSpotify::Category.list(country: 'BR')
end
expect(categories.map(&:name)) .to include('Top Lists', 'Pop', 'Chill')
end
end
describe 'Category#complete!' do
let(:category) do
RSpotify::Category.new({'id' => 'party'})
end
it 'should fetch the complete information correctly' do
VCR.use_cassette('category:find:party') do
category.complete!
end
expect(category.href) .to eq 'https://api.spotify.com/v1/browse/categories/party'
expect(category.icons.first['url']) .to eq 'https://datsnxq1rwndn.cloudfront.net/media/derived/party-274x274_73d1907a7371c3bb96a288390a96ee27_0_0_274_274.jpg'
expect(category.name) .to eq 'Party'
end
end
describe 'Category#playlists' do
let(:category) do
# Get party category as a testing sample
VCR.use_cassette('category:find:party') do
RSpotify::Category.find('party')
end
end
it 'should get correct playlists' do
playlists = VCR.use_cassette('category:party:playlists') do
category.playlists
end
expect(playlists) .to be_an Array
expect(playlists.size) .to eq 20
expect(playlists.first) .to be_an RSpotify::Playlist
expect(playlists.map(&:name)) .to include('Teen Party', 'Weekend Hangouts', 'Dance Party')
end
it 'should get correct playlists with additional options' do
playlists = VCR.use_cassette('category:party:playlists:limit:10:offset:20') do
category.playlists(limit: 10, offset: 20)
end
expect(playlists.size) .to eq 10
expect(playlists.map(&:name)) .to include('Indie Brunch', 'Hipster Funk', 'Party Hits')
playlists = VCR.use_cassette('category:party:playlists:country:BR') do
category.playlists(country: 'BR')
end
expect(playlists.map(&:name)) .to include('Lista VIP', 'Sexta', 'Modo Freestyle')
end
end
end
| {
"content_hash": "2ba599592aacbbd87ae01a123762348b",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 164,
"avg_line_length": 38.596330275229356,
"alnum_prop": 0.6429759923936297,
"repo_name": "markusherzog/rspotify",
"id": "4636ea82c03546cf2c2f7731683662f053eb8ad3",
"size": "4207",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "spec/lib/rspotify/category_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "93985"
}
],
"symlink_target": ""
} |
from .equals import equals
def equals_nocurry_test():
assert equals("foo", "foo")
def equals_curry_test():
assert equals("foo")("foo")
| {
"content_hash": "d73f0c0fe75ce031796cb4f3d3a96407",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 31,
"avg_line_length": 16.333333333333332,
"alnum_prop": 0.6530612244897959,
"repo_name": "jackfirth/pyramda",
"id": "2cc8d1c17dbe108b15a8c1719e33e84932986290",
"size": "147",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pyramda/relation/equals_test.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "41755"
}
],
"symlink_target": ""
} |
module SweetAlert2
module Rails
class Engine < ::Rails::Engine; end
end
end | {
"content_hash": "4baaf00a77f102bc428920f558a4f3e1",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 39,
"avg_line_length": 16.6,
"alnum_prop": 0.7108433734939759,
"repo_name": "SciMed/sweetalert2-rails",
"id": "4c81e981d59bb31cd8fc7382991523d03eb0e8d2",
"size": "83",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/sweetalert2/engine.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "12506"
},
{
"name": "JavaScript",
"bytes": "29"
},
{
"name": "Ruby",
"bytes": "1014"
}
],
"symlink_target": ""
} |
package goryachev.common.io;
import goryachev.common.util.CList;
public class CSVParser
{
private char separator = ',';
private char quoteChar = '"';
private char escapeChar = '\\';
private boolean strictQuotes;
private boolean ignoreLeadingWhiteSpace = true;
private boolean inCell;
private String savedLine;
public CSVParser()
{
}
public void setSeparatorChar(char c)
{
separator = c;
}
public void setQuoteChar(char c)
{
quoteChar = c;
}
public void setEscapeChar(char c)
{
escapeChar = c;
}
public void setStrictQuotes(boolean on)
{
strictQuotes = on;
}
public void setIgnoreLeadingWhitespace(boolean on)
{
ignoreLeadingWhiteSpace = on;
}
protected boolean isPending()
{
return savedLine != null;
}
protected String[] parseLineMulti(String nextLine) throws Exception
{
return parseLine(nextLine, true);
}
public String[] parseLine(String nextLine) throws Exception
{
return parseLine(nextLine, false);
}
protected String[] parseLine(String nextLine, boolean multi) throws Exception
{
if(!multi && savedLine != null)
{
savedLine = null;
}
if(nextLine == null)
{
if(savedLine != null)
{
String s = savedLine;
savedLine = null;
return new String[] { s };
}
else
{
return null;
}
}
CList<String> tokensOnThisLine = new CList<String>();
StringBuilder sb = new StringBuilder(256);
boolean inQuotes = false;
if(savedLine != null)
{
sb.append(savedLine);
savedLine = null;
inQuotes = true;
}
for(int i = 0; i < nextLine.length(); i++)
{
char c = nextLine.charAt(i);
if(c == this.escapeChar)
{
if(isNextCharacterEscapable(nextLine, inQuotes || inCell, i))
{
sb.append(nextLine.charAt(i + 1));
i++;
}
}
else if(c == quoteChar)
{
if(isNextCharacterEscapedQuote(nextLine, inQuotes || inCell, i))
{
sb.append(nextLine.charAt(i + 1));
i++;
}
else
{
if(!strictQuotes)
{
if
(
(i > 2) &&
(nextLine.charAt(i - 1) != separator) &&
(nextLine.length() > (i + 1) && nextLine.charAt(i + 1) != separator)
)
{
if(ignoreLeadingWhiteSpace && sb.length() > 0 && isWhiteSpace(sb))
{
sb.setLength(0);
}
else
{
sb.append(c);
}
}
}
inQuotes = !inQuotes;
}
inCell = !inCell;
}
else if(c == separator && !inQuotes)
{
tokensOnThisLine.add(sb.toString());
sb.setLength(0);
inCell = false;
}
else
{
if(!strictQuotes || inQuotes)
{
sb.append(c);
inCell = true;
}
}
}
if(inQuotes)
{
if(multi)
{
sb.append("\n");
savedLine = sb.toString();
sb = null;
}
else
{
throw new Exception("quoted value must be terminated");
}
}
if(sb != null)
{
tokensOnThisLine.add(sb.toString());
}
return tokensOnThisLine.toArray(new String[tokensOnThisLine.size()]);
}
protected boolean isNextCharacterEscapable(String nextLine, boolean inQuotes, int i)
{
return
inQuotes &&
(nextLine.length() > (i + 1)) &&
(nextLine.charAt(i + 1) == quoteChar || nextLine.charAt(i + 1) == escapeChar);
}
protected boolean isNextCharacterEscapedQuote(String nextLine, boolean inQuotes, int i)
{
return
inQuotes &&
(nextLine.length() > (i + 1)) &&
(nextLine.charAt(i + 1) == quoteChar);
}
protected boolean isWhiteSpace(CharSequence sb)
{
boolean result = true;
for(int i = 0; i < sb.length(); i++)
{
char c = sb.charAt(i);
if(!Character.isWhitespace(c))
{
return false;
}
}
return result;
}
}
| {
"content_hash": "4b2f355d98e7898f437b996d5808ca14",
"timestamp": "",
"source": "github",
"line_count": 212,
"max_line_length": 88,
"avg_line_length": 18.29245283018868,
"alnum_prop": 0.5657555440948943,
"repo_name": "andy-goryachev/ReqTraq",
"id": "9182ef2c4c61740027140ae8b5327dc836b38bda",
"size": "3941",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/goryachev/common/io/CSVParser.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1029488"
}
],
"symlink_target": ""
} |
namespace Renci.SshNet.Messages.Connection
{
/// <summary>
/// Represents SSH_MSG_CHANNEL_CLOSE message.
/// </summary>
[Message("SSH_MSG_CHANNEL_CLOSE", 97)]
public class ChannelCloseMessage : ChannelMessage
{
/// <summary>
/// Initializes a new instance of the <see cref="ChannelCloseMessage"/> class.
/// </summary>
public ChannelCloseMessage()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ChannelCloseMessage"/> class.
/// </summary>
/// <param name="localChannelNumber">The local channel number.</param>
public ChannelCloseMessage(uint localChannelNumber)
: base(localChannelNumber)
{
}
}
}
| {
"content_hash": "b8a3c52e8984354901bbbeefccf3d9a2",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 86,
"avg_line_length": 30.423076923076923,
"alnum_prop": 0.5701643489254109,
"repo_name": "GenericHero/SSH.NET",
"id": "61e2d09a232a4918e2b51ccff558d62cf4debce3",
"size": "793",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "src/Renci.SshNet/Messages/Connection/ChannelCloseMessage.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "868"
},
{
"name": "C#",
"bytes": "3464565"
}
],
"symlink_target": ""
} |
var assert = require('chai').assert;
var reverseString = require('../reverse_string');
describe('TestReverseString', function() {
it('test reverseString', function() {
assert.equal('olleh', reverseString('hello'));
});
}); | {
"content_hash": "5f16fbab5e5f164903e7036d119fea07",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 50,
"avg_line_length": 28.875,
"alnum_prop": 0.6753246753246753,
"repo_name": "huhuanming/leetcode",
"id": "fc2c8ec619bdb57036486a38427c9919b4378453",
"size": "231",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Nodejs/test/test_reverse_string.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Awk",
"bytes": "1163"
},
{
"name": "C",
"bytes": "59802"
},
{
"name": "Go",
"bytes": "2165"
},
{
"name": "HTML",
"bytes": "97"
},
{
"name": "Java",
"bytes": "2755"
},
{
"name": "JavaScript",
"bytes": "1617"
},
{
"name": "Python",
"bytes": "3435"
},
{
"name": "Ruby",
"bytes": "2908"
},
{
"name": "Swift",
"bytes": "5998"
}
],
"symlink_target": ""
} |
#ifndef QQMLJSGLOBAL_P_H
#define QQMLJSGLOBAL_P_H
#include <QtCore/qglobal.h>
#ifdef QT_CREATOR
# define QT_QML_BEGIN_NAMESPACE
# define QT_QML_END_NAMESPACE
# ifdef QDECLARATIVEJS_BUILD_DIR
# define QML_PARSER_EXPORT Q_DECL_EXPORT
# elif QML_BUILD_STATIC_LIB
# define QML_PARSER_EXPORT
# else
# define QML_PARSER_EXPORT Q_DECL_IMPORT
# endif // QQMLJS_BUILD_DIR
#else // !QT_CREATOR
# define QT_QML_BEGIN_NAMESPACE QT_BEGIN_NAMESPACE
# define QT_QML_END_NAMESPACE QT_END_NAMESPACE
# if defined(QT_BUILD_QMLDEVTOOLS_LIB) || defined(QT_QMLDEVTOOLS_LIB)
// QmlDevTools is a static library
# define QML_PARSER_EXPORT
# elif defined(QT_BUILD_QML_LIB)
# define QML_PARSER_EXPORT Q_DECL_EXPORT
# else
# define QML_PARSER_EXPORT Q_DECL_IMPORT
# endif
#endif // QT_CREATOR
#endif // QQMLJSGLOBAL_P_H
| {
"content_hash": "be850cf7593faca4008d7b0e44265674",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 70,
"avg_line_length": 26.03125,
"alnum_prop": 0.7214885954381752,
"repo_name": "RikoOphorst/blowbox",
"id": "fe2cbe7d1d1cd3ffa6a48f1e763c91eb892eb245",
"size": "2411",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "dependencies/qt/Include/QtQmlDevTools/5.5.1/QtQmlDevTools/private/qqmljsglobal_p.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "836"
},
{
"name": "C++",
"bytes": "250806"
},
{
"name": "CSS",
"bytes": "25182"
},
{
"name": "HLSL",
"bytes": "1209"
}
],
"symlink_target": ""
} |
package de.ehex.foss.gematik.specifications.gemSpec_HBA_ObjSys;
import static de.ehex.foss.gematik.specifications.AFOType.MUST;
import static java.util.Objects.nonNull;
import de.ehex.foss.gematik.specifications.AFO;
import de.ehex.foss.gematik.specifications.AFOType;
/**
* Enumeration of all – currently considered – {@link AFO}s of {@code [gemSpec_HBA_ObjSys]}.
*
* @author Jonas Pfeiffer
* @since May 10th, 2017
*
* @deprecated WTF! Gematik publishes AFOs multiple times within the same release! This AFO source should be removed in
* favor of {@link de.ehex.foss.gematik.specifications.gemSpec_HBA_ObjSys_G2_1.AFOs};
*/
@Deprecated
public enum AFOs implements AFO {
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2032("Card-G2-A_2032_DOUBLET", "K_Initialisierung: Änderung von Zugriffsregeln"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2033("Card-G2-A_2033_DOUBLET", "K_Initialisierung: Ordnerattribute"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2034("Card-G2-A_2034_DOUBLET", "K_Initialisierung: Dateiattribute"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2035("Card-G2-A_2035_DOUBLET", "K_Initialisierung: Zugriffsregeln für besondere Kommandos"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2036("Card-G2-A_2036_DOUBLET", "K_Initialisierung Anzahl logischer Kanäle"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2038("Card-G2-A_2038_DOUBLET", "K_Personalisierung: Druck der CAN auf den HBA bei Verwendung der optionalen kontaktlosen Schnittstelle"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2039("Card-G2-A_2039_DOUBLET", "K_Initialisierung: Wert des Attributes root"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2040("Card-G2-A_2040_DOUBLET", "K_Personalisierung und K_Initialisierung: Wert des Attributes answerToReset"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2041("Card-G2-A_2041_DOUBLET", "K_Personalisierung: Wert des Attributes iccsn8"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2042("Card-G2-A_2042_DOUBLET", "K_Initialisierung: Inhalt persistentPublicKeyList"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2043("Card-G2-A_2043_DOUBLET", "K_Personalisierung und K_Initialisierung: ATR-Kodierung"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2044("Card-G2-A_2044_DOUBLET", "K_Personalisierung und K_Initialisierung: TC1 Byte im ATR"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2045("Card-G2-A_2045_DOUBLET", "K_Personalisierung und K_Initialisierung: Vorgaben für Historical Bytes"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2046("Card-G2-A_2046_DOUBLET", "K_Personalisierung: Kompatibilität zu G1-Karten"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2047("Card-G2-A_2047_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2048("Card-G2-A_2048_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / EF.ATR"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2055("Card-G2-A_2055_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / EF.DIR"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2057("Card-G2-A_2057_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / EF.GDO"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2058("Card-G2-A_2058_DOUBLET", "K_Personalisierung: Personalisiertes Attribut von EF.GDO"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2059("Card-G2-A_2059_DOUBLET", "K_Initialisierung: Attribute von MF / EF.Version2"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2060("Card-G2-A_2060_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / EF.C.CA_HPC.CS.R2048"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2061("Card-G2-A_2061_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / EF.C.CA_HPC.CS.E256"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2063("Card-G2-A_2063_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / EF.C.HPC.AUTR_CVC.R2048"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2064("Card-G2-A_2064_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / EF.C.HPC.AUTR_CVC.E256"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2067("Card-G2-A_2067_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / EF.C.HPC.AUTD_SUK_CVC.E256"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2069("Card-G2-A_2069_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / PIN.CH"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2070("Card-G2-A_2070_DOUBLET", "K_Personalisierung: Länge der PUK für den HBA"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2071("Card-G2-A_2071_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / PrK.HPC.AUTR_CVC.R2048"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2072("Card-G2-A_2072_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / PrK.HPC.AUTR_CVC.E256"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2075("Card-G2-A_2075_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / PrK.HPC.AUTD_SUK_CVC.E256"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2077("Card-G2-A_2077_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / PuK.RCA.CS.R2048"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2078("Card-G2-A_2078_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / PuK.RCA.CS.E256"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2080("Card-G2-A_2080_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / SK.CMS.AES128"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2081("Card-G2-A_2081_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / SK.CMS.AES256"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2082("Card-G2-A_2082_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / DF.HPA"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2083("Card-G2-A_2083_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / DF.HPA / EF.HPD"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2084("Card-G2-A_2084_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / DF.QES"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2085("Card-G2-A_2085_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / DF.QES / PrK.HP.QES.R2048"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2088("Card-G2-A_2088_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / DF.QES / PIN.QES"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2089("Card-G2-A_2089_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / DF.QES / EF.SSEC"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2090("Card-G2-A_2090_DOUBLET", "K_Initialisierung: Inhalt von EF.SSEC"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2091("Card-G2-A_2091_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / DF.QES / EF.C.HP.QES.R2048"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2094("Card-G2-A_2094_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / DF.QES / EF.C.HP.QES-AC1"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2095("Card-G2-A_2095_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / DF.QES / EF.C.HP.QES-AC2"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2096("Card-G2-A_2096_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / DF.QES / EF.C.HP.QES-AC3"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2097("Card-G2-A_2097_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / DF.ESIGN"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2098("Card-G2-A_2098_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / DF.ESIGN / PrK.HP.AUT.R2048"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2101("Card-G2-A_2101_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / DF.ESIGN / PrK.HP.ENC.R2048"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2107("Card-G2-A_2107_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / DF.ESIGN / EF.C.HP.AUT.R2048"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2110("Card-G2-A_2110_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / DF.ESIGN / EF.C.HP.ENC.R2048"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2117("Card-G2-A_2117_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / DF.CIA.QES"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2118("Card-G2-A_2118_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / DF.CIA.ESIGN"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2119("Card-G2-A_2119_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / DF.CIA.QES / EF.CIA.CIAInfo"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2120("Card-G2-A_2120_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / DF.CIA.QES / EF.OD (Object Directory)"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2121("Card-G2-A_2121_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / DF.CIA.QES / EF.AOD (Authentication Object Directory)"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2122("Card-G2-A_2122_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / DF.CIA.QES / EF.PrKD (Private Key Directory)"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2123("Card-G2-A_2123_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / DF.CIA.QES / EF.CD(Certificate Directory)"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2124("Card-G2-A_2124_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / DF.AUTO"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2125("Card-G2-A_2125_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / DF.AUTO / PrK.HP.AUTO.R2048"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2128("Card-G2-A_2128_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / DF.AUTO / PIN.AUTO"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2129("Card-G2-A_2129_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / DF:ATUO / PIN.SO"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2130("Card-G2-A_2130_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / DF.AUTO / EF.C.HP.AUTO1.R2048"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2131("Card-G2-A_2131_DOUBLET", "K_Initialisierung: Initialisierte : MF / DF.AUTO / EF.C.HP.AUTO2.R2048"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2673("Card-G2-A_2673_DOUBLET", "K_Personalisierung und K_Initialisierung: Wert von „positionLogicalEndOfFile“"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2675("Card-G2-A_2675_DOUBLET", "K_Initialisierung: Initialisierte : Wert von PrK.AUTO.R2048"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2676("Card-G2-A_2676_DOUBLET", "K_Personalisierung: Wert von PIN.AUTO"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2677("Card-G2-A_2677_DOUBLET", "K_Personalisierung: Wert von PUK für PIN.AUTO"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2678("Card-G2-A_2678_DOUBLET", "K_Personalisierung: Wert von PIN.SO"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2679("Card-G2-A_2679_DOUBLET", "K_Personalisierung: Wert von PUK für PIN.SO"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2680("Card-G2-A_2680_DOUBLET", "K_Personalisierung: Inhalt von EF.C.HP.AUTO1.R2048"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2681("Card-G2-A_2681_DOUBLET", "K_Personalisierung: Inhalt von EF.C.HP.AUTO2. R2048"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2682("Card-G2-A_2682_DOUBLET", "K_Personalisierung: Unterbindung der Nutzung von DF.AUTO - PIN.AUTO"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2856("Card-G2-A_2856_DOUBLET", "K_Personalisierung: Unterbindung der Nutzung von DF.AUTO - PIN.SO"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2867("Card-G2-A_2867_DOUBLET", "K_HBA: Vorhandensein einer USB-Schnittstelle"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2868("Card-G2-A_2868_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / SK.CAN"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_2869("Card-G2-A_2869_DOUBLET", "K_Personalisierung: Generierung der CAN bei Verwendung der optionalen kontaktlosen Schnittstelle des HBA"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3005("Card-G2-A_3005_DOUBLET", "Absicherung der Kartenadministration"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3006("Card-G2-A_3006_DOUBLET", "K_HBA: USB-Schnittstelle"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3007("Card-G2-A_3007_DOUBLET", "K_HBA: Kontaktlose Schnittstelle"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3009("Card-G2-A_3009_DOUBLET", "K_HBA: Zusatzanforderungen für kontaktlose Schnittstelle"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3010("Card-G2-A_3010_DOUBLET", "K_Initialisierung und K_Personalisierung: Kontaktlose Schnittstelle wird nicht genutzt"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3011("Card-G2-A_3011_DOUBLET", "K_Initialisierung: Kontaktlose Schnittstelle im COS nicht vorhanden"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3014("Card-G2-A_3014_DOUBLET", "K_HBA: Vorhandensein Kryptobox"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3015("Card-G2-A_3015_DOUBLET", "K_Personalisierung und K_Initialisierung: Historical Bytes im ATR"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3016("Card-G2-A_3016_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / PuK.RCA.ADMINCMS.CS.E256"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3181("Card-G2-A_3181_DOUBLET", "K_Initialisierung: Größe persistentPublicKeyList"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3182("Card-G2-A_3182_DOUBLET", "K_Initialisierung: Verwendbarkeit der Objekte in anderen SEs, kein konkretes SE genannt"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3183("Card-G2-A_3183_DOUBLET", "K_Initialisierung: Eigenschaften der Objekte in anderen SEs, kein konkretes SE genannt"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3184("Card-G2-A_3184_DOUBLET", "K_Initialisierung: Verhalten der Objekte, konkretes SE genannt"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3185("Card-G2-A_3185_DOUBLET", "K_Initialisierung: Verwendbarkeit der Objekte in anderen SEs, konkretes SE genannt"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3186("Card-G2-A_3186_DOUBLET", "K_Initialisierung: Eigenschaften der Objekte in anderen SEs, konkretes SE genannt"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3199("Card-G2-A_3199_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / EF.CardAccess"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3266("Card-G2-A_3266_DOUBLET", "K_Initialisierung: Wert von pointInTime"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3270("Card-G2-A_3270_DOUBLET", "K_Initialisierung: CHANGE REFERENCE DATA bei Nutzung der Leer-PIN für PIN.AUTO"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3271("Card-G2-A_3271_DOUBLET", "K_Initialisierung: CHANGE REFERENCE DATA bei Nutzung der Leer-PIN für PIN.SO"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3277("Card-G2-A_3277_DOUBLET", "K_Personalisierung und K_Initialisierung: Konformität kontaktlose Schnittstelle"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3278("Card-G2-A_3278_DOUBLET", "K_Initialisierung: Initialisiertes Attribut numberOfOctet von MF / EF.ATR"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3281("Card-G2-A_3281_DOUBLET", "K_Personalisierung: Personalisierte Attribute von MF / EF.C.CA_HPC.CS.R2048"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3282("Card-G2-A_3282_DOUBLET", "K_Personalisierung: Personalisierte Attribute von MF / EF.C.CA_HPC.CS.E256"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3283("Card-G2-A_3283_DOUBLET", "K_Personalisierung: Personalisierte Attribute von MF / EF.C.HPC.AUTR_CVC.R2048"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3284("Card-G2-A_3284_DOUBLET", "K_Personalisierung: Personalisierte Attribute von MF / EF.C.HPC.AUTR_CVC.E256"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3285("Card-G2-A_3285_DOUBLET", "K_Personalisierung: Personalisierte Attribute von MF / EF.C.HPC.AUTD_SUK_CVC.E256"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3286("Card-G2-A_3286_DOUBLET", "K_Personalisierung: Personalisierte Attribute von MF / PIN.CH"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3287("Card-G2-A_3287_DOUBLET", "K_Personalisierung: Personalisierte Attribute von MF / PrK.HPC.AUTR_CVC.R2048"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3288("Card-G2-A_3288_DOUBLET", "K_Personalisierung: Personalisierte Attribute von MF / PrK.HPC.AUTR_CVC.E256"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3289("Card-G2-A_3289_DOUBLET", "K_Personalisierung: Personalisierte Attribute von MF / PrK.HPC.AUTD_SUK_CVC.E256"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3290("Card-G2-A_3290_DOUBLET", "K_Personalisierung: Personalisierte Attribute von MF / PuK.RCA.ADMINCMS.CS.E256"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3291("Card-G2-A_3291_DOUBLET", "K_Personalisierung: Personalisierte Attribute von MF / SK.CMS.AES128"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3292("Card-G2-A_3292_DOUBLET", "K_Personalisierung: Personalisierte Attribute von MF / SK.CMS.AES256"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3293("Card-G2-A_3293_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / SK.CUP.AES128"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3294("Card-G2-A_3294_DOUBLET", "K_Personalisierung: Personalisierte Attribute von MF / SK.CUP.AES128"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3295("Card-G2-A_3295_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / SK.CUP.AES256"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3296("Card-G2-A_3296_DOUBLET", "K_Personalisierung: Personalisierte Attribute von MF / SK.CUP.AES256"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3297("Card-G2-A_3297_DOUBLET", "K_Personalisierung: Personalisierte Attribute von MF / SK.CAN"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3298("Card-G2-A_3298_DOUBLET", "K_Personalisierung: Personalisierte Attribute von MF / DF.QES / PrK.HP.QES.R2048"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3299("Card-G2-A_3299_DOUBLET", "K_Personalisierung: Personalisierte Attribute von MF / DF.QES / PIN.QES"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3301("Card-G2-A_3301_DOUBLET", "K_Personalisierung: Personalisierte Attribute von MF / DF.QES / EF.C.HP.QES.R2048"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3302("Card-G2-A_3302_DOUBLET", "K_Personalisierung: Personalisierte Attribute von MF / DF.QES / EF.C.HP.QES-AC1"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3303("Card-G2-A_3303_DOUBLET", "K_Personalisierung: Personalisierte Attribute von MF / DF.QES / EF.C.HP.QES-AC2"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3304("Card-G2-A_3304_DOUBLET", "K_Personalisierung: Personalisierte Attribute von MF / DF.QES / EF.C.HP.QES-AC3"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3305("Card-G2-A_3305_DOUBLET", "K_Personalisierung: Personalisierte Attribute von MF / DF.ESIGN / PrK.HP.AUT.R2048"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3306("Card-G2-A_3306_DOUBLET", "K_Personalisierung: Personalisierte Attribute von MF / DF.ESIGN / PrK.HP.ENC.R2048"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3307("Card-G2-A_3307_DOUBLET", "K_Personalisierung: Personalisierte Attribute von MF / DF.ESIGN / EF.C.HP.AUT.R2048"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3308("Card-G2-A_3308_DOUBLET", "K_Personalisierung: Personalisierte Attribute von MF / DF.ESIGN / EF.C.HP.ENC.R2048"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3314("Card-G2-A_3314_DOUBLET", "K_Personalisierung: Personalisierte Attribute von MF / DF.AUTO / PrK.HP.AUTO.R3072"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3315("Card-G2-A_3315_DOUBLET", "K_Personalisierung: Personalisierte Attribute von MF / DF.AUTO / PIN.AUTO"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3316("Card-G2-A_3316_DOUBLET", "K_Personalisierung: Personalisierte Attribute von MF / DF.AUTO / PIN.SO"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3317("Card-G2-A_3317_DOUBLET", "K_Personalisierung: Personalisierte Attribute von MF / DF.AUTO / EF.C.HP.AUTO1.R2048"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3318("Card-G2-A_3318_DOUBLET", "K_Personalisierung: Personalisierte Attribute von MF / DF.AUTO / EF.C.HP.AUTO2.R2048"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3320("Card-G2-A_3320_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / DF.CIA.ESIGN / EF.CIA.CIAInfo"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3321("Card-G2-A_3321_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / DF.CIA.ESIGN / EF.OD (Object Directory)"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3322("Card-G2-A_3322_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / DF.CIA.ESIGN / EF.AOD (Authentication Object Directory)"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3323("Card-G2-A_3323_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / DF.CIA.ESIGN / EF.PrKD (Private Key Directory)"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3324("Card-G2-A_3324_DOUBLET", "K_Initialisierung: Initialisierte Attribute von MF / DF.CIA.ESIGN / EF.CD (Certificate Directory)"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3325("Card-G2-A_3325_DOUBLET", "K_Initialisierung und K_Personalisierung: Abweichung von Festlegungen zum Zwecke der Personalisierung"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3326("Card-G2-A_3326_DOUBLET", "K_Personalisierung: Personalisierte Attribute von MF / PuK.RCA.CS.R2048 für Testkarten"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3327("Card-G2-A_3327_DOUBLET", "K_Personalisierung: Personalisierte Attribute von MF / PuK.RCA.CS.E256 für Testkarten"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3385("Card-G2-A_3385_DOUBLET", "K_Personalisierung: Festlegung von CHR in MF / EF.C.HPC.AUTR_CVC.R2048"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3386("Card-G2-A_3386_DOUBLET", "K_Personalisierung: Festlegung von CHR in MF / EF.C.HPC.AUTR_CVC.E256"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3387("Card-G2-A_3387_DOUBLET", "K_Personalisierung: Festlegung von CHR in MF / EF.C.HPC.AUTD_SUK_CVC.E256"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3395("Card-G2-A_3395_DOUBLET", "K_Personalisierung: personalisierter Wert von pointInTime"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3523("Card-G2-A_3523_DOUBLET", "K_Personalisierung: Schlüsselgenerierung auf der Karte"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3590("Card-G2-A_3590_DOUBLET", "Symmetrische Kartenadministration"),
// TODO: AFO-Typ klären derzeit implizit MUSS-AFO
Card_G2_A_3591("Card-G2-A_3591_DOUBLET", "Schlüsselspeicherung"),
;
private final String afoID;
private final AFOType level;
private final String title;
private AFOs(final String afoID, final String title) {
this(afoID, title, MUST);
}
private AFOs(final String afoID, final String title, final AFOType level) {
assert nonNull(afoID) : "There must be a non-null AFO id!";
assert !afoID.isEmpty() : "There must be a non-empty AFO id!";
assert nonNull(title) : "There must be a non-null AFO title!";
assert !title.isEmpty() : "There must be a non-empty AFO title!";
assert nonNull(level) : "There must be a non-null AFO type!";
this.afoID = afoID;
this.title = title;
this.level = level;
}
@Override
public String getAfoId() {
assert nonNull(this.afoID) : "Class invariant violation!";
assert !this.afoID.isEmpty() : "Class invariant violation!";
return this.afoID;
}
@Override
public String getLabel() {
assert nonNull(this.title) : "Class invariant violation!";
assert !this.title.isEmpty() : "Class invariant violation!";
return this.title;
}
@Override
public AFOType getType() {
assert nonNull(this.level) : "Class invariant violation!";
return this.level;
}
} | {
"content_hash": "e357d6c44432c6465374c08a3606643e",
"timestamp": "",
"source": "github",
"line_count": 499,
"max_line_length": 157,
"avg_line_length": 54.06613226452906,
"alnum_prop": 0.709070017420957,
"repo_name": "ghostcity/gematik-specifications",
"id": "412a8703f15325b188d10254ffa602c7ddde3da2",
"size": "27146",
"binary": false,
"copies": "2",
"ref": "refs/heads/OPB1.6/2017-07-12",
"path": "src/main/java/de/ehex/foss/gematik/specifications/gemSpec_HBA_ObjSys/AFOs.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "1310205"
}
],
"symlink_target": ""
} |
import React, { Component, PropTypes } from 'react';
import styles from './styles.css';
import twitter from 'twitter-text';
const TWEET_MAX_LENGTH = 140;
const CHARACTERS_PER_MEDIA = 24;
export default class TweetEditor extends Component {
static propTypes = {
onChange: PropTypes.func.isRequired,
defaultValue: PropTypes.string,
};
static defaultProps = {
defaultValue: ''
};
constructor (props) {
super(props);
this.state = {
content: props.defaultValue,
image: '',
};
}
onChange = (value) => {
this.setState(value, () => this.props.onChange(this.state));
};
getCharactersLeft = () => {
const contentLength = twitter.getTweetLength(this.state.content);
const imageLength = this.state.image ? CHARACTERS_PER_MEDIA : 0;
const left = TWEET_MAX_LENGTH - contentLength - imageLength;
if (left === 1 || left === -1) {
return `${left} character left`;
}
return `${left} characters left`;
};
render () {
return (
<form>
<textarea
className={styles.contentInput}
placeholder="Tweet content..."
onChange={(event) => this.onChange({ content: event.target.value })}
value={this.state.content}
/>
<input
type="url"
className={styles.imageInput}
placeholder="Image's url"
onChange={(event) => this.onChange({ image: event.target.value })}
value={this.state.image}
/>
<div className={styles.contentCounter}>
{this.getCharactersLeft()}
</div>
</form>
);
}
}
TweetEditor.propTypes = {
};
| {
"content_hash": "df30fbf557b6861318831fdf88a25efc",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 78,
"avg_line_length": 23.542857142857144,
"alnum_prop": 0.5934466019417476,
"repo_name": "Zhouzi/Poffer",
"id": "3257ceca016c2dbed513a8ad89f547b7ce9522df",
"size": "1648",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/components/TweetEditor/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "9171"
},
{
"name": "HTML",
"bytes": "1815"
},
{
"name": "JavaScript",
"bytes": "46636"
}
],
"symlink_target": ""
} |
package com.jacky.permanent;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service
{
AlarmManager mAlarmManager = null;
PendingIntent mPendingIntent = null;
@Override
public void onCreate()
{
//start the service through alarm repeatly
Intent intent = new Intent(getApplicationContext(), MyService.class);
mAlarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
mPendingIntent = PendingIntent.getService(this, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
long now = System.currentTimeMillis();
mAlarmManager.setInexactRepeating(AlarmManager.RTC, now, 300, mPendingIntent);
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Toast.makeText(getApplicationContext(), "Callback Successed!", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent)
{
return null;
}
@Override
public void onDestroy()
{
super.onDestroy();
}
}
| {
"content_hash": "15315650404b8e58a71e164272603436",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 92,
"avg_line_length": 25.340425531914892,
"alnum_prop": 0.7237615449202351,
"repo_name": "andyiac/PermanentService",
"id": "0d34824ea36ce9baeadb00b8f9cd0896c207f224",
"size": "1191",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/com/jacky/permanent/MyService.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "2966"
}
],
"symlink_target": ""
} |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using log4net.Appender;
using log4net.Core;
using log4net.Repository;
namespace log4net.Util
{
/// <summary>
/// Keep appenders and logging busy with occasional "Alive" notice
/// </summary>
/// <remarks>
/// <para>
/// This may serve to:
///
/// * force roll over of files even with little logging,
/// * maintain and track application instances health
///
/// </para>
/// <para>
/// A single thread does the time scheduling and calling.
/// It is implemented as a static singleton.
/// Appenders can be <see cref="Manage"/>d and <see cref="Release"/>d.
/// When at least one appender is managed, thread executes. Otherwise it stops.
/// </para>
/// <para>
/// </para>
/// It's made to be thread safe.
/// The code locks <see cref="m_control_locker"/> to synchronize, wait and pulse.
/// Additionally the code locks the <see cref="m_calls_locker"/> for any operation with appenders.
/// </remarks>
/// <author>Robert Sevcik</author>
public sealed class KeepAlive : IDisposable
{
/// <summary>
/// The only single static instance of this class
/// </summary>
public static readonly KeepAlive Instance = new KeepAlive();
/// <summary>
/// Let a callback be called by KeepAlive regularly;
/// </summary>
/// <param name="alivecall">callback to be called</param>
/// <param name="interval">how often</param>
public void Manage(AliveCall alivecall, int interval)
{
lock (m_control_locker)
{
lock (m_calls_locker)
{
m_calls[alivecall] = MakeConfig(alivecall, interval);
}
if (!m_stop) Start();
Monitor.PulseAll(m_control_locker);
}
}
/// <summary>
/// Stop managing an appender
/// </summary>
/// <param name="alivecall">callback to be released</param>
public void Release(AliveCall alivecall)
{
lock (m_control_locker)
{
lock (m_calls_locker)
{
m_calls.Remove(alivecall);
}
Monitor.PulseAll(m_control_locker);
}
}
/// <summary>
/// Used to lock operations on this (Start, Stop, Manage, Release)
/// </summary>
readonly object m_control_locker = new object();
/// <summary>
/// Used to lock operations on <see cref="m_calls"/>
/// </summary>
readonly object m_calls_locker = new object();
/// <summary>
/// Internal appender and config store
/// </summary>
readonly IDictionary<AliveCall, Config> m_calls = new Dictionary<AliveCall, Config>();
/// <summary>
/// The Alive thread
/// </summary>
Thread m_thread;
/// <summary>
/// flag indication that <see cref="Run"/> should terminate.
/// </summary>
bool m_stop;
/// <summary>
/// Initiate the <see cref="Run"/> loop
/// </summary>
private void Start()
{
lock (m_control_locker)
{
if (m_thread == null || !m_thread.IsAlive)
{
m_thread = new Thread(Run);
m_thread.Name = String.Format("{0}-{1}", typeof(KeepAlive).Name, m_thread.ManagedThreadId);
m_thread.IsBackground = true;
m_thread.Start();
}
}
}
/// <summary>
/// This is fatal.
/// </summary>
public void Stop()
{
lock (m_control_locker)
{
m_stop = true;
Monitor.PulseAll(m_control_locker);
}
if (m_thread != null && m_thread.IsAlive)
{
m_thread.Join();
}
}
/// <summary>
/// Loop as long as not <see cref="m_stop"/>
/// </summary>
private void Run()
{
var maxSnooze = TimeSpan.FromMilliseconds(500);
try
{
lock (m_control_locker)
{
while (!m_stop)
{
while (!m_stop && m_calls.Count == 0)
{
// suspend activity if there's nothing to do
Monitor.Wait(m_control_locker, maxSnooze);
Monitor.PulseAll(m_control_locker);
}
if (m_stop) break;
var snooze = ExecuteSchedule(maxSnooze);
Monitor.Wait(m_control_locker, snooze);
Monitor.PulseAll(m_control_locker);
}
}
}
catch (Exception x)
{
m_stop = true;
LogLog.Error(GetType(), "Alive.Run() failed.", x);
}
finally
{
LogLog.Warn(GetType(), "Alive.Run() finished.");
}
}
private TimeSpan ExecuteSchedule(TimeSpan maxSnooze)
{
var now = DateTime.UtcNow;
var waketime = now + maxSnooze;
var scheduledConfigs = new List<Config>();
lock (m_calls_locker)
{
foreach (var config in m_calls.Values)
{
if (now.AddMilliseconds(10) >= config.Schedule)
{
scheduledConfigs.Add(config);
// round to a multiple of interval with an offset
var wake_ms = (now - s_refdt).TotalMilliseconds + config.Interval + 10;
wake_ms -= wake_ms % config.Interval;
wake_ms = Math.Round(wake_ms) + config.Offset;
// set new schedule
config.Schedule = s_refdt.AddMilliseconds(wake_ms);
}
if (waketime > config.Schedule) waketime = config.Schedule;
}
}
// execute scheduled actions
foreach (var config in scheduledConfigs) MakeCall(config);
var snooze = waketime - DateTime.UtcNow;
if (snooze < TimeSpan.Zero) return TimeSpan.Zero;
if (snooze > maxSnooze) return maxSnooze;
return snooze;
}
private void MakeCall(Config config)
{
try
{
config.Call();
}
catch (Exception x)
{
if (!config.ExceptionLogged)
{
config.ExceptionLogged = true;
LogLog.Error(GetType(), "Exception in Alive.MakeCall(). Further exceptions will not be logged for this call.", x);
}
}
}
void IDisposable.Dispose()
{
Stop();
}
Config MakeConfig(AliveCall alivecall, int interval)
{
var config = new Config()
{
Interval = interval,
Schedule = DateTime.Today,
Call = alivecall
};
if (config.Interval <= 0)
config.Interval = 60000;
while (config.Offset == 0)
config.Offset = new Random((int)(DateTime.Now.Ticks % int.MaxValue)).Next(config.Interval);
return config;
}
/// <summary>
/// Per-appender config structure
/// </summary>
private class Config
{
/// <summary>
/// Interval to keep alive with
/// </summary>
public int Interval;
/// <summary>
/// Offset to the interval.
/// </summary>
/// <remarks>
/// Randomize the logging time so that if many apps log come together, they don't compete too much.
/// Still keep the regular interval.
/// </remarks>
public int Offset;
/// <summary>
/// Next run schedule
/// </summary>
public DateTime Schedule;
/// <summary>
/// This call has been problematic. This helps reduce verbosity in case of permanent failure.
/// </summary>
public bool ExceptionLogged;
/// <summary>
/// The AliveCall delegate to be called
/// </summary>
public AliveCall Call;
}
/// <summary>
/// Alive call action delegate
/// </summary>
public delegate void AliveCall();
private static readonly DateTime s_refdt = DateTime.ParseExact("1970", "yyyy", CultureInfo.InvariantCulture);
}
}
| {
"content_hash": "14f59494622e162d6a40c6e173a1ec4c",
"timestamp": "",
"source": "github",
"line_count": 318,
"max_line_length": 134,
"avg_line_length": 32.25157232704402,
"alnum_prop": 0.484399375975039,
"repo_name": "robajz/log4net.Ext.Json",
"id": "0968a9668be1db93fa9e62dc850981e22696fb86",
"size": "10258",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "log4net.Ext.Json/Util/KeepAlive.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "218416"
},
{
"name": "Shell",
"bytes": "1662"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<!-- Generated with http://android-holo-colors.com -->
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="AppTheme" parent="@style/_AppTheme"/>
<style name="_AppTheme" parent="android:Theme.Holo.Light">
<item name="android:editTextBackground">@drawable/apptheme_edit_text_holo_light</item>
<item name="android:textColorHighlight">#99afcca6</item>
<item name="android:textSelectHandleLeft">@drawable/apptheme_text_select_handle_left</item>
<item name="android:textSelectHandleRight">@drawable/apptheme_text_select_handle_right</item>
<item name="android:textSelectHandle">@drawable/apptheme_text_select_handle_middle</item>
<item name="android:autoCompleteTextViewStyle">@style/AutoCompleteTextViewAppTheme</item>
<item name="android:listChoiceIndicatorMultiple">@drawable/apptheme_btn_check_holo_light</item>
<item name="android:listChoiceIndicatorSingle">@drawable/apptheme_btn_radio_holo_light</item>
<item name="android:buttonStyle">@style/ButtonAppTheme</item>
<item name="android:imageButtonStyle">@style/ImageButtonAppTheme</item>
<item name="android:dropDownSpinnerStyle">@style/SpinnerAppTheme</item>
<item name="android:progressBarStyleHorizontal">@style/ProgressBarAppTheme</item>
<item name="android:seekBarStyle">@style/SeekBarAppTheme</item>
<item name="android:ratingBarStyle">@style/RatingBarAppTheme</item>
<item name="android:ratingBarStyleIndicator">@style/RatingBarBigAppTheme</item>
<item name="android:ratingBarStyleSmall">@style/RatingBarSmallAppTheme</item>
<item name="android:buttonStyleToggle">@style/ToggleAppTheme</item>
<item name="android:listChoiceBackgroundIndicator">@drawable/apptheme_list_selector_holo_light</item>
<item name="android:activatedBackgroundIndicator">@drawable/apptheme_activated_background_holo_light</item>
<item name="android:fastScrollThumbDrawable">@drawable/apptheme_fastscroll_thumb_holo</item>
</style>
</resources> | {
"content_hash": "3d0c07c4a528592172b0aa3de3f4f973",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 111,
"avg_line_length": 41.89795918367347,
"alnum_prop": 0.7622990745250853,
"repo_name": "jquintus/spikes",
"id": "61151ba9e728ac0b38272884b29206f4e1c388f5",
"size": "2053",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "XamarinSpikes/ShoppingCart/ShoppingCart/ShoppingCart.Android/Resources/values-v11/themes_apptheme.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "109"
},
{
"name": "C#",
"bytes": "814163"
},
{
"name": "CSS",
"bytes": "513"
},
{
"name": "Gherkin",
"bytes": "759"
},
{
"name": "HTML",
"bytes": "5127"
},
{
"name": "Java",
"bytes": "21060"
},
{
"name": "JavaScript",
"bytes": "10714"
},
{
"name": "Pascal",
"bytes": "48546"
}
],
"symlink_target": ""
} |
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using FluentAssertions.Execution;
namespace FluentAssertions.Primitives;
/// <summary>
/// Contains a number of methods to assert that a <see cref="HttpResponseMessage"/> is in the expected state.
/// </summary>
[DebuggerNonUserCode]
public class HttpResponseMessageAssertions : HttpResponseMessageAssertions<HttpResponseMessageAssertions>
{
public HttpResponseMessageAssertions(HttpResponseMessage value)
: base(value)
{
}
}
/// <summary>
/// Contains a number of methods to assert that a <see cref="HttpResponseMessage" /> is in the expected state.
/// </summary>
[DebuggerNonUserCode]
public class HttpResponseMessageAssertions<TAssertions> : ObjectAssertions<HttpResponseMessage, TAssertions>
where TAssertions : HttpResponseMessageAssertions<TAssertions>
{
protected HttpResponseMessageAssertions(HttpResponseMessage value)
: base(value)
{
}
/// <summary>
/// Asserts that the <see cref="HttpStatusCode"/> is successful (2xx).
/// </summary>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> BeSuccessful(string because = "", params object[] becauseArgs)
{
var success = Execute.Assertion
.ForCondition(Subject is not null)
.BecauseOf(because, becauseArgs)
.FailWith("Expected HttpStatusCode to be successful (2xx){reason}, but HttpResponseMessage was <null>.");
if (success)
{
Execute.Assertion
.ForCondition(Subject!.IsSuccessStatusCode)
.BecauseOf(because, becauseArgs)
.FailWith("Expected HttpStatusCode to be successful (2xx){reason}, but found {0}.", Subject.StatusCode);
}
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that the <see cref="HttpStatusCode"/> is redirection (3xx).
/// </summary>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> BeRedirection(string because = "", params object[] becauseArgs)
{
var success = Execute.Assertion
.ForCondition(Subject is not null)
.BecauseOf(because, becauseArgs)
.FailWith("Expected HttpStatusCode to be redirection (3xx){reason}, but HttpResponseMessage was <null>.");
if (success)
{
Execute.Assertion
.ForCondition((int)Subject!.StatusCode is >= 300 and <= 399)
.BecauseOf(because, becauseArgs)
.FailWith("Expected HttpStatusCode to be redirection (3xx){reason}, but found {0}.", Subject.StatusCode);
}
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that the <see cref="HttpStatusCode"/> is either client (4xx) or server error (5xx).
/// </summary>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> HaveError(string because = "", params object[] becauseArgs)
{
var success = Execute.Assertion
.ForCondition(Subject is not null)
.BecauseOf(because, becauseArgs)
.FailWith("Expected HttpStatusCode to be an error{reason}, but HttpResponseMessage was <null>.");
if (success)
{
Execute.Assertion
.ForCondition(IsClientError() || IsServerError())
.BecauseOf(because, becauseArgs)
.FailWith("Expected HttpStatusCode to be an error{reason}, but found {0}.", Subject.StatusCode);
}
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that the <see cref="HttpStatusCode"/> is client error (4xx).
/// </summary>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> HaveClientError(string because = "", params object[] becauseArgs)
{
var success = Execute.Assertion
.ForCondition(Subject is not null)
.BecauseOf(because, becauseArgs)
.FailWith("Expected HttpStatusCode to be client error (4xx){reason}, but HttpResponseMessage was <null>.");
if (success)
{
Execute.Assertion
.ForCondition(IsClientError())
.BecauseOf(because, becauseArgs)
.FailWith("Expected HttpStatusCode to be client error (4xx){reason}, but found {0}.", Subject.StatusCode);
}
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that the <see cref="HttpStatusCode"/> is server error (5xx).
/// </summary>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> HaveServerError(string because = "", params object[] becauseArgs)
{
var success = Execute.Assertion
.ForCondition(Subject is not null)
.BecauseOf(because, becauseArgs)
.FailWith("Expected HttpStatusCode to be server error (5xx){reason}, but HttpResponseMessage was <null>.");
if (success)
{
Execute.Assertion
.ForCondition(IsServerError())
.BecauseOf(because, becauseArgs)
.FailWith("Expected HttpStatusCode to be server error (5xx){reason}, but found {0}.", Subject.StatusCode);
}
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that the <see cref="HttpStatusCode"/> is equal to the specified <paramref name="expected"/> value.
/// </summary>
/// <param name="expected">The expected value</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because" />.
/// </param>
public AndConstraint<TAssertions> HaveStatusCode(HttpStatusCode expected, string because = "", params object[] becauseArgs)
{
var success = Execute.Assertion
.ForCondition(Subject is not null)
.BecauseOf(because, becauseArgs)
.FailWith("Expected HttpStatusCode to be {0}{reason}, but HttpResponseMessage was <null>.", expected);
if (success)
{
Execute.Assertion
.ForCondition(Subject!.StatusCode == expected)
.BecauseOf(because, becauseArgs)
.FailWith("Expected HttpStatusCode to be {0}{reason}, but found {1}.", expected, Subject.StatusCode);
}
return new AndConstraint<TAssertions>((TAssertions)this);
}
/// <summary>
/// Asserts that the <see cref="HttpStatusCode"/> is not equal to the specified <paramref name="unexpected"/> value.
/// </summary>
/// <param name="unexpected">The unexpected value</param>
/// <param name="because">
/// A formatted phrase as is supported by <see cref="string.Format(string,object[])" /> explaining why the assertion
/// is needed. If the phrase does not start with the word <i>because</i>, it is prepended automatically.
/// </param>
/// <param name="becauseArgs">
/// Zero or more objects to format using the placeholders in <paramref name="because"/>.
/// </param>
public AndConstraint<TAssertions> NotHaveStatusCode(HttpStatusCode unexpected, string because = "", params object[] becauseArgs)
{
var success = Execute.Assertion
.ForCondition(Subject is not null)
.BecauseOf(because, becauseArgs)
.FailWith("Expected HttpStatusCode not to be {0}{reason}, but HttpResponseMessage was <null>.", unexpected);
if (success)
{
Execute.Assertion
.ForCondition(Subject!.StatusCode != unexpected)
.BecauseOf(because, becauseArgs)
.FailWith("Expected HttpStatusCode not to be {0}{reason}, but found {1}.", unexpected, Subject.StatusCode);
}
return new AndConstraint<TAssertions>((TAssertions)this);
}
private bool IsServerError() => (int)Subject.StatusCode is >= 500 and <= 599;
private bool IsClientError() => (int)Subject.StatusCode is >= 400 and <= 499;
protected override string Identifier => "HTTP response message";
}
| {
"content_hash": "ec14306cd5c4bb45f20a7c4dd9836623",
"timestamp": "",
"source": "github",
"line_count": 235,
"max_line_length": 132,
"avg_line_length": 44.170212765957444,
"alnum_prop": 0.6436416184971099,
"repo_name": "jnyrup/fluentassertions",
"id": "5132d56eb627b799e25dc108ef2fdf0582d710ef",
"size": "10382",
"binary": false,
"copies": "3",
"ref": "refs/heads/develop",
"path": "Src/FluentAssertions/Primitives/HttpResponseMessageAssertions.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "304"
},
{
"name": "C#",
"bytes": "4597564"
},
{
"name": "PowerShell",
"bytes": "4155"
},
{
"name": "Shell",
"bytes": "3102"
}
],
"symlink_target": ""
} |
from werkzeug.utils import cached_property
from flask import json
from flask.testing import FlaskClient
from .repr import repr_str_short
class TestResponseMixin(object):
@cached_property
def json(self):
return json.loads(self.data)
@cached_property
def content(self):
return self.data.decode(self.charset)
def __repr__(self, full=False):
content = self.content if full else repr_str_short(self.content, 128)
return '<Response {}: {}>'.format(self.status, content)
class TestClient(FlaskClient):
def open(self, *args, **kwargs):
if 'json' in kwargs:
kwargs['data'] = json.dumps(kwargs.pop('json'))
kwargs['content_type'] = 'application/json'
return super(TestClient, self).open(*args, **kwargs)
def register_test_helpers(app):
if not issubclass(app.response_class, TestResponseMixin):
class TestResponse(TestResponseMixin, app.response_class):
pass
app.response_class = TestResponse
app.test_client_class = TestClient
def check_gevent_concurrency(sleep='time.sleep', callback=None):
if isinstance(sleep, str):
module = __import__(''.join(sleep.split('.')[:-1]))
sleep = getattr(module, sleep.split('.')[-1])
callback = callback or (lambda x: print('concurrency={}'.format(x)))
check_gevent_concurrency._flag = False
def _set_concurrency():
sleep(0.01)
check_gevent_concurrency._flag = True
def _check_concurrency():
sleep(0.02)
callback(check_gevent_concurrency._flag)
import gevent
gevent.joinall([
gevent.spawn(_check_concurrency),
gevent.spawn(_set_concurrency),
])
| {
"content_hash": "162ae9e387947a80ca750fc8430f0f5b",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 77,
"avg_line_length": 29.5,
"alnum_prop": 0.6469900642898889,
"repo_name": "vgavro/flask-vgavro-utils",
"id": "37245fa1a444389310415d92230eee8ae2abfc44",
"size": "1711",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "flask_vgavro_utils/tests.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Python",
"bytes": "79862"
},
{
"name": "Shell",
"bytes": "2338"
}
],
"symlink_target": ""
} |
package org.apache.flink.runtime.rest.handler.legacy.messages;
import org.apache.flink.runtime.rest.messages.RequestBody;
import org.apache.flink.runtime.rest.util.RestMapperUtils;
import org.apache.flink.util.TestLogger;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Assert;
import org.junit.Test;
/**
* Test base for verifying that marshalling / unmarshalling REST {@link RequestBody}s work properly.
*/
public abstract class RestRequestMarshallingTestBase<R extends RequestBody> extends TestLogger {
/**
* Returns the class of the test response.
*
* @return class of the test response type
*/
protected abstract Class<R> getTestRequestClass();
/**
* Returns an instance of a response to be tested.
*
* @return instance of the expected test response
*/
protected abstract R getTestRequestInstance() throws Exception;
/**
* Tests that we can marshal and unmarshal the response.
*/
@Test
public void testJsonMarshalling() throws Exception {
final R expected = getTestRequestInstance();
ObjectMapper objectMapper = RestMapperUtils.getStrictObjectMapper();
JsonNode json = objectMapper.valueToTree(expected);
final R unmarshalled = objectMapper.treeToValue(json, getTestRequestClass());
Assert.assertEquals(expected, unmarshalled);
}
}
| {
"content_hash": "d2ecd3eda293643421c14ee81b9f045e",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 100,
"avg_line_length": 28.851063829787233,
"alnum_prop": 0.7721238938053098,
"repo_name": "PangZhi/flink",
"id": "2eb37cb044e4b71992950837366d7352ce88bda0",
"size": "2161",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "flink-runtime/src/test/java/org/apache/flink/runtime/rest/handler/legacy/messages/RestRequestMarshallingTestBase.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "4792"
},
{
"name": "CSS",
"bytes": "18100"
},
{
"name": "CoffeeScript",
"bytes": "89007"
},
{
"name": "HTML",
"bytes": "86524"
},
{
"name": "Java",
"bytes": "32040257"
},
{
"name": "JavaScript",
"bytes": "8267"
},
{
"name": "Python",
"bytes": "166860"
},
{
"name": "Scala",
"bytes": "5993825"
},
{
"name": "Shell",
"bytes": "95755"
}
],
"symlink_target": ""
} |
/**
* The configuration for the AirConsole constructor.
* @typedef {object} AirConsole~Config
* @property {string} orientation - AirConsole.ORIENTATION_PORTRAIT or
* AirConsole.ORIENTATION_LANDSCAPE.
* @property {boolean|undefined} synchronize_time - If set to true, you can
* call getServerTime() to get the time on the game server.
* Default is false.
* @property {boolean|undefiend} setup_document - Sets up the document so
* nothing is selectable, zoom is fixed to 1 and scrolling is
* disabled (iOS 8 clients drop out of fullscreen when scrolling).
* Default: true
* @property {number|undefined} device_motion - If set, onDeviceMotion gets
* called every "device_motion" milliseconds with data from the
* accelerometer and the gyroscope. Recommended value: 100.
* Only for controllers.
*/
/**
* Your gateway object to AirConsole.
* There are getter and setter functions for all properties.
* Do not access properties of this object directly.
* @constructor
* @param {AirConsole~Config} opts - Constructor config.
*/
function AirConsole(opts) {
this.init_(opts);
}
/**
* The device ID of the game screen.
* @constant {number}
*/
AirConsole.SCREEN = 0;
/**
* The portrait orientation.
* @constant {string}
*/
AirConsole.ORIENTATION_PORTRAIT = "portrait";
/**
* The landscape orientation.
* @constant {string}
*/
AirConsole.ORIENTATION_LANDSCAPE = "landscape";
/**
* Sends a message to another device.
* @param device_id {number|undefined} - The device ID to send the message to.
* If "device_id" is undefined, the
* message is sent to all devices (except
* this one).
* @param data
*/
AirConsole.prototype.message = function(device_id, data) {
if (this.device_id !== undefined) {
this.postMessage_({ action: "message", to: device_id, data: data });
}
};
/**
* Sends a message to all connected devices.
* @param data
*/
AirConsole.prototype.broadcast = function(data) {
this.message(undefined, data);
};
/**
* Gets called when the game console is ready.
* This event also also fires onConnect for all devices that already are
* connected and have loaded your game.
* This event also fires onCustomDeviceStateChange for all devices that are
* connected, have loaded your game and have set a custom Device State.
* @abstract
* @param {string} code - The AirConsole join code.
*/
AirConsole.prototype.onReady = function(code) {};
/**
* Gets called when a device has connected and loaded the game.
* @abstract
* @param {number} device_id - the device ID that loaded the game.
*/
AirConsole.prototype.onConnect = function(device_id) {};
/**
* Gets called when a device has left the game.
* @abstract
* @param {number} device_id - the device ID that left the game.
*/
AirConsole.prototype.onDisconnect = function(device_id) {};
/**
* Gets called when a message is received from another device
* that called message() or broadcast().
* If you dont want to parse messages yourself and prefer an event driven
* approach, have a look at http://github.com/AirConsole/airconsole-events/
* @abstract
* @param {number} device_id - The device ID that sent the message.
* @param {serializable} data - The data that was sent.
*/
AirConsole.prototype.onMessage = function(device_id, data) {};
/**
* Gets called when a device updates it's custom DeviceState
* by calling setCustomDeviceState or setCustomDeviceStateProperty.
* Make sure you understand the power of device states:
* http://developers.airconsole.com/#/guides/device_ids_and_states
* @abstract
* @param {number} device_id - the device ID that changed its custom
* DeviceState.
* @param {Object} custom_data - The custom DeviceState data value
*/
AirConsole.prototype.onCustomDeviceStateChange = function(device_id,
custom_data) {};
/**
* Gets called when a device updates it's profile pic, nickname or email.
* @abstract
* @param {number} device_id - The device_id that changed its profile.
*/
AirConsole.prototype.onDeviceProfileChange = function(device_id) {};
/**
* Gets called when a device joins/leaves a game session or updates its
* DeviceState (custom DeviceState, profile pic, nickname, internal state).
* This is function is also called every time onConnect, onDisconnect or
* onCustomDeviceStateChange, onDeviceProfileChange is called.
* It's like their root function.
* @abstract
* @param {number} device_id - the device_id that changed its DeviceState.
* @param user_data {AirConsole~DeviceState} - the data of that device.
* If undefined, the device has left.
*/
AirConsole.prototype.onDeviceStateChange = function(device_id, device_data) {};
/**
* Gets called if the request of requestEmailAddress() was granted.
* For privacy reasons, you need to whitelist your game in order to receive
* the email address of the user. To whitelist your game, contact
* developers@airconsole.com. For development purposes, localhost is always
* allowed.
* @abstract
* @param {string|undefined} email_address - The email address of the user if
* it was set.
*/
AirConsole.prototype.onEmailAddress = function(email_address) {};
/**
* Gets called every X milliseconds with device motion data iff the
* AirConsole was instantiated with the "device_motion" opts set to the
* interval in milliseconds. Only works for controllers.
* Note: Some browsers do not allow games to access accelerometer and gyroscope
* in an iframe (your game). So use this method if you need gyroscope
* or accelerometer data.
* @abstract
* @param {object} data - data.x, data.y, data.z for accelerometer
* data.alpha, data.beta, data.gamma for gyroscope
*/
AirConsole.prototype.onDeviceMotion = function(data) {};
/**
* Gets called when the screen sets the active players by calling
* setActivePlayers().
* @abstract
* @param {number|undefined} player_number - The player number of this device.
* Can be undefined if this device
* is not part of the active players.
*/
AirConsole.prototype.onActivePlayersChange = function(player_number) {};
/**
* Takes all currently connected controllers and assigns them a player number.
* Can only be called by the screen. You don't have to use this helper
* function, but this mechanism is very convenient if you want to know which
* device is the first player, the second player, the third player ...
* The assigned player numbers always start with 0 and are consecutive.
* You can hardcode player numbers, but not device_ids.
* Once the screen has called setActivePlayers you can get the device_id of
* the first player by calling convertPlayerNumberToDeviceId(0), the device_id
* of the second player by calling convertPlayerNumberToDeviceId(1), ...
* You can also convert device_ids to player numbers by calling
* convertDeviceIdToPlayerNumber(device_id). You can get all device_ids that
* are active players by calling getActivePlayerDeviceIds().
* The screen can call this function every time a game round starts.
* @param {number} max_players - The maximum number of controllers that should
* get a player number assigned.
*/
AirConsole.prototype.setActivePlayers = function(max_players) {
if (this.getDeviceId() != AirConsole.SCREEN) {
throw "Only the AirConsole.SCREEN can set the active players!";
}
this.device_id_to_player_cache = undefined;
var players = this.getControllerDeviceIds();
if (max_players !== undefined) {
players = players.slice(0, Math.min(players.length, max_players));
}
this.devices[AirConsole.SCREEN]["players"] = players;
this.set_("players", players);
};
/**
* Returns an array of device_ids of the active players previously set by the
* screen by calling setActivePlayers. The first device_id in the array is the
* first player, the second device_id in the array is the second player, ...
* @returns {Array}
*/
AirConsole.prototype.getActivePlayerDeviceIds = function() {
return this.devices[AirConsole.SCREEN]["players"] || [];
}
/**
* Returns the device_id of a player, if the player is part of the active
* players previously set by the screen by calling setActivePlayers. If fewer
* players are in the game than the passed in player_number or the active
* players have not been set by the screen, this function returns undefined.
* @param player_number
* @returns {number|undefined}
*/
AirConsole.prototype.convertPlayerNumberToDeviceId = function(player_number) {
return this.getActivePlayerDeviceIds()[player_number];
};
/**
* Returns the player number for a device_id, if the device_id is part of the
* active players previously set by the screen by calling setActivePlayers.
* Player numbers are zero based and are consecutive. If the device_id is not
* part of the active players, this function returns undefined.
* @param device_id
* @returns {number|undefined}
*/
AirConsole.prototype.convertDeviceIdToPlayerNumber = function(device_id) {
if (!this.device_id_to_player_cache) {
this.device_id_to_player_cache = {};
var players = this.devices[AirConsole.SCREEN]["players"];
for (var i = 0; i < players.length; ++i) {
this.device_id_to_player_cache[players[i]] = i;
}
}
return this.device_id_to_player_cache[device_id];
};
/**
* Returns the device_id of this device.
* Every device in an AirConsole session has a device_id.
* The screen always has device_id 0. You can use the AirConsole.SCREEN
* constant instead of 0.
* All controllers also get a device_id. You can NOT assume that the device_ids
* of controllers are consecutive or that they start at 1.
*
* DO NOT HARDCODE CONTROLLER DEVICE IDS!
*
* If you want to have a logic with "players numbers" (Player 0, Player 1,
* Player 2, Player 3) use the setActivePlayers helper function! You can
* hardcode player numbers, but not device_ids.
*
* Within an AirConsole session, devices keep the same device_id when they
* disconnect and reconnect. Different controllers will never get the same
* device_id in a session. Every device_id remains reserved for the device that
* originally got it.
*
* For more info read
* http:// developers.airconsole.com/#/guides/device_ids_and_states
*
* @return {number}
*/
AirConsole.prototype.getDeviceId = function() {
return this.device_id;
};
/**
* Returns the globally unique id of a device.
* @param {number|undefined} device_id - The device id for which you want the
* uid. Default is this device.
* @return {string|undefined}
*/
AirConsole.prototype.getUID = function(device_id) {
if (device_id === undefined) {
device_id = this.device_id;
}
var device_data = this.devices[device_id];
if (device_data) {
return device_data.uid;
}
};
/**
* Returns the nickname of a user.
* @param {number|undefined} device_id - The device id for which you want the
* nickname. Default is this device.
* Screens don't have nicknames.
* @return {string|undefined}
*/
AirConsole.prototype.getNickname = function(device_id) {
if (device_id === undefined) {
device_id = this.device_id;
}
var device_data = this.devices[device_id];
if (device_data) {
return device_data.nickname || ("Guest " + device_id);
}
};
/**
* Returns the url to a profile picture of the user.
* @param {number|undefined} device_id - The device id for which you want the
* profile picture. Default is this
* device. Screens don't have profile
* pictures.
* @param {number|undefined} size - The size of in pixels of the picture.
* Default is 64.
* @return {string|undefined}
*/
AirConsole.prototype.getProfilePicture = function(device_id, size) {
if (device_id === undefined) {
device_id = this.device_id;
}
var device_data = this.devices[device_id];
if (device_data) {
var url = "https://www.airconsole.com/api/profile-picture?uid=" +
device_data.uid + "&size=" + (size||64);
if (device_data.picture) {
url += "&v=" + device_data.picture;
}
return url;
}
};
/**
* Returns the device ID of the master controller.
* @return {number|undefined}
*/
AirConsole.prototype.getMasterControllerDeviceId = function() {
return this.getControllerDeviceIds()[0];
};
/**
* Returns all controller device ids that have loaded your game.
* @return {Array}
*/
AirConsole.prototype.getControllerDeviceIds = function() {
var result = [];
var game_url = this.getGameUrl_(document.location.href);
for (var i = AirConsole.SCREEN + 1; i < this.devices.length; ++i) {
if (this.devices[i] &&
this.getGameUrl_(this.devices[i].location) == game_url) {
result.push(i);
}
}
return result;
};
/**
* Returns the current time of the game server.
* This allows you to have a synchronized clock: You can send the server
* time in a message to know exactly at what point something happened on a
* device. This function can only be called if the AirConsole was instantiated
* with the "synchronize_time" opts set to true and after onReady was called.
* @return {number} Timestamp in milliseconds.
*/
AirConsole.prototype.getServerTime = function() {
if (this.server_time_offset === false) {
throw "AirConsole constructor was not called with " +
"{synchronize_time: true}";
}
return new Date().getTime() + this.server_time_offset;
};
/**
* Gets the custom DeviceState of a device.
* @param {number|undefined} device_id - The device ID of which you want the
* custom state. Default is this device.
* @return {Object|undefined} The custom data previously set by the device.
*/
AirConsole.prototype.getCustomDeviceState = function(device_id) {
if (device_id === undefined) {
device_id = this.device_id;
}
var device_data = this.devices[device_id];
if (device_data && this.getGameUrl_(document.location.href) ==
this.getGameUrl_(device_data.location)) {
return device_data["custom"];
}
};
/**
* Sets the custom DeviceState of this device.
* @param {Object} data - The custom data to set.
*/
AirConsole.prototype.setCustomDeviceState = function(data) {
if (this.device_id !== undefined) {
this.devices[this.device_id]["custom"] = data;
this.set_("custom", data);
}
};
/**
* Sets a property in the custom DeviceState of this device.
* @param {String} key - The property name.
* @param {mixed} value - The property value.
*/
AirConsole.prototype.setCustomDeviceStateProperty = function(key, value) {
if (this.device_id !== undefined) {
var state = this.getCustomDeviceState();
if (state === undefined) {
state = {};
} else if (typeof state !== "object") {
throw "Custom DeviceState needs to be of type object";
}
state[key] = value;
this.setCustomDeviceState(state);
}
};
/**
* Request that all devices return to the AirConsole store.
*/
AirConsole.prototype.navigateHome = function() {
this.set_("home", true);
};
/**
* Request that all devices load a game by url.
*/
AirConsole.prototype.navigateTo = function(url) {
this.set_("home", url);
};
/**
* Shows or hides the default UI.
* @param {boolean} visible - Whether to show or hide the default UI.
*/
AirConsole.prototype.showDefaultUI = function(visible) {
this.set_("default_ui", visible);
};
/**
* Sets the device orientation.
* @param {string} orientation - AirConsole.ORIENTATION_PORTRAIT or
* AirConsole.ORIENTATION_LANDSCAPE.
*/
AirConsole.prototype.setOrientation = function(orientation) {
this.set_("orientation", orientation);
};
/**
* Requests the email address of this device and calls onEmailAddress iff the
* request was granted. For privacy reasons, you need to whitelist your
* game in order to receive the email address of the user. To whitelist your
* game, contact developers@airconsole.com. For development purposes, localhost
* is always allowed.
*/
AirConsole.prototype.requestEmailAddress = function() {
this.set_("email", true);
};
/**
* Returns true if a user is logged in.
* @param {number|undefined} device_id - The device_id of the user.
* Default is this device.
* @returns {boolean}
*/
AirConsole.prototype.isUserLoggedIn = function(device_id) {
if (device_id == undefined) {
device_id = this.device_id;
}
var data = this.devices[device_id];
if (data) {
return data.auth;
}
}
/**
* Lets the user change his nickname, profile picture and email address.
* If you need a real nickname of the user, use this function.
* onDeviceProfileChange will be called if the user logs in.
*/
AirConsole.prototype.editProfile = function() {
this.set_("login", true);
};
/**
* DeviceState contains information about a device in this session.
* Use the helper methods getUID, getNickname, getProfilePicture and
* getCustomDeviceState to access this data.
* @typedef {object} AirConsole~DeviceState
* @property {string} uid - The globally unique ID of the user.
* @property {string|undefined} custom - Custom device data that this API can
* set.
* @property {string|undefined} nickname - The nickname of the user.
* @property {boolean|undefined} slow_connection - If the user has a high
* server latency.
*/
/* --------------------- ONLY PRIVATE FUNCTIONS BELLOW --------------------- */
/**
* Initializes the AirConsole.
* @param {AirConsole~Config} opts - The Config.
* @private
*/
AirConsole.prototype.init_ = function(opts) {
opts = opts || {};
var me = this;
window.addEventListener('error', function(e) {
var stack = undefined;
if (e.error && e.error.stack) {
stack = e.error.stack;
}
me.postMessage_({
"action": "jserror",
"url": document.location.href,
"exception": {
"message": e.message,
"error": {
"stack": stack
},
"filename": e.filename,
"lineno": e.lineno,
"colno": e.colno
}
});
});
me.version = "1.3.0";
me.devices = [];
me.server_time_offset = opts.synchronize_time ? 0 : false;
window.addEventListener(
"message",
function (event) {
var data = event.data;
var game_url = me.getGameUrl_(document.location.href);
if (data.action == "device_motion") {
me.onDeviceMotion(data.data);
} else if (data.action == "message") {
if (me.device_id !== undefined) {
if (me.devices[data.from] &&
game_url == me.getGameUrl_(me.devices[data.from].location)) {
me.onMessage(data.from, data.data);
}
}
} else if (data.action == "update") {
if (me.device_id !== undefined) {
var game_url_before = null;
var game_url_after = null;
var before = me.devices[data.device_id];
if (before) {
game_url_before = me.getGameUrl_(before.location);
}
if (data.device_data) {
game_url_after = me.getGameUrl_(data.device_data.location);
}
me.devices[data.device_id] = data.device_data;
me.onDeviceStateChange(data.device_id, data.device_data);
if (game_url_before != game_url && game_url_after == game_url) {
me.onConnect(data.device_id);
} else if (game_url_before == game_url &&
game_url_after != game_url) {
me.onDisconnect(data.device_id);
} else if (data.device_data &&
data.device_data._is_custom_update &&
game_url_after == game_url) {
me.onCustomDeviceStateChange(data.device_id,
data.device_data.custom);
} else if (data.device_data &&
data.device_data._is_players_update &&
game_url_after == game_url) {
me.device_id_to_player_cache = null;
me.onActivePlayersChange(me.convertDeviceIdToPlayerNumber(
me.getDeviceId()));
} else if (data.device_data &&
data.device_data._is_profile_update &&
game_url_after == game_url) {
me.onDeviceProfileChange(data.device_id);
}
}
} else if (data.action == "ready") {
me.device_id = data.device_id;
me.devices = data.devices;
if (me.server_time_offset !== false) {
me.server_time_offset = data.server_time_offset || 0;
}
me.onReady(data.code);
var game_url = me.getGameUrl_(document.location.href);
for (var i = 0; i < me.devices.length; ++i) {
if (i != me.getDeviceId() && me.devices[i] &&
me.getGameUrl_(me.devices[i].location) == game_url) {
me.onConnect(i);
var custom_state = me.getCustomDeviceState(i);
if (custom_state !== undefined) {
me.onCustomDeviceStateChange(i, custom_state);
}
}
}
} else if (data.action == "profile") {
if (me.device_id) {
var state = me.devices[me.device_id];
state["auth"] = data.auth;
state["nickname"] = data.nickname;
state["picture"] = data.picture;
me.onDeviceStateChange(me.device_id, state);
me.onDeviceProfileChange(me.device_id);
}
} else if (data.action == "email") {
me.onEmailAddress(data.email);
}
},
false);
this.set_("orientation", opts.orientation);
if (opts.setup_document !== false) {
this.setupDocument_();
}
this.postMessage_({
action: "ready",
version: me.version,
device_motion: opts.device_motion,
synchronize_time: opts.synchronize_time,
location: document.location.href
});
}
/**
* @private
* @param {String} url - A url.
* @return {String} Returns the root game url over http.
*/
AirConsole.prototype.getGameUrl_ = function(url) {
if (!url) {
return;
}
url = url.split("#")[0];
url = url.split("?")[0];
if (url.indexOf("screen.html", url.length - 11) !== -1) {
url = url.substr(0, url.length - 11);
}
if (url.indexOf("controller.html", url.length - 15) !== -1) {
url = url.substr(0, url.length - 15);
}
if (url.indexOf("https://") == 0) {
url = "http://" + url.substr(8);
}
return url;
};
/**
* Posts a message to the parent window.
* @private
* @param {Object} data - the data to be sent to the parent window.
*/
AirConsole.prototype.postMessage_ = function(data) {
try {
window.parent.postMessage(data, document.referrer);
} catch(e) {
console.log("Posting message to parent failed: " + JSON.stringify(data));
}
};
/**
* Sets a variable in the external AirConsole framework.
* @private
* @param {string} key - The key to set.
* @param {serializable} value - The value to set.
*/
AirConsole.prototype.set_ = function(key, value) {
this.postMessage_({ action: "set", key: key, value: value });
};
/**
* Adds default css rules to documents so nothing is selectable, zoom is
* fixed to 1 and preventing scrolling down (iOS 8 clients drop out of
* fullscreen when scrolling).
* @private
*/
AirConsole.prototype.setupDocument_ = function() {
var style = document.createElement("style");
style.type = "text/css";
var css_code =
"html {\n" +
" -ms-touch-action: pan-x;\n" +
"}\n" +
"body {\n" +
" -webkit-touch-callout: none;\n" +
" -webkit-text-size-adjust: none;\n" +
" -ms-text-size-adjust: none;\n" +
" -webkit-user-select: none;\n" +
" -moz-user-select: none;\n" +
" -ms-user-select: none;\n" +
" user-select: none;\n" +
" -webkit-highlight: none;\n" +
" -webkit-tap-highlight-color: rgba(0,0,0,0);\n" +
" -webkit-tap-highlight-color: transparent;\n" +
" -ms-touch-action: pan-y;\n" +
" -ms-content-zooming: none;\n" +
"}\n" +
"\n" +
"input, textarea {\n" +
" -webkit-user-select: text;\n" +
" -moz-user-select: text;\n" +
" -ms-user-select: text;\n" +
" user-select: text;\n" +
"}\n" +
"-ms-@viewport {\n" +
" width: device-width;\n" +
" initial-scale: 1;\n" +
" zoom: 1;\n" +
" min-zoom: 1;\n" +
" max-zoom: 1;\n" +
" user-zoom: fixed;\n" +
"}";
if (style.styleSheet) {
style.styleSheet.cssText = css_code;
} else {
style.appendChild(document.createTextNode(css_code));
}
var meta = document.createElement("meta");
meta.setAttribute("name", "viewport");
meta.setAttribute("content", "width=device-width, minimum-scale=1, " +
"initial-scale=1, user-scalable=no");
var head = document.getElementsByTagName("head")[0];
head.appendChild(meta);
head.appendChild(style);
document.addEventListener('touchmove', function (e) {
e.preventDefault();
});
};
| {
"content_hash": "e2faeabb6bdef38de0a6749db8ac4f07",
"timestamp": "",
"source": "github",
"line_count": 763,
"max_line_length": 79,
"avg_line_length": 33.8519003931848,
"alnum_prop": 0.6316156258469162,
"repo_name": "PeteE/roro",
"id": "a364e96ce338105949a51d7ceefc5962aa985e3b",
"size": "26332",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "python/robot_server/airconsole-controls/airconsole-1.3.0.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Arduino",
"bytes": "2204"
},
{
"name": "C",
"bytes": "3282"
},
{
"name": "C++",
"bytes": "14661"
},
{
"name": "CSS",
"bytes": "6867"
},
{
"name": "HTML",
"bytes": "35046"
},
{
"name": "JavaScript",
"bytes": "105332"
},
{
"name": "Makefile",
"bytes": "416"
},
{
"name": "Processing",
"bytes": "961"
},
{
"name": "Protocol Buffer",
"bytes": "483"
},
{
"name": "Python",
"bytes": "11259"
}
],
"symlink_target": ""
} |
<?php
/**
* @file admin/profile.php
* @brief Update staff information for individual
* @description
*
* @author adarby
* @date Jan 2011
* @todo
*/
use SubjectsPlus\Control\Staff;
use SubjectsPlus\Control\Querier;
$page_title = "Admin::Users";
include("../includes/header.php");
// init
$feedback = "";
$ok_record_id = $_SESSION["staff_id"];
//////////////////
// Record View
//////////////////
if (isset($_POST["submit_record"])) {
// Submit form
$record = new Staff($_POST["staff_id"], "post", TRUE);
//////////////////////////////////
// Is this an insert or an update?
//////////////////////////////////
if ($_POST["staff_id"] == "") {
$record->insertRecord();
$ok_record_id = $record->getRecordId();
} else {
$record->updateRecord("brief");
}
// Show feedback
$feedback = $record->getMessage();
// See query?
//$record->deBug();
} else {
/////////////////////
// Start the record display
////////////////////
$record = new Staff($ok_record_id, '', TRUE);
// show feedback if it isn't already set
if (!$feedback) {
$feedback = $record->getMessage();
}
echo "<div class=\"feedback\">$feedback</div><br /><br />";
}
$record->outputSelfEditForm();
//$record->deBug();
include("../includes/footer.php");
?>
<script type="text/javascript">
var headshot_location = "<?php print $record->getHeadshotLoc(); ?>";
$(function (){
////////////////
// Check Submit
// When the form has been submitted, check required fields
////////////////
$("#new_record").submit( function () {
// If a required field is empty, set zonk to 1, and change the bg colour
// of the offending field
var alerter = 0;
$("*[class*=required_field]").each(function() {
// get contents of string, trim off whitespace
var our_contents = $(this).val();
var our_contents = jQuery.trim(our_contents );
if (our_contents == '') {
$(this).attr("style", "background-color:#FFDFDF");
alerter = 1;
} else {
$(this).attr("style", "background-color:none");
}
return alerter;
});
// Popup warning if required fields not complete
if (alerter == 1) {
alert("<?php print _("You must complete all required form fields."); ?>");
return false;
}
});
//////////////////
// Add red star to labels of required inputs
//////////////////
$("*[class*=required_field]").prevUntil('div', 'span').append('<span style="color: red;">*</span>');
//////////////////
// Make sure that delete was intentional
//////////////////
$('.delete_button').livequery('click', function(event) {
$(this).after('<div class="rec_delete_confirm"><?php print $rusure; ?> <a id="confirm-yes-<?php print $ok_record_id; ?>"><?php print $textyes; ?></a> | <a id="confirm-no"><?php print $textno; ?></a></div>');
return false;
});
$('a[id*=confirm-yes]').livequery('click', function(event) {
var this_record_id = $(this).attr("id").split("-");
var delete_url = "user.php?staff_id=" + this_record_id[2] + "&delete_record=true";
window.location.replace(delete_url);
return false;
});
$('a[id*=confirm-no]')
.livequery('click', function(event) {
$(this).parent().remove();
return false;
});
});
</script>
| {
"content_hash": "80bfa85d4c4057ee87d99cb8777c004d",
"timestamp": "",
"source": "github",
"line_count": 150,
"max_line_length": 220,
"avg_line_length": 24.793333333333333,
"alnum_prop": 0.4845388545307878,
"repo_name": "lalvarezcu/subjectsplus",
"id": "e3b4e478c56ebcae82217ec48433068ed8796d47",
"size": "3719",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "control/admin/profile.php",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "484"
},
{
"name": "CSS",
"bytes": "540300"
},
{
"name": "HTML",
"bytes": "299163"
},
{
"name": "JavaScript",
"bytes": "660508"
},
{
"name": "PHP",
"bytes": "3568283"
}
],
"symlink_target": ""
} |
//
// UIView+KeyboardResizer.h
//
// Created by Toshiro Sugii on 3/1/15.
// Copyright (c) 2015 Toshiro Sugii. All rights reserved.
//
#import <UIKit/UIKit.h>
@protocol UIViewKeyboardResizerDelegate <NSObject>
@optional
- (void)viewWillResize:(UIView *)view;
- (void)viewDidResize:(UIView *)view;
- (void)viewDidTap:(UIView *)view;
@end
@interface UIView (KeyboardResizer)
/**
* Make UIView observing keyboard notifications
*/
- (void)startKeyboardObserver __attribute__((deprecated));
- (void)startKeyboardObserverWithDelegate:(id<UIViewKeyboardResizerDelegate>)delegate __attribute__((deprecated));
- (void)startKeyboardResizerObserver;
- (void)startKeyboardResizerObserverWithDelegate:(id<UIViewKeyboardResizerDelegate>)delegate;
/**
* Stop observing keyboard notifications
* You should call this method before the UIView is released
*/
- (void)stopKeyboardObserver __attribute__((deprecated));
- (void)stopKeyboardResizerObserver;
@end
| {
"content_hash": "333a6ad903a0eaf410cacce1ade0cc34",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 114,
"avg_line_length": 24.641025641025642,
"alnum_prop": 0.7565036420395421,
"repo_name": "rtoshiro/TXViewKeyboardResizer",
"id": "7dfe0a488712cbcd877f13cea8dce9122ff196f1",
"size": "961",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Pod/Classes/UIView+KeyboardResizer.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1301"
},
{
"name": "Objective-C",
"bytes": "122638"
},
{
"name": "Ruby",
"bytes": "3648"
},
{
"name": "Shell",
"bytes": "13836"
}
],
"symlink_target": ""
} |
import difflib
import sys
import pgcs.core.data
import pgcs.core.diff
import pgcs.core.load
core = pgcs.core
import pgcs.html.diff
html = pgcs.html
def get_object_name(object):
return "%s.%s" % (object.namespace.name, object.get_name())
def get_diff_name(diff):
return get_object_name(diff.objects[0])
def _copy_constraint(parent, name, definition):
print "ALTER TABLE %s ADD CONSTRAINT %s %s;" % (parent, name, definition)
def copy_primary_key(parent, object):
columns = [c.name for c in object.columns]
definition = "PRIMARY KEY (%s)" % ", ".join(columns)
_copy_constraint(parent, object.name, definition)
def copy_foreign_key(parent, object):
_copy_constraint(parent, object.name, object.definition)
def copy_check_column_constraint(parent, object):
_copy_constraint(parent, object.name, object.definition)
def alter_check_column_constraint(parent, object):
print "ALTER TABLE %s DROP CONSTRAINT %s;" % (parent, object.name)
copy_check_column_constraint(parent, object)
def copy_unique_column_constraint(parent, object):
_copy_constraint(parent, object.name, object.definition)
copiers = {
core.data.PrimaryKey: copy_primary_key,
core.data.ForeignKey: copy_foreign_key,
core.data.CheckColumnConstraint: copy_check_column_constraint,
core.data.UniqueColumnConstraint: copy_unique_column_constraint,
}
alterers = {
core.data.CheckColumnConstraint: alter_check_column_constraint,
}
def copy_entry(parent, entry):
obj1, obj2 = entry.objects
if obj1 is not None and obj2 is None:
kind = type(obj1)
copier = copiers.get(kind)
if copier:
copier(parent, obj1)
if obj1 is not None and obj2 is not None:
kind = type(obj1)
alterer = alterers.get(kind)
if alterer:
alterer(parent, obj1)
def copy_entries(parent_diff, named_object_list):
parent_name = get_diff_name(parent_diff)
if named_object_list:
for entry in named_object_list.entries:
copy_entry(parent_name, entry)
def create_trigger(parent, object):
print "%s;" % object.description
def drop_trigger(parent, object):
print "DROP TRIGGER %s ON %s;" % (object.name, parent)
def alter_trigger(parent, object):
drop_trigger(parent, object)
create_trigger(parent, object)
def alter_trigger_entries(parent_diff, named_object_list):
parent_name = get_diff_name(parent_diff)
if named_object_list:
for entry in named_object_list.entries:
obj1, obj2 = entry.objects
if obj1 is not None and obj2 is not None:
alter_trigger(parent_name, obj1)
elif obj1 is not None:
create_trigger(parent_name, obj1)
elif obj2 is not None:
drop_trigger(parent_name, obj2)
def copy_table_column(table, object):
definition = "%s.%s" % (object.type.namespace.name, object.type.name)
if object.notnull:
definition += " NOT NULL"
if object.default:
definition += " DEFAULT %s" % object.default
print "ALTER TABLE %s ADD COLUMN %s %s;" % (table, object.name, definition)
def handle_table_columns(table_diff, seq1, seq2):
table_name = get_diff_name(table_diff)
hash1 = [html.diff.NamedHash(o) for o in seq1]
hash2 = [html.diff.NamedHash(o) for o in seq2]
match = difflib.SequenceMatcher(a=hash1, b=hash2)
inserted = {}
deleted = {}
for tag, i1, i2, j1, j2 in match.get_opcodes():
if tag in ("delete", "replace"):
for obj in seq1[i1:i2]:
deleted[obj.name] = obj
elif tag == "insert":
for obj in seq2[j1:j2]:
inserted[obj.name] = obj
for name, obj in deleted.iteritems():
if name not in inserted:
copy_table_column(table_name, obj)
def handle_table(diff):
if diff.columns:
handle_table_columns(diff, *diff.columns.lists)
copy_entries(diff, diff.constraints)
alter_trigger_entries(diff, diff.triggers)
def handle_function(diff):
if diff.source1:
obj1, obj2 = diff.objects
if obj1 is not None and obj2 is not None:
for referer in obj2.xrefs:
assert isinstance(referer, core.data.Trigger)
drop_trigger(get_object_name(referer.table), referer)
name = get_object_name(obj2)
print "DROP FUNCTION %s;" % name
print "CREATE FUNCTION %s ... ADD CODE HERE ... ;" % name
print "ALTER FUNCTION %s OWNER TO galleria;" % get_object_name(obj2)
for referer in obj2.xrefs:
create_trigger(get_object_name(referer.table), referer)
handlers = {
# core.diff.Function: handle_function,
core.diff.Table: handle_table,
}
def get_entries(named_object_list):
if named_object_list:
return named_object_list.entries
else:
return []
def get_diff(entry):
obj1, obj2 = entry.diff.objects
if obj1 is not None and obj2 is not None:
return entry.diff
else:
return None
def _get_diffs(diff):
for entry in get_entries(diff.languages):
yield get_diff(entry)
for entry in get_entries(diff.namespaces):
for seq in (entry.diff.types,
entry.diff.indexes,
entry.diff.tables,
entry.diff.views,
entry.diff.sequences,
entry.diff.functions):
for e in get_entries(seq):
yield get_diff(e)
def get_diffs(diff):
for diff in _get_diffs(diff):
if diff is not None:
yield diff
def main():
source, target = sys.argv[1:]
databases = core.load.load_databases([source, target])
diff_tree = core.diff.diff_databases(databases)
for diff in get_diffs(diff_tree):
kind = type(diff)
handler = handlers.get(kind)
if handler:
handler(diff)
if __name__ == "__main__":
main()
| {
"content_hash": "9aeeb767d4bb3aee25a52deffd3edc8f",
"timestamp": "",
"source": "github",
"line_count": 199,
"max_line_length": 76,
"avg_line_length": 26.814070351758794,
"alnum_prop": 0.704272863568216,
"repo_name": "somia/pgcs",
"id": "0159e28aee588fc8c2ac8045c198cbbc8c0f7f71",
"size": "5336",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pgcs/tool/alter.py",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="lang:clipboard.copy" content="Copy to clipboard">
<meta name="lang:clipboard.copied" content="Copied to clipboard">
<meta name="lang:search.language" content="en">
<meta name="lang:search.pipeline.stopwords" content="True">
<meta name="lang:search.pipeline.trimmer" content="True">
<meta name="lang:search.result.none" content="No matching documents">
<meta name="lang:search.result.one" content="1 matching document">
<meta name="lang:search.result.other" content="# matching documents">
<meta name="lang:search.tokenizer" content="[\s\-]+">
<link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin>
<link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet">
<style>
body,
input {
font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif
}
code,
kbd,
pre {
font-family: "Roboto Mono", "Courier New", Courier, monospace
}
</style>
<link rel="stylesheet" href="../_static/stylesheets/application.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/>
<link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/>
<link rel="stylesheet" href="../_static/fonts/material-icons.css"/>
<meta name="theme-color" content="#3f51b5">
<script src="../_static/javascripts/modernizr.js"></script>
<title>statsmodels.base.distributed_estimation.DistributedResults.pvalues — statsmodels</title>
<link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png">
<link rel="manifest" href="../_static/icons/site.webmanifest">
<link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191">
<meta name="msapplication-TileColor" content="#2b5797">
<meta name="msapplication-config" content="../_static/icons/browserconfig.xml">
<link rel="stylesheet" href="../_static/stylesheets/examples.css">
<link rel="stylesheet" href="../_static/stylesheets/deprecation.css">
<link rel="stylesheet" href="../_static/material.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />
<script id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
<script src="../_static/jquery.js"></script>
<script src="../_static/underscore.js"></script>
<script src="../_static/doctools.js"></script>
<script src="../_static/language_data.js"></script>
<script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script>
<script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["$", "$"], ["\\(", "\\)"]], "processEscapes": true, "ignoreClass": "document", "processClass": "math|output_area"}})</script>
<link rel="shortcut icon" href="../_static/favicon.ico"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="statsmodels.base.distributed_estimation.DistributedResults.tvalues" href="statsmodels.base.distributed_estimation.DistributedResults.tvalues.html" />
<link rel="prev" title="statsmodels.base.distributed_estimation.DistributedResults.llf" href="statsmodels.base.distributed_estimation.DistributedResults.llf.html" />
</head>
<body dir=ltr
data-md-color-primary=indigo data-md-color-accent=blue>
<svg class="md-svg">
<defs data-children-count="0">
<svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg>
</defs>
</svg>
<input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer">
<input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search">
<label class="md-overlay" data-md-component="overlay" for="__drawer"></label>
<a href="#generated/statsmodels.base.distributed_estimation.DistributedResults.pvalues" tabindex="1" class="md-skip"> Skip to content </a>
<header class="md-header" data-md-component="header">
<nav class="md-header-nav md-grid">
<div class="md-flex navheader">
<div class="md-flex__cell md-flex__cell--shrink">
<a href="../index.html" title="statsmodels"
class="md-header-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" height="26"
alt="statsmodels logo">
</a>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label>
</div>
<div class="md-flex__cell md-flex__cell--stretch">
<div class="md-flex__ellipsis md-header-nav__title" data-md-component="title">
<span class="md-header-nav__topic">statsmodels v0.12.1</span>
<span class="md-header-nav__topic"> statsmodels.base.distributed_estimation.DistributedResults.pvalues </span>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--search md-header-nav__button" for="__search"></label>
<div class="md-search" data-md-component="search" role="dialog">
<label class="md-search__overlay" for="__search"></label>
<div class="md-search__inner" role="search">
<form class="md-search__form" action="../search.html" method="GET" name="search">
<input type="text" class="md-search__input" name="q" placeholder="Search"
autocapitalize="off" autocomplete="off" spellcheck="false"
data-md-component="query" data-md-state="active">
<label class="md-icon md-search__icon" for="__search"></label>
<button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1">

</button>
</form>
<div class="md-search__output">
<div class="md-search__scrollwrap" data-md-scrollfix>
<div class="md-search-result" data-md-component="result">
<div class="md-search-result__meta">
Type to start searching
</div>
<ol class="md-search-result__list"></ol>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<div class="md-header-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
</div>
<script src="../_static/javascripts/version_dropdown.js"></script>
<script>
var json_loc = "../_static/versions.json",
target_loc = "../../",
text = "Versions";
$( document ).ready( add_version_dropdown(json_loc, target_loc, text));
</script>
</div>
</nav>
</header>
<div class="md-container">
<nav class="md-tabs" data-md-component="tabs">
<div class="md-tabs__inner md-grid">
<ul class="md-tabs__list">
<li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li>
<li class="md-tabs__item"><a href="../large_data.html" class="md-tabs__link">Working with Large Data Sets</a></li>
<li class="md-tabs__item"><a href="statsmodels.base.distributed_estimation.DistributedResults.html" class="md-tabs__link">statsmodels.base.distributed_estimation.DistributedResults</a></li>
</ul>
</div>
</nav>
<main class="md-main">
<div class="md-main__inner md-grid" data-md-component="container">
<div class="md-sidebar md-sidebar--primary" data-md-component="navigation">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--primary" data-md-level="0">
<label class="md-nav__title md-nav__title--site" for="__drawer">
<a href="../index.html" title="statsmodels" class="md-nav__button md-logo">
<img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48">
</a>
<a href="../index.html"
title="statsmodels">statsmodels v0.12.1</a>
</label>
<div class="md-nav__source">
<a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github">
<div class="md-source__icon">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
<use xlink:href="#__github" width="24" height="24"></use>
</svg>
</div>
<div class="md-source__repository">
statsmodels
</div>
</a>
</div>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../install.html" class="md-nav__link">Installing statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../gettingstarted.html" class="md-nav__link">Getting started</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html" class="md-nav__link">User Guide</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../user-guide.html#background" class="md-nav__link">Background</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a>
<ul class="md-nav__list">
<li class="md-nav__item">
<a href="../stats.html" class="md-nav__link">Statistics <code class="xref py py-mod docutils literal notranslate"><span class="pre">stats</span></code></a>
</li>
<li class="md-nav__item">
<a href="../contingency_tables.html" class="md-nav__link">Contingency tables</a>
</li>
<li class="md-nav__item">
<a href="../imputation.html" class="md-nav__link">Multiple Imputation with Chained Equations</a>
</li>
<li class="md-nav__item">
<a href="../emplike.html" class="md-nav__link">Empirical Likelihood <code class="xref py py-mod docutils literal notranslate"><span class="pre">emplike</span></code></a>
</li>
<li class="md-nav__item">
<a href="../distributions.html" class="md-nav__link">Distributions</a>
</li>
<li class="md-nav__item">
<a href="../graphics.html" class="md-nav__link">Graphics</a>
</li>
<li class="md-nav__item">
<a href="../iolib.html" class="md-nav__link">Input-Output <code class="xref py py-mod docutils literal notranslate"><span class="pre">iolib</span></code></a>
</li>
<li class="md-nav__item">
<a href="../tools.html" class="md-nav__link">Tools</a>
</li>
<li class="md-nav__item">
<a href="../large_data.html" class="md-nav__link">Working with Large Data Sets</a>
</li>
<li class="md-nav__item">
<a href="../optimization.html" class="md-nav__link">Optimization</a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a>
</li>
<li class="md-nav__item">
<a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a>
</li></ul>
</li>
<li class="md-nav__item">
<a href="../examples/index.html" class="md-nav__link">Examples</a>
</li>
<li class="md-nav__item">
<a href="../api.html" class="md-nav__link">API Reference</a>
</li>
<li class="md-nav__item">
<a href="../about.html" class="md-nav__link">About statsmodels</a>
</li>
<li class="md-nav__item">
<a href="../dev/index.html" class="md-nav__link">Developer Page</a>
</li>
<li class="md-nav__item">
<a href="../release/index.html" class="md-nav__link">Release Notes</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-sidebar md-sidebar--secondary" data-md-component="toc">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--secondary">
<ul class="md-nav__list" data-md-scrollfix="">
<li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.base.distributed_estimation.DistributedResults.pvalues.rst.txt">Show Source</a> </li>
<li id="searchbox" class="md-nav__item"></li>
</ul>
</nav>
</div>
</div>
</div>
<div class="md-content">
<article class="md-content__inner md-typeset" role="main">
<h1 id="generated-statsmodels-base-distributed-estimation-distributedresults-pvalues--page-root">statsmodels.base.distributed_estimation.DistributedResults.pvalues<a class="headerlink" href="#generated-statsmodels-base-distributed-estimation-distributedresults-pvalues--page-root" title="Permalink to this headline">¶</a></h1>
<dl class="py attribute">
<dt id="statsmodels.base.distributed_estimation.DistributedResults.pvalues">
<code class="sig-prename descclassname">DistributedResults.</code><code class="sig-name descname">pvalues</code><a class="headerlink" href="#statsmodels.base.distributed_estimation.DistributedResults.pvalues" title="Permalink to this definition">¶</a></dt>
<dd><p>The two-tailed p values for the t-stats of the params.</p>
</dd></dl>
</article>
</div>
</div>
</main>
</div>
<footer class="md-footer">
<div class="md-footer-nav">
<nav class="md-footer-nav__inner md-grid">
<a href="statsmodels.base.distributed_estimation.DistributedResults.llf.html" title="statsmodels.base.distributed_estimation.DistributedResults.llf"
class="md-flex md-footer-nav__link md-footer-nav__link--prev"
rel="prev">
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-back md-footer-nav__button"></i>
</div>
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span
class="md-footer-nav__direction"> Previous </span> statsmodels.base.distributed_estimation.DistributedResults.llf </span>
</div>
</a>
<a href="statsmodels.base.distributed_estimation.DistributedResults.tvalues.html" title="statsmodels.base.distributed_estimation.DistributedResults.tvalues"
class="md-flex md-footer-nav__link md-footer-nav__link--next"
rel="next">
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span
class="md-flex__ellipsis"> <span
class="md-footer-nav__direction"> Next </span> statsmodels.base.distributed_estimation.DistributedResults.tvalues </span>
</div>
<div class="md-flex__cell md-flex__cell--shrink"><i
class="md-icon md-icon--arrow-forward md-footer-nav__button"></i>
</div>
</a>
</nav>
</div>
<div class="md-footer-meta md-typeset">
<div class="md-footer-meta__inner md-grid">
<div class="md-footer-copyright">
<div class="md-footer-copyright__highlight">
© Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
</div>
Last updated on
Oct 29, 2020.
<br/>
Created using
<a href="http://www.sphinx-doc.org/">Sphinx</a> 3.2.1.
and
<a href="https://github.com/bashtage/sphinx-material/">Material for
Sphinx</a>
</div>
</div>
</div>
</footer>
<script src="../_static/javascripts/application.js"></script>
<script>app.initialize({version: "1.0.4", url: {base: ".."}})</script>
</body>
</html> | {
"content_hash": "bd53381487fa35b64ae6e194b6963a9d",
"timestamp": "",
"source": "github",
"line_count": 498,
"max_line_length": 999,
"avg_line_length": 37.8714859437751,
"alnum_prop": 0.6003711558854719,
"repo_name": "statsmodels/statsmodels.github.io",
"id": "656f51a8a09b261bf50034b87fac83f81fd7cba9",
"size": "18864",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "v0.12.1/generated/statsmodels.base.distributed_estimation.DistributedResults.pvalues.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
module BlurredImageTag
VERSION = "0.1.2"
end
| {
"content_hash": "57423c671cdb24e582350428a87c3629",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 22,
"avg_line_length": 15.666666666666666,
"alnum_prop": 0.723404255319149,
"repo_name": "KRaikk/blurred_image_tag",
"id": "225d2d4d383a8a42765bb4e46352a5edcd4fb29b",
"size": "47",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/blurred_image_tag/version.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "636"
},
{
"name": "Ruby",
"bytes": "2009"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html SYSTEM "about:legacy-compat">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<title>phpDox - Filestack\Mixins\TransformationMixin::createTransformUrl</title>
<link rel="stylesheet" type="text/css" href="../../css/style.css" media="screen"/>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
</head>
<body>
<nav class="topnav">
<ul>
<li>
<div class="logo"><span>/**</span>phpDox</div>
</li>
<li class="separator">
<a href="../../index.html">Overview</a>
</li>
<li class="separator">
<a href="../../namespaces.html">Namespaces</a>
</li>
<li>
<a href="../../classes.html">Classes</a>
</li>
<li>
<a href="../../traits.html">Traits</a>
</li>
<li class="separator">
<a href="../../source/index.html">Source</a>
</li>
</ul>
</nav>
<div id="mainstage">
<div class="box">
<ul class="breadcrumb">
<li>
<a href="../../index.html">Overview</a>
</li>
<li class="separator">
<a href="../../classes.html">Classes</a>
</li>
<li class="separator">
<a href="../../classes.html#Filestack_Mixins">Filestack\Mixins</a>
</li>
<li class="separator">
<a title="Filestack\Mixins\TransformationMixin" href="../../traits/Filestack_Mixins_TransformationMixin.html">TransformationMixin</a>
</li>
<li class="separator">createTransformUrl</li>
</ul>
</div>
<nav class="box">
<ul>
<li>
<a href="#introduction">Introduction</a>
</li>
<li>
<a href="#synopsis">Synopsis</a>
</li>
<li>
<a href="#parameter">Parameter</a>
</li>
<li>
<a href="#return">Return</a>
</li>
<li>
<a href="#throws">Throws</a>
</li>
<li>
<a href="../../source/mixins/TransformationMixin.php.html#line248">Source</a>
</li>
</ul>
</nav>
<section>
<h1><small>Filestack\Mixins\TransformationMixin::</small>createTransformUrl</h1>
<h4>Create the transform parts of the transformation url</h4>
<p/>
<ul/>
<h2 id="signature">Signature</h2>
<div class="styled synopsis">
<code>protected function createTransformUrl(string
$api_key,
string
$type,
<a title="Filestack\Mixins\sring" href="../../traits/Filestack_Mixins_sring.html">sring</a>
$resource,
string
$tasks_str,
[<a title="Filestack\Mixins\FilestackSecurity" href="../../traits/Filestack_Mixins_FilestackSecurity.html">FilestackSecurity</a>
$security = NULL] )
</code>
</div>
<h2 id="parameterlist">Parameters</h2>
<dl class="styled">
<dt><code>$api_key</code>
—
string</dt>
<dd>Filestack API Key</dd>
<dt><code>$type</code>
—
string</dt>
<dd>Type of transformation:<br/>image, audio, video</dd>
<dt><code>$resource</code>
—
object</dt>
<dd>url or Filestack handle<br/><br/><br/> </dd>
<dt><code>$tasks_str</code>
—
string</dt>
<dd>tranformation tasks part of url</dd>
<dt><code>$security</code>
—
object</dt>
<dd>Filestack Security object if needed<br/><br/><br/> </dd>
</dl>
<h2 id="return">Returns</h2>
<dl class="styled">
<dt>string</dt>
<dd/>
</dl>
<h2 id="throws">Errors/Exceptions</h2>
<dl class="styled">
<dt>
<code>
<a title="Filestack\FilestackException" href="../../traits/Filestack_FilestackException.html">FilestackException</a>
</code>
</dt>
<dd>if API call fails, e.g 404 file not found</dd>
</dl>
</section>
</div>
<footer>
<span>Generated using phpDox 0.12.0 - Copyright (C) 2010 - 2020 by Arne Blankerts and Contributors</span>
</footer>
</body>
</html>
| {
"content_hash": "25c6c30f577330daec8d74d8d4802484",
"timestamp": "",
"source": "github",
"line_count": 134,
"max_line_length": 145,
"avg_line_length": 33.26119402985075,
"alnum_prop": 0.49001570563159075,
"repo_name": "filestack/filestack-php",
"id": "554f03bac3698495c53a837cb220a0d95cde50e7",
"size": "4468",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/traits/Filestack_Mixins_TransformationMixin/createTransformUrl.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PHP",
"bytes": "262127"
}
],
"symlink_target": ""
} |
using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Core.Data;
using Core.Domain.Security;
using System.Collections.Generic;
namespace Api.Data.Repositories
{
public class SecurityRepository : ISecurityRepository
{
private readonly ApiDbContext _context;
public SecurityRepository(ApiDbContext context)
{
_context = context;
}
public void AddRole(SecurityRole role)
{
throw new NotImplementedException();
}
public void AddUser(User user)
{
if (user.Id == 0)
_context.Users.Add(user);
else
_context.Update(user);
_context.SaveChanges();
}
public SecurityRole GetRole(string roleName)
{
throw new NotImplementedException();
}
public User GetUser(string username)
{
return _context.Users
.Include(u => u.Roles)
.ThenInclude(u => u.SecurityRole.Permissions)
.ThenInclude(u => u.SecurityPermission.Group)
.Where(u => u.UserName == username)
.FirstOrDefault();
}
public IEnumerable<User> GetAllUsers()
{
var users = _context.Users.Include(u => u.Roles)
.ThenInclude(u => u.SecurityRole.Permissions)
.ThenInclude(u => u.SecurityPermission.Group);
return users;
}
public IEnumerable<SecurityRole> GetAllRoles()
{
var roles = _context.SecurityRoles.Include(r => r.Permissions)
.ThenInclude(r => r.SecurityPermission.RolePermissions)
.ThenInclude(r => r.SecurityPermission.Group);
return roles;
}
public IEnumerable<SecurityGroup> GetAllGroups()
{
var groups = _context.SecurityGroups.Include(g => g.Permissions)
.ThenInclude(g => g.RolePermissions)
.ThenInclude(g => g.SecurityPermission);
return groups;
}
}
}
| {
"content_hash": "afcf1b30d92fc66ad01dccf8b49266a5",
"timestamp": "",
"source": "github",
"line_count": 75,
"max_line_length": 76,
"avg_line_length": 28.2,
"alnum_prop": 0.5588652482269504,
"repo_name": "AccountGo/accountgo",
"id": "76edb54ff20b8ae6d7567bd2b6b95c72db5efa64",
"size": "2117",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "src/Api/Data/Repositories/SecurityRepository.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "791896"
},
{
"name": "CSS",
"bytes": "52065"
},
{
"name": "Dockerfile",
"bytes": "1527"
},
{
"name": "HTML",
"bytes": "192599"
},
{
"name": "JavaScript",
"bytes": "30509"
},
{
"name": "TSQL",
"bytes": "59670"
},
{
"name": "TypeScript",
"bytes": "189469"
}
],
"symlink_target": ""
} |
#include <openssl/core.h>
#include <openssl/core_dispatch.h>
#include "internal/core.h"
#include "internal/property.h"
#include "internal/provider.h"
struct algorithm_data_st {
OSSL_LIB_CTX *libctx;
int operation_id; /* May be zero for finding them all */
int (*pre)(OSSL_PROVIDER *, int operation_id, int no_store, void *data,
int *result);
int (*reserve_store)(int no_store, void *data);
void (*fn)(OSSL_PROVIDER *, const OSSL_ALGORITHM *, int no_store,
void *data);
int (*unreserve_store)(void *data);
int (*post)(OSSL_PROVIDER *, int operation_id, int no_store, void *data,
int *result);
void *data;
};
/*
* Process one OSSL_ALGORITHM array, for the operation |cur_operation|,
* by constructing methods for all its implementations and adding those
* to the appropriate method store.
* Which method store is appropriate is given by |no_store| ("permanent"
* if 0, temporary if 1) and other data in |data->data|.
*
* Returns:
* -1 to quit adding algorithm implementations immediately
* 0 if not successful, but adding should continue
* 1 if successful so far, and adding should continue
*/
static int algorithm_do_map(OSSL_PROVIDER *provider, const OSSL_ALGORITHM *map,
int cur_operation, int no_store, void *cbdata)
{
struct algorithm_data_st *data = cbdata;
int ret = 0;
if (!data->reserve_store(no_store, data->data))
/* Error, bail out! */
return -1;
/* Do we fulfill pre-conditions? */
if (data->pre == NULL) {
/* If there is no pre-condition function, assume "yes" */
ret = 1;
} else if (!data->pre(provider, cur_operation, no_store, data->data,
&ret)) {
/* Error, bail out! */
ret = -1;
goto end;
}
/*
* If pre-condition not fulfilled don't add this set of implementations,
* but do continue with the next. This simply means that another thread
* got to it first.
*/
if (ret == 0) {
ret = 1;
goto end;
}
if (map != NULL) {
const OSSL_ALGORITHM *thismap;
for (thismap = map; thismap->algorithm_names != NULL; thismap++)
data->fn(provider, thismap, no_store, data->data);
}
/* Do we fulfill post-conditions? */
if (data->post == NULL) {
/* If there is no post-condition function, assume "yes" */
ret = 1;
} else if (!data->post(provider, cur_operation, no_store, data->data,
&ret)) {
/* Error, bail out! */
ret = -1;
}
end:
data->unreserve_store(data->data);
return ret;
}
/*
* Given a provider, process one operation given by |data->operation_id|, or
* if that's zero, process all known operations.
* For each such operation, query the associated OSSL_ALGORITHM array from
* the provider, then process that array with |algorithm_do_map()|.
*/
static int algorithm_do_this(OSSL_PROVIDER *provider, void *cbdata)
{
struct algorithm_data_st *data = cbdata;
int first_operation = 1;
int last_operation = OSSL_OP__HIGHEST;
int cur_operation;
int ok = 1;
if (data->operation_id != 0)
first_operation = last_operation = data->operation_id;
for (cur_operation = first_operation;
cur_operation <= last_operation;
cur_operation++) {
int no_store = 0; /* Assume caching is ok */
const OSSL_ALGORITHM *map = NULL;
int ret = 0;
map = ossl_provider_query_operation(provider, cur_operation,
&no_store);
ret = algorithm_do_map(provider, map, cur_operation, no_store, data);
ossl_provider_unquery_operation(provider, cur_operation, map);
if (ret < 0)
/* Hard error, bail out immediately! */
return 0;
/* If post-condition not fulfilled, set general failure */
if (!ret)
ok = 0;
}
return ok;
}
void ossl_algorithm_do_all(OSSL_LIB_CTX *libctx, int operation_id,
OSSL_PROVIDER *provider,
int (*pre)(OSSL_PROVIDER *, int operation_id,
int no_store, void *data, int *result),
int (*reserve_store)(int no_store, void *data),
void (*fn)(OSSL_PROVIDER *provider,
const OSSL_ALGORITHM *algo,
int no_store, void *data),
int (*unreserve_store)(void *data),
int (*post)(OSSL_PROVIDER *, int operation_id,
int no_store, void *data, int *result),
void *data)
{
struct algorithm_data_st cbdata = { 0, };
cbdata.libctx = libctx;
cbdata.operation_id = operation_id;
cbdata.pre = pre;
cbdata.reserve_store = reserve_store;
cbdata.fn = fn;
cbdata.unreserve_store = unreserve_store;
cbdata.post = post;
cbdata.data = data;
if (provider == NULL) {
ossl_provider_doall_activated(libctx, algorithm_do_this, &cbdata);
} else {
OSSL_LIB_CTX *libctx2 = ossl_provider_libctx(provider);
/*
* If a provider is given, its library context MUST match the library
* context we're passed. If this turns out not to be true, there is
* a programming error in the functions up the call stack.
*/
if (!ossl_assert(ossl_lib_ctx_get_concrete(libctx)
== ossl_lib_ctx_get_concrete(libctx2)))
return;
cbdata.libctx = libctx2;
algorithm_do_this(provider, &cbdata);
}
}
char *ossl_algorithm_get1_first_name(const OSSL_ALGORITHM *algo)
{
const char *first_name_end = NULL;
size_t first_name_len = 0;
char *ret;
if (algo->algorithm_names == NULL)
return NULL;
first_name_end = strchr(algo->algorithm_names, ':');
if (first_name_end == NULL)
first_name_len = strlen(algo->algorithm_names);
else
first_name_len = first_name_end - algo->algorithm_names;
ret = OPENSSL_strndup(algo->algorithm_names, first_name_len);
if (ret == NULL)
ERR_raise(ERR_LIB_EVP, ERR_R_MALLOC_FAILURE);
return ret;
}
| {
"content_hash": "9d7aee4351472ce842314ded70c125c2",
"timestamp": "",
"source": "github",
"line_count": 192,
"max_line_length": 79,
"avg_line_length": 33.223958333333336,
"alnum_prop": 0.5725035271986205,
"repo_name": "jens-maus/amissl",
"id": "c245c814d98c6b26d29dd89ce01f1f4da2503b04",
"size": "6714",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "openssl/crypto/core_algorithm.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "220093"
},
{
"name": "C",
"bytes": "40078080"
},
{
"name": "C++",
"bytes": "726352"
},
{
"name": "DIGITAL Command Language",
"bytes": "5687"
},
{
"name": "Emacs Lisp",
"bytes": "3734"
},
{
"name": "M4",
"bytes": "46625"
},
{
"name": "Makefile",
"bytes": "31856"
},
{
"name": "Module Management System",
"bytes": "1304"
},
{
"name": "Pawn",
"bytes": "4674"
},
{
"name": "Perl",
"bytes": "6850162"
},
{
"name": "Python",
"bytes": "1366"
},
{
"name": "Raku",
"bytes": "23696"
},
{
"name": "Roff",
"bytes": "4324"
},
{
"name": "Ruby",
"bytes": "1103"
},
{
"name": "SWIG",
"bytes": "269167"
},
{
"name": "Shell",
"bytes": "116450"
},
{
"name": "SourcePawn",
"bytes": "2892"
},
{
"name": "eC",
"bytes": "7473"
},
{
"name": "sed",
"bytes": "502"
}
],
"symlink_target": ""
} |
package io.aos.concurrent.spl0.cs08.example5;
import javax.swing.*;
import java.awt.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
public class AnimatedCharacterDisplayCanvas extends CharacterDisplayCanvas
implements CharacterListener, Runnable {
private volatile boolean done = false;
private int curX;
private Lock lock = new ReentrantLock();
private Condition cv = lock.newCondition();
private Thread timer = null;
public AnimatedCharacterDisplayCanvas(CharacterSource cs) {
super(cs);
}
public synchronized void newCharacter(CharacterEvent ce) {
curX = 0;
tmpChar[0] = (char) ce.character;
repaint();
}
public synchronized void paintComponent(Graphics gc) {
if (tmpChar[0] == 0)
return;
Dimension d = getSize();
int charWidth = fm.charWidth(tmpChar[0]);
gc.clearRect(0, 0, d.width, d.height);
gc.drawChars(tmpChar, 0, 1, curX++, fontHeight);
if (curX > d.width - charWidth)
curX = 0;
}
public void run() {
try {
lock.lock();
while (true) {
try {
if (done) {
cv.await();
} else {
repaint();
cv.await(100, TimeUnit.MILLISECONDS);
}
} catch (InterruptedException ie) {
return;
}
}
} finally {
lock.unlock();
}
}
public void setDone(boolean b) {
try {
lock.lock();
done = b;
if (timer == null) {
timer = new Thread(this);
timer.start();
}
if (!done) cv.signal();
} finally {
lock.unlock();
}
}
}
| {
"content_hash": "c5107446e0e6f6b965b4896b3820c182",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 74,
"avg_line_length": 26.27777777777778,
"alnum_prop": 0.5021141649048626,
"repo_name": "XClouded/t4f-core",
"id": "f2cfdbe22f3042c0b3f2eaddaf447cae19035520",
"size": "3080",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "java/concurrent/src/main/java/io/aos/concurrent/spl0/cs08/example5/AnimatedCharacterDisplayCanvas.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
/* @Twig/Exception/trace.html.twig */
class __TwigTemplate_5600eea3d2fcd24cbe55cdc5b279f4e837003e204365ebf7d02815618e9bf8ba extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
$__internal_db61892a142306da2d87410a7856459675423973ba5c4001aa2e7ddf44a77f60 = $this->env->getExtension("Symfony\\Bundle\\WebProfilerBundle\\Twig\\WebProfilerExtension");
$__internal_db61892a142306da2d87410a7856459675423973ba5c4001aa2e7ddf44a77f60->enter($__internal_db61892a142306da2d87410a7856459675423973ba5c4001aa2e7ddf44a77f60_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "@Twig/Exception/trace.html.twig"));
$__internal_d3b350085002a4579cf6dfbbc5de71a1692d17829a731fbf0e13948b25939e30 = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension");
$__internal_d3b350085002a4579cf6dfbbc5de71a1692d17829a731fbf0e13948b25939e30->enter($__internal_d3b350085002a4579cf6dfbbc5de71a1692d17829a731fbf0e13948b25939e30_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "@Twig/Exception/trace.html.twig"));
// line 1
if ($this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "function", array())) {
// line 2
echo " at
<strong>
<abbr title=\"";
// line 4
echo twig_escape_filter($this->env, $this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "class", array()), "html", null, true);
echo "\">";
echo twig_escape_filter($this->env, $this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "short_class", array()), "html", null, true);
echo "</abbr>
";
// line 5
echo twig_escape_filter($this->env, ($this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "type", array()) . $this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "function", array())), "html", null, true);
echo "
</strong>
(";
// line 7
echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\CodeExtension')->formatArgs($this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "args", array()));
echo ")
";
}
// line 9
echo "
";
// line 10
if (((($this->getAttribute((isset($context["trace"]) ? $context["trace"] : null), "file", array(), "any", true, true) && $this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "file", array())) && $this->getAttribute((isset($context["trace"]) ? $context["trace"] : null), "line", array(), "any", true, true)) && $this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "line", array()))) {
// line 11
echo " ";
echo (($this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "function", array())) ? ("<br />") : (""));
echo "
in ";
// line 12
echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\CodeExtension')->formatFile($this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "file", array()), $this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "line", array()));
echo "
";
// line 13
ob_start();
// line 14
echo " <a href=\"#\" onclick=\"toggle('trace-";
echo twig_escape_filter($this->env, (((isset($context["prefix"]) ? $context["prefix"] : $this->getContext($context, "prefix")) . "-") . (isset($context["i"]) ? $context["i"] : $this->getContext($context, "i"))), "html", null, true);
echo "'); switchIcons('icon-";
echo twig_escape_filter($this->env, (((isset($context["prefix"]) ? $context["prefix"] : $this->getContext($context, "prefix")) . "-") . (isset($context["i"]) ? $context["i"] : $this->getContext($context, "i"))), "html", null, true);
echo "-open', 'icon-";
echo twig_escape_filter($this->env, (((isset($context["prefix"]) ? $context["prefix"] : $this->getContext($context, "prefix")) . "-") . (isset($context["i"]) ? $context["i"] : $this->getContext($context, "i"))), "html", null, true);
echo "-close'); return false;\">
<img class=\"toggle\" id=\"icon-";
// line 15
echo twig_escape_filter($this->env, (((isset($context["prefix"]) ? $context["prefix"] : $this->getContext($context, "prefix")) . "-") . (isset($context["i"]) ? $context["i"] : $this->getContext($context, "i"))), "html", null, true);
echo "-close\" alt=\"-\" src=\"data:image/gif;base64,R0lGODlhEgASAMQSANft94TG57Hb8GS44ez1+mC24IvK6ePx+Wa44dXs92+942e54o3L6W2844/M6dnu+P/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABIALAAAAAASABIAQAVCoCQBTBOd6Kk4gJhGBCTPxysJb44K0qD/ER/wlxjmisZkMqBEBW5NHrMZmVKvv9hMVsO+hE0EoNAstEYGxG9heIhCADs=\" style=\"display: ";
echo (((0 == (isset($context["i"]) ? $context["i"] : $this->getContext($context, "i")))) ? ("inline") : ("none"));
echo "\" />
<img class=\"toggle\" id=\"icon-";
// line 16
echo twig_escape_filter($this->env, (((isset($context["prefix"]) ? $context["prefix"] : $this->getContext($context, "prefix")) . "-") . (isset($context["i"]) ? $context["i"] : $this->getContext($context, "i"))), "html", null, true);
echo "-open\" alt=\"+\" src=\"data:image/gif;base64,R0lGODlhEgASAMQTANft99/v+Ga44bHb8ITG52S44dXs9+z1+uPx+YvK6WC24G+944/M6W28443L6dnu+Ge54v/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABMALAAAAAASABIAQAVS4DQBTiOd6LkwgJgeUSzHSDoNaZ4PU6FLgYBA5/vFID/DbylRGiNIZu74I0h1hNsVxbNuUV4d9SsZM2EzWe1qThVzwWFOAFCQFa1RQq6DJB4iIQA7\" style=\"display: ";
echo (((0 == (isset($context["i"]) ? $context["i"] : $this->getContext($context, "i")))) ? ("none") : ("inline"));
echo "\" />
</a>
";
echo trim(preg_replace('/>\s+</', '><', ob_get_clean()));
// line 19
echo " <div id=\"trace-";
echo twig_escape_filter($this->env, (((isset($context["prefix"]) ? $context["prefix"] : $this->getContext($context, "prefix")) . "-") . (isset($context["i"]) ? $context["i"] : $this->getContext($context, "i"))), "html", null, true);
echo "\" style=\"display: ";
echo (((0 == (isset($context["i"]) ? $context["i"] : $this->getContext($context, "i")))) ? ("block") : ("none"));
echo "\" class=\"trace\">
";
// line 20
echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\CodeExtension')->fileExcerpt($this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "file", array()), $this->getAttribute((isset($context["trace"]) ? $context["trace"] : $this->getContext($context, "trace")), "line", array()));
echo "
</div>
";
}
$__internal_db61892a142306da2d87410a7856459675423973ba5c4001aa2e7ddf44a77f60->leave($__internal_db61892a142306da2d87410a7856459675423973ba5c4001aa2e7ddf44a77f60_prof);
$__internal_d3b350085002a4579cf6dfbbc5de71a1692d17829a731fbf0e13948b25939e30->leave($__internal_d3b350085002a4579cf6dfbbc5de71a1692d17829a731fbf0e13948b25939e30_prof);
}
public function getTemplateName()
{
return "@Twig/Exception/trace.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 93 => 20, 86 => 19, 78 => 16, 72 => 15, 63 => 14, 61 => 13, 57 => 12, 52 => 11, 50 => 10, 47 => 9, 42 => 7, 37 => 5, 31 => 4, 27 => 2, 25 => 1,);
}
/** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
public function getSource()
{
@trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);
return $this->getSourceContext()->getCode();
}
public function getSourceContext()
{
return new Twig_Source("{% if trace.function %}
at
<strong>
<abbr title=\"{{ trace.class }}\">{{ trace.short_class }}</abbr>
{{ trace.type ~ trace.function }}
</strong>
({{ trace.args|format_args }})
{% endif %}
{% if trace.file is defined and trace.file and trace.line is defined and trace.line %}
{{ trace.function ? '<br />' : '' }}
in {{ trace.file|format_file(trace.line) }}
{% spaceless %}
<a href=\"#\" onclick=\"toggle('trace-{{ prefix ~ '-' ~ i }}'); switchIcons('icon-{{ prefix ~ '-' ~ i }}-open', 'icon-{{ prefix ~ '-' ~ i }}-close'); return false;\">
<img class=\"toggle\" id=\"icon-{{ prefix ~ '-' ~ i }}-close\" alt=\"-\" src=\"data:image/gif;base64,R0lGODlhEgASAMQSANft94TG57Hb8GS44ez1+mC24IvK6ePx+Wa44dXs92+942e54o3L6W2844/M6dnu+P/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABIALAAAAAASABIAQAVCoCQBTBOd6Kk4gJhGBCTPxysJb44K0qD/ER/wlxjmisZkMqBEBW5NHrMZmVKvv9hMVsO+hE0EoNAstEYGxG9heIhCADs=\" style=\"display: {{ 0 == i ? 'inline' : 'none' }}\" />
<img class=\"toggle\" id=\"icon-{{ prefix ~ '-' ~ i }}-open\" alt=\"+\" src=\"data:image/gif;base64,R0lGODlhEgASAMQTANft99/v+Ga44bHb8ITG52S44dXs9+z1+uPx+YvK6WC24G+944/M6W28443L6dnu+Ge54v/+/l614P///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABMALAAAAAASABIAQAVS4DQBTiOd6LkwgJgeUSzHSDoNaZ4PU6FLgYBA5/vFID/DbylRGiNIZu74I0h1hNsVxbNuUV4d9SsZM2EzWe1qThVzwWFOAFCQFa1RQq6DJB4iIQA7\" style=\"display: {{ 0 == i ? 'none' : 'inline' }}\" />
</a>
{% endspaceless %}
<div id=\"trace-{{ prefix ~ '-' ~ i }}\" style=\"display: {{ 0 == i ? 'block' : 'none' }}\" class=\"trace\">
{{ trace.file|file_excerpt(trace.line) }}
</div>
{% endif %}
", "@Twig/Exception/trace.html.twig", "E:\\OpenServer\\domains\\jobeet\\vendor\\symfony\\symfony\\src\\Symfony\\Bundle\\TwigBundle\\Resources\\views\\Exception\\trace.html.twig");
}
}
| {
"content_hash": "c138f082fbdad611f560e5f9c00fc6ca",
"timestamp": "",
"source": "github",
"line_count": 155,
"max_line_length": 499,
"avg_line_length": 68.90967741935484,
"alnum_prop": 0.6118340979309054,
"repo_name": "aonufrienko/simplepraice",
"id": "975a4dde4d33e6fcd435d56e8fbe80a47eefb752",
"size": "10681",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "var/cache/dev/twig/51/5133e34164921986f212595c0c0e4a5c515c6950d88ec66ddbc05c005da61c3b.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "3605"
},
{
"name": "HTML",
"bytes": "4968"
},
{
"name": "PHP",
"bytes": "89988"
}
],
"symlink_target": ""
} |
package com.siyeh.ig.performance;
import com.intellij.codeInspection.CommonQuickFixBundle;
import com.intellij.psi.CommonClassNames;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiLocalVariable;
import com.intellij.psi.PsiType;
import com.intellij.psi.util.PsiUtil;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.InspectionGadgetsFix;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static com.intellij.util.ObjectUtils.tryCast;
public class SetReplaceableByEnumSetInspection extends BaseInspection {
@Override
@NotNull
public String getDisplayName() {
return InspectionGadgetsBundle.message("set.replaceable.by.enum.set.display.name");
}
@Override
@NotNull
protected String buildErrorString(Object... infos) {
return InspectionGadgetsBundle.message("set.replaceable.by.enum.set.problem.descriptor");
}
@Nullable
@Override
protected InspectionGadgetsFix buildFix(Object... infos) {
if (infos.length != 1) return null;
PsiLocalVariable localVariable = tryCast(infos[0], PsiLocalVariable.class);
if (localVariable == null) return null;
PsiType[] parameters = CollectionReplaceableByEnumCollectionVisitor.extractParameterType(localVariable, 1);
if (parameters == null) return null;
PsiType enumParameter = parameters[0];
PsiClass probablyEnum = PsiUtil.resolveClassInClassTypeOnly(enumParameter);
if (probablyEnum == null || !probablyEnum.isEnum()) return null;
String text = "java.util.EnumSet.noneOf(" + enumParameter.getCanonicalText() + ".class)";
return new ReplaceExpressionWithTextFix(text, CommonQuickFixBundle.message("fix.replace.with.x", "EnumSet"));
}
@Override
public BaseInspectionVisitor buildVisitor() {
return new SetReplaceableByEnumSetVisitor();
}
private static class SetReplaceableByEnumSetVisitor extends CollectionReplaceableByEnumCollectionVisitor {
@NotNull
@Override
protected List<String> getUnreplaceableCollectionNames() {
return Arrays.asList("java.util.concurrent.CopyOnWriteArraySet", "java.util.concurrent.ConcurrentSkipListSet",
"java.util.LinkedHashSet");
}
@NotNull
@Override
protected List<String> getReplaceableCollectionNames() {
return Collections.singletonList(CommonClassNames.JAVA_UTIL_HASH_SET);
}
@NotNull
@Override
protected String getReplacementCollectionName() {
return "java.util.EnumSet";
}
@NotNull
@Override
protected String getBaseCollectionName() {
return CommonClassNames.JAVA_UTIL_SET;
}
}
}
| {
"content_hash": "f406ed96411c8ef76d5f9fec6594729b",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 116,
"avg_line_length": 33.214285714285715,
"alnum_prop": 0.7594982078853046,
"repo_name": "msebire/intellij-community",
"id": "327269d9f92cd6c9cf62d786de19002d6b25676c",
"size": "3404",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/performance/SetReplaceableByEnumSetInspection.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>rem: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.11.2 / rem - 8.5.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
rem
<small>
8.5.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-03-25 16:47:04 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-03-25 16:47:04 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
coq 8.11.2 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.06.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.06.1 Official 4.06.1 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.3 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "matej.kosik@inria.fr"
homepage: "https://github.com/coq-contribs/rem"
license: "LGPL 2"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/Rem"]
depends: [
"ocaml"
"coq" {>= "8.5" & < "8.6~"}
]
tags: [ "keyword:rem theorem" "keyword:baire space" "category:Mathematics/Real Calculus and Topology" ]
authors: [ "Henk Barendregt <>" ]
bug-reports: "https://github.com/coq-contribs/rem/issues"
dev-repo: "git+https://github.com/coq-contribs/rem.git"
synopsis: "Rem Theorem in Baire space"
description: "A formalisation of Rem Theorem in Baire space"
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/rem/archive/v8.5.0.tar.gz"
checksum: "md5=9cfe80021e26bdacd51e405f76f6084a"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-rem.8.5.0 coq.8.11.2</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.11.2).
The following dependencies couldn't be met:
- coq-rem -> coq < 8.6~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-rem.8.5.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "f6fe246d02675395c271971614972845",
"timestamp": "",
"source": "github",
"line_count": 160,
"max_line_length": 159,
"avg_line_length": 40.78125,
"alnum_prop": 0.5295019157088122,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "040659edf958be421c46ad2c127cb587d5de8830",
"size": "6550",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.06.1-2.0.5/released/8.11.2/rem/8.5.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package uk.joshiejack.harvestcore.world.storage;
import com.google.common.collect.Maps;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import net.minecraft.world.storage.WorldSavedData;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.PlayerEvent;
import uk.joshiejack.harvestcore.HCConfig;
import uk.joshiejack.harvestcore.HarvestCore;
import uk.joshiejack.harvestcore.network.PacketSyncPlayerData;
import uk.joshiejack.harvestcore.world.mine.Mine;
import uk.joshiejack.harvestcore.world.mine.dimension.MineData;
import uk.joshiejack.penguinlib.events.NewDayEvent;
import uk.joshiejack.penguinlib.network.PenguinNetwork;
import uk.joshiejack.penguinlib.util.helpers.minecraft.NBTHelper;
import uk.joshiejack.penguinlib.util.helpers.minecraft.PlayerHelper;
import javax.annotation.Nonnull;
import java.util.Collection;
import java.util.Map;
import java.util.UUID;
@Mod.EventBusSubscriber(modid = HarvestCore.MODID)
public class SavedData extends WorldSavedData {
private static final String DATA_NAME = "HC-Data";
private final Map<UUID, Mailroom> mailrooms = Maps.newHashMap();
private final Int2ObjectMap<WildernessData> wilderness = new Int2ObjectOpenHashMap<>(); //Dimension > Wilderness Data
private final Int2ObjectMap<MineData> mine = new Int2ObjectOpenHashMap<>(); //Dimension > Mine Data
public SavedData() { super(DATA_NAME);}
public SavedData(String name) {
super(name);
}
private static SavedData get(World world) {
SavedData instance = (SavedData) world.loadData(SavedData.class, DATA_NAME);
if (instance == null) {
instance = new SavedData(DATA_NAME);
world.setData(DATA_NAME, instance);
instance.markDirty(); //Save the file
}
return instance;
}
@SubscribeEvent
public static void onPlayerJoinedWorld(PlayerEvent.PlayerLoggedInEvent event) {
getMailroom(event.player.world, PlayerHelper.getUUIDForPlayer(event.player)).synchronize(event.player.world); //Synchro the mail to the player
PenguinNetwork.sendToClient(new PacketSyncPlayerData(event.player, "Blueprints"), event.player);
PenguinNetwork.sendToClient(new PacketSyncPlayerData(event.player, "Notes"), event.player);
PenguinNetwork.sendToClient(new PacketSyncPlayerData(event.player, "NotesRead"), event.player);
}
public static MineData getMineDataFromName(World world, String name) {
return getMineData(world, Mine.BY_NAME.getInt(name));
}
public static MineData getMineData(World world, int dimension) {
SavedData data = SavedData.get(world);
if (!data.mine.containsKey(dimension)) {
data.mine.put(dimension, new MineData());
data.markDirty();
}
return data.mine.get(dimension);
}
public static WildernessData getWildernessDataForDimension(World world, int dim) {
return SavedData.get(world).getWildernessData(dim);
}
private WildernessData getWildernessData(int dim) {
if (!wilderness.containsKey(dim)) {
wilderness.put(dim, new WildernessData());
markDirty(); //Save the changes
}
return wilderness.get(dim);
}
@SubscribeEvent
public static void onNewDay(NewDayEvent event) {
SavedData data = get(event.getWorld());
data.mailrooms.values().forEach((m) -> m.onNewDay(event.getWorld()));
if (HCConfig.enableWildernessSpawns) {
data.getWildernessData(event.getWorld().provider.getDimension()).onNewDay(event.getWorld());
}
data.markDirty();
}
public static Mailroom getMailroom(World world, UUID uuid) {
SavedData instance = get(world);
if (!instance.mailrooms.containsKey(uuid)) {
instance.mailrooms.put(uuid, new Mailroom(uuid));
}
return instance.mailrooms.get(uuid);
}
public static Collection<Mailroom> getMailrooms(World world) {
return get(world).mailrooms.values();
}
public static void save(World world) {
get(world).markDirty();
}
@Override
@Nonnull
public NBTTagCompound writeToNBT(@Nonnull NBTTagCompound tag) {
tag.setTag("Mailrooms", NBTHelper.serialize(mailrooms));
tag.setTag("Wilderness", NBTHelper.writeDimensionMap(wilderness));
tag.setTag("Mines", NBTHelper.writeDimensionMap(mine));
return tag;
}
@Override
public void readFromNBT(@Nonnull NBTTagCompound tag) {
NBTHelper.deserialize(this, Mailroom.class, tag.getTagList("Mailrooms", 10), mailrooms);
NBTHelper.readDimensionMap(wilderness, tag.getTagList("Wilderness", 10), WildernessData.class);
NBTHelper.readDimensionMap(mine, tag.getTagList("Mines", 10), MineData.class);
}
}
| {
"content_hash": "1992582146c531bfbc58c5379e24634d",
"timestamp": "",
"source": "github",
"line_count": 128,
"max_line_length": 150,
"avg_line_length": 39.265625,
"alnum_prop": 0.7136888181456427,
"repo_name": "joshiejack/Harvest-Festival",
"id": "9dc2c66d9e3e18f2cefb32963c6984cbcc8e5538",
"size": "5026",
"binary": false,
"copies": "1",
"ref": "refs/heads/1.12.2",
"path": "src/main/java/uk/joshiejack/harvestcore/world/storage/SavedData.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "1131422"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 300101 $ -->
<refentry xml:id="function.oci-set-action" xmlns="http://docbook.org/ns/docbook">
<refnamediv>
<refname>oci_set_action</refname>
<refpurpose>Sets the action name</refpurpose>
</refnamediv>
<refsect1 role="description">
&reftitle.description;
<methodsynopsis>
<type>bool</type><methodname>oci_set_action</methodname>
<methodparam><type>resource</type><parameter>connection</parameter></methodparam>
<methodparam><type>string</type><parameter>action_name</parameter></methodparam>
</methodsynopsis>
<para>
Sets the action name for Oracle tracing.
</para>
<para>
The action name is registered with the database when the next
'roundtrip' from PHP to the database occurs, typically when an SQL
statement is executed.
</para>
<para>
The action name can subsequently be queried from database administration
views such as <literal>V$SESSION</literal>. It can be used for
tracing and monitoring such as with <literal>V$SQLAREA</literal>
and <literal>DBMS_MONITOR.SERV_MOD_ACT_STAT_ENABLE</literal>.
</para>
<para>
The value may be retained across persistent connections.
</para>
</refsect1>
<refsect1 role="parameters">
&reftitle.parameters;
<para>
<variablelist>
<varlistentry>
<term><parameter>connection</parameter></term>
<listitem>
&oci.parameter.connection;
</listitem>
</varlistentry>
<varlistentry>
<term><parameter>action_name</parameter></term>
<listitem>
<para>
User chosen string up to 32 bytes long.
</para>
</listitem>
</varlistentry>
</variablelist>
</para>
</refsect1>
<refsect1 role="returnvalues">
&reftitle.returnvalues;
<para>
&return.success;
</para>
</refsect1>
<refsect1 role="examples">
&reftitle.examples;
<para>
<example>
<title>Setting the action</title>
<programlisting role="php">
<![CDATA[
<?php
$c = oci_connect('hr', 'welcome', 'localhost/XE');
// Record the action
oci_set_action($c, 'Friend Lookup');
// Code that causes a roundtrip, for example a query:
$s = oci_parse($c, 'select * from dual');
oci_execute($s);
oci_fetch_all($s, $res);
sleep(30);
?>
]]>
</programlisting>
<screen>
<![CDATA[
// While the script is running, the administrator can see the actions
// being performed:
sqlplus system/welcome
SQL> select action from v$session;
]]>
</screen>
</example>
</para>
</refsect1>
<refsect1 role="notes">
&reftitle.notes;
&oci.availability.note.10g;
&oci.clientinfo.tip;
&oci.roundtrip.caution;
</refsect1>
<refsect1 role="seealso">
&reftitle.seealso;
<para>
<simplelist>
<member><function>oci_set_module_name</function></member>
<member><function>oci_set_client_info</function></member>
<member><function>oci_set_client_identifier</function></member>
</simplelist>
</para>
</refsect1>
</refentry>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->
| {
"content_hash": "a92240369d77790a89f949379f481455",
"timestamp": "",
"source": "github",
"line_count": 140,
"max_line_length": 84,
"avg_line_length": 24.264285714285716,
"alnum_prop": 0.6888430968501619,
"repo_name": "mziyut/.vim",
"id": "80dff96b73913bd0ef54fea82e5aa67d3b51d790",
"size": "3397",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "dict/.neocomplete-php/phpdoc/en/reference/oci8/functions/oci-set-action.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2223"
},
{
"name": "Ruby",
"bytes": "939"
},
{
"name": "Shell",
"bytes": "582"
},
{
"name": "Vim script",
"bytes": "22415"
}
],
"symlink_target": ""
} |
<?php
namespace app\controllers;
use app\forms\InterviewEditForm;
use app\forms\InterviewJoinForm;
use app\forms\InterviewRejectForm;
use app\services\StaffService;
use Yii;
use app\models\Interview;
use app\models\InterviewSearch;
use yii\base\Module;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* InterviewController implements the CRUD actions for Interview model.
*/
class InterviewController extends Controller
{
private $staffService;
public function __construct($id, Module $module, StaffService $staffService, array $config = [])
{
$this->staffService = $staffService;
parent::__construct($id, $module, $config = []);
}
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all Interview models.
* @return mixed
*/
public function actionIndex()
{
$searchModel = new InterviewSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Interview model.
* @param integer $id
* @return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Interview model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
{
$model = new Interview();
$model->scenario = Interview::SCENARIO_CREATE;
$model->date = date("Y-m-d");
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Пригласить на интервью
*/
public function actionJoin(){
$form = new InterviewJoinForm();
if($form->load(Yii::$app->request->post()) && $form->validate()){
// Внедение зависимостей
// 1 вариант
// $service = Yii::$container->get(StaffService::class);
// 2 вариант
// $service = Yii::createObject(StaffService::class);
// 3 вариант. Переопределение конструктора
$interview = $this->staffService->joinToInterview($form->lastName, $form->firstName, $form->email, $form->date);
return $this->redirect(['view', 'id'=>$interview->id]);
} else {
return $this->render('join', ['joinForm' => $form]);
}
}
/**
* Updates an existing Interview model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id
* @return mixed
*/
public function actionUpdate($id)
{
$interview = $this->findModel($id);
$form = new InterviewEditForm($interview);
if ($form->load(Yii::$app->request->post()) && $form->validate()) {
$model = $this->staffService->editInterview($id, $form->lastName, $form->firstName, $form->email, $form->date);
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'updateForm' => $form,
]);
}
}
public function actionReject($id){
$interview = Interview::findOne($id);
if($interview == null)throw new \InvalidArgumentException();
$form = new InterviewRejectForm();
if($form->load(Yii::$app->request->post()) && $form->validate()){
$this->staffService->rejectInterview($id, $form->reason);
return $this->redirect('index');
}
return $this->render('reject', ['rejectForm' => $form]);
}
/**
* Deletes an existing Interview model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* @param integer $id
* @return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the Interview model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return Interview the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Interview::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
| {
"content_hash": "73f536a784ce9728b475954f61d8ca6d",
"timestamp": "",
"source": "github",
"line_count": 186,
"max_line_length": 124,
"avg_line_length": 27.548387096774192,
"alnum_prop": 0.5487900078064013,
"repo_name": "Romario25/emploee",
"id": "5390edbf60a3a375edb8cdc195ca6ddf1bff6ccd",
"size": "5212",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "controllers/InterviewController.php",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "1030"
},
{
"name": "CSS",
"bytes": "1364"
},
{
"name": "PHP",
"bytes": "206632"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Phyllosticta baccharidis Dearn. & House
### Remarks
null | {
"content_hash": "76b31d1309af68a0a15273877b081c5f",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 11.076923076923077,
"alnum_prop": 0.7152777777777778,
"repo_name": "mdoering/backbone",
"id": "8b2b8a623b8f506ec45197a65ba1ac8d86808320",
"size": "207",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Ascomycota/Dothideomycetes/Botryosphaeriales/Botryosphaeriaceae/Phyllosticta/Phyllosticta baccharidis/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php defined('BX_DOL') or die('hack attempt');
class BxFilesUploaderHTML5 extends BxTemplUploaderHTML5
{
protected $_oModule;
public function __construct ($aObject, $sStorageObject, $sUniqId, $oTemplate)
{
parent::__construct($aObject, $sStorageObject, $sUniqId, $oTemplate);
$this->_oModule = BxDolModule::getInstance('bx_files');
}
protected function getGhostTemplateVars($aFile, $iProfileId, $iContentId, $oStorage, $oImagesTranscoder)
{
$sTitle = $this->_oModule->_oDb->getFileTitle($aFile['id']);
$a = array(
'file_title' => $sTitle ? $sTitle : $aFile['file_name']
);
$a['file_title_attr'] = bx_html_attribute($a['file_title']);
return $a;
}
protected function isUseTranscoderForPreview($oImagesTranscoder, $aFile)
{
if (!$oImagesTranscoder)
return false;
if (in_array($aFile['ext'], array('jpg', 'jpeg', 'png', 'gif', /* when ImageMagick is used - 'tif', 'tiff', 'bmp', 'ico', 'psd' */)) && (is_a($oImagesTranscoder, 'BxDolTranscoderImage') || is_a($oImagesTranscoder, 'BxDolTranscoderProxy')))
return true;
return false;
}
protected function isAdmin ($iContentId = 0)
{
return $this->_oModule->_isModerator (false);
}
}
/** @} */
| {
"content_hash": "07b8e46efd5ebbeb6090f979b78b45ac",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 247,
"avg_line_length": 32.46341463414634,
"alnum_prop": 0.599549211119459,
"repo_name": "boonex/trident",
"id": "5ee3bb5a5a0f366939caca2193dac85ca805b36c",
"size": "1501",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "modules/boonex/files/updates/9.0.1_9.0.2/source/classes/BxFilesUploaderHTML5.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "1763"
},
{
"name": "CSS",
"bytes": "1481231"
},
{
"name": "HTML",
"bytes": "690596"
},
{
"name": "JavaScript",
"bytes": "4916309"
},
{
"name": "PHP",
"bytes": "28451148"
},
{
"name": "Shell",
"bytes": "1265"
}
],
"symlink_target": ""
} |
from puzzle.server.settings import BaseConfig
def test_BaseConfig():
assert not BaseConfig.DEBUG
| {
"content_hash": "8b49ef7f955366303fa946333d2b4125",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 45,
"avg_line_length": 20.6,
"alnum_prop": 0.7864077669902912,
"repo_name": "robinandeer/puzzle",
"id": "395321d448c6f0794439271bff3be236432bd966",
"size": "127",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/server/test_settings.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "251"
},
{
"name": "HTML",
"bytes": "55258"
},
{
"name": "JavaScript",
"bytes": "1100"
},
{
"name": "Python",
"bytes": "233511"
}
],
"symlink_target": ""
} |
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in_systm.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <netdb.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include "jvm.h"
#include "jni_util.h"
#include "net_util.h"
#include "java_net_Inet4AddressImpl.h"
/* the initial size of our hostent buffers */
#define HENT_BUF_SIZE 1024
#define BIG_HENT_BUF_SIZE 10240 /* a jumbo-sized one */
#ifndef __GLIBC__
/* gethostname() is in libc.so but I can't find a header file for it */
extern int gethostname(char *buf, int buf_len);
#endif
/************************************************************************
* Inet4AddressImpl
*/
/*
* Class: java_net_Inet4AddressImpl
* Method: getLocalHostName
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL
Java_java_net_Inet4AddressImpl_getLocalHostName(JNIEnv *env, jobject this) {
char hostname[MAXHOSTNAMELEN+1];
hostname[0] = '\0';
if (JVM_GetHostName(hostname, MAXHOSTNAMELEN)) {
/* Something went wrong, maybe networking is not setup? */
strcpy(hostname, "localhost");
} else {
#ifdef __linux__
/* On Linux gethostname() says "host.domain.sun.com". On
* Solaris gethostname() says "host", so extra work is needed.
*/
#else
/* Solaris doesn't want to give us a fully qualified domain name.
* We do a reverse lookup to try and get one. This works
* if DNS occurs before NIS in /etc/resolv.conf, but fails
* if NIS comes first (it still gets only a partial name).
* We use thread-safe system calls.
*/
#endif /* __linux__ */
struct hostent res, res2, *hp;
char buf[HENT_BUF_SIZE];
char buf2[HENT_BUF_SIZE];
int h_error=0;
#ifdef __GLIBC__
gethostbyname_r(hostname, &res, buf, sizeof(buf), &hp, &h_error);
#else
hp = gethostbyname_r(hostname, &res, buf, sizeof(buf), &h_error);
#endif
if (hp) {
#ifdef __GLIBC__
gethostbyaddr_r(hp->h_addr, hp->h_length, AF_INET,
&res2, buf2, sizeof(buf2), &hp, &h_error);
#else
hp = gethostbyaddr_r(hp->h_addr, hp->h_length, AF_INET,
&res2, buf2, sizeof(buf2), &h_error);
#endif
if (hp) {
/*
* If gethostbyaddr_r() found a fully qualified host name,
* returns that name. Otherwise, returns the hostname
* found by gethostname().
*/
char *p = hp->h_name;
if ((strlen(hp->h_name) > strlen(hostname))
&& (strncmp(hostname, hp->h_name, strlen(hostname)) == 0)
&& (*(p + strlen(hostname)) == '.'))
strcpy(hostname, hp->h_name);
}
}
}
return (*env)->NewStringUTF(env, hostname);
}
static jclass ni_iacls;
static jclass ni_ia4cls;
static jmethodID ni_ia4ctrID;
static jfieldID ni_iaaddressID;
static jfieldID ni_iahostID;
static jfieldID ni_iafamilyID;
static int initialized = 0;
/*
* Find an internet address for a given hostname. Note that this
* code only works for addresses of type INET. The translation
* of %d.%d.%d.%d to an address (int) occurs in java now, so the
* String "host" shouldn't *ever* be a %d.%d.%d.%d string
*
* Class: java_net_Inet4AddressImpl
* Method: lookupAllHostAddr
* Signature: (Ljava/lang/String;)[[B
*/
JNIEXPORT jobjectArray JNICALL
Java_java_net_Inet4AddressImpl_lookupAllHostAddr(JNIEnv *env, jobject this,
jstring host) {
const char *hostname;
jobject name;
jobjectArray ret = 0;
struct hostent res, *hp = 0;
char buf[HENT_BUF_SIZE];
/* temporary buffer, on the off chance we need to expand */
char *tmp = NULL;
int h_error=0;
if (!initialized) {
ni_iacls = (*env)->FindClass(env, "java/net/InetAddress");
ni_iacls = (*env)->NewGlobalRef(env, ni_iacls);
ni_ia4cls = (*env)->FindClass(env, "java/net/Inet4Address");
ni_ia4cls = (*env)->NewGlobalRef(env, ni_ia4cls);
ni_ia4ctrID = (*env)->GetMethodID(env, ni_ia4cls, "<init>", "()V");
ni_iaaddressID = (*env)->GetFieldID(env, ni_iacls, "address", "I");
ni_iafamilyID = (*env)->GetFieldID(env, ni_iacls, "family", "I");
ni_iahostID = (*env)->GetFieldID(env, ni_iacls, "hostName", "Ljava/lang/String;");
initialized = 1;
}
if (IS_NULL(host)) {
JNU_ThrowNullPointerException(env, "host is null");
return 0;
}
hostname = JNU_GetStringPlatformChars(env, host, JNI_FALSE);
CHECK_NULL_RETURN(hostname, NULL);
/*
* Workaround for Solaris bug 4160367 - if a hostname contains a
* white space then 0.0.0.0 is returned
*/
if (isspace(hostname[0])) {
JNU_ThrowByName(env, JNU_JAVANETPKG "UnknownHostException",
(char *)hostname);
JNU_ReleaseStringPlatformChars(env, host, hostname);
return NULL;
}
/* Try once, with our static buffer. */
#ifdef __GLIBC__
gethostbyname_r(hostname, &res, buf, sizeof(buf), &hp, &h_error);
#else
hp = gethostbyname_r(hostname, &res, buf, sizeof(buf), &h_error);
#endif
/* With the re-entrant system calls, it's possible that the buffer
* we pass to it is not large enough to hold an exceptionally
* large DNS entry. This is signaled by errno->ERANGE. We try once
* more, with a very big size.
*/
if (hp == NULL && errno == ERANGE) {
if ((tmp = (char*)malloc(BIG_HENT_BUF_SIZE))) {
#ifdef __GLIBC__
gethostbyname_r(hostname, &res, tmp, BIG_HENT_BUF_SIZE,
&hp, &h_error);
#else
hp = gethostbyname_r(hostname, &res, tmp, BIG_HENT_BUF_SIZE,
&h_error);
#endif
}
}
if (hp != NULL) {
struct in_addr **addrp = (struct in_addr **) hp->h_addr_list;
int len = sizeof(struct in_addr);
int i = 0;
while (*addrp != (struct in_addr *) 0) {
i++;
addrp++;
}
name = (*env)->NewStringUTF(env, hostname);
if (IS_NULL(name)) {
goto cleanupAndReturn;
}
ret = (*env)->NewObjectArray(env, i, ni_iacls, NULL);
if (IS_NULL(ret)) {
/* we may have memory to free at the end of this */
goto cleanupAndReturn;
}
addrp = (struct in_addr **) hp->h_addr_list;
i = 0;
while (*addrp) {
jobject iaObj = (*env)->NewObject(env, ni_ia4cls, ni_ia4ctrID);
if (IS_NULL(iaObj)) {
ret = NULL;
goto cleanupAndReturn;
}
(*env)->SetIntField(env, iaObj, ni_iaaddressID,
ntohl((*addrp)->s_addr));
(*env)->SetObjectField(env, iaObj, ni_iahostID, name);
(*env)->SetObjectArrayElement(env, ret, i, iaObj);
addrp++;
i++;
}
} else {
JNU_ThrowByName(env, JNU_JAVANETPKG "UnknownHostException",
(char *)hostname);
ret = NULL;
}
cleanupAndReturn:
JNU_ReleaseStringPlatformChars(env, host, hostname);
if (tmp != NULL) {
free(tmp);
}
return ret;
}
/*
* Class: java_net_Inet4AddressImpl
* Method: getHostByAddr
* Signature: (I)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL
Java_java_net_Inet4AddressImpl_getHostByAddr(JNIEnv *env, jobject this,
jbyteArray addrArray) {
jstring ret = NULL;
jint addr;
struct hostent hent, *hp = 0;
char buf[HENT_BUF_SIZE];
int h_error = 0;
char *tmp = NULL;
/*
* We are careful here to use the reentrant version of
* gethostbyname because at the Java level this routine is not
* protected by any synchronization.
*
* Still keeping the reentrant platform dependent calls temporarily
* We should probably conform to one interface later.
*
*/
jbyte caddr[4];
(*env)->GetByteArrayRegion(env, addrArray, 0, 4, caddr);
addr = ((caddr[0]<<24) & 0xff000000);
addr |= ((caddr[1] <<16) & 0xff0000);
addr |= ((caddr[2] <<8) & 0xff00);
addr |= (caddr[3] & 0xff);
addr = htonl(addr);
#ifdef __GLIBC__
gethostbyaddr_r((char *)&addr, sizeof(addr), AF_INET, &hent,
buf, sizeof(buf), &hp, &h_error);
#else
hp = gethostbyaddr_r((char *)&addr, sizeof(addr), AF_INET, &hent,
buf, sizeof(buf), &h_error);
#endif
/* With the re-entrant system calls, it's possible that the buffer
* we pass to it is not large enough to hold an exceptionally
* large DNS entry. This is signaled by errno->ERANGE. We try once
* more, with a very big size.
*/
if (hp == NULL && errno == ERANGE) {
if ((tmp = (char*)malloc(BIG_HENT_BUF_SIZE))) {
#ifdef __GLIBC__
gethostbyaddr_r((char *)&addr, sizeof(addr), AF_INET,
&hent, tmp, BIG_HENT_BUF_SIZE, &hp, &h_error);
#else
hp = gethostbyaddr_r((char *)&addr, sizeof(addr), AF_INET,
&hent, tmp, BIG_HENT_BUF_SIZE, &h_error);
#endif
} else {
JNU_ThrowOutOfMemoryError(env, "getHostByAddr");
}
}
if (hp == NULL) {
JNU_ThrowByName(env, JNU_JAVANETPKG "UnknownHostException", NULL);
} else {
ret = (*env)->NewStringUTF(env, hp->h_name);
}
if (tmp) {
free(tmp);
}
return ret;
}
#define SET_NONBLOCKING(fd) { \
int flags = fcntl(fd, F_GETFL); \
flags |= O_NONBLOCK; \
fcntl(fd, F_SETFL, flags); \
}
/**
* ping implementation.
* Send a ICMP_ECHO_REQUEST packet every second until either the timeout
* expires or a answer is received.
* Returns true is an ECHO_REPLY is received, otherwise, false.
*/
static jboolean
ping4(JNIEnv *env, jint fd, struct sockaddr_in* him, jint timeout,
struct sockaddr_in* netif, jint ttl) {
jint size;
jint n, len, hlen1, icmplen;
char sendbuf[1500];
char recvbuf[1500];
struct icmp *icmp;
struct ip *ip;
struct sockaddr sa_recv;
jchar pid, seq;
jint tmout2;
struct timeval tv;
size_t plen;
/* Initialize the sequence number to a suitable random number and
shift right one place to allow sufficient room for increamenting. */
seq = ((unsigned short)rand()) >> 1;
/* icmp_id is a 16 bit data type, therefore down cast the pid */
pid = (jchar)getpid();
size = 60*1024;
setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size));
/*
* sets the ttl (max number of hops)
*/
if (ttl > 0) {
setsockopt(fd, IPPROTO_IP, IP_TTL, &ttl, sizeof(ttl));
}
/*
* a specific interface was specified, so let's bind the socket
* to that interface to ensure the requests are sent only through it.
*/
if (netif != NULL) {
if (bind(fd, (struct sockaddr*)netif, sizeof(struct sockaddr_in)) < 0) {
NET_ThrowNew(env, errno, "Can't bind socket");
close(fd);
return JNI_FALSE;
}
}
/*
* Make the socket non blocking so we can use select
*/
SET_NONBLOCKING(fd);
do {
/*
* create the ICMP request
*/
icmp = (struct icmp *) sendbuf;
icmp->icmp_type = ICMP_ECHO;
icmp->icmp_code = 0;
icmp->icmp_id = htons(pid);
icmp->icmp_seq = htons(seq);
gettimeofday(&tv, NULL);
memcpy(icmp->icmp_data, &tv, sizeof(tv));
plen = ICMP_ADVLENMIN + sizeof(tv);
icmp->icmp_cksum = 0;
icmp->icmp_cksum = in_cksum((u_short *)icmp, plen);
/*
* send it
*/
n = sendto(fd, sendbuf, plen, 0, (struct sockaddr *)him,
sizeof(struct sockaddr));
if (n < 0 && errno != EINPROGRESS ) {
NET_ThrowNew(env, errno, "Can't send ICMP packet");
close(fd);
return JNI_FALSE;
}
tmout2 = timeout > 1000 ? 1000 : timeout;
do {
tmout2 = NET_Wait(env, fd, NET_WAIT_READ, tmout2);
if (tmout2 >= 0) {
len = sizeof(sa_recv);
n = recvfrom(fd, recvbuf, sizeof(recvbuf), 0, &sa_recv, &len);
ip = (struct ip*) recvbuf;
hlen1 = (ip->ip_hl) << 2;
icmp = (struct icmp *) (recvbuf + hlen1);
icmplen = n - hlen1;
/*
* We did receive something, but is it what we were expecting?
* I.E.: A ICMP_ECHOREPLY packet with the proper PID and sequence number.
*/
if (icmplen >= 8 && icmp->icmp_type == ICMP_ECHOREPLY &&
(ntohs(icmp->icmp_seq) == seq) && (ntohs(icmp->icmp_id) == pid)) {
close(fd);
return JNI_TRUE;
}
}
} while (tmout2 > 0);
timeout -= 1000;
seq++;
} while (timeout >0);
close(fd);
return JNI_FALSE;
}
/*
* Class: java_net_Inet4AddressImpl
* Method: isReachable0
* Signature: ([bI[bI)Z
*/
JNIEXPORT jboolean JNICALL
Java_java_net_Inet4AddressImpl_isReachable0(JNIEnv *env, jobject this,
jbyteArray addrArray,
jint timeout,
jbyteArray ifArray,
jint ttl) {
jint addr;
jbyte caddr[4];
jint fd;
struct sockaddr_in him;
struct sockaddr_in* netif = NULL;
struct sockaddr_in inf;
int len = 0;
int connect_rv = -1;
int sz;
memset((char *) caddr, 0, sizeof(caddr));
memset((char *) &him, 0, sizeof(him));
sz = (*env)->GetArrayLength(env, addrArray);
if (sz != 4) {
return JNI_FALSE;
}
(*env)->GetByteArrayRegion(env, addrArray, 0, 4, caddr);
addr = ((caddr[0]<<24) & 0xff000000);
addr |= ((caddr[1] <<16) & 0xff0000);
addr |= ((caddr[2] <<8) & 0xff00);
addr |= (caddr[3] & 0xff);
addr = htonl(addr);
him.sin_addr.s_addr = addr;
him.sin_family = AF_INET;
len = sizeof(him);
/*
* If a network interface was specified, let's create the address
* for it.
*/
if (!(IS_NULL(ifArray))) {
memset((char *) caddr, 0, sizeof(caddr));
(*env)->GetByteArrayRegion(env, ifArray, 0, 4, caddr);
addr = ((caddr[0]<<24) & 0xff000000);
addr |= ((caddr[1] <<16) & 0xff0000);
addr |= ((caddr[2] <<8) & 0xff00);
addr |= (caddr[3] & 0xff);
addr = htonl(addr);
inf.sin_addr.s_addr = addr;
inf.sin_family = AF_INET;
inf.sin_port = 0;
netif = &inf;
}
/*
* Let's try to create a RAW socket to send ICMP packets
* This usually requires "root" privileges, so it's likely to fail.
*/
fd = JVM_Socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
if (fd != -1) {
/*
* It didn't fail, so we can use ICMP_ECHO requests.
*/
return ping4(env, fd, &him, timeout, netif, ttl);
}
/*
* Can't create a raw socket, so let's try a TCP socket
*/
fd = JVM_Socket(AF_INET, SOCK_STREAM, 0);
if (fd == JVM_IO_ERR) {
/* note: if you run out of fds, you may not be able to load
* the exception class, and get a NoClassDefFoundError
* instead.
*/
NET_ThrowNew(env, errno, "Can't create socket");
return JNI_FALSE;
}
if (ttl > 0) {
setsockopt(fd, IPPROTO_IP, IP_TTL, &ttl, sizeof(ttl));
}
/*
* A network interface was specified, so let's bind to it.
*/
if (netif != NULL) {
if (bind(fd, (struct sockaddr*)netif, sizeof(struct sockaddr_in)) < 0) {
NET_ThrowNew(env, errno, "Can't bind socket");
close(fd);
return JNI_FALSE;
}
}
/*
* Make the socket non blocking so we can use select/poll.
*/
SET_NONBLOCKING(fd);
/* no need to use NET_Connect as non-blocking */
him.sin_port = htons(7); /* Echo */
connect_rv = JVM_Connect(fd, (struct sockaddr *)&him, len);
/**
* connection established or refused immediately, either way it means
* we were able to reach the host!
*/
if (connect_rv == 0 || errno == ECONNREFUSED) {
close(fd);
return JNI_TRUE;
} else {
int optlen;
switch (errno) {
case ENETUNREACH: /* Network Unreachable */
case EAFNOSUPPORT: /* Address Family not supported */
case EADDRNOTAVAIL: /* address is not available on the remote machine */
#ifdef __linux__
case EINVAL:
/*
* On some Linuxes, when bound to the loopback interface, connect
* will fail and errno will be set to EINVAL. When that happens,
* don't throw an exception, just return false.
*/
#endif /* __linux__ */
close(fd);
return JNI_FALSE;
}
if (errno != EINPROGRESS) {
NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "ConnectException",
"connect failed");
close(fd);
return JNI_FALSE;
}
timeout = NET_Wait(env, fd, NET_WAIT_CONNECT, timeout);
if (timeout >= 0) {
/* has connection been established? */
optlen = sizeof(connect_rv);
if (JVM_GetSockOpt(fd, SOL_SOCKET, SO_ERROR, (void*)&connect_rv,
&optlen) <0) {
connect_rv = errno;
}
if (connect_rv == 0 || connect_rv == ECONNREFUSED) {
close(fd);
return JNI_TRUE;
}
}
close(fd);
return JNI_FALSE;
}
}
| {
"content_hash": "1f2620c424e20bcffb7e27bfae670b8f",
"timestamp": "",
"source": "github",
"line_count": 557,
"max_line_length": 88,
"avg_line_length": 31.89048473967684,
"alnum_prop": 0.5509767494229578,
"repo_name": "andreagenso/java2scala",
"id": "ccf06a645dd22aab5b079311666684b474f358e0",
"size": "18975",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "test/J2s/java/openjdk-6-src-b27/jdk/src/solaris/native/java/net/Inet4AddressImpl.c",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "8983"
},
{
"name": "Awk",
"bytes": "26041"
},
{
"name": "Batchfile",
"bytes": "1796"
},
{
"name": "C",
"bytes": "20159882"
},
{
"name": "C#",
"bytes": "7630"
},
{
"name": "C++",
"bytes": "4513460"
},
{
"name": "CSS",
"bytes": "5128"
},
{
"name": "DTrace",
"bytes": "68220"
},
{
"name": "HTML",
"bytes": "1302117"
},
{
"name": "Haskell",
"bytes": "244134"
},
{
"name": "Java",
"bytes": "129267130"
},
{
"name": "JavaScript",
"bytes": "182900"
},
{
"name": "Makefile",
"bytes": "711241"
},
{
"name": "Objective-C",
"bytes": "66163"
},
{
"name": "Python",
"bytes": "137817"
},
{
"name": "Roff",
"bytes": "2630160"
},
{
"name": "Scala",
"bytes": "25599"
},
{
"name": "Shell",
"bytes": "888136"
},
{
"name": "SourcePawn",
"bytes": "78"
}
],
"symlink_target": ""
} |
import { Injectable } from '@angular/core';
import { Hero } from './hero';
import { HEROES } from './mock-heroes';
@Injectable()
export class HeroService {
getHeroes(): Promise<Hero[]> {
return Promise.resolve(HEROES);
}
getHero(id: number): Promise<Hero> {
return this.getHeroes()
.then(heroes => heroes.find(hero => hero.id === id));
}
}
| {
"content_hash": "42af85b0a738589e2a6168213e1439f8",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 73,
"avg_line_length": 26,
"alnum_prop": 0.5897435897435898,
"repo_name": "jacraven/angular2",
"id": "0482b388d8c1fcb93cd13973a24fb6b28dd5208f",
"size": "390",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/hero.service.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5056"
},
{
"name": "HTML",
"bytes": "1617"
},
{
"name": "JavaScript",
"bytes": "17321"
},
{
"name": "TypeScript",
"bytes": "6629"
}
],
"symlink_target": ""
} |
extern void registerMathFunctions(CTinyJS *tinyJS);
#endif
| {
"content_hash": "38a04e2c9b34395d80fc092e4aa0098a",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 51,
"avg_line_length": 20,
"alnum_prop": 0.8166666666666667,
"repo_name": "manu88/Celesta",
"id": "cb5489f140f91b218286ee97c3c728f543619b15",
"size": "208",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "Core/JSMachine/TinyJS/TinyJS_MathFunctions.h",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "332079"
},
{
"name": "C++",
"bytes": "1765597"
},
{
"name": "JavaScript",
"bytes": "62211"
},
{
"name": "Makefile",
"bytes": "9949"
}
],
"symlink_target": ""
} |
import {VariableSource} from '../../src/service/variable-source';
import {installUrlReplacementsForEmbed} from '../../src/service/url-replacements-impl';
describes.realWin('amp-pixel', {amp: true}, env => {
let win;
let whenFirstVisiblePromise, whenFirstVisibleResolver;
let pixel;
let implementation;
beforeEach(() => {
win = env.win;
whenFirstVisiblePromise = new Promise(resolve => {
whenFirstVisibleResolver = resolve;
});
env.sandbox
.stub(env.ampdoc, 'whenFirstVisible')
.callsFake(() => whenFirstVisiblePromise);
createPixel('https://pubads.g.doubleclick.net/activity;dc_iu=1/abc;ord=1?');
});
function createPixel(src, referrerPolicy) {
pixel = win.document.createElement('amp-pixel');
pixel.setAttribute('src', src);
if (referrerPolicy) {
pixel.setAttribute('referrerpolicy', referrerPolicy);
}
win.document.body.appendChild(pixel);
const buildPromise = pixel.build();
implementation = pixel.implementation_;
return buildPromise;
}
/**
* @param {string=} opt_src
* @return {!Promise<?Image>}
*/
function trigger(opt_src) {
if (opt_src != null) {
pixel.setAttribute('src', opt_src);
}
whenFirstVisibleResolver();
return whenFirstVisiblePromise.then(() => {
expect(implementation.triggerPromise_).to.be.not.null;
return implementation.triggerPromise_;
});
}
it('should be non-displayed', () => {
expect(pixel.style.width).to.equal('0px');
expect(pixel.style.height).to.equal('0px');
expect(pixel.getAttribute('aria-hidden')).to.equal('true');
expect(pixel).to.have.display('none');
});
it('should NOT trigger when src is empty', () => {
expect(pixel.children).to.have.length(0);
expect(implementation.triggerPromise_).to.be.null;
return trigger('').then(img => {
expect(implementation.triggerPromise_).to.be.ok;
expect(img).to.be.undefined;
});
});
it('should trigger when doc becomes visible', () => {
expect(pixel.children).to.have.length(0);
expect(implementation.triggerPromise_).to.be.null;
return trigger().then(img => {
expect(implementation.triggerPromise_).to.be.ok;
expect(img.src).to.equal(
'https://pubads.g.doubleclick.net/activity;dc_iu=1/abc;ord=1?'
);
});
});
it('should allow protocol-relative URLs', () => {
const url = '//pubads.g.doubleclick.net/activity;dc_iu=1/abc;ord=2';
return trigger(url).then(img => {
// Protocol is resolved to `http:` relative to test server.
expect(img.src).to.equal(
'http://pubads.g.doubleclick.net/activity;dc_iu=1/abc;ord=2'
);
});
});
it('should disallow http URLs', () => {
const url = 'http://pubads.g.doubleclick.net/activity;dc_iu=1/abc;ord=2';
return expect(trigger(url)).to.eventually.be.rejectedWith(
/src attribute must start with/
);
});
it('should disallow relative URLs', () => {
const url = '/activity;dc_iu=1/abc;ord=2';
return expect(trigger(url)).to.eventually.be.rejectedWith(
/src attribute must start with/
);
});
it('should disallow fake-protocol URLs', () => {
const url = 'https/activity;dc_iu=1/abc;ord=2';
return expect(trigger(url)).to.eventually.be.rejectedWith(
/src attribute must start with/
);
});
it('should replace URL parameters', () => {
env.sandbox.stub(Math, 'random').callsFake(() => 111);
const url = 'https://pubads.g.doubleclick.net/activity;r=RANDOM';
return trigger(url).then(img => {
expect(img.src).to.equal(
'https://pubads.g.doubleclick.net/activity;r=111'
);
});
});
it('should throw for referrerpolicy with value other than no-referrer', () => {
return allowConsoleError(() => {
return createPixel(
'https://pubads.g.doubleclick.net/activity;dc_iu=1/abc;ord=1?',
'origin'
).then(
() => {
throw new Error('must have failed.');
},
reason => {
expect(reason.message).to.match(/referrerpolicy/);
}
);
});
});
});
describes.realWin(
'amp-pixel in embed',
{
amp: {
ampdoc: 'fie',
},
},
env => {
class TestVariableSource extends VariableSource {
constructor() {
super(env.ampdoc);
}
initialize() {
this.set('TEST', () => 'value1');
}
}
let win;
let whenFirstVisiblePromise, whenFirstVisibleResolver;
let pixel;
let implementation;
beforeEach(() => {
win = env.win;
whenFirstVisiblePromise = new Promise(resolve => {
whenFirstVisibleResolver = resolve;
});
env.sandbox
.stub(env.ampdoc, 'whenFirstVisible')
.callsFake(() => whenFirstVisiblePromise);
installUrlReplacementsForEmbed(env.ampdoc, win, new TestVariableSource());
pixel = win.document.createElement('amp-pixel');
pixel.setAttribute(
'src',
'https://pubads.g.doubleclick.net/activity;dc_iu=1/abc;ord=1?'
);
win.document.body.appendChild(pixel);
pixel.build();
implementation = pixel.implementation_;
});
/**
* @param {string=} opt_src
* @return {!Promise<?Image>}
*/
function trigger(opt_src) {
if (opt_src) {
pixel.setAttribute('src', opt_src);
}
whenFirstVisibleResolver();
return whenFirstVisiblePromise.then(() => {
expect(implementation.triggerPromise_).to.be.not.null;
return implementation.triggerPromise_;
});
}
it("should use embed's URL replacer", () => {
const url = 'https://pubads.g.doubleclick.net/activity;t=TEST';
return trigger(url).then(img => {
expect(img.src).to.equal(
'https://pubads.g.doubleclick.net/activity;t=value1'
);
});
});
}
);
| {
"content_hash": "7e6c0edbbfe63614c7937a13a46afa14",
"timestamp": "",
"source": "github",
"line_count": 203,
"max_line_length": 87,
"avg_line_length": 28.886699507389164,
"alnum_prop": 0.6111869031377899,
"repo_name": "tlong2/amphtml",
"id": "7b527f73e898b806f311ea34fb8935a2d46f12e9",
"size": "6491",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "test/unit/test-amp-pixel.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "471155"
},
{
"name": "Go",
"bytes": "7443"
},
{
"name": "HTML",
"bytes": "2028893"
},
{
"name": "Java",
"bytes": "872367"
},
{
"name": "JavaScript",
"bytes": "17116700"
},
{
"name": "Python",
"bytes": "79734"
},
{
"name": "Shell",
"bytes": "19697"
},
{
"name": "Yacc",
"bytes": "23470"
}
],
"symlink_target": ""
} |
package e2e
import (
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
"github.com/GoogleCloudPlatform/kubernetes/pkg/client"
"github.com/GoogleCloudPlatform/kubernetes/pkg/labels"
"github.com/GoogleCloudPlatform/kubernetes/pkg/util"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("ReplicationController", func() {
var c *client.Client
BeforeEach(func() {
var err error
c, err = loadClient()
Expect(err).NotTo(HaveOccurred())
})
It("should serve a basic image on each replica with a public image", func() {
ServeImageOrFail(c, "basic", "kubernetes/serve_hostname:1.1")
})
It("should serve a basic image on each replica with a private image", func() {
switch testContext.provider {
case "gce", "gke", "aws":
ServeImageOrFail(c, "private", "gcr.io/_b_k8s_test/serve_hostname:1.0")
default:
By(fmt.Sprintf("Skipping private variant, which is only supported for providers gce, gke and aws (not %s)",
testContext.provider))
}
})
})
// A basic test to check the deployment of an image using
// a replication controller. The image serves its hostname
// which is checked for each replica.
func ServeImageOrFail(c *client.Client, test string, image string) {
ns := api.NamespaceDefault
name := "my-hostname-" + test + "-" + string(util.NewUUID())
replicas := 2
// Create a replication controller for a service
// that serves its hostname on port 8080.
// The source for the Docker containter kubernetes/serve_hostname is
// in contrib/for-demos/serve_hostname
By(fmt.Sprintf("Creating replication controller %s", name))
controller, err := c.ReplicationControllers(ns).Create(&api.ReplicationController{
ObjectMeta: api.ObjectMeta{
Name: name,
},
Spec: api.ReplicationControllerSpec{
Replicas: replicas,
Selector: map[string]string{
"name": name,
},
Template: &api.PodTemplateSpec{
ObjectMeta: api.ObjectMeta{
Labels: map[string]string{"name": name},
},
Spec: api.PodSpec{
Containers: []api.Container{
{
Name: name,
Image: image,
Ports: []api.Port{{ContainerPort: 9376, HostPort: 8080}},
},
},
},
},
},
})
Expect(err).NotTo(HaveOccurred())
// Cleanup the replication controller when we are done.
defer func() {
// Resize the replication controller to zero to get rid of pods.
controller.Spec.Replicas = 0
if _, err = c.ReplicationControllers(ns).Update(controller); err != nil {
By(fmt.Sprintf("Failed to resize replication controller %s to zero: %v", name, err))
}
// Delete the replication controller.
if err = c.ReplicationControllers(ns).Delete(name); err != nil {
By(fmt.Sprintf("Failed to delete replication controller %s: %v", name, err))
}
}()
// List the pods, making sure we observe all the replicas.
listTimeout := time.Minute
label := labels.SelectorFromSet(labels.Set(map[string]string{"name": name}))
pods, err := c.Pods(ns).List(label)
Expect(err).NotTo(HaveOccurred())
t := time.Now()
for {
By(fmt.Sprintf("Controller %s: Found %d pods out of %d", name, len(pods.Items), replicas))
if len(pods.Items) == replicas {
break
}
if time.Since(t) > listTimeout {
Fail(fmt.Sprintf(
"Controller %s: Gave up waiting for %d pods to come up after seeing only %d pods after %v seconds",
name, replicas, len(pods.Items), time.Since(t).Seconds()))
}
time.Sleep(5 * time.Second)
pods, err = c.Pods(ns).List(label)
Expect(err).NotTo(HaveOccurred())
}
// Wait for the pods to enter the running state. Waiting loops until the pods
// are running so non-running pods cause a timeout for this test.
for _, pod := range pods.Items {
err = waitForPodRunning(c, pod.Name, 300*time.Second)
Expect(err).NotTo(HaveOccurred())
}
// Try to make sure we get a hostIP for each pod.
hostIPTimeout := 2 * time.Minute
t = time.Now()
for i, pod := range pods.Items {
for {
p, err := c.Pods(ns).Get(pod.Name)
Expect(err).NotTo(HaveOccurred())
if p.Status.HostIP != "" {
By(fmt.Sprintf("Controller %s: Replica %d has hostIP: %s", name, i+1, p.Status.HostIP))
break
}
if time.Since(t) >= hostIPTimeout {
Fail(fmt.Sprintf("Controller %s: Gave up waiting for hostIP of replica %d after %v seconds",
name, i, time.Since(t).Seconds()))
}
By(fmt.Sprintf("Controller %s: Retrying to get the hostIP of replica %d", name, i+1))
time.Sleep(5 * time.Second)
}
}
// Re-fetch the pod information to update the host port information.
pods, err = c.Pods(ns).List(label)
Expect(err).NotTo(HaveOccurred())
// Verify that something is listening.
for i, pod := range pods.Items {
resp, err := http.Get(fmt.Sprintf("http://%s:8080", pod.Status.HostIP))
if err != nil {
Fail(fmt.Sprintf("Controller %s: Failed to GET from replica %d: %v", name, i+1, err))
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
Fail(fmt.Sprintf("Controller %s: Expected OK status code for replica %d but got %d", name, i+1, resp.StatusCode))
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
Fail(fmt.Sprintf("Controller %s: Failed to read the body of the GET response from replica %d: %v",
name, i+1, err))
}
// The body should be the pod name.
if string(body) != pod.Name {
Fail(fmt.Sprintf("Controller %s: Replica %d expected response %s but got %s", name, i+1, pod.Name, string(body)))
}
By(fmt.Sprintf("Controller %s: Got expected result from replica %d: %s", name, i+1, string(body)))
}
}
| {
"content_hash": "c360c6795b4e3914e619cfd0cddc123c",
"timestamp": "",
"source": "github",
"line_count": 170,
"max_line_length": 116,
"avg_line_length": 32.588235294117645,
"alnum_prop": 0.6749097472924188,
"repo_name": "simon3z/kubernetes",
"id": "0b5ec8efd2cde24b41e944ed08611039f5599af9",
"size": "6118",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "test/e2e/rc.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "3153"
},
{
"name": "Go",
"bytes": "5188567"
},
{
"name": "Java",
"bytes": "3258"
},
{
"name": "JavaScript",
"bytes": "11912"
},
{
"name": "Makefile",
"bytes": "7244"
},
{
"name": "PHP",
"bytes": "1029"
},
{
"name": "Python",
"bytes": "7895"
},
{
"name": "Scheme",
"bytes": "1112"
},
{
"name": "Shell",
"bytes": "446092"
}
],
"symlink_target": ""
} |
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import chai, { expect } from 'chai';
import { renderOnce } from 'test/helpers/render';
import Button from '#button';
describe('button', () => {
describe('basic', () => {
it('exists', () => {
expect(Button).to.exist;
});
it('is a component', () => {
expect(TestUtils.isCompositeComponent(renderOnce(Button()))).to.be.true;
});
});
describe('render', () => {
beforeEach(function() {
this.renderWithProps = props => {
this.rootComponent = renderOnce(Button(props));
this.rootComponentDOMNode = ReactDOM.findDOMNode(this.rootComponent);
this.inputControlDOMNode = TestUtils.findRenderedDOMComponentWithClass(this.rootComponent, 'button__control');
};
this.renderWithProps();
});
describe('DOM', () => {
it('initial', function() {
expect(this.inputControlDOMNode.tagName).to.be.equal('INPUT');
expect(this.inputControlDOMNode.type).to.be.equal('button');
expect(this.rootComponentDOMNode).to.be.a.block('button');
expect(this.inputControlDOMNode).to.be.an.elem({
block: 'button',
elem: 'control'
});
});
it('hover', function() {
TestUtils.Simulate.mouseEnter(this.inputControlDOMNode);
expect(this.rootComponentDOMNode).to.have.mods({ hovered: true });
TestUtils.Simulate.mouseLeave(this.inputControlDOMNode);
expect(this.rootComponentDOMNode).to.not.have.mods({ hovered: true });
});
it('focus/blur', function() {
TestUtils.Simulate.focus(this.inputControlDOMNode);
expect(this.rootComponentDOMNode).to.have.mods({ focused: true });
TestUtils.Simulate.blur(this.inputControlDOMNode);
expect(this.rootComponentDOMNode).to.not.have.mods({ focused: true });
});
it('pressed', function() {
TestUtils.Simulate.mouseDown(this.inputControlDOMNode);
expect(this.rootComponentDOMNode).to.have.mods({ pressed: true });
TestUtils.Simulate.mouseUp(this.inputControlDOMNode);
expect(this.rootComponentDOMNode).to.not.have.mods({ pressed: true });
});
it('disabled', function() {
this.renderWithProps({ disabled: true });
expect(this.rootComponentDOMNode).to.have.mods({ disabled: true });
});
it('children', function() {
this.renderWithProps({
children: React.createElement('div', {
key: 'test',
className: 'test-children'
})
});
expect(
TestUtils.findRenderedDOMComponentWithClass(this.rootComponent, 'test-children')
).to.be.block('test-children');
});
});
describe('callbacks', () => {
it('onFocus', function() {
const spy = chai.spy();
this.renderWithProps({ onFocus: spy });
TestUtils.Simulate.focus(this.inputControlDOMNode);
expect(spy).to.have.been.called.once;
this.renderWithProps();
TestUtils.Simulate.focus(this.inputControlDOMNode);
expect(spy).to.have.been.called.once;
});
it('onBlur', function() {
const spy = chai.spy();
this.renderWithProps({ onBlur: spy });
TestUtils.Simulate.blur(this.inputControlDOMNode);
expect(spy).to.have.been.called.once;
this.renderWithProps();
TestUtils.Simulate.blur(this.inputControlDOMNode);
expect(spy).to.have.been.called.once;
});
it('onClick', function() {
const spy = chai.spy();
this.renderWithProps({ onClick: spy });
TestUtils.Simulate.click(this.inputControlDOMNode);
expect(spy).to.have.been.called.once;
this.renderWithProps();
TestUtils.Simulate.click(this.inputControlDOMNode);
expect(spy).to.have.been.called.once;
});
it('onMouseEnter', function() {
const spy = chai.spy();
this.renderWithProps({ onMouseEnter: spy });
TestUtils.Simulate.mouseEnter(this.inputControlDOMNode);
expect(spy).to.have.been.called.once;
this.renderWithProps();
TestUtils.Simulate.mouseEnter(this.inputControlDOMNode);
expect(spy).to.have.been.called.once;
});
it('onMouseLeave', function() {
const spy = chai.spy();
this.renderWithProps({ onMouseLeave: spy });
TestUtils.Simulate.mouseLeave(this.inputControlDOMNode);
expect(spy).to.have.been.called.once;
this.renderWithProps();
TestUtils.Simulate.mouseLeave(this.inputControlDOMNode);
expect(spy).to.have.been.called.once;
});
it('onMouseDown', function() {
const spy = chai.spy();
this.renderWithProps({ onMouseDown: spy });
TestUtils.Simulate.mouseDown(this.inputControlDOMNode);
expect(spy).to.have.been.called.once;
this.renderWithProps();
TestUtils.Simulate.mouseDown(this.inputControlDOMNode);
expect(spy).to.have.been.called.once;
});
it('onMouseUp', function() {
const spy = chai.spy();
this.renderWithProps({ onMouseUp: spy });
TestUtils.Simulate.mouseUp(this.inputControlDOMNode);
expect(spy).to.have.been.called.once;
this.renderWithProps();
TestUtils.Simulate.mouseUp(this.inputControlDOMNode);
expect(spy).to.have.been.called.once;
});
});
});
});
| {
"content_hash": "43e71e4df3725cbd7032c99d03bcf6f6",
"timestamp": "",
"source": "github",
"line_count": 172,
"max_line_length": 126,
"avg_line_length": 37.2093023255814,
"alnum_prop": 0.53328125,
"repo_name": "yummies/core-components",
"id": "a50a21479194dc9ff9b6fc34155244e4d2560821",
"size": "6400",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/src/button/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "233"
},
{
"name": "JavaScript",
"bytes": "144215"
}
],
"symlink_target": ""
} |
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "protocolrecords/GetContainersResponse.h"
using namespace libyarn;
using namespace testing;
class TestGetContainersResponse: public ::testing::Test {
protected:
GetContainersResponse getResponse;
};
TEST_F(TestGetContainersResponse, TestGetProto)
{
GetContainersResponseProto getResponseProto;
getResponseProto = getResponse.getProto();
SUCCEED();
}
| {
"content_hash": "6b1c5165104f294ce4ecb6808ea86998",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 57,
"avg_line_length": 19.09090909090909,
"alnum_prop": 0.8,
"repo_name": "wengyanqing/incubator-hawq",
"id": "bfb4e54a52cd9b9a0446c8ffc1a4f9c74a1d7646",
"size": "1227",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "depends/libyarn/test/unit/TestProtocolRecords/TestGetContainersResponse.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "5196"
},
{
"name": "Batchfile",
"bytes": "11532"
},
{
"name": "C",
"bytes": "32468088"
},
{
"name": "C++",
"bytes": "5012439"
},
{
"name": "CMake",
"bytes": "161906"
},
{
"name": "Csound Score",
"bytes": "179"
},
{
"name": "DTrace",
"bytes": "1154"
},
{
"name": "HTML",
"bytes": "69676"
},
{
"name": "Java",
"bytes": "2469984"
},
{
"name": "Lex",
"bytes": "196336"
},
{
"name": "M4",
"bytes": "82922"
},
{
"name": "Makefile",
"bytes": "441655"
},
{
"name": "Objective-C",
"bytes": "16038"
},
{
"name": "PLSQL",
"bytes": "198268"
},
{
"name": "PLpgSQL",
"bytes": "2523278"
},
{
"name": "Perl",
"bytes": "867241"
},
{
"name": "Perl 6",
"bytes": "1707"
},
{
"name": "Python",
"bytes": "166388"
},
{
"name": "Roff",
"bytes": "30181"
},
{
"name": "SQLPL",
"bytes": "193461"
},
{
"name": "Shell",
"bytes": "235883"
},
{
"name": "Smarty",
"bytes": "244244"
},
{
"name": "Thrift",
"bytes": "9459"
},
{
"name": "XS",
"bytes": "8309"
},
{
"name": "Yacc",
"bytes": "440492"
}
],
"symlink_target": ""
} |
module.exports = function (grunt) {
grunt.registerTask('linkAssetsBuildProd', [
'sails-linker:prodJsRelative',
'sails-linker:prodStylesRelative',
]);
};
| {
"content_hash": "0a43efb2df545194dcf8201d1ca08cca",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 45,
"avg_line_length": 27.5,
"alnum_prop": 0.703030303030303,
"repo_name": "tahosa/openracer-node",
"id": "7682ea7fcac2c10d46b955c3320a2f86a49773f2",
"size": "165",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "grunt/register/linkAssetsBuildProd.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1537"
},
{
"name": "HTML",
"bytes": "9689"
},
{
"name": "JavaScript",
"bytes": "40760"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>
i2geo - CurriculumTexts
</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="/xwiki/skins/curriki8/extjs/resources/css/ext%2Dall.css" rel="stylesheet" type="text/css" />
<link href="/xwiki/js/curriki-js.css" type="text/css" rel="stylesheet" type="text/css" />
<link href="/xwiki/bin/skin/skins/curriki8/style.css" rel="stylesheet" type="text/css" />
<link href="/xwiki/bin/skin/skins/curriki8/style2.css" rel="stylesheet" type="text/css" />
</head>
<body style="background-color: #ffffff; padding: 5px; text-align: left;">
<H1 CLASS="heading-1" ID="HCurriculumBrowsingAndChoosing"><SPAN>Curriculum Browsing And Choosing</SPAN></H1>
<p>This should be read from
<a href="http://i2geo.net/xwiki/bin/view/Main/CurriculumTexts">the curriculum texts page</a>.
</body>
</html>
| {
"content_hash": "f97bd477312351e1d0cfd12f4dafa90d",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 112,
"avg_line_length": 48.90909090909091,
"alnum_prop": 0.6905204460966543,
"repo_name": "i2geo/i2gCurriki",
"id": "4fb183d3819cd9edf950fc045d3b3a34aa29868b",
"size": "1076",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "static/CurriculumTexts/index_old.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "34411"
},
{
"name": "Java",
"bytes": "531135"
},
{
"name": "JavaScript",
"bytes": "6295201"
},
{
"name": "Perl",
"bytes": "566"
},
{
"name": "Python",
"bytes": "2066"
},
{
"name": "Shell",
"bytes": "13196"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<openerp>
<data>
<record id="view_account_treasury_report_tree" model="ir.ui.view">
<field name="name">account.treasury.report.tree</field>
<field name="model">account.treasury.report</field>
<field name="arch" type="xml">
<tree string="Treasury Analysis" create="false">
<field name="date" invisible="1"/>
<field name="fiscalyear_id"/>
<field name="period_id"/>
<field name="debit"/>
<field name="credit"/>
<field name="balance"/>
<field name="starting_balance"/>
<field name="ending_balance"/>
<field name="company_id" groups="base.group_multi_company"/>
</tree>
</field>
</record>
<record id="view_account_treasury_report_graph" model="ir.ui.view">
<field name="name">account.treasury.report.graph</field>
<field name="model">account.treasury.report</field>
<field name="arch" type="xml">
<graph string="Treasury Analysis" type="bar">
<field name="period_id"/>
<field name="balance" operator="+"/>
</graph>
</field>
</record>
<record id="view_account_treasury_report_search" model="ir.ui.view">
<field name="name">account.treasury.report.search</field>
<field name="model">account.treasury.report</field>
<field name="arch" type="xml">
<search string="Treasury Analysis">
<field name="fiscalyear_id"/>
<field name="period_id"/>
<field name="company_id" groups="base.group_multi_company"/>
</search>
</field>
</record>
<record id="action_account_treasury_report_all" model="ir.actions.act_window">
<field name="name">Treasury Analysis</field>
<field name="res_model">account.treasury.report</field>
<field name="view_type">form</field>
<field name="view_mode">tree,graph</field>
<field name="search_view_id" ref="view_account_treasury_report_search"/>
<field name="view_id" ref="view_account_treasury_report_tree"/>
<field name="context">{'group_by':[], 'group_by_no_leaf':0}</field>
<field name="help">From this view, have an analysis of your treasury. It sums the balance of every accounting entries made on liquidity accounts per period.</field>
</record>
<menuitem action="action_account_treasury_report_all" id="menu_action_account_treasury_report_all"
parent="account.menu_finance_reporting"
groups="group_account_manager"
sequence="2"/>
</data>
</openerp>
| {
"content_hash": "fb3b01cd65caad4a0972aad2cdfebb13",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 172,
"avg_line_length": 47.80701754385965,
"alnum_prop": 0.5875229357798165,
"repo_name": "ntiufalara/openerp7",
"id": "be6ae0dfdc9844a1e0e0d0da4389e0283d497bb1",
"size": "2725",
"binary": false,
"copies": "53",
"ref": "refs/heads/master",
"path": "openerp/addons/account/report/account_treasury_report_view.xml",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "9611"
},
{
"name": "C#",
"bytes": "93691"
},
{
"name": "C++",
"bytes": "108790"
},
{
"name": "CSS",
"bytes": "583265"
},
{
"name": "Groff",
"bytes": "8138"
},
{
"name": "HTML",
"bytes": "125159"
},
{
"name": "JavaScript",
"bytes": "5109152"
},
{
"name": "Makefile",
"bytes": "14036"
},
{
"name": "NSIS",
"bytes": "14114"
},
{
"name": "PHP",
"bytes": "14033"
},
{
"name": "Python",
"bytes": "9373763"
},
{
"name": "Ruby",
"bytes": "220"
},
{
"name": "Shell",
"bytes": "6430"
},
{
"name": "XSLT",
"bytes": "156761"
}
],
"symlink_target": ""
} |
<html><body><p><!-- saved from url=(0024)http://docs.autodesk.com -->
<!DOCTYPE html>
<!-- Mirrored from help.autodesk.com/cloudhelp/2016/ENU/Maya-Tech-Docs/PyMel/generated/functions/pymel.core.general/pymel.core.general.selectionConnection.html by HTTrack Website Copier/3.x [XR&CO'2014], Sat, 01 Aug 2015 05:39:19 GMT -->
<!-- Added by HTTrack --><meta content="text/html;charset=utf-8" http-equiv="content-type"/><!-- /Added by HTTrack -->
</p>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
<title>pymel.core.general.selectionConnection — PyMEL 1.0.7 documentation</title>
<link href="../../../_static/nature.css" rel="stylesheet" type="text/css"/>
<link href="../../../_static/pygments.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: '../../../',
VERSION: '1.0.7',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script src="../../../_static/jquery.js" type="text/javascript"></script>
<script src="../../../_static/underscore.js" type="text/javascript"></script>
<script src="../../../_static/doctools.js" type="text/javascript"></script>
<link href="../../../index-2.html" rel="top" title="PyMEL 1.0.7 documentation"/>
<link href="../../pymel.core.general.html" rel="up" title="pymel.core.general"/>
<link href="pymel.core.general.setAttr.html" rel="next" title="pymel.core.general.setAttr"/>
<link href="pymel.core.general.selectedNodes.html" rel="prev" title="pymel.core.general.selectedNodes"/>
<link href="../../../../style/adsk.cpm.css" rel="stylesheet" type="text/css"/><meta content="expert" name="experiencelevel"/><meta content="programmer" name="audience"/><meta content="enable" name="user-comments"/><meta content="ENU" name="language"/><meta content="MAYAUL" name="product"/><meta content="2016" name="release"/><meta content="Customization" name="book"/><meta content="Maya-Tech-Docs" name="component"/><meta content="/view/MAYAUL/2016/ENU/" name="helpsystempath"/><meta content="04/03/2015" name="created"/><meta content="04/03/2015" name="modified"/><meta content="Navigation
index
modules |
next |
previous |
PyMEL 1.0.7 documentation »
pymel.core.general »
pymel.core.general.selectionConnection ¶
selectionConnection ( *args , **kwargs ) ¶
This command creates a named selectionConnection object. This object is simply a shared selection list. It may be used
by editors to share their highlight data. For example, an outliner may attach its selected list to one of these objects,
and a graph..." name="description"/><meta content="__PyMel_generated_functions_pymel_core_general_pymel_core_general_selectionConnection_html" name="topicid"/>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a accesskey="I" href="../../../genindex.html" title="General Index">index</a></li>
<li class="right">
<a href="../../../py-modindex.html" title="Python Module Index">modules</a> |</li>
<li class="right">
<a accesskey="N" href="pymel.core.general.setAttr.html" title="pymel.core.general.setAttr">next</a> |</li>
<li class="right">
<a accesskey="P" href="pymel.core.general.selectedNodes.html" title="pymel.core.general.selectedNodes">previous</a> |</li>
<li><a href="../../../index-2.html">PyMEL 1.0.7 documentation</a> »</li>
<li><a accesskey="U" href="../../pymel.core.general.html">pymel.core.general</a> »</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body">
<div class="section" id="pymel-core-general-selectionconnection">
<h1>pymel.core.general.selectionConnection<a class="headerlink" href="#pymel-core-general-selectionconnection" title="Permalink to this headline">¶</a></h1>
<dl class="function">
<dt id="pymel.core.general.selectionConnection"><a name="//apple_ref/cpp/Function/pymel.core.general.selectionConnection"></a>
<tt class="descname">selectionConnection</tt><big>(</big><em>*args</em>, <em>**kwargs</em><big>)</big><a class="headerlink" href="#pymel.core.general.selectionConnection" title="Permalink to this definition">¶</a></dt>
<dd><p>This command creates a named selectionConnection object. This object is simply a shared selection list. It may be used
by editors to share their highlight data. For example, an outliner may attach its selected list to one of these objects,
and a graph editor may use the same object as a list source. Then, the graph editor would only display objects that are
selected in the outliner. Selection connections are UI objects which contain a list of model objects. Selection
connections are useful for specifying which objects are to be displayed within a particular editor. Editor’s have three
plug socketswhere a selection connection may be attached. They are: mainListConnectionan inputsocket which contains a
list of objects that are to be displayed within the editorselectionConnectionan outputsocket which contains a list of
objects that are selectedwithin the editorhighlightConnectionan inputsocket which contains a list of objects that are to
be highlightedwithin the editorThere are several different types of selection connections that may be created. They
include: activeLista selection connection which contains a list of everything in the model which is active (which
includes geometry objects and keys)modelLista selection connection which contains a list of all the geometry (i.e.
excluding keys) objects that are currently activekeyframeLista selection connection which contains a list of all the
keys that are currently activeworldLista selection connection which contains a list of all the objects in the
worldobjectLista selection connection which contains one model object (which may be a set)listLista selection connection
which contains a list of selection connectionseditorLista selection connection which contains a list of objects that are
attached to the mainListConnection of the specified editorsetLista selection connection which contains a list of all the
sets in the worldcharacterLista selection connection which contains a list of all the characters in the
worldhighlightLista selection connection which contains a list of objects to be highlighted in some fashionBelow is an
example selectionConnection network between two editors. Editor 1 is setup to display objects on the activeList. Editor
2 is setup to display objects which are selected within Editor 1, and objects that are selected in Editor 2 are
highlighted within Editor 1: – Editor 1– – Editor 2– inputList–| main | | <a href="#id1"><span class="problematic" id="id2">|-|</span></a> main | | | |
sele <a href="#id3"><span class="problematic" id="id4">|–|</span></a> | | sele <a href="#id5"><span class="problematic" id="id6">|–|</span></a> <a href="#id7"><span class="problematic" id="id8">|-|</span></a> high | | | high | | | | ————- ————- |
<a href="#id9"><span class="problematic" id="id10">|————- fromEditor2 ————-|</span></a> The following commands will establish this network: selectionConnection
-activeList inputList; selectionConnection fromEditor1; selectionConnection fromEditor2; editor -edit
-mainListConnection inputList Editor1; editor -edit -selectionConnection fromEditor1 Editor1; editor -edit
-mainListConnection fromEditor1 Editor2; editor -edit -selectionConnection fromEditor2 Editor2; editor -edit
-highlightConnection fromEditor2 Editor1; Note: to delete a selection connectionuse the deleteUI commandNote: commands
which expect objects may be given a selection connection instead, and the command will operate upon the objects wrapped
by the selection connectionNote: the graph editor and the dope sheet are the only editors which can use the editor
connection to the highlightConnection of another editorWARNING: some flag combinations may not behave as you expect.
The command is really intended for internal use for managing the outliner used by the various editors.</p>
<p class="rubric">Flags:</p>
<table border="1" class="docutils">
<colgroup>
<col width="1%"></col>
<col width="61%"></col>
<col width="19%"></col>
<col width="19%"></col>
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head" colspan="2">Long Name / Short Name</th>
<th class="head">Argument Types</th>
<th class="head">Properties</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td colspan="2"><tt class="docutils literal"><span class="pre">activeCacheList</span></tt> / <tt class="docutils literal"><span class="pre">atc</span></tt></td>
<td><em>bool</em></td>
<td><img alt="../../../_images/create.gif" class="first last" src="../../../_images/create.gif"/>
</td>
</tr>
<tr class="row-odd"><td> </td>
<td colspan="3"><dl class="first last docutils">
<dt>Specifies that this connection should reflect the cache that objects on the active list belong to.</dt>
<dd></dd>
</dl>
</td>
</tr>
<tr class="row-even"><td colspan="2"><tt class="docutils literal"><span class="pre">activeCharacterList</span></tt> / <tt class="docutils literal"><span class="pre">acl</span></tt></td>
<td><em>bool</em></td>
<td><img alt="../../../_images/create.gif" class="first last" src="../../../_images/create.gif"/>
</td>
</tr>
<tr class="row-odd"><td> </td>
<td colspan="3"><dl class="first last docutils">
<dt>Specifies that this connection should reflect the characters that objects on the active list belong to.</dt>
<dd></dd>
</dl>
</td>
</tr>
<tr class="row-even"><td colspan="2"><tt class="docutils literal"><span class="pre">activeList</span></tt> / <tt class="docutils literal"><span class="pre">act</span></tt></td>
<td><em>bool</em></td>
<td><img alt="../../../_images/create.gif" class="first last" src="../../../_images/create.gif"/>
</td>
</tr>
<tr class="row-odd"><td> </td>
<td colspan="3"><dl class="first last docutils">
<dt>Specifies that this connection should reflect the active list (geometry objects and keys).</dt>
<dd></dd>
</dl>
</td>
</tr>
<tr class="row-even"><td colspan="2"><tt class="docutils literal"><span class="pre">addScript</span></tt> / <tt class="docutils literal"><span class="pre">addScript</span></tt></td>
<td><em>script</em></td>
<td><img alt="../../../_images/create.gif" class="first" src="../../../_images/create.gif"/>
<img alt="../../../_images/query.gif" src="../../../_images/query.gif"/>
<img alt="../../../_images/edit.gif" class="last" src="../../../_images/edit.gif"/>
</td>
</tr>
<tr class="row-odd"><td> </td>
<td colspan="3"><dl class="first last docutils">
<dt>Specify a script to be called when something is added to the selection.</dt>
<dd></dd>
</dl>
</td>
</tr>
<tr class="row-even"><td colspan="2"><tt class="docutils literal"><span class="pre">addTo</span></tt> / <tt class="docutils literal"><span class="pre">add</span></tt></td>
<td><em>unicode</em></td>
<td><img alt="../../../_images/create.gif" class="first" src="../../../_images/create.gif"/>
<img alt="../../../_images/edit.gif" class="last" src="../../../_images/edit.gif"/>
</td>
</tr>
<tr class="row-odd"><td> </td>
<td colspan="3"><dl class="first last docutils">
<dt>The name of a selection connection that should be added to this list of connections.</dt>
<dd></dd>
</dl>
</td>
</tr>
<tr class="row-even"><td colspan="2"><tt class="docutils literal"><span class="pre">characterList</span></tt> / <tt class="docutils literal"><span class="pre">cl</span></tt></td>
<td><em>bool</em></td>
<td><img alt="../../../_images/create.gif" class="first last" src="../../../_images/create.gif"/>
</td>
</tr>
<tr class="row-odd"><td> </td>
<td colspan="3"><dl class="first last docutils">
<dt>Specifies that this connection should reflect all the characters in the world.</dt>
<dd></dd>
</dl>
</td>
</tr>
<tr class="row-even"><td colspan="2"><tt class="docutils literal"><span class="pre">clear</span></tt> / <tt class="docutils literal"><span class="pre">clr</span></tt></td>
<td><em>bool</em></td>
<td><img alt="../../../_images/create.gif" class="first" src="../../../_images/create.gif"/>
<img alt="../../../_images/edit.gif" class="last" src="../../../_images/edit.gif"/>
</td>
</tr>
<tr class="row-odd"><td> </td>
<td colspan="3"><dl class="first last docutils">
<dt>Remove everything from the selection connection.</dt>
<dd></dd>
</dl>
</td>
</tr>
<tr class="row-even"><td colspan="2"><tt class="docutils literal"><span class="pre">connectionList</span></tt> / <tt class="docutils literal"><span class="pre">lst</span></tt></td>
<td><em>bool</em></td>
<td><img alt="../../../_images/create.gif" class="first" src="../../../_images/create.gif"/>
<img alt="../../../_images/query.gif" class="last" src="../../../_images/query.gif"/>
</td>
</tr>
<tr class="row-odd"><td> </td>
<td colspan="3"><dl class="first last docutils">
<dt>Specifies that this connection should contain a list of selection connections.</dt>
<dd></dd>
</dl>
</td>
</tr>
<tr class="row-even"><td colspan="2"><tt class="docutils literal"><span class="pre">defineTemplate</span></tt> / <tt class="docutils literal"><span class="pre">dt</span></tt></td>
<td><em>unicode</em></td>
<td><img alt="../../../_images/create.gif" class="first last" src="../../../_images/create.gif"/>
</td>
</tr>
<tr class="row-odd"><td> </td>
<td colspan="3"><p class="first">Puts a command in a mode where any other flags and args are parsed and added to the command template specified in the argument. They will be used as default
arguments in any subsequent invocations of the command when templateName is set as the current template.</p>
<blockquote class="last">
<div></div></blockquote>
</td>
</tr>
<tr class="row-even"><td colspan="2"><tt class="docutils literal"><span class="pre">deselect</span></tt> / <tt class="docutils literal"><span class="pre">d</span></tt></td>
<td><em>PyNode</em></td>
<td><img alt="../../../_images/create.gif" class="first" src="../../../_images/create.gif"/>
<img alt="../../../_images/edit.gif" class="last" src="../../../_images/edit.gif"/>
</td>
</tr>
<tr class="row-odd"><td> </td>
<td colspan="3"><dl class="first last docutils">
<dt>Remove something from the selection. Flag can have multiple arguments, passed either as a tuple or a list.</dt>
<dd></dd>
</dl>
</td>
</tr>
<tr class="row-even"><td colspan="2"><tt class="docutils literal"><span class="pre">editor</span></tt> / <tt class="docutils literal"><span class="pre">ed</span></tt></td>
<td><em>unicode</em></td>
<td><img alt="../../../_images/create.gif" class="first" src="../../../_images/create.gif"/>
<img alt="../../../_images/query.gif" src="../../../_images/query.gif"/>
<img alt="../../../_images/edit.gif" class="last" src="../../../_images/edit.gif"/>
</td>
</tr>
<tr class="row-odd"><td> </td>
<td colspan="3"><dl class="first last docutils">
<dt>Specifies that this connection should reflect the -mainListConnection of the specified editor.</dt>
<dd></dd>
</dl>
</td>
</tr>
<tr class="row-even"><td colspan="2"><tt class="docutils literal"><span class="pre">exists</span></tt> / <tt class="docutils literal"><span class="pre">ex</span></tt></td>
<td><em>bool</em></td>
<td><img alt="../../../_images/create.gif" class="first last" src="../../../_images/create.gif"/>
</td>
</tr>
<tr class="row-odd"><td> </td>
<td colspan="3"><dl class="first last docutils">
<dt>Returns true|false depending upon whether the specified object exists. Other flags are ignored.</dt>
<dd></dd>
</dl>
</td>
</tr>
<tr class="row-even"><td colspan="2"><tt class="docutils literal"><span class="pre">filter</span></tt> / <tt class="docutils literal"><span class="pre">f</span></tt></td>
<td><em>unicode</em></td>
<td><img alt="../../../_images/create.gif" class="first" src="../../../_images/create.gif"/>
<img alt="../../../_images/query.gif" src="../../../_images/query.gif"/>
<img alt="../../../_images/edit.gif" class="last" src="../../../_images/edit.gif"/>
</td>
</tr>
<tr class="row-odd"><td> </td>
<td colspan="3"><p class="first">Optionally specifies an itemFilter for this connection. An empty string () clears the current filter. If a filter is specified, all the information going into the
selectionConnection must first pass through the filter before being accepted. NOTE: filters can only be attached to regular selectionConnections. They cannot be
attached to any connection created using the -act, -mdl, -key, -wl, -sl, -cl, -lst, -obj, or -ren flags. We strongly recommend that you do not attach filters to a
selectionConnection — it is better to attach your filter to the editor that is using the selectionConnection instead.</p>
<blockquote class="last">
<div></div></blockquote>
</td>
</tr>
<tr class="row-even"><td colspan="2"><tt class="docutils literal"><span class="pre">findObject</span></tt> / <tt class="docutils literal"><span class="pre">fo</span></tt></td>
<td><em>PyNode</em></td>
<td><img alt="../../../_images/query.gif" class="first last" src="../../../_images/query.gif"/>
</td>
</tr>
<tr class="row-odd"><td> </td>
<td colspan="3"><dl class="first last docutils">
<dt>Find a selection connection in this list that wraps the specified object.</dt>
<dd></dd>
</dl>
</td>
</tr>
<tr class="row-even"><td colspan="2"><tt class="docutils literal"><span class="pre">g</span></tt> / <tt class="docutils literal"><span class="pre">g</span></tt></td>
<td><em>bool</em></td>
<td><img alt="../../../_images/create.gif" class="first" src="../../../_images/create.gif"/>
<img alt="../../../_images/query.gif" src="../../../_images/query.gif"/>
<img alt="../../../_images/edit.gif" class="last" src="../../../_images/edit.gif"/>
</td>
</tr>
<tr class="row-odd"><td> </td>
<td colspan="3"><dl class="first last docutils">
<dt>A global selection connection cannot be deleted by any script commands.</dt>
<dd></dd>
</dl>
</td>
</tr>
<tr class="row-even"><td colspan="2"><tt class="docutils literal"><span class="pre">highlightList</span></tt> / <tt class="docutils literal"><span class="pre">hl</span></tt></td>
<td><em>bool</em></td>
<td><img alt="../../../_images/create.gif" class="first last" src="../../../_images/create.gif"/>
</td>
</tr>
<tr class="row-odd"><td> </td>
<td colspan="3"><dl class="first last docutils">
<dt>Specifies that this connection is being used as a highlight list.</dt>
<dd></dd>
</dl>
</td>
</tr>
<tr class="row-even"><td colspan="2"><tt class="docutils literal"><span class="pre">identify</span></tt> / <tt class="docutils literal"><span class="pre">id</span></tt></td>
<td><em>bool</em></td>
<td><img alt="../../../_images/query.gif" class="first last" src="../../../_images/query.gif"/>
</td>
</tr>
<tr class="row-odd"><td> </td>
<td colspan="3"><p class="first">Find out what type of selection connection this is. May be: activeList | modelList | keyframeList | worldList | objectList listList | editorList | connection |
unknown</p>
<blockquote class="last">
<div></div></blockquote>
</td>
</tr>
<tr class="row-even"><td colspan="2"><tt class="docutils literal"><span class="pre">keyframeList</span></tt> / <tt class="docutils literal"><span class="pre">key</span></tt></td>
<td><em>bool</em></td>
<td><img alt="../../../_images/create.gif" class="first last" src="../../../_images/create.gif"/>
</td>
</tr>
<tr class="row-odd"><td> </td>
<td colspan="3"><dl class="first last docutils">
<dt>Specifies that this connection should reflect the animation portion of the active list.</dt>
<dd></dd>
</dl>
</td>
</tr>
<tr class="row-even"><td colspan="2"><tt class="docutils literal"><span class="pre">lock</span></tt> / <tt class="docutils literal"><span class="pre">lck</span></tt></td>
<td><em>bool</em></td>
<td><img alt="../../../_images/create.gif" class="first" src="../../../_images/create.gif"/>
<img alt="../../../_images/query.gif" src="../../../_images/query.gif"/>
<img alt="../../../_images/edit.gif" class="last" src="../../../_images/edit.gif"/>
</td>
</tr>
<tr class="row-odd"><td> </td>
<td colspan="3"><dl class="first last docutils">
<dt>For activeList connections, locking the connection means that it will not listen to activeList changes.</dt>
<dd></dd>
</dl>
</td>
</tr>
<tr class="row-even"><td colspan="2"><tt class="docutils literal"><span class="pre">modelList</span></tt> / <tt class="docutils literal"><span class="pre">mdl</span></tt></td>
<td><em>bool</em></td>
<td><img alt="../../../_images/create.gif" class="first last" src="../../../_images/create.gif"/>
</td>
</tr>
<tr class="row-odd"><td> </td>
<td colspan="3"><dl class="first last docutils">
<dt>Specifies that this connection should reflect the modeling (i.e. excluding keys) portion of the active list.</dt>
<dd></dd>
</dl>
</td>
</tr>
<tr class="row-even"><td colspan="2"><tt class="docutils literal"><span class="pre">object</span></tt> / <tt class="docutils literal"><span class="pre">obj</span></tt></td>
<td><em>PyNode</em></td>
<td><img alt="../../../_images/create.gif" class="first" src="../../../_images/create.gif"/>
<img alt="../../../_images/query.gif" src="../../../_images/query.gif"/>
<img alt="../../../_images/edit.gif" class="last" src="../../../_images/edit.gif"/>
</td>
</tr>
<tr class="row-odd"><td> </td>
<td colspan="3"><p class="first">Specifies that this connection should wrap around the specified object (which may be a set). Query will return all the members of the selection connection (if
the connection wraps a set, the set members will be returned)</p>
<blockquote class="last">
<div></div></blockquote>
</td>
</tr>
<tr class="row-even"><td colspan="2"><tt class="docutils literal"><span class="pre">parent</span></tt> / <tt class="docutils literal"><span class="pre">p</span></tt></td>
<td><em>unicode</em></td>
<td><img alt="../../../_images/create.gif" class="first" src="../../../_images/create.gif"/>
<img alt="../../../_images/query.gif" src="../../../_images/query.gif"/>
<img alt="../../../_images/edit.gif" class="last" src="../../../_images/edit.gif"/>
</td>
</tr>
<tr class="row-odd"><td> </td>
<td colspan="3"><p class="first">The name of a UI object this should be attached to. When the parent is destroyed, the selectionConnection will auto-delete. If no parent is specified, the
connection is created in the current controlLayout.</p>
<blockquote class="last">
<div></div></blockquote>
</td>
</tr>
<tr class="row-even"><td colspan="2"><tt class="docutils literal"><span class="pre">remove</span></tt> / <tt class="docutils literal"><span class="pre">rm</span></tt></td>
<td><em>unicode</em></td>
<td><img alt="../../../_images/create.gif" class="first" src="../../../_images/create.gif"/>
<img alt="../../../_images/edit.gif" class="last" src="../../../_images/edit.gif"/>
</td>
</tr>
<tr class="row-odd"><td> </td>
<td colspan="3"><dl class="first last docutils">
<dt>The name of a selection connection that should be removed from this list of connections.</dt>
<dd></dd>
</dl>
</td>
</tr>
<tr class="row-even"><td colspan="2"><tt class="docutils literal"><span class="pre">removeScript</span></tt> / <tt class="docutils literal"><span class="pre">rs</span></tt></td>
<td><em>script</em></td>
<td><img alt="../../../_images/create.gif" class="first" src="../../../_images/create.gif"/>
<img alt="../../../_images/query.gif" src="../../../_images/query.gif"/>
<img alt="../../../_images/edit.gif" class="last" src="../../../_images/edit.gif"/>
</td>
</tr>
<tr class="row-odd"><td> </td>
<td colspan="3"><dl class="first last docutils">
<dt>Specify a script to be called when something is removed from the selection.</dt>
<dd></dd>
</dl>
</td>
</tr>
<tr class="row-even"><td colspan="2"><tt class="docutils literal"><span class="pre">select</span></tt> / <tt class="docutils literal"><span class="pre">s</span></tt></td>
<td><em>PyNode</em></td>
<td><img alt="../../../_images/create.gif" class="first" src="../../../_images/create.gif"/>
<img alt="../../../_images/edit.gif" class="last" src="../../../_images/edit.gif"/>
</td>
</tr>
<tr class="row-odd"><td> </td>
<td colspan="3"><dl class="first last docutils">
<dt>Add something to the selection. This does not replace the existing selection.</dt>
<dd></dd>
</dl>
</td>
</tr>
<tr class="row-even"><td colspan="2"><tt class="docutils literal"><span class="pre">setList</span></tt> / <tt class="docutils literal"><span class="pre">sl</span></tt></td>
<td><em>bool</em></td>
<td><img alt="../../../_images/create.gif" class="first last" src="../../../_images/create.gif"/>
</td>
</tr>
<tr class="row-odd"><td> </td>
<td colspan="3"><dl class="first last docutils">
<dt>Specifies that this connection should reflect all the sets in the world.</dt>
<dd></dd>
</dl>
</td>
</tr>
<tr class="row-even"><td colspan="2"><tt class="docutils literal"><span class="pre">switch</span></tt> / <tt class="docutils literal"><span class="pre">sw</span></tt></td>
<td><em>bool</em></td>
<td><img alt="../../../_images/create.gif" class="first" src="../../../_images/create.gif"/>
<img alt="../../../_images/query.gif" class="last" src="../../../_images/query.gif"/>
</td>
</tr>
<tr class="row-odd"><td> </td>
<td colspan="3"><p class="first">Acts as a modifier to -connectionList which sets the list of objects to be the first non-empty selection connection. selection connections are tested in the
order in which they are added.</p>
<blockquote class="last">
<div></div></blockquote>
</td>
</tr>
<tr class="row-even"><td colspan="2"><tt class="docutils literal"><span class="pre">useTemplate</span></tt> / <tt class="docutils literal"><span class="pre">ut</span></tt></td>
<td><em>unicode</em></td>
<td><img alt="../../../_images/create.gif" class="first last" src="../../../_images/create.gif"/>
</td>
</tr>
<tr class="row-odd"><td> </td>
<td colspan="3"><dl class="first last docutils">
<dt>Force the command to use a command template other than the current one.</dt>
<dd></dd>
</dl>
</td>
</tr>
<tr class="row-even"><td colspan="2"><tt class="docutils literal"><span class="pre">worldList</span></tt> / <tt class="docutils literal"><span class="pre">wl</span></tt></td>
<td><em>bool</em></td>
<td><img alt="../../../_images/create.gif" class="first last" src="../../../_images/create.gif"/>
</td>
</tr>
<tr class="row-odd"><td> </td>
<td colspan="3"><dl class="first last docutils">
<dt>Specifies that this connection should reflect all objects in the world.</dt>
<dd></dd>
</dl>
</td>
</tr>
</tbody>
</table>
<p>Derived from mel command <tt class="xref py py-obj docutils literal"><span class="pre">maya.cmds.selectionConnection</span></tt></p>
<p class="rubric">Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">pymel.core</span> <span class="kn">as</span> <span class="nn">pm</span>
<span class="c"># Example 1.</span>
<span class="c">#</span>
<span class="c"># Create a window with two Outliner editors and a</span>
<span class="c"># selection connection network. Editor 1 will display the</span>
<span class="c"># current scene's active list. Editor 2 will display the items</span>
<span class="c"># selected in Editor 1.</span>
<span class="c">#</span>
<span class="n">window</span> <span class="o">=</span> <span class="n">pm</span><span class="o">.</span><span class="n">window</span><span class="p">(</span><span class="s">'window'</span><span class="p">,</span> <span class="n">wh</span><span class="o">=</span><span class="p">(</span><span class="mi">400</span><span class="p">,</span> <span class="mi">300</span><span class="p">))</span>
<span class="n">pm</span><span class="o">.</span><span class="n">paneLayout</span><span class="p">(</span> <span class="n">configuration</span><span class="o">=</span><span class="s">'vertical2'</span> <span class="p">)</span>
<span class="c"># Result: ui.PaneLayout('window|paneLayout14') #</span>
<span class="n">editor1</span> <span class="o">=</span> <span class="n">pm</span><span class="o">.</span><span class="n">outlinerEditor</span><span class="p">()</span>
<span class="n">editor2</span> <span class="o">=</span> <span class="n">pm</span><span class="o">.</span><span class="n">outlinerEditor</span><span class="p">()</span>
<span class="c"># Create the selection connection network.</span>
<span class="c">#</span>
<span class="n">inputList</span> <span class="o">=</span> <span class="n">pm</span><span class="o">.</span><span class="n">selectionConnection</span><span class="p">(</span> <span class="n">activeList</span><span class="o">=</span><span class="bp">True</span> <span class="p">)</span>
<span class="n">fromEditor1</span> <span class="o">=</span> <span class="n">pm</span><span class="o">.</span><span class="n">selectionConnection</span><span class="p">()</span>
<span class="n">fromEditor2</span> <span class="o">=</span> <span class="n">pm</span><span class="o">.</span><span class="n">selectionConnection</span><span class="p">()</span>
<span class="n">pm</span><span class="o">.</span><span class="n">editor</span><span class="p">(</span> <span class="n">editor1</span><span class="p">,</span> <span class="n">edit</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">mainListConnection</span><span class="o">=</span><span class="n">inputList</span> <span class="p">)</span>
<span class="c"># Result: u'window|paneLayout14|outlinerEditor2' #</span>
<span class="n">pm</span><span class="o">.</span><span class="n">editor</span><span class="p">(</span> <span class="n">editor1</span><span class="p">,</span> <span class="n">edit</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">selectionConnection</span><span class="o">=</span><span class="n">fromEditor1</span> <span class="p">)</span>
<span class="c"># Result: u'window|paneLayout14|outlinerEditor2' #</span>
<span class="n">pm</span><span class="o">.</span><span class="n">editor</span><span class="p">(</span> <span class="n">editor2</span><span class="p">,</span> <span class="n">edit</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">mainListConnection</span><span class="o">=</span><span class="n">fromEditor1</span> <span class="p">)</span>
<span class="c"># Result: u'window|paneLayout14|outlinerEditor3' #</span>
<span class="n">pm</span><span class="o">.</span><span class="n">editor</span><span class="p">(</span> <span class="n">editor2</span><span class="p">,</span> <span class="n">edit</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">selectionConnection</span><span class="o">=</span><span class="n">fromEditor2</span> <span class="p">)</span>
<span class="c"># Result: u'window|paneLayout14|outlinerEditor3' #</span>
<span class="n">pm</span><span class="o">.</span><span class="n">showWindow</span><span class="p">(</span> <span class="n">window</span> <span class="p">)</span>
<span class="c"># Create some objects and select them.</span>
<span class="c">#</span>
<span class="n">pm</span><span class="o">.</span><span class="n">sphere</span><span class="p">()</span>
<span class="c"># Result: [nt.Transform(u'nurbsSphere1'), nt.MakeNurbSphere(u'makeNurbSphere1')] #</span>
<span class="n">pm</span><span class="o">.</span><span class="n">cone</span><span class="p">()</span>
<span class="c"># Result: [nt.Transform(u'nurbsCone1'), nt.MakeNurbCone(u'makeNurbCone1')] #</span>
<span class="n">pm</span><span class="o">.</span><span class="n">cylinder</span><span class="p">()</span>
<span class="c"># Result: [nt.Transform(u'nurbsCylinder1'), nt.MakeNurbCylinder(u'makeNurbCylinder1')] #</span>
<span class="n">pm</span><span class="o">.</span><span class="n">select</span><span class="p">(</span> <span class="nb">all</span><span class="o">=</span><span class="bp">True</span> <span class="p">)</span>
<span class="c"># Now as you select objects on the left side, they will be</span>
<span class="c"># displayed on the right side. You can also add a callback</span>
<span class="c"># script to do further processing on the list when objects</span>
<span class="c"># are added. (Use -removeScript for when objects are removed.)</span>
<span class="k">def</span> <span class="nf">addScriptCallback</span><span class="p">(</span> <span class="n">array</span> <span class="p">):</span>
<span class="k">print</span> <span class="s">"Contents of callback array: </span><span class="si">%s</span><span class="se">\n</span><span class="s">"</span> <span class="o">%</span> <span class="n">array</span>
<span class="n">pm</span><span class="o">.</span><span class="n">selectionConnection</span><span class="p">(</span> <span class="n">fromEditor1</span><span class="p">,</span> <span class="n">e</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">addScript</span><span class="o">=</span><span class="n">addScriptCallback</span> <span class="p">)</span>
<span class="c"># Result: u'selectionConnection2' #</span>
<span class="c"># Example 2.</span>
<span class="c">#</span>
<span class="c"># Create a selection connection for a paritcular object. Delete</span>
<span class="c"># the selection connection and the object.</span>
<span class="c">#</span>
<span class="n">pm</span><span class="o">.</span><span class="n">sphere</span><span class="p">(</span> <span class="n">name</span><span class="o">=</span><span class="s">'sphere'</span> <span class="p">)</span>
<span class="c"># Result: [nt.Transform(u'sphere'), nt.MakeNurbSphere(u'makeNurbSphere2')] #</span>
<span class="c"># Create a selection connection to wrap the sphere.</span>
<span class="c">#</span>
<span class="n">pm</span><span class="o">.</span><span class="n">selectionConnection</span><span class="p">(</span> <span class="s">'holder'</span><span class="p">,</span> <span class="nb">object</span><span class="o">=</span><span class="s">'sphere'</span> <span class="p">)</span>
<span class="c"># Result: u'holder' #</span>
<span class="c"># Select the sphere using the selection connection.</span>
<span class="c">#</span>
<span class="n">pm</span><span class="o">.</span><span class="n">select</span><span class="p">(</span> <span class="s">'holder'</span> <span class="p">)</span>
<span class="c"># Delete the members (sphere) of the selection connection</span>
<span class="c">#</span>
<span class="n">pm</span><span class="o">.</span><span class="n">delete</span><span class="p">(</span> <span class="s">'holder'</span> <span class="p">)</span>
<span class="c"># Delete the selection connection (does not delete the members of</span>
<span class="c"># the selection connection.</span>
<span class="c">#</span>
<span class="n">pm</span><span class="o">.</span><span class="n">deleteUI</span><span class="p">(</span> <span class="s">'holder'</span> <span class="p">)</span>
<span class="c"># Result: u'' #</span>
</pre></div>
</div>
</dd></dl>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar">
<div class="sphinxsidebarwrapper">
<h4>Previous topic</h4>
<p class="topless"><a href="pymel.core.general.selectedNodes.html" title="previous chapter">pymel.core.general.selectedNodes</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="pymel.core.general.setAttr.html" title="next chapter">pymel.core.general.setAttr</a></p>
<h3><a href="../../../modules.html">Core Modules</a></h3>
<ul>
<li><a class="reference external" href="../../pymel.core.animation.html#module-pymel.core.animation"><tt class="xref">animation</tt></a></li>
<li><a class="reference external" href="../../pymel.core.effects.html#module-pymel.core.effects"><tt class="xref">effects</tt></a></li>
<li><a class="reference external" href="../../pymel.core.general.html#module-pymel.core.general"><tt class="xref">general</tt></a></li>
<li><a class="reference external" href="../../pymel.core.language.html#module-pymel.core.language"><tt class="xref">language</tt></a></li>
<li><a class="reference external" href="../../pymel.core.modeling.html#module-pymel.core.modeling"><tt class="xref">modeling</tt></a></li>
<li><a class="reference external" href="../../pymel.core.rendering.html#module-pymel.core.rendering"><tt class="xref">rendering</tt></a></li>
<li><a class="reference external" href="../../pymel.core.system.html#module-pymel.core.system"><tt class="xref">system</tt></a></li>
<li><a class="reference external" href="../../pymel.core.windows.html#module-pymel.core.windows"><tt class="xref">windows</tt></a></li>
</ul>
<h3><a href="../../../modules.html">Type Modules</a></h3>
<ul>
<li><a class="reference external" href="../../pymel.core.datatypes.html#module-pymel.core.datatypes"><tt class="xref">datatypes</tt></a></li>
<li><a class="reference external" href="../../pymel.core.nodetypes.html#module-pymel.core.nodetypes"><tt class="xref">nodetypes</tt></a></li>
<li><a class="reference external" href="../../pymel.core.uitypes.html#module-pymel.core.uitypes"><tt class="xref">uitypes</tt></a></li>
</ul>
<h3><a href="../../../modules.html">Other Modules</a></h3>
<ul>
<li><a class="reference external" href="../../pymel.api.plugins.html#module-pymel.api.plugins"><tt class="xref">plugins</tt></a></li>
<li><a class="reference external" href="../../pymel.mayautils.html#module-pymel.mayautils"><tt class="xref">mayautils</tt></a></li>
<li><a class="reference external" href="../../pymel.util.html#module-pymel.util"><tt class="xref">util</tt></a></li>
<li><a class="reference external" href="../../pymel.versions.html#module-pymel.versions"><tt class="xref">versions</tt></a>
</li><li><a class="reference external" href="../../pymel.tools.html#module-pymel.tools"><tt class="xref">tools</tt></a></li>
</ul>
<!--
<ul>
<li><a class="reference external" href="../../pymel.core.animation.html.html#module-pymel.core.animation"><tt class="xref">animation</tt></a></li>
<li><a class="reference external" href="../../pymel.core.datatypes.html.html#module-pymel.core.datatypes"><tt class="xref">datatypes</tt></a></li>
<li><a class="reference external" href="../../pymel.core.effects.html.html#module-pymel.core.effects"><tt class="xref">effects</tt></a></li>
<li><a class="reference external" href="../../pymel.core.general.html.html#module-pymel.core.general"><tt class="xref">general</tt></a></li>
<li><a class="reference external" href="../../pymel.core.language.html.html#module-pymel.core.language"><tt class="xref">language</tt></a></li>
<li><a class="reference external" href="../../pymel.core.modeling.html.html#module-pymel.core.modeling"><tt class="xref">modeling</tt></a></li>
<li><a class="reference external" href="../../pymel.core.nodetypes.html.html#module-pymel.core.nodetypes"><tt class="xref">nodetypes</tt></a></li>
<li><a class="reference external" href="../../pymel.core.rendering.html.html#module-pymel.core.rendering"><tt class="xref">rendering</tt></a></li>
<li><a class="reference external" href="../../pymel.core.system.html.html#module-pymel.core.system"><tt class="xref">system</tt></a></li>
<li><a class="reference external" href="../../pymel.core.windows.html.html#module-pymel.core.windows"><tt class="xref">windows</tt></a></li>
<li><a class="reference external" href="../../pymel.util.html.html#module-pymel.util"><tt class="xref">pymel.util</tt></a></li>
</ul>
-->
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../../../_sources/generated/functions/pymel.core.general/pymel.core.general.selectionConnection.txt" rel="nofollow">Show Source</a></li>
</ul>
<div id="searchbox" style="display: none">
<h3>Quick search</h3>
<form action="http://help.autodesk.com/cloudhelp/2016/ENU/Maya-Tech-Docs/PyMel/search.html" class="search" method="get"></form>
<input name="q" type="text"/>
<input type="submit" value="Go"/>
<input name="check_keywords" type="hidden" value="yes"/>
<input name="area" type="hidden" value="default"/>
<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="../../../py-modindex.html" title="Python Module Index">modules</a> |</li>
<li class="right">
<a href="pymel.core.general.setAttr.html" title="pymel.core.general.setAttr">next</a> |</li>
<li class="right">
<a href="pymel.core.general.selectedNodes.html" title="pymel.core.general.selectedNodes">previous</a> |</li>
<li><a href="../../../index-2.html">PyMEL 1.0.7 documentation</a> »</li>
<li><a href="../../pymel.core.general.html">pymel.core.general</a> »</li>
</ul>
</div>
<div class="footer">
© Copyright 2009, Chad Dombrova.
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.2.3.
</div>
<!-- Mirrored from help.autodesk.com/cloudhelp/2016/ENU/Maya-Tech-Docs/PyMel/generated/functions/pymel.core.general/pymel.core.general.selectionConnection.html by HTTrack Website Copier/3.x [XR&CO'2014], Sat, 01 Aug 2015 05:39:19 GMT -->
</body></html> | {
"content_hash": "ffc3c2aa72e32129b0153594c130c04e",
"timestamp": "",
"source": "github",
"line_count": 675,
"max_line_length": 594,
"avg_line_length": 60.76148148148148,
"alnum_prop": 0.6652606427073682,
"repo_name": "alexwidener/PyMelDocset",
"id": "d656d13cda4f15b25028dd737dc9f7631c4b13d1",
"size": "41108",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "PyMel.docset/Contents/Resources/Documents/generated/functions/pymel.core.general/pymel.core.general.selectionConnection.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "16618"
},
{
"name": "HTML",
"bytes": "97827047"
},
{
"name": "JavaScript",
"bytes": "24674"
}
],
"symlink_target": ""
} |
import argparse
import os
import subprocess
import shlex
import re
polly_src_dir = '''@POLLY_SOURCE_DIR@'''
polly_lib_dir = '''@POLLY_LIB_DIR@'''
shlibext = '''@LLVM_SHLIBEXT@'''
llvm_tools_dir = '''@LLVM_TOOLS_DIR@'''
link_polly_into_tools = not '''@LINK_POLLY_INTO_TOOLS@'''.lower() in {'','0','n','no','off','false','notfound','link_polly_into_tools-notfound'}
runre = re.compile(r'\s*\;\s*RUN\s*\:(?P<tool>.*)')
filecheckre = re.compile(r'\s*(?P<tool>.*)\|\s*(?P<filecheck>FileCheck\s[^|]*)')
emptyline = re.compile(r'\s*(\;\s*)?')
commentline = re.compile(r'\s*(\;.*)?')
def ltrim_emptylines(lines,meta=None):
while len(lines) and emptyline.fullmatch(lines[0]):
del lines[0]
if meta is not None:
del meta[0]
def rtrim_emptylines(lines):
while len(lines) and emptyline.fullmatch(lines[-1]):
del lines[-1]
def trim_emptylines(lines):
ltrim_emptylines(lines)
rtrim_emptylines(lines)
def complete_exename(path, filename):
complpath = os.path.join(path, filename)
if os.path.isfile(complpath):
return complpath
elif os.path.isfile(complpath + '.exe'):
return complpath + '.exe'
return filename
def indention(line):
for i,c in enumerate(line):
if c != ' ' and c != '\t':
return i
return None
def common_indent(lines):
indentions = (indention(line) for line in lines)
indentions = (indent for indent in indentions if indent is not None)
return min(indentions,default=0)
funcre = re.compile(r'^ Function: \S*$')
regionre = re.compile(r'^ Region: \S*$')
depthre = re.compile(r'^ Max Loop Depth: .*')
paramre = re.compile(r' [0-9a-z-A-Z_]+\: .*')
def classyfier1(lines):
i = iter(lines)
line = i.__next__()
while True:
if line.startswith("Printing analysis 'Polly - Calculate dependences' for region: "):
yield {'PrintingDependenceInfo'}
elif line.startswith("remark: "):
yield {'Remark'}
elif funcre.fullmatch(line):
yield {'Function'}
elif regionre.fullmatch(line):
yield { 'Region'}
elif depthre.fullmatch(line):
yield {'MaxLoopDepth'}
elif line == ' Invariant Accesses: {':
while True:
yield { 'InvariantAccesses'}
if line == ' }':
break
line = i.__next__()
elif line == ' Context:':
yield {'Context'}
line = i.__next__()
yield {'Context'}
elif line == ' Assumed Context:':
yield {'AssumedContext'}
line = i.__next__()
yield {'AssumedContext'}
elif line == ' Invalid Context:':
yield {'InvalidContext'}
line = i.__next__()
yield {'InvalidContext'}
elif line == ' Boundary Context:':
yield {'BoundaryContext'}
line = i.__next__()
yield {'BoundaryContext'}
line = i.__next__()
while paramre.fullmatch(line):
yield {'Param'}
line = i.__next__()
continue
elif line == ' Arrays {':
while True:
yield {'Arrays'}
if line == ' }':
break
line = i.__next__()
elif line == ' Arrays (Bounds as pw_affs) {':
while True:
yield {'PwAffArrays'}
if line == ' }':
break
line = i.__next__()
elif line.startswith(' Alias Groups ('):
while True:
yield {'AliasGroups'}
line = i.__next__()
if not line.startswith(' '):
break
continue
elif line == ' Statements {':
while True:
yield {'Statements'}
if line == ' }':
break
line = i.__next__()
elif line == ' RAW dependences:':
yield {'RAWDep','BasicDep','Dep','DepInfo'}
line = i.__next__()
while line.startswith(' '):
yield {'RAWDep','BasicDep','Dep','DepInfo'}
line = i.__next__()
continue
elif line == ' WAR dependences:':
yield {'WARDep','BasicDep','Dep','DepInfo'}
line = i.__next__()
while line.startswith(' '):
yield {'WARDep','BasicDep','Dep','DepInfo'}
line = i.__next__()
continue
elif line == ' WAW dependences:':
yield {'WAWDep','BasicDep','Dep','DepInfo'}
line = i.__next__()
while line.startswith(' '):
yield {'WAWDep','BasicDep','Dep','DepInfo'}
line = i.__next__()
continue
elif line == ' Reduction dependences:':
yield {'RedDep','Dep','DepInfo'}
line = i.__next__()
while line.startswith(' '):
yield {'RedDep','Dep','DepInfo'}
line = i.__next__()
continue
elif line == ' Transitive closure of reduction dependences:':
yield {'TransitiveClosureDep','DepInfo'}
line = i.__next__()
while line.startswith(' '):
yield {'TransitiveClosureDep','DepInfo'}
line = i.__next__()
continue
elif line.startswith("New access function '"):
yield {'NewAccessFunction'}
elif line == 'Schedule before flattening {':
while True:
yield {'ScheduleBeforeFlattening'}
if line == '}':
break
line = i.__next__()
elif line == 'Schedule after flattening {':
while True:
yield {'ScheduleAfterFlattening'}
if line == '}':
break
line = i.__next__()
else:
yield set()
line = i.__next__()
def classyfier2(lines):
i = iter(lines)
line = i.__next__()
while True:
if funcre.fullmatch(line):
while line.startswith(' '):
yield {'FunctionDetail'}
line = i.__next__()
continue
elif line.startswith("Printing analysis 'Polly - Generate an AST from the SCoP (isl)' for region: "):
yield {'PrintingIslAst'}
line = i.__next__()
while not line.startswith('Printing analysis'):
yield {'AstDetail'}
line = i.__next__()
continue
else:
yield set()
line = i.__next__()
replrepl = {'{{':'{{[{][{]}}','}}': '{{[}][}]}}', '[[':'{{\[\[}}',']]': '{{\]\]}}'}
replre = re.compile('|'.join(re.escape(k) for k in replrepl.keys()))
def main():
parser = argparse.ArgumentParser(description="Update CHECK lines")
parser.add_argument('testfile',help="File to update (absolute or relative to --testdir)")
parser.add_argument('--check-style',choices=['CHECK','CHECK-NEXT'],default='CHECK-NEXT',help="What kind of checks lines to generate")
parser.add_argument('--check-position',choices=['end','before-content','autodetect'],default='autodetect',help="Where to add the CHECK lines into the file; 'autodetect' searches for the first 'CHECK' line ind inserts it there")
parser.add_argument('--check-include',action='append',default=[], help="What parts of the output lines to check; use syntax 'CHECK=include' to apply to one CHECK-prefix only (by default, everything)")
parser.add_argument('--check-label-include',action='append',default=[],help="Use CHECK-LABEL for these includes")
parser.add_argument('--check-part-newline',action='store_true',help="Add empty line between different check parts")
parser.add_argument('--prefix-only',action='append',default=None,help="Update only these prefixes (default: all)")
parser.add_argument('--bindir',help="Location of the opt program")
parser.add_argument('--testdir',help="Root dir for unit tests")
parser.add_argument('--inplace','-i',action='store_true',help="Replace input file")
parser.add_argument('--output','-o',help="Write changed input to this file")
known = parser.parse_args()
if not known.inplace and known.output is None:
print("Must specify what to do with output (--output or --inplace)")
exit(1)
if known.inplace and known.output is not None:
print("--inplace and --output are mutually exclusive")
exit(1)
outfile = known.output
filecheckparser = argparse.ArgumentParser(add_help=False)
filecheckparser.add_argument('-check-prefix','--check-prefix',default='CHECK')
filename = known.testfile
for dir in ['.', known.testdir, os.path.join(polly_src_dir,'test'), polly_src_dir]:
if not dir:
continue
testfilename = os.path.join(dir,filename)
if os.path.isfile(testfilename):
filename = testfilename
break
if known.inplace:
outfile = filename
allchecklines = []
checkprefixes = []
with open(filename, 'r') as file:
oldlines = [line.rstrip('\r\n') for line in file.readlines()]
runlines = []
for line in oldlines:
m = runre.match(line)
if m:
runlines.append(m.group('tool'))
continuation = ''
newrunlines = []
for line in runlines:
if line.endswith('\\'):
continuation += line[:-2] + ' '
else:
newrunlines.append(continuation + line)
continuation = ''
if continuation:
newrunlines.append(continuation)
for line in newrunlines:
m = filecheckre.match(line)
if not m:
continue
tool, filecheck = m.group('tool', 'filecheck')
filecheck = shlex.split(filecheck)
tool = shlex.split(tool)
if known.bindir is not None:
tool[0] = complete_exename(known.bindir, tool[0])
if os.path.isdir(llvm_tools_dir):
tool[0] = complete_exename(llvm_tools_dir, tool[0])
check_prefix = filecheckparser.parse_known_args(filecheck)[0].check_prefix
if known.prefix_only is not None and not check_prefix in known.prefix_only:
continue
if check_prefix in checkprefixes:
continue
checkprefixes.append(check_prefix)
newtool = []
optstderr = None
for toolarg in tool:
toolarg = toolarg.replace('%s', filename)
toolarg = toolarg.replace('%S', os.path.dirname(filename))
if toolarg == '%loadPolly':
if not link_polly_into_tools:
newtool += ['-load',os.path.join(polly_lib_dir,'LLVMPolly' + shlibext)]
newtool.append('-polly-process-unprofitable')
newtool.append('-polly-remarks-minimal')
elif toolarg == '2>&1':
optstderr = subprocess.STDOUT
else:
newtool.append(toolarg)
tool = newtool
inpfile = None
i = 1
while i < len(tool):
if tool[i] == '<':
inpfile = tool[i + 1]
del tool[i:i + 2]
continue
i += 1
if inpfile:
with open(inpfile) as inp:
retlines = subprocess.check_output(tool,universal_newlines=True,stdin=inp,stderr=optstderr)
else:
retlines = subprocess.check_output(tool,universal_newlines=True,stderr=optstderr)
retlines = [line.replace('\t', ' ') for line in retlines.splitlines()]
check_include = []
for checkme in known.check_include + known.check_label_include:
parts = checkme.split('=')
if len(parts) == 2:
if parts[0] == check_prefix:
check_include.append(parts[1])
else:
check_include.append(checkme)
if check_include:
filtered_retlines = []
classified_retlines = []
lastmatch = None
for line,kind in ((line,class1.union(class2)) for line,class1,class2 in zip(retlines,classyfier1(retlines), classyfier2(retlines))):
match = kind.intersection(check_include)
if match:
if lastmatch != match:
filtered_retlines.append('')
classified_retlines.append({'Separator'})
filtered_retlines.append(line)
classified_retlines.append(kind)
lastmatch = match
retlines = filtered_retlines
else:
classified_retlines = (set() for line in retlines)
rtrim_emptylines(retlines)
ltrim_emptylines(retlines,classified_retlines)
retlines = [replre.sub(lambda m: replrepl[m.group(0)], line) for line in retlines]
indent = common_indent(retlines)
retlines = [line[indent:] for line in retlines]
checklines = []
previous_was_empty = True
for line,kind in zip(retlines,classified_retlines):
if line:
if known.check_style == 'CHECK' and known.check_label_include:
if not kind.isdisjoint(known.check_label_include):
checklines.append('; ' + check_prefix + '-LABEL: ' + line)
else:
checklines.append('; ' + check_prefix + ': ' + line)
elif known.check_style == 'CHECK':
checklines.append('; ' + check_prefix + ': ' + line)
elif known.check_label_include and known.check_label_include:
if not kind.isdisjoint(known.check_label_include):
checklines.append('; ' + check_prefix + '-LABEL: ' + line)
elif previous_was_empty:
checklines.append('; ' + check_prefix + ': ' + line)
else:
checklines.append('; ' + check_prefix + '-NEXT: ' + line)
else:
if previous_was_empty:
checklines.append('; ' + check_prefix + ': ' + line)
else:
checklines.append('; ' + check_prefix + '-NEXT: ' + line)
previous_was_empty = False
else:
if not 'Separator' in kind or known.check_part_newline:
checklines.append(';')
previous_was_empty = True
allchecklines.append(checklines)
if not checkprefixes:
return
checkre = re.compile(r'^\s*\;\s*(' + '|'.join([re.escape(s) for s in checkprefixes]) + ')(\-NEXT|\-DAG|\-NOT|\-LABEL|\-SAME)?\s*\:')
firstcheckline = None
firstnoncommentline = None
headerlines = []
newlines = []
uptonowlines = []
emptylines = []
lastwascheck = False
for line in oldlines:
if checkre.match(line):
if firstcheckline is None:
firstcheckline = len(newlines) + len(emptylines)
if not lastwascheck:
uptonowlines += emptylines
emptylines = []
lastwascheck = True
elif emptyline.fullmatch(line):
emptylines.append(line)
else:
newlines += uptonowlines
newlines += emptylines
newlines.append(line)
emptylines = []
uptonowlines = []
lastwascheck = False
for i,line in enumerate(newlines):
if not commentline.fullmatch(line):
firstnoncommentline = i
break
with open(outfile,'w',newline='') as file:
def writelines(lines):
for line in lines:
file.write(line)
file.write('\n')
if firstcheckline is not None and known.check_position == 'autodetect':
writelines(newlines[:firstcheckline])
writelines(uptonowlines)
for i,checklines in enumerate(allchecklines):
if i != 0:
file.write('\n')
writelines(checklines)
writelines(newlines[firstcheckline:])
writelines(emptylines)
elif firstnoncommentline is not None and known.check_position == 'before-content':
headerlines = newlines[:firstnoncommentline]
rtrim_emptylines(headerlines)
contentlines = newlines[firstnoncommentline:]
ltrim_emptylines(contentlines)
writelines(headerlines)
for checklines in allchecklines:
file.write('\n')
writelines(checklines)
file.write('\n')
writelines(contentlines)
writelines(uptonowlines)
writelines(emptylines)
else:
writelines(newlines)
rtrim_emptylines(newlines)
for checklines in allchecklines:
file.write('\n\n')
writelines(checklines)
if __name__ == '__main__':
main()
| {
"content_hash": "11a373183d30cb59cde05124b8af4c46",
"timestamp": "",
"source": "github",
"line_count": 453,
"max_line_length": 231,
"avg_line_length": 38.03532008830022,
"alnum_prop": 0.5286128845037725,
"repo_name": "youtube/cobalt_sandbox",
"id": "318fcfe53c9f3f4ce703588bf220df7c2442a800",
"size": "17414",
"binary": false,
"copies": "6",
"ref": "refs/heads/main",
"path": "third_party/llvm-project/polly/test/update_check.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
export USE_CYTHON=True
export PERFORMING_CONDA_BUILD=True
export LIBRARY_PATH="${CONDA_PREFIX}/lib"
export CPLUS_INCLUDE_PATH="${CONDA_PREFIX}/include"
if [ "$(uname)" == "Darwin" ]; then
export MACOSX_DEPLOYMENT_TARGET=10.12
fi
pushd sucpp
make api
popd
$PYTHON -m pip install --no-deps --ignore-installed .
| {
"content_hash": "23eef91a2c3b467445d2a8a638d99d84",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 53,
"avg_line_length": 22.571428571428573,
"alnum_prop": 0.7278481012658228,
"repo_name": "bioconda/recipes",
"id": "a074c3ceb3e6e69064acc7e251f3012a44b7cf81",
"size": "329",
"binary": false,
"copies": "10",
"ref": "refs/heads/master",
"path": "recipes/unifrac/build.sh",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "55032"
},
{
"name": "Makefile",
"bytes": "539"
},
{
"name": "Perl",
"bytes": "767"
},
{
"name": "Python",
"bytes": "38996"
},
{
"name": "Shell",
"bytes": "250193"
}
],
"symlink_target": ""
} |
{-# LANGUAGE TypeOperators,
GADTs,
FlexibleContexts#-}
module Obsidian.GCDObsidian.AddOn.SortLang where
import Obsidian.GCDObsidian.Exp
import Obsidian.GCDObsidian.Kernel
import Obsidian.GCDObsidian.Program
import Obsidian.GCDObsidian.Array
import Obsidian.GCDObsidian.Sync
import Obsidian.GCDObsidian.Library
--temporary
import qualified Obsidian.GCDObsidian.CodeGen.CUDA as CUDA
import Control.Category
import Prelude hiding ((.),id)
import Data.Bits
import Data.Word
data a :-> b where
Pure :: (Array a -> Array b) -> (Array a :-> Array b)
Two :: (Array a :-> Array b) -> (Array a :-> Array b)
-- TODO: Add
-- Ilv
-- Vee
-- And whatever else is needed for sorting/merging
Sync :: Syncable a e => a e :-> Array e
SLSeq :: (Array a :-> Array b)
-> (Array b :-> Array c)
-> (Array a :-> Array c)
compile :: (a :-> b) -> a -> Kernel b
compile (Pure f) = pure f
compile (Two p) = compileTwo 1 p
compile Sync = sync
compile (SLSeq f g) = compile f ->- compile g
compileTwo :: Int -> (Array a :-> Array b) -> Array a -> Kernel (Array b)
compileTwo n (Pure f) = pure$ twoK n f
compileTwo n (SLSeq f g) = compileTwo n f ->- compileTwo n g
compileTwo n Sync = sync
compileTwo n (Two p) = compileTwo (n+1) p
test1 :: Array (Exp Int) :-> Array (Exp Int)
test1 = Two (Pure rev `SLSeq` Sync `SLSeq` Pure rev)
getTest1 = putStrLn$ CUDA.genKernel "test1" (compile test1) (namedArray "hej" 64)
test2 :: Array (Exp Int) :-> Array (Exp Int)
test2 = Two (Pure rev `SLSeq` Sync `SLSeq` (Two (Pure rev)))
getTest2 = putStrLn$ CUDA.genKernel "test2" (compile test2) (namedArray "hej" 64)
test3 :: Array (Exp Int) :-> Array (Exp Int)
test3 = Two (Pure rev `SLSeq` Sync `SLSeq` (Two (Pure rev `SLSeq` Sync `SLSeq` (Two (Pure rev)))))
getTest3 = putStrLn$ CUDA.genKernel "test3" (compile test3) (namedArray "hej" 64)
sklansky :: Int
-> (Exp Int -> Exp Int -> Exp Int)
-> (Array (Exp Int) :-> Array (Exp Int))
sklansky 0 op = Pure id
sklansky n op = Two (sklansky (n-1) op) `SLSeq` Pure (fan op)
`SLSeq` Sync
fan op arr = conc (a1, (fmap (op c) a2))
where (a1,a2) = halve arr
c = a1 ! (fromIntegral (len a1 - 1))
getSklansky = putStrLn$ CUDA.genKernel "Sklansky" (compile (sklansky 3 (+))) (namedArray "hej" 8) | {
"content_hash": "3b38b43158024232b57608e65cc1f483",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 100,
"avg_line_length": 28.857142857142858,
"alnum_prop": 0.6142739273927392,
"repo_name": "svenssonjoel/GCDObsidian",
"id": "0331058d0d1aee0ece36172878b5a28d425ecb7a",
"size": "2424",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Obsidian/GCDObsidian/AddOn/SortLang.hs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "6916"
},
{
"name": "Haskell",
"bytes": "197014"
}
],
"symlink_target": ""
} |
using System.Collections.Generic;
namespace MahjongBuddy.MjGames.Dto
{
public class GetMjGamesOutput
{
public IEnumerable<MjGameDto> Items{ get; set; }
}
}
| {
"content_hash": "54ec20c63b898bf76033ecffd0e6661a",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 56,
"avg_line_length": 19.77777777777778,
"alnum_prop": 0.6966292134831461,
"repo_name": "tthiatma/mj-buddy-ntier",
"id": "9d63e000d42226e098da93c5ae4b73f617232d06",
"size": "180",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "MahjongBuddy.Application/MjGames/Dto/GetMjGamesOutput.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "107"
},
{
"name": "C#",
"bytes": "253146"
},
{
"name": "CSS",
"bytes": "99684"
},
{
"name": "HTML",
"bytes": "728"
},
{
"name": "JavaScript",
"bytes": "827968"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<title>org.deidentifier.arx.gui.view.impl.common (ARX GUI Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
</head>
<body>
<h1 class="bar"><a href="../../../../../../../org/deidentifier/arx/gui/view/impl/common/package-summary.html" target="classFrame">org.deidentifier.arx.gui.view.impl.common</a></h1>
<div class="indexContainer">
<h2 title="Interfaces">Interfaces</h2>
<ul title="Interfaces">
<li><a href="ComponentStatusLabelProgressProvider.html" title="interface in org.deidentifier.arx.gui.view.impl.common" target="classFrame"><i>ComponentStatusLabelProgressProvider</i></a></li>
</ul>
<h2 title="Classes">Classes</h2>
<ul title="Classes">
<li><a href="ClipboardHandlerTable.html" title="class in org.deidentifier.arx.gui.view.impl.common" target="classFrame">ClipboardHandlerTable</a></li>
<li><a href="ClipboardHandlerTree.html" title="class in org.deidentifier.arx.gui.view.impl.common" target="classFrame">ClipboardHandlerTree</a></li>
<li><a href="ComponentDataTable.html" title="class in org.deidentifier.arx.gui.view.impl.common" target="classFrame">ComponentDataTable</a></li>
<li><a href="ComponentFilterTable.html" title="class in org.deidentifier.arx.gui.view.impl.common" target="classFrame">ComponentFilterTable</a></li>
<li><a href="ComponentStatus.html" title="class in org.deidentifier.arx.gui.view.impl.common" target="classFrame">ComponentStatus</a></li>
<li><a href="ComponentStatusLabel.html" title="class in org.deidentifier.arx.gui.view.impl.common" target="classFrame">ComponentStatusLabel</a></li>
<li><a href="ComponentTable.html" title="class in org.deidentifier.arx.gui.view.impl.common" target="classFrame">ComponentTable</a></li>
<li><a href="ComponentTitledBorder.html" title="class in org.deidentifier.arx.gui.view.impl.common" target="classFrame">ComponentTitledBorder</a></li>
<li><a href="ComponentTitledFolder.html" title="class in org.deidentifier.arx.gui.view.impl.common" target="classFrame">ComponentTitledFolder</a></li>
<li><a href="ComponentTitledFolderButton.html" title="class in org.deidentifier.arx.gui.view.impl.common" target="classFrame">ComponentTitledFolderButton</a></li>
<li><a href="ViewData.html" title="class in org.deidentifier.arx.gui.view.impl.common" target="classFrame">ViewData</a></li>
<li><a href="ViewDataInput.html" title="class in org.deidentifier.arx.gui.view.impl.common" target="classFrame">ViewDataInput</a></li>
<li><a href="ViewDataOutput.html" title="class in org.deidentifier.arx.gui.view.impl.common" target="classFrame">ViewDataOutput</a></li>
<li><a href="ViewHierarchy.html" title="class in org.deidentifier.arx.gui.view.impl.common" target="classFrame">ViewHierarchy</a></li>
</ul>
</div>
</body>
</html>
| {
"content_hash": "43d7ef622011cf08d3d6dbfda6a94505",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 191,
"avg_line_length": 85.5,
"alnum_prop": 0.7512899896800825,
"repo_name": "TheRealRasu/arx",
"id": "55f90ae9063a075f251520c4ee876234ab7fa24a",
"size": "2907",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "doc/gui/org/deidentifier/arx/gui/view/impl/common/package-frame.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "61796"
},
{
"name": "Java",
"bytes": "4061036"
}
],
"symlink_target": ""
} |
const path = require('path');
const webpack = require('webpack');
const TerserPlugin = require('terser-webpack-plugin');
module.exports = {
mode: 'production',
// mode: 'development',
entry: {
main: path.join(__dirname, 'tmp', './src/main'),
},
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js'
},
resolve: {
extensions: ['.js']
},
module: {
rules: [{
test: /\.js?$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader'
}
]
}]
},
optimization: {
minimizer: [
new TerserPlugin({
terserOptions: {
parse: {
// we want terser to parse ecma 8 code. However, we don't want it
// to apply any minfication steps that turns valid ecma 5 code
// into invalid ecma 5 code. This is why the 'compress' and 'output'
// sections only apply transformations that are ecma 5 safe
// https://github.com/facebook/create-react-app/pull/4234
ecma: 8,
},
compress: {
ecma: 5,
warnings: false,
// Disabled because of an issue with Uglify breaking seemingly valid code:
// https://github.com/facebook/create-react-app/issues/2376
// Pending further investigation:
// https://github.com/mishoo/UglifyJS2/issues/2011
comparisons: false,
},
mangle: {
safari10: true,
},
output: {
ecma: 5,
comments: false,
// Turned on because emoji and regex is not minified properly using default
// https://github.com/facebook/create-react-app/issues/2488
ascii_only: true,
},
},
// Use multi-process parallel running to improve the build speed
// Default number of concurrent runs: os.cpus().length - 1
parallel: true,
// Enable file caching
cache: true,
}),
]
},
plugins: [
new webpack.DefinePlugin({
'process.env': { NODE_ENV: JSON.stringify('production') }
}),
],
};
| {
"content_hash": "1e34ea05e1a655bce77bc92691995ba0",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 81,
"avg_line_length": 25.783783783783782,
"alnum_prop": 0.6063941299790356,
"repo_name": "krausest/js-framework-benchmark",
"id": "75b58eb859bd2d31de67afec705ed4ce05eb7b8e",
"size": "1908",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "frameworks/keyed/angular/webpack.config.js",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "826"
},
{
"name": "C#",
"bytes": "6022"
},
{
"name": "CSS",
"bytes": "6054"
},
{
"name": "Clojure",
"bytes": "10816"
},
{
"name": "Dhall",
"bytes": "455"
},
{
"name": "Dockerfile",
"bytes": "1608"
},
{
"name": "Elm",
"bytes": "15949"
},
{
"name": "HTML",
"bytes": "834877"
},
{
"name": "Handlebars",
"bytes": "9737"
},
{
"name": "Haskell",
"bytes": "18642"
},
{
"name": "Imba",
"bytes": "6204"
},
{
"name": "JavaScript",
"bytes": "6914687"
},
{
"name": "Less",
"bytes": "202873"
},
{
"name": "Marko",
"bytes": "2628"
},
{
"name": "Nix",
"bytes": "1744"
},
{
"name": "OCaml",
"bytes": "10678"
},
{
"name": "PureScript",
"bytes": "6684"
},
{
"name": "Reason",
"bytes": "14793"
},
{
"name": "Riot",
"bytes": "6753"
},
{
"name": "Rust",
"bytes": "146341"
},
{
"name": "Scala",
"bytes": "6487"
},
{
"name": "Shell",
"bytes": "2544"
},
{
"name": "Svelte",
"bytes": "7202"
},
{
"name": "TypeScript",
"bytes": "855285"
},
{
"name": "Vue",
"bytes": "7266"
}
],
"symlink_target": ""
} |
namespace System.Web.UI.WebControls {
using System;
using System.Web.UI.WebControls;
/// <devdoc>
/// <para>Creates a special cell that is contained within a DataControlField.</para>
/// </devdoc>
public class DataControlFieldCell : TableCell {
DataControlField _containingField;
public DataControlFieldCell(DataControlField containingField) {
_containingField = containingField;
}
protected DataControlFieldCell(HtmlTextWriterTag tagKey, DataControlField containingField) : base(tagKey) {
_containingField = containingField;
}
public DataControlField ContainingField {
get {
return _containingField;
}
}
/// <summary>
/// <see cref='System.Web.UI.WebControls.DataControlFieldCell'/> gets the value of ValidateRequestMode from it's <see cref='System.Web.UI.WebControls.DataControlFieldCell.ContainingField'/>.
/// The ValidateRequestMode property should not be set directly on <see cref='System.Web.UI.WebControls.DataControlFieldCell'/>.
/// </summary>
public override ValidateRequestMode ValidateRequestMode {
get {
return _containingField.ValidateRequestMode;
}
set {
throw new InvalidOperationException(SR.GetString(SR.DataControlFieldCell_ShouldNotSetValidateRequestMode));
}
}
}
}
| {
"content_hash": "0eb1c72d813b0ea5c3d8b6bc9bc20158",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 199,
"avg_line_length": 32.8,
"alnum_prop": 0.6456639566395664,
"repo_name": "akoeplinger/referencesource",
"id": "4db8e53a08beda72f111bd9ba0c52f13a7c74a1f",
"size": "1851",
"binary": false,
"copies": "17",
"ref": "refs/heads/mono",
"path": "System.Web/UI/WebControls/DataControlFieldCell.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "125913009"
}
],
"symlink_target": ""
} |
namespace ui {
int ModifierDomKeyToEventFlag(DomKey key) {
switch (key) {
case DomKey::ALT:
return EF_ALT_DOWN;
case DomKey::ALT_GRAPH:
return EF_ALTGR_DOWN;
// ChromeOS uses F16 to represent CapsLock before the rewriting stage,
// based on the historical X11 implementation.
// TODO post-X11: Switch to use CapsLock uniformly.
case DomKey::F16:
case DomKey::CAPS_LOCK:
return EF_CAPS_LOCK_DOWN;
case DomKey::CONTROL:
return EF_CONTROL_DOWN;
case DomKey::HYPER:
return EF_MOD3_DOWN;
case DomKey::META:
return EF_ALT_DOWN;
case DomKey::OS:
return EF_COMMAND_DOWN;
case DomKey::SHIFT:
return EF_SHIFT_DOWN;
case DomKey::SUPER:
return EF_MOD3_DOWN;
default:
return EF_NONE;
}
// Not represented:
// DomKey::ACCEL
// DomKey::FN
// DomKey::FN_LOCK
// DomKey::NUM_LOCK
// DomKey::SCROLL_LOCK
// DomKey::SYMBOL
// DomKey::SYMBOL_LOCK
}
} // namespace ui
| {
"content_hash": "54e3e14e296efb9461b87a523f0fdd2d",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 74,
"avg_line_length": 25,
"alnum_prop": 0.626,
"repo_name": "PeterWangIntel/chromium-crosswalk",
"id": "4d69673571683c6c6b9158e4aaba3a2bb9f14987",
"size": "1299",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "ui/events/ozone/layout/layout_util.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "AppleScript",
"bytes": "6973"
},
{
"name": "Arduino",
"bytes": "464"
},
{
"name": "Assembly",
"bytes": "34367"
},
{
"name": "Batchfile",
"bytes": "8451"
},
{
"name": "C",
"bytes": "9385814"
},
{
"name": "C++",
"bytes": "234925784"
},
{
"name": "CSS",
"bytes": "951745"
},
{
"name": "DM",
"bytes": "60"
},
{
"name": "Emacs Lisp",
"bytes": "988"
},
{
"name": "Groff",
"bytes": "2494"
},
{
"name": "HTML",
"bytes": "29070071"
},
{
"name": "Java",
"bytes": "10107231"
},
{
"name": "JavaScript",
"bytes": "20170506"
},
{
"name": "Makefile",
"bytes": "68234"
},
{
"name": "Objective-C",
"bytes": "1845625"
},
{
"name": "Objective-C++",
"bytes": "9478782"
},
{
"name": "PHP",
"bytes": "97817"
},
{
"name": "PLpgSQL",
"bytes": "178732"
},
{
"name": "Perl",
"bytes": "63937"
},
{
"name": "Protocol Buffer",
"bytes": "465313"
},
{
"name": "Python",
"bytes": "8153532"
},
{
"name": "Shell",
"bytes": "473684"
},
{
"name": "Standard ML",
"bytes": "5034"
},
{
"name": "XSLT",
"bytes": "418"
},
{
"name": "nesC",
"bytes": "18347"
}
],
"symlink_target": ""
} |
package org.spongepowered.mod.mixin.core.client.server;
import static com.google.common.base.Preconditions.checkNotNull;
import net.minecraft.client.Minecraft;
import net.minecraft.server.integrated.IntegratedServer;
import net.minecraft.world.WorldSettings;
import net.minecraft.world.WorldType;
import org.spongepowered.api.util.annotation.NonnullByDefault;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.common.bridge.server.integrated.IntegratedServerBridge;
import org.spongepowered.common.mixin.core.server.MinecraftServerMixin;
@NonnullByDefault
@Mixin(IntegratedServer.class)
public abstract class IntegratedServerMixin_Forge extends MinecraftServerMixin implements IntegratedServerBridge {
@Shadow @Final private WorldSettings worldSettings;
@Shadow @Final private Minecraft mc;
private boolean forgeImpl$isNewSave;
/**
* @author bloodmc
*
* @reason In order to guarantee that both client and server load worlds the
* same using our custom logic, we call super and handle any client specific
* cases there.
* Reasoning: This avoids duplicate code and makes it easier to maintain.
*/
@Override
@Overwrite
public void loadAllWorlds(final String overworldFolder, final String unused, final long seed, final WorldType type, final String generator) {
super.loadAllWorlds(overworldFolder, unused, seed, type, generator);
}
@Override
public WorldSettings bridge$getSettings() {
return this.worldSettings;
}
@Override
public void bridge$markNewSave() {
this.forgeImpl$isNewSave = true;
}
@Override
public boolean bridge$isNewSave() {
return this.forgeImpl$isNewSave;
}
}
| {
"content_hash": "c85b3e5e4cb5c1938f43587d6d114bfa",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 145,
"avg_line_length": 33.96363636363636,
"alnum_prop": 0.7617773019271948,
"repo_name": "SpongePowered/SpongeForge",
"id": "de3ece097860cf2ea4415cb4c596d4bde66ffb60",
"size": "3115",
"binary": false,
"copies": "1",
"ref": "refs/heads/stable-7",
"path": "src/main/java/org/spongepowered/mod/mixin/core/client/server/IntegratedServerMixin_Forge.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "1080621"
},
{
"name": "Shell",
"bytes": "1072"
}
],
"symlink_target": ""
} |