text
stringlengths
2
1.04M
meta
dict
<?php namespace GitLive\Helper; use GitLive\GitBase; /** * Class Resource * * @category GitCommand * @package GitLive\Hepler * @subpackage Core * @author akito<akito-artisan@five-foxes.com> * @author suzunone<suzunone.eleven@gmail.com> * @copyright Project Git Live * @license MIT * @version GIT: $Id$ * @link https://github.com/Git-Live/git-live * @see https://github.com/Git-Live/git-live * @since 2021/12/30 */ class Resource extends GitBase { /** * @param string $file * @param string $default * @return string */ public function get(string $file, string $default = ''): string { $file_path = RESOURCES_DIR . DIRECTORY_SEPARATOR . $file; return is_file($file_path) ? file_get_contents($file_path) : $default; } /** * @param string $signature_name * @param string $default * @return string */ public function help(string $signature_name, string $default = ''): string { $file = str_replace(':', DIRECTORY_SEPARATOR, $signature_name . '.md'); $help_path = RESOURCES_DIR . DIRECTORY_SEPARATOR . 'help' . DIRECTORY_SEPARATOR . 'lang' . DIRECTORY_SEPARATOR; if (is_file($help_path . GIT_LIVE_LANG . DIRECTORY_SEPARATOR . $file)) { return file_get_contents($help_path . GIT_LIVE_LANG . DIRECTORY_SEPARATOR . $file); } if (is_file($help_path . 'en_US' . DIRECTORY_SEPARATOR . $file)) { return file_get_contents($help_path . 'en_US' . DIRECTORY_SEPARATOR . $file); } return $default; } }
{ "content_hash": "352c3e8486fa6e0722c3c6df4c323fb9", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 119, "avg_line_length": 28.785714285714285, "alnum_prop": 0.6011166253101737, "repo_name": "Git-Live/git-live", "id": "3df05e949ca3f247b5b02917b3768c722338a253", "size": "2123", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/libs/GitLive/Helper/Resource.php", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "81" }, { "name": "PHP", "bytes": "1153545" }, { "name": "Shell", "bytes": "1766" } ], "symlink_target": "" }
* Update dependencies * Fix Windows CO * Add sponsor for Duckly ### 0.1.9 (2021-10-12) * Fix potential security vulnerabilities ### 0.1.8 (2021-07-31) * Fix potential security vulnerabilities ### 0.1.7 (2021-07-09) * Support new vscode apis * Fix bugs ### 0.1.6 (2021-01-06) * Also check linkedEditing setting * Fix [#562](https://github.com/formulahendry/vscode-auto-rename-tag/issues/562) ### 0.1.5 (2020-10-11) * [#556](https://github.com/formulahendry/vscode-auto-rename-tag/pull/556): Improve auto renaming with React ### 0.1.4 (2020-07-03) * [#541](https://github.com/formulahendry/vscode-auto-rename-tag/pull/541): fix tag starting with $ * [#544](https://github.com/formulahendry/vscode-auto-rename-tag/pull/544): fix script and style rename ### 0.1.3 (2020-05-16) * Skip HTML and Handlebars files when the setting `editor.renameOnType` is enabled ### 0.1.2 (2020-04-21) * Kudos to [@SimonSiefke](https://github.com/SimonSiefke) for [rewriting the logic of this extension](https://github.com/formulahendry/vscode-auto-rename-tag/pull/511) ### 0.1.1 (2019-10-27) * Add notice about performance issue ### 0.1.0 (2019-06-02) * [#105](https://github.com/formulahendry/vscode-auto-rename-tag/pull/105): Bug fixes ### 0.0.15 (2017-11-04) * Add support for Multi Root Workspace ### 0.0.14 (2017-06-19) * Fix [#30](https://github.com/formulahendry/vscode-auto-rename-tag/issues/30) ### 0.0.13 (2017-06-18) * Fix [#24](https://github.com/formulahendry/vscode-auto-rename-tag/issues/24) and [#29](https://github.com/formulahendry/vscode-auto-rename-tag/issues/29) ### 0.0.12 (2017-05-21) * Fix [#15](https://github.com/formulahendry/vscode-auto-rename-tag/issues/15) and [#21](https://github.com/formulahendry/vscode-auto-rename-tag/issues/21): Undo and redo are broken ### 0.0.11 * Fix [GitHub issue#12](https://github.com/formulahendry/vscode-auto-rename-tag/issues/12): Not work when using OPTION+DELETE (or CTRL+BACKSPACE) ### 0.0.10 * Fix [GitHub issue#17](https://github.com/formulahendry/vscode-auto-rename-tag/issues/17): Unexpected renaming when moving row with "alt+down" ### 0.0.9 * Fix [GitHub issue#14](https://github.com/formulahendry/vscode-auto-rename-tag/issues/14): Avoid renaming tag when moving rows with "alt+up/down" ### 0.0.8 * Fix [GitHub issue#11](https://github.com/formulahendry/vscode-auto-rename-tag/issues/11) ### 0.0.7 * Fix [GitHub issue#8](https://github.com/formulahendry/vscode-auto-rename-tag/issues/8) ### 0.0.6 * Merge [PR#7](https://github.com/formulahendry/vscode-auto-rename-tag/pull/7): Remove console.log * Update README.md to clarify the configuration for `auto-rename-tag.activationOnLanguage` ### 0.0.5 * Fix [GitHub issue#6](https://github.com/formulahendry/vscode-auto-rename-tag/issues/6) ### 0.0.4 * Add support for tag name that contains ```- _ : .``` ### 0.0.3 * Fix paired tags not updated when there are void elements or self-closing tags between paired tags * Fix [GitHub issue#2](https://github.com/formulahendry/vscode-auto-rename-tag/issues/2) * Fix [GitHub issue#3](https://github.com/formulahendry/vscode-auto-rename-tag/issues/3) * Parse document independently instead of using SAXParser of parse5 npm package to avoid uncontrollable parse behavior ### 0.0.2 * Update logo ### 0.0.1 * Initial Release
{ "content_hash": "5597cd56fe9c7928ac69e172a778fe0a", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 181, "avg_line_length": 39.62352941176471, "alnum_prop": 0.7042755344418052, "repo_name": "ealbertos/dotfiles", "id": "ce1f98aa07f113a68bb85fe1a8eacb2d470c3958", "size": "3393", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vscode.symlink/extensions/formulahendry.auto-rename-tag-0.1.10/CHANGELOG.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "99972" }, { "name": "EJS", "bytes": "2437" }, { "name": "HTML", "bytes": "47081" }, { "name": "JavaScript", "bytes": "3546995" }, { "name": "Less", "bytes": "183" }, { "name": "Python", "bytes": "134723" }, { "name": "Ruby", "bytes": "127567" }, { "name": "Shell", "bytes": "34790" }, { "name": "TSQL", "bytes": "258" }, { "name": "TypeScript", "bytes": "37162" }, { "name": "Vim Script", "bytes": "60888" }, { "name": "Vim Snippet", "bytes": "11523" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <CustomFieldTranslation xmlns="http://soap.sforce.com/2006/04/metadata"> <name>Primary_Affl_Field__c</name> <help>Het label van het contactpersoonveld dat de waarde bevat van de primaire account voor dit recordtype.</help> <label>Primair affiliatieveld</label> </CustomFieldTranslation>
{ "content_hash": "a191650ce19792514e9813407cebadfa", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 118, "avg_line_length": 56.333333333333336, "alnum_prop": 0.7485207100591716, "repo_name": "SalesforceFoundation/HEDAP", "id": "818234b027913391be082b9f65e936a3d425cf69", "size": "338", "binary": false, "copies": "1", "ref": "refs/heads/feature/234", "path": "force-app/main/default/objectTranslations/Affl_Mappings__c-nl_NL/Primary_Affl_Field__c.fieldTranslation-meta.xml", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Apex", "bytes": "1599605" }, { "name": "CSS", "bytes": "621" }, { "name": "HTML", "bytes": "145319" }, { "name": "JavaScript", "bytes": "61802" }, { "name": "Python", "bytes": "28442" }, { "name": "RobotFramework", "bytes": "26714" } ], "symlink_target": "" }
package study.ejb2.lifecycle.stateless; import java.rmi.RemoteException; import javax.ejb.EJBObject; /** * The component interface. * Here we should redefine all business method that the bean does, * but declaring that it throws RemoteException. */ public interface EjbStatelessComponent extends EJBObject { public void doStuff() throws RemoteException; }
{ "content_hash": "2ed45f311913d5b78b6fc2a1ffae9154", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 66, "avg_line_length": 27, "alnum_prop": 0.7592592592592593, "repo_name": "wesleyegberto/study-ocbcd", "id": "fbf19f52f1a12aa85f01f299b47f1b0cb572824b", "size": "378", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "EjbLifecycleStudy/ejbModule/study/ejb2/lifecycle/stateless/EjbStatelessComponent.java", "mode": "33261", "license": "mit", "language": [ { "name": "Java", "bytes": "231435" } ], "symlink_target": "" }
This API can be used on Android > 2.2 To use it, you must [download the library](https://github.com/downloads/holalabs/holaio-android/HolaIO.zip), put it in your workspace, and import it from Eclipse. After that, you have to go to your project's properties, go to the Android menu and add HolaIO as a library. You can also check out the [demo app](https://github.com/holalabs/holaio-android/tree/master/Example). ## Object HolaIO(String APIKey) Creates an instance of HolaIO with the specified API key. Usage: ``` java HolaIO io = new HolaIO("yourapikey"); ``` ## Function HolaIO.get(String url, String selector, Boolean inner, Boolean cache, new AsyncResponseHandler() {}) Get the content specified in the following (obligatory) parameters: - URL: A valid URL without the protocol scheme, because holaIO currently only works with HTTP so it’ll add the prefix by default. Example: `holalabs.com` - Selector: A valid CSS3 selector. If you want to get more than a selector at a time, strip them by commas. Example: `a, .primary.content` - Inner or outer: Specify if you want to extract the innerHTML content or the whole content of your selection (outerHTML). Possible values: true for inner or false for outer - Cache: You have the possibility of caching the content received by your request. In that case, when doing that request a second time while the app stays opened, it will get the content cached instead of doing the request again. Possible values: "true" if you would like to cache the request and "false" if not. - AsyncResponseHandler(): Pass a new AsyncResponseHandler() and override onSuccess(JsonObject content), this is where you do what you need to do with your content. You can also override onFinish() to run code after the thread that gets the content has ended. This can be used to update the UI for example. There's also onError(Throwable error, String response) where you can handle any errors that might occur during the request. Usage: ``` java HolaIO io = new HolaIO("yourapikey"); io.get("google.com", "a span", true, true, new AsyncResponseHandler() { @Override public void onSuccess(JSONObject content) { // Have fun! } @Overrid public void onError(Throwable error, String response) { // Handle the error } @Override public void onFinish() { // Whatever you need to do after onSuccess like updating the UI. } }); ```
{ "content_hash": "b279743d9f3d1f6d03a20de4773e0bf5", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 431, "avg_line_length": 51.73913043478261, "alnum_prop": 0.7546218487394958, "repo_name": "holalabs/holaio-android", "id": "d8bb99c24f5b4bc1b85e4668a39c515fb1c8ce3c", "size": "2411", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "14815" } ], "symlink_target": "" }
Dewpoint plugin calculates dewpoint temperature in K. Formula used is taken from "The Relationship between Relative Humidity and the Dewpoint Temperature in Moist Air, A Simple Conversion and Applications" by Mark G. Lawrence (http://journals.ametsoc.org/doi/pdf/10.1175/BAMS-86-2-225). Plugin has been optimized for GPU use. # Required source parameters * T = air temperature (K) * r = relative humidity (%) * g = gas constant ratio between water vapor and air, 461.5 J / K * kg * h = latent heat for water vaporization, 2.5e6 J / kg # Output parameters TD-C Unit of resulting parameter is Kelvin. # Method of calculation td = T / (1 - T * ln(r * 0.01) * g / h) Relative humidity values are capped to maximum 100%. # Per-plugin configuration options None
{ "content_hash": "9559cba742c0987a88dfe254016a36ec", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 232, "avg_line_length": 27.607142857142858, "alnum_prop": 0.7309184993531694, "repo_name": "fmidev/himan", "id": "996d28fc112a4e7e519ba1ac0a66af89befc5deb", "size": "784", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/plugin-dewpoint.md", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "57572" }, { "name": "C++", "bytes": "1534412" }, { "name": "Cuda", "bytes": "192153" }, { "name": "Dockerfile", "bytes": "588" }, { "name": "Lua", "bytes": "153455" }, { "name": "Makefile", "bytes": "4309" }, { "name": "Python", "bytes": "23587" } ], "symlink_target": "" }
/** * DO NOT MODIFY, GENERATED BY TOOLS */ package com.titanium.news.models.base; import java.sql.Timestamp; import java.util.Date; /** * @author JinMa * */ public class NewsTypeBase { private int id=-1; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
{ "content_hash": "bc4396485b0d90b96a4a3a928fd92a0f", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 40, "avg_line_length": 12.325, "alnum_prop": 0.5699797160243407, "repo_name": "chineseweapon/kickIE6", "id": "d90287ada8c7b98fe13bd4a9d26409e0e3edeffd", "size": "493", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "train/src/main/java/com/titanium/news/models/base/NewsTypeBase.java", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "283136" }, { "name": "FreeMarker", "bytes": "68741" }, { "name": "HTML", "bytes": "348366" }, { "name": "Java", "bytes": "1207219" }, { "name": "JavaScript", "bytes": "1777358" } ], "symlink_target": "" }
package prefuse.data; import java.util.ArrayList; import java.util.Iterator; import javax.swing.event.TableModelEvent; import prefuse.data.column.Column; import prefuse.data.column.ColumnMetadata; import prefuse.data.event.EventConstants; import prefuse.data.event.ExpressionListener; import prefuse.data.event.ProjectionListener; import prefuse.data.event.TableListener; import prefuse.data.expression.BooleanLiteral; import prefuse.data.expression.Expression; import prefuse.data.expression.Predicate; import prefuse.data.tuple.TableTuple; import prefuse.data.util.AcceptAllColumnProjection; import prefuse.data.util.CascadedRowManager; import prefuse.data.util.ColumnProjection; import prefuse.util.collections.CompositeIterator; import prefuse.util.collections.IntIterator; /** * <p>Table subclass featuring a "cascaded" table design - a CascadedTable can * have a parent table, from which it inherits a potentially filtered set of * rows and columns. Child tables may override the columns of the parent by * having a column of the same name as that of the parent, in which case the * parent's column will not be accessible.</p> * * <p>Table rows of the parent table can be selectively included by providing * a {@link prefuse.data.expression.Predicate} that filters the parent rows. * Columns of the parent table can be selectively included by providing * a {@link prefuse.data.util.ColumnProjection} indicating the columns to * include.</p> * * <p>Tuple instances backed by a CascadedTable will be not be equivalent to * the tuples backed by the parent table. However, setting a value in a * CascadedTable that is inherited from a parent table <em>will</em> update * the value in the parent table.</p> * * @author <a href="http://jheer.org">jeffrey heer</a> */ public class CascadedTable extends Table { /** Cascaded parent table */ protected Table m_parent; /** List of included parent column names */ protected ArrayList m_pnames; /** ColumnProjection determining which columns of the parent table * are included in this table. */ protected ColumnProjection m_colFilter; /** Selection Predicate determining which rows of the parent table * are included in this table. */ protected Predicate m_rowFilter; /** An internal listener class */ protected Listener m_listener; // ------------------------------------------------------------------------ // Constructor /** * Create a new CascadedTable. By default all rows and columns of the * parent table are included in this one. * @param parent the parent Table to use */ public CascadedTable(Table parent) { this(parent, null, null); } /** * Create a new CascadedTable. By default all columns of the parent * table are included in this one. * @param parent the parent Table to use * @param rowFilter a Predicate determining which rows of the parent * table to include in this one. */ public CascadedTable(Table parent, Predicate rowFilter) { this(parent, rowFilter, null); } /** * Create a new CascadedTable. By default all rows of the parent * table are included in this one. * @param parent the parent Table to use * @param colFilter a ColumnProjection determining which columns of the * parent table to include in this one. */ public CascadedTable(Table parent, ColumnProjection colFilter) { this(parent, null, colFilter); } /** * Create a new CascadedTable. * @param parent the parent Table to use * @param rowFilter a Predicate determining which rows of the parent * table to include in this one. * @param colFilter a ColumnProjection determining which columns of the * parent table to include in this one. */ public CascadedTable(Table parent, Predicate rowFilter, ColumnProjection colFilter) { this(parent, rowFilter, colFilter, TableTuple.class); } /** * Create a new CascadedTable. * @param parent the parent Table to use * @param rowFilter a Predicate determining which rows of the parent * table to include in this one. * @param colFilter a ColumnProjection determining which columns of the * parent table to include in this one. * @param tupleType the class type of the Tuple instances to use */ protected CascadedTable(Table parent, Predicate rowFilter, ColumnProjection colFilter, Class tupleType) { super(0, 0, tupleType); m_parent = parent; m_pnames = new ArrayList(); m_rows = new CascadedRowManager(this); m_listener = new Listener(); setColumnProjection(colFilter); setRowFilter(rowFilter); m_parent.addTableListener(m_listener); } // -- non-cascading version ----------------------------------------------- /** * Create a CascadedTable without a backing parent table. */ protected CascadedTable() { this(TableTuple.class); } /** * Create a CascadedTable without a backing parent table. * @param tupleType the class type of the Tuple instances to use */ protected CascadedTable(Class tupleType) { super(0, 0, tupleType); m_pnames = new ArrayList(); } // ------------------------------------------------------------------------ // Filter Methods /** * Determines which columns are inherited from the backing parent table. */ protected void filterColumns() { if ( m_parent == null ) return; for ( int i=0; i<m_pnames.size(); ++i ) { String name = (String)m_pnames.get(i); Column col = m_parent.getColumn(i); boolean contained = m_names.contains(name); if ( !m_colFilter.include(col, name) || contained ) { m_pnames.remove(i--); if ( !contained ) { ((ColumnEntry)m_entries.get(name)).dispose(); m_entries.remove(name); } // fire notification fireTableEvent(m_rows.getMinimumRow(), m_rows.getMaximumRow(), i, EventConstants.DELETE); } } m_pnames.clear(); Iterator pcols = m_parent.getColumnNames(); for ( int i=0, j=m_columns.size(); pcols.hasNext(); ++i ) { String name = (String)pcols.next(); Column col = m_parent.getColumn(i); if ( m_colFilter.include(col, name) && !m_names.contains(name) ) { m_pnames.add(name); ColumnEntry entry = (ColumnEntry)m_entries.get(name); if ( entry == null ) { entry = new ColumnEntry(j++, col, new ColumnMetadata(this, name)); m_entries.put(name, entry); // fire notification fireTableEvent(m_rows.getMinimumRow(), m_rows.getMaximumRow(), i, EventConstants.INSERT); } else { entry.colnum = j++; } m_lastCol = m_columns.size()-1; } } } /** * Manually trigger a re-filtering of the rows of this table. If the * filtering predicate concerns only items within this table, calling * this method should be unnecessary. It is only when the filtering * predicate references data outside of this table that a manual * re-filtering request may be necessary. For example, filtering * valid edges of a graph from a pool of candidate edges will depend * on the available nodes. * @see prefuse.data.util.ValidEdgePredicate */ public void filterRows() { if ( m_parent == null ) return; CascadedRowManager rowman = (CascadedRowManager)m_rows; IntIterator crows = m_rows.rows(); while ( crows.hasNext() ) { int crow = crows.nextInt(); if ( !m_rowFilter.getBoolean( m_parent.getTuple(rowman.getParentRow(crow))) ) { removeCascadedRow(crow); } } Iterator ptuples = m_parent.tuples(m_rowFilter); while ( ptuples.hasNext() ) { Tuple pt = (Tuple)ptuples.next(); int prow = pt.getRow(); if ( rowman.getChildRow(prow) == -1 ) addCascadedRow(prow); } } /** * Get the ColumnProjection determining which columns of the * parent table are included in this one. * @return the ColumnProjection of this CascadedTable */ public ColumnProjection getColumnProjection() { return m_colFilter; } /** * Sets the ColumnProjection determining which columns of the * parent table are included in this one. * @param colFilter a ColumnProjection determining which columns of the * parent table to include in this one. */ public void setColumnProjection(ColumnProjection colFilter) { if ( m_colFilter != null ) { m_colFilter.removeProjectionListener(m_listener); } m_colFilter = colFilter==null ? new AcceptAllColumnProjection() : colFilter; m_colFilter.addProjectionListener(m_listener); filterColumns(); } /** * Gets ths Predicate determining which rows of the parent * table are included in this one. * @return the row filtering Predicate of this CascadedTable */ public Predicate getRowFilter() { return m_rowFilter; } /** * Sets the Predicate determining which rows of the parent * table are included in this one. * @param rowFilter a Predicate determining which rows of the parent * table to include in this one. */ public void setRowFilter(Predicate rowFilter) { if ( m_rowFilter != null ) { m_rowFilter.removeExpressionListener(m_listener); } m_rowFilter = rowFilter==null ? BooleanLiteral.TRUE : rowFilter; if ( m_rowFilter != BooleanLiteral.TRUE ) m_rowFilter.addExpressionListener(m_listener); filterRows(); } // ------------------------------------------------------------------------ // Table Metadata /** * @see prefuse.data.Table#getColumnCount() */ public int getColumnCount() { return m_columns.size() + m_pnames.size(); } /** * Get the number of columns explicitly stored by this table (i.e., all * columns that are not inherited from the parent table). * @return the number of locally stored columns */ public int getLocalColumnCount() { return m_columns.size(); } // ------------------------------------------------------------------------ // Parent Table Methods /** * Get the parent table from which this cascaded table inherits values. * @return the parent table */ public Table getParentTable() { return m_parent; } /** * Given a row in this table, return the corresponding row in the parent * table. * @param row a row in this table * @return the corresponding row in the parent table */ public int getParentRow(int row) { return ((CascadedRowManager)m_rows).getParentRow(row); } /** * Given a row in the parent table, return the corresponding row, if any, * in this table. * @param prow a row in the parent table * @return the corresponding row in this table, or -1 if the given parent * row is not inherited by this table */ public int getChildRow(int prow) { return ((CascadedRowManager)m_rows).getChildRow(prow); } // ------------------------------------------------------------------------ // Row Operations /** * @see prefuse.data.Table#addRow() */ public int addRow() { if ( m_parent != null ) { throw new IllegalStateException( "Add row not supported for CascadedTable."); } else { return super.addRow(); } } /** * @see prefuse.data.Table#addRows(int) */ public void addRows(int nrows) { if ( m_parent != null ) { throw new IllegalStateException( "Add rows not supported for CascadedTable."); } else { super.addRows(nrows); } } /** * @see prefuse.data.Table#removeRow(int) */ public boolean removeRow(int row) { if ( m_parent != null ) { throw new IllegalStateException( "Remove row not supported for CascadedTable."); } else { return super.removeRow(row); } } /** * Internal method for adding a new cascaded row backed by * the given parent row. * @param prow the parent row to inherit * @return the row number ofr the newly added row in this table */ protected int addCascadedRow(int prow) { int r = m_rows.addRow(); ((CascadedRowManager)m_rows).put(r, prow); updateRowCount(); fireTableEvent(r, r, TableModelEvent.ALL_COLUMNS, TableModelEvent.INSERT); return r; } /** * Internal method for removing a cascaded row from this table. * @param row the row to remove * @return true if the row was successfully removed, false otherwise */ protected boolean removeCascadedRow(int row) { boolean rv = super.removeRow(row); if ( rv ) ((CascadedRowManager)m_rows).remove(row); return rv; } // ------------------------------------------------------------------------ // Column Operations /** * @see prefuse.data.Table#getColumnName(int) */ public String getColumnName(int col) { int local = m_names.size(); if ( col >= local ) { return (String)m_pnames.get(col-local); } else { return (String)m_names.get(col); } } /** * @see prefuse.data.Table#getColumnNumber(prefuse.data.column.Column) */ public int getColumnNumber(Column col) { int idx = m_columns.indexOf(col); if ( idx == -1 && m_parent != null ) { idx = m_parent.getColumnNumber(col); if ( idx == -1 ) return idx; String name = m_parent.getColumnName(idx); idx = m_pnames.indexOf(name); if ( idx != -1 ) idx += m_columns.size(); } return idx; } /** * @see prefuse.data.Table#getColumn(int) */ public Column getColumn(int col) { m_lastCol = col; int local = m_names.size(); if ( col >= local && m_parent != null ) { return m_parent.getColumn((String)m_pnames.get(col-local)); } else { return (Column)m_columns.get(col); } } /** * @see prefuse.data.Table#hasColumn(java.lang.String) */ protected boolean hasColumn(String name) { int idx = getColumnNumber(name); return idx >= 0 && idx < getLocalColumnCount(); } /** * @see prefuse.data.Table#getColumnNames() */ protected Iterator getColumnNames() { if ( m_parent == null ) { return m_names.iterator(); } else { return new CompositeIterator(m_names.iterator(), m_pnames.iterator()); } } /** * Invalidates this table's cached schema. This method should be called * whenever columns are added or removed from this table. */ protected void invalidateSchema() { super.invalidateSchema(); this.filterColumns(); } // ------------------------------------------------------------------------ // Listener Methods /** * Internal listener class handling updates from the backing parent table, * the column projection, or the row selection predicate. */ private class Listener implements TableListener, ProjectionListener, ExpressionListener { public void tableChanged(Table t, int start, int end, int col, int type) { // must come from parent if ( t != m_parent ) return; CascadedRowManager rowman = (CascadedRowManager)m_rows; // switch on the event type switch ( type ) { case EventConstants.UPDATE: { // do nothing if update on all columns, as this is only // used to indicate a non-measurable update. if ( col == EventConstants.ALL_COLUMNS ) { break; } // process each update, check if filtered state changes for ( int r=start, cr=-1; r<=end; ++r ) { if ( (cr=rowman.getChildRow(r)) != -1 ) { // the parent row has a corresponding row in this table if ( m_rowFilter.getBoolean(m_parent.getTuple(r)) ) { // row still passes the filter, check the column int idx = getColumnNumber(m_parent.getColumnName(col)); if ( idx >= getLocalColumnCount() ) fireTableEvent(cr, cr, idx, EventConstants.UPDATE); } else { // row no longer passes the filter, remove it removeCascadedRow(cr); } } else { // does it now pass the filter due to the update? if ( m_rowFilter.getBoolean(m_parent.getTuple(r)) ) { if ( (cr=rowman.getChildRow(r)) < 0 ) addCascadedRow(r); } } } break; } case EventConstants.DELETE: { if ( col == EventConstants.ALL_COLUMNS ) { // entire rows deleted for ( int r=start, cr=-1; r<=end; ++r ) { if ( (cr=rowman.getChildRow(r)) != -1 ) removeCascadedRow(cr); } } else { // column deleted filterColumns(); } break; } case EventConstants.INSERT: if ( col == EventConstants.ALL_COLUMNS ) { // entire rows added for ( int r=start; r<=end; ++r ) { if ( m_rowFilter.getBoolean(m_parent.getTuple(r)) ) { if ( rowman.getChildRow(r) < 0 ) addCascadedRow(r); } } } else { // column added filterColumns(); } break; } } public void projectionChanged(ColumnProjection projection) { if ( projection == m_colFilter ) filterColumns(); } public void expressionChanged(Expression expr) { if ( expr == m_rowFilter ) filterRows(); } } } // end of class CascadedTable
{ "content_hash": "fabc2185802ccc8b1dbf44d79ef18bba", "timestamp": "", "source": "github", "line_count": 569, "max_line_length": 84, "avg_line_length": 34.8804920913884, "alnum_prop": 0.5457247946792966, "repo_name": "ezegarra/microbrowser", "id": "ab47b56936bf2bbaaeba3ccf240797be7a02fd93", "size": "19847", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/prefuse/data/CascadedTable.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "1387" }, { "name": "HTML", "bytes": "17064" }, { "name": "Java", "bytes": "3210397" }, { "name": "PLSQL", "bytes": "982379" }, { "name": "PLpgSQL", "bytes": "3792" }, { "name": "Python", "bytes": "20754" }, { "name": "R", "bytes": "3202" }, { "name": "Shell", "bytes": "587" } ], "symlink_target": "" }
/* * The password for the Bitcoin brainwallet can be found in the * "The Adventures of Sherlock Holmes" which you can retrieve from Gutenberg.org. * It will consist of a continuous string of alphabetical characters pulled from * the books text. * * The password will be 20-46 characters, so it should match /[a-zA-Z]{20,46}/ * * An example: * * "No sign of it?" * * "Absolutely none." * * Holmes laughed. "It is quite a pretty little problem," said he. * * Would be turned into this: * * "NosignofitAbsolutelynoneHolmeslaughedItisquiteaprettylittleproblemsaidhe" * * and the password could be 'bsolutelynoneHolmeslaughedItisquitea' * * You can test your strings against the method willItSpend: * * willItSpend('bsolutelynoneHolmeslaughedItisq') === false * * While a correct guess will return the brainwallets password * * willItSpend('bsolutelynoneHolmeslaughedItisquitea') === "[brainwallet password]" * * Then go to Brainwallet.org and transfer the Bitcoin to your account * * Good luck! */ var crypto = require('crypto'), solutionSha = "e9227d485a0732bf2b329c61e1eae86656e2e7a6a0e2d6ffa808c91090fe2347", hmacKey = "YahooWalletChallenge", challengeWallet = '1Khe9pCs34qRZX5jRffzC1Hxy33tnfi3T8'; module.exports = { name: "Sherlock password challenge", solutionSha: solutionSha, wallet: challengeWallet, willItSpend: function (str) { var hash = crypto.createHash('sha256').update(str).digest('hex'); // Hardening the brainwallet password into a SHA1 HMAC hash. if (hash === solutionSha) { return crypto.createHmac('sha1', hmacKey).update(str).digest('hex'); } return false; }, // Solved by https://github.com/crodas // https://blockchain.info/tx/1132b64834b5ec29cf5ae010241184a8d108c5ab8e3249e6aa3f85ea2a92f579 isSolved: true }
{ "content_hash": "c07a466fb119c3a0829331dcc2ca00d7", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 96, "avg_line_length": 32.232142857142854, "alnum_prop": 0.7379501385041551, "repo_name": "mdp/node-at-yahoo", "id": "20601e4a52882925aea20abfa9a24bedf2aedeff", "size": "1805", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/challenges/sherlock.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "3974" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>algebra: 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.13.2 / algebra - 8.7.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> algebra <small> 8.7.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-09-11 19:32:31 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-09-11 19:32:31 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 conf-gmp 4 Virtual package relying on a GMP lib system installation coq 8.13.2 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.13.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.13.1 Official release 4.13.1 ocaml-config 2 OCaml Switch Configuration ocaml-options-vanilla 1 Ensure that OCaml is compiled with no special options enabled ocamlfind 1.9.5 A library manager for OCaml zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/algebra&quot; license: &quot;LGPL 2.1&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Algebra&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.7&quot; &amp; &lt; &quot;8.8~&quot;} ] tags: [ &quot;keyword: algebra&quot; &quot;category: Mathematics/Algebra&quot; &quot;date: 1999-03&quot; ] authors: [ &quot;Loïc Pottier [http://www-sop.inria.fr/croap/personnel/Loic.Pottier/home.html]&quot; ] bug-reports: &quot;https://github.com/coq-contribs/algebra/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/algebra.git&quot; synopsis: &quot;Basics notions of algebra&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/algebra/archive/v8.7.0.tar.gz&quot; checksum: &quot;md5=270a31a595cf4d5462f36fdac5cf1e22&quot; } </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-algebra.8.7.0 coq.8.13.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.13.2). The following dependencies couldn&#39;t be met: - coq-algebra -&gt; coq &lt; 8.8~ -&gt; ocaml &lt; 4.10 base of this switch (use `--unlock-base&#39; 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-algebra.8.7.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": "237cd732e7997eb7fd7c0965bfa3eb6f", "timestamp": "", "source": "github", "line_count": 162, "max_line_length": 159, "avg_line_length": 42.26543209876543, "alnum_prop": 0.535709069665547, "repo_name": "coq-bench/coq-bench.github.io", "id": "d3e055ca6ddf6611dcc8c2f545955bdf4c532a90", "size": "6873", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.13.1-2.0.10/released/8.13.2/algebra/8.7.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
Imports System Imports System.Reflection Imports System.Runtime.InteropServices ' Le informazioni generali relative a un assembly sono controllate dal seguente ' insieme di attributi. Per modificare le informazioni associate a un assembly ' occorre quindi modificare i valori di questi attributi. ' Rivedere i valori degli attributi dell'assembly. <Assembly: AssemblyTitle("UNOLibs.Net")> <Assembly: AssemblyDescription("UnoLibs libary special CodeProject Version")> <Assembly: AssemblyCompany("uno team")> <Assembly: AssemblyProduct("UNOLibs.Net")> <Assembly: AssemblyCopyright("uno team")> <Assembly: AssemblyTrademark("uno team")> <Assembly: AssemblyVersion("1.2.0.1")> <Assembly: CLSCompliant(True)> 'Se il progetto viene esposto a COM, il GUID che segue verrà utilizzato per creare l'ID della libreria dei tipi. <Assembly: Guid("027229CB-9915-4FB5-B334-9D702141B024")> ' Le informazioni sulla versione di un assembly sono costituite dai seguenti valori: ' ' Numero di versione principale ' Numero di versione secondario ' Numero build ' Revisione ' ' È possibile specificare tutti i valori oppure impostare valori predefiniti per i numeri relativi alla revisione e alla build ' utilizzando il carattere "*" come mostrato di seguito:
{ "content_hash": "78f5d4c4a22f958ed910433399949495", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 126, "avg_line_length": 41.096774193548384, "alnum_prop": 0.7762951334379906, "repo_name": "niikoo/NProj", "id": "2890d9067c95fec9cf5641d3ab71af6e918217fa", "size": "1274", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Windows/Skole/LAN_Server_Gui/UNOLibs.Net/AssemblyInfo.vb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "11" }, { "name": "ApacheConf", "bytes": "52" }, { "name": "Batchfile", "bytes": "2984" }, { "name": "C", "bytes": "88" }, { "name": "C#", "bytes": "491427" }, { "name": "C++", "bytes": "1736" }, { "name": "CSS", "bytes": "83007" }, { "name": "HTML", "bytes": "76471" }, { "name": "Inno Setup", "bytes": "3564" }, { "name": "Java", "bytes": "1500" }, { "name": "JavaScript", "bytes": "552934" }, { "name": "Objective-C", "bytes": "240" }, { "name": "PHP", "bytes": "353013" }, { "name": "PLpgSQL", "bytes": "563" }, { "name": "Perl", "bytes": "459" }, { "name": "Perl6", "bytes": "11" }, { "name": "PowerShell", "bytes": "26081" }, { "name": "Python", "bytes": "11" }, { "name": "Ruby", "bytes": "11" }, { "name": "Visual Basic", "bytes": "510807" }, { "name": "XSLT", "bytes": "21697" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <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>japan</title> <meta name="description" content="Olivier's blog about life and work. "> <meta name="author" content="Olivier Nguyen"> <meta name="copyright" content="&copy; Olivier Nguyen 2015"> <!-- External libraries --> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css"> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.5/styles/monokai_sublime.min.css"> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/lightbox2/2.7.1/css/lightbox.css"> <!-- Favicon and other icons (made with http://www.favicon-generator.org/) --> <link rel="shortcut icon" href="/blog/assets/icons/favicon.ico" type="image/x-icon"> <link rel="icon" href="/blog/assets/icons/favicon.ico" type="image/x-icon"> <link rel="apple-touch-icon" sizes="57x57" href="/blog/assets/icons/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="/blog/assets/icons/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="/blog/assets/icons/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="/blog/assets/icons/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="/blog/assets/icons/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="/blog/assets/icons/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="/blog/assets/icons/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="/blog/assets/icons/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="/blog/assets/icons/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="/blog/assets/icons/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="/blog/assets/icons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="/blog/assets/icons/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="/blog/assets/icons/favicon-16x16.png"> <link rel="manifest" href="/blog/assets/icons/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="/blog/assets/icons/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <!-- Facebook OGP cards --> <meta property="og:description" content="Olivier's blog about life and work. " /> <meta property="og:url" content="http://olinguyen.github.io" /> <meta property="og:site_name" content="Olive Hoops Through Life" /> <meta property="og:title" content="japan" /> <meta property="og:type" content="website" /> <meta property="og:image" content="http://olinguyen.github.io/blog/assets/logo.png" /> <meta property="og:image:type" content="image/png" /> <meta property="og:image:width" content="612" /> <meta property="og:image:height" content="605" /> <!-- Twitter: card tags --> <meta name="twitter:card" content="summary"> <meta name="twitter:title" content="japan"> <meta name="twitter:description" content="Olivier's blog about life and work. "> <meta name="twitter:image" content="http://olinguyen.github.io/blog/assets/logo.png"> <meta name="twitter:url" content="http://olinguyen.github.io"> <!-- Site styles --> <link rel="stylesheet" href="/blog/css/main.css"> <link rel="canonical" href="http://olinguyen.github.io/blog//category/japan/"> <link rel="alternate" type="application/rss+xml" title="Olive Hoops Through Life" href="http://olinguyen.github.io/blog//feed.xml" /> </head> <body> <header class="navigation" role="banner"> <div class="navigation-wrapper"> <a href="/blog/" class="logo"> <img src="/blog/assets/logo.png" alt="Olive Hoops Through Life"> </a> <a href="javascript:void(0)" class="navigation-menu-button" id="js-mobile-menu"> <i class="fa fa-bars"></i> </a> <nav role="navigation"> <ul id="js-navigation-menu" class="navigation-menu show"> <li class="nav-link"><a href="/blog/about/">About</a> <li class="nav-link"><a href="/blog/posts/">Posts</a> </ul> </nav> </div> </header> <div class="page-content"> <div class="wrapper"> <div class="page"> <header class="post-header"> <h1 class="post-title">Posts in "Japan"</h1> </header> <span class="page-divider"> <span class="one"></span> <span class="two"></span> </span> <article class="post-content"> <ul class="posts-list"> <li><strong><a class="post-link" href="/blog/japan/2015/09/19/hiking-in-japan.html">Hiking in Japan</a></strong><span class="post-date"> - September 19, 2015</span></li> <li><strong><a class="post-link" href="/blog/japan/2015/01/24/there-he-go.html">There He Go</a></strong><span class="post-date"> - January 24, 2015</span></li> </ul> </article> </div> </div> <br> </div> <footer class="site-footer"> <div class="wrapper"> <h3 class="footer-heading">Olive Hoops Through Life</h3> <div class="site-navigation"> <p><strong>Site Map</strong></p> <ul class="pages"> <li class="nav-link"><a href="/blog/about/">About</a> <li class="nav-link"><a href="/blog/posts/">Posts</a> </ul> </div> <div class="site-contact"> <p><strong>Contact</strong> <ul class="social-media-list"> <li> <a href="mailto:nguyenolive@gmail.com"> <i class="fa fa-envelope-o"></i> <span class="username">nguyenolive@gmail.com</span> </a> </li> <li> <a href="https://github.com/olinguyen" title="Fork me on GitHub"> <i class="fa fa-github"></i> <span class="username">oliviernguyen</span> </a> </li> <li> <a href="https://ca.linkedin.com/in/nguyenolivier" title="Connect with me on LinkedIn"> <i class="fa fa-linkedin"></i> <span class="username">Olivier Nguyen</span> </a> </li> <li> <a href="https://instagram.com/oliviernguyen" title="Follow me on Instagram"> <i class="fa fa-instagram"></i> <span class="username">oliviernguyen</span> </a> </li> </ul> </div> <div class="site-signature"> <p class="rss-subscribe text"><strong>Subscribe <a href="/blog/feed.xml">via RSS</a></strong></p> <p class="text">Olivier's blog about life and work. </p> </div> </div> </footer> <!-- Scripts --> <script src="//code.jquery.com/jquery-1.11.2.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.5/highlight.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/lightbox2/2.7.1/js/lightbox.min.js"></script> <script> $(document).ready(function() { // Syntax highlighting hljs.initHighlightingOnLoad(); // Header var menuToggle = $('#js-mobile-menu').unbind(); $('#js-navigation-menu').removeClass("show"); menuToggle.on('click', function(e) { e.preventDefault(); $('#js-navigation-menu').slideToggle(function(){ if($('#js-navigation-menu').is(':hidden')) { $('#js-navigation-menu').removeAttr('style'); } }); }); }); </script> </body> </html>
{ "content_hash": "9c5ed5e9d295732a93b81dafee817764", "timestamp": "", "source": "github", "line_count": 273, "max_line_length": 172, "avg_line_length": 29.076923076923077, "alnum_prop": 0.5991433610481229, "repo_name": "olinguyen/blog", "id": "2ef05ee01b8c5ec286302549aea73f752ee1e4b3", "size": "7938", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_site/category/japan/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "59155" }, { "name": "HTML", "bytes": "112258" }, { "name": "Ruby", "bytes": "7132" } ], "symlink_target": "" }
package org.apache.wicket.protocol.http.request; import org.apache.wicket.RequestCycle; import org.apache.wicket.request.target.resource.ResourceStreamRequestTarget; import org.apache.wicket.util.resource.WebExternalResourceStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Request target that is not a Wicket resource. For example, such a resource could denote an image * in the web application directory (not mapped to a Wicket servlet). NOTE: this target can only be * used in a servlet environment with {@link org.apache.wicket.protocol.http.WebRequestCycle}s. * * <p> * <b>NOTE:</b> this class is a wrapper around * {@link ResourceStreamRequestTarget#ResourceStreamRequestTarget(org.apache.wicket.util.resource.IResourceStream)} * , and kept for compatibility purposes. * </p> * * @author Eelco Hillenius */ public class WebExternalResourceRequestTarget extends ResourceStreamRequestTarget { /** log. */ private static final Logger log = LoggerFactory.getLogger(WebExternalResourceRequestTarget.class); /** the relative url of the external resource. */ private final String uri; /** * Construct. * * @param uri * the relative url of the external resource */ public WebExternalResourceRequestTarget(String uri) { super(new WebExternalResourceStream(uri)); this.uri = uri; } /** * Gets the url to the external resource. * * @return the url to the external resource */ public final String getUrl() { return uri; } /** * @see org.apache.wicket.IRequestTarget#detach(org.apache.wicket.RequestCycle) */ @Override public void detach(RequestCycle requestCycle) { } /** * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (obj instanceof WebExternalResourceRequestTarget) { WebExternalResourceRequestTarget that = (WebExternalResourceRequestTarget)obj; return uri.equals(that.uri); } return false; } /** * @see java.lang.Object#hashCode() */ @Override public int hashCode() { int result = "WebExternalResourceRequestTarget".hashCode(); result += uri.hashCode(); return 17 * result; } /** * @see java.lang.Object#toString() */ @Override public String toString() { return "[WebExternalResourceRequestTarget@" + hashCode() + " " + uri + "]"; } }
{ "content_hash": "08c756092e40092c146e844fadaee1e9", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 115, "avg_line_length": 24.642105263157895, "alnum_prop": 0.7236223835967536, "repo_name": "Servoy/wicket", "id": "ee039c4c1862da7e9e8897ac6278ba524641ea23", "size": "3143", "binary": false, "copies": "1", "ref": "refs/heads/wicket-1.4.x", "path": "wicket/src/main/java/org/apache/wicket/protocol/http/request/WebExternalResourceRequestTarget.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "58903" }, { "name": "HTML", "bytes": "772575" }, { "name": "Java", "bytes": "8970322" }, { "name": "JavaScript", "bytes": "203125" }, { "name": "Perl", "bytes": "2053" }, { "name": "Roff", "bytes": "95314" }, { "name": "Shell", "bytes": "13496" }, { "name": "XSLT", "bytes": "2567" } ], "symlink_target": "" }
var usingChars = "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"; var charBase = usingChars.length; /** * Convert a BASE10 Integer to BASE58 String * @param {*} num BASE10 Integer */ function encode(num){ var encoded = ''; while (num){ var remainder = num % charBase; num = Math.floor(num / charBase); encoded = usingChars[remainder].toString() + encoded; } return encoded; } /** * Convert a BASE58 String to BASE10 Integer * @param {*} str BASE58 */ function decode(str){ var decoded = 0; while (str){ var index = usingChars.indexOf(str[0]); var power = str.length - 1; decoded += index * (Math.pow(charBase, power)); str = str.substring(1); } return decoded; } module.exports.encode = encode; module.exports.decode = decode;
{ "content_hash": "5c31952700aafac080b2558a9b01630f", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 78, "avg_line_length": 23.294117647058822, "alnum_prop": 0.6717171717171717, "repo_name": "WindSekirun/SimpleUrlShortener", "id": "a1d4f8d62e11a7ee712cd36ffbe8bd8ac6b8d749", "size": "792", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "base58.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "590" }, { "name": "HTML", "bytes": "1621" }, { "name": "JavaScript", "bytes": "6266" } ], "symlink_target": "" }
@implementation CommentView //@synthesize titleLabel; @synthesize discussTableView; @synthesize m_Delegate; @synthesize bottomBack; @synthesize discussFiled; - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { // Initialization code UIView *viewHeader = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 64)]; viewHeader.backgroundColor = [UIColor clearColor]; UITableView *tableView = [[UITableView alloc] initWithFrame:DISCUSSTABLEVIEW_FRAME]; tableView.backgroundColor = [UIColor clearColor]; tableView.tableHeaderView = viewHeader; tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine; tableView.rowHeight = 50; self.discussTableView = tableView; [viewHeader release]; [self addSubview:discussTableView]; [tableView release]; //底部黑色背景 UIImageView *bottomBackView = [[UIImageView alloc] initWithFrame:BOTTOM_BACK_FRAME]; self.bottomBack = bottomBackView; self.bottomBack.userInteractionEnabled = YES; self.bottomBack.image = [UIImage imageNamed:@"table6.png"]; [self addSubview:self.bottomBack]; [bottomBackView release]; point = bottomBack.center; //输入框背景 UIImageView *textFieldBack = [[UIImageView alloc] initWithFrame:TEXTFIELD_BACK_FRAME]; textFieldBack.image = [UIImage imageNamed:@"table7.png"]; [bottomBack addSubview:textFieldBack]; [textFieldBack release]; UITextField *discussFileds = [[UITextField alloc] initWithFrame:DISCUSSFIELD_FRAME]; self.discussFiled = discussFileds; self.discussFiled.font = [UIFont fontWithName:@"Arial" size:13]; self.discussFiled.delegate = self; self.discussFiled.placeholder = @"请输入评论(200字以内)"; [bottomBack addSubview:self.discussFiled]; [discussFileds release]; UIButton *publishBtn = [[UIButton alloc] initWithFrame:PUBLISH_BUTTON_FRAME]; [publishBtn addTarget:self action:@selector(publishComment) forControlEvents:UIControlEventTouchUpInside]; [publishBtn setBackgroundImage:[UIImage imageNamed:@"button_13.png"] forState:UIControlStateNormal]; [bottomBack addSubview:publishBtn]; [publishBtn release]; } return self; } - (void)keyboardWillChangeFrame:(NSNotification *)notification { self.bottomBack.center = point; NSValue *keyboardBoundsValue = [[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey]; CGRect keyboardBounds; [keyboardBoundsValue getValue:&keyboardBounds]; CGPoint changePoint = bottomBack.center; changePoint.y -= keyboardBounds.size.height; [UIView animateWithDuration:0.3 animations:^{ self.bottomBack.center = changePoint; }]; NSLog(@"%.2f",keyboardBounds.size.height); } - (BOOL)textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; return YES; } - (void)textFieldDidBeginEditing:(UITextField *)textField { } - (void)textFieldDidEndEditing:(UITextField *)textField { [UIView animateWithDuration:0.3 animations:^{ self.bottomBack.center = point; }]; } - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string]; if ([string isEqualToString:@"&"]) { return NO; } if ([toBeString length] > 200) { textField.text = [toBeString substringToIndex:200]; UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"输入评论内容过长!" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil]; [alert show]; [alert release]; return NO; } return YES; } - (void)publishComment { [discussFiled resignFirstResponder]; if (m_Delegate && [m_Delegate respondsToSelector:@selector(submitComment:)]) { [m_Delegate submitComment:discussFiled.text]; } } - (void)dealloc { [discussTableView release]; [bottomBack release]; [discussFiled release]; [super dealloc]; } @end
{ "content_hash": "8fcb07c2fc8ecd58e46dd2a8a1024d73", "timestamp": "", "source": "github", "line_count": 120, "max_line_length": 151, "avg_line_length": 35.325, "alnum_prop": 0.6900212314225053, "repo_name": "HarrisLee/HeyXuanWu", "id": "a9fab482816d4b710581b9d6afa09a06a0a0386c", "size": "4865", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Hey!XuanWu/Hey!XuanWu/UIViews/CommentView/CommentView.m", "mode": "33261", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "825491" }, { "name": "Objective-C++", "bytes": "6011" } ], "symlink_target": "" }
1. Make Pull Requests to **DEV BRANCH** 2. Keep 1 Pull Request to a single feature 3. Explain what you did in the PR message Thanks for all the help ^_^
{ "content_hash": "029a6d234dce465e4913b8e5b0983eef", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 42, "avg_line_length": 30.8, "alnum_prop": 0.7272727272727273, "repo_name": "Wizkiller96/WizBot-Updated", "id": "41c7249a455c5ddb686405978b26588a87b027e6", "size": "177", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/Contribution Guide.md", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "780293" }, { "name": "Perl", "bytes": "2041" } ], "symlink_target": "" }
<!-- @license Copyright (c) 2015 The Polymer Project Authors. All rights reserved. This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by Google as part of the polymer project is also subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt --> <link rel="import" href="..\..\bower_components/polymer/polymer.html"> <dom-module id="addattendance-item-card"> <template> <style> :host { display: block; } .heading-att, .contain-atten{ @apply(--layout-horizontal); } .contain-atten{ padding: 1%; font-size: 105%; height: 5em; } .heading-att{ background-color: #969696; padding: 1%; } .heading-att p{ font-weight: bold; font-size: 115%; } .sno, .attname, .attencheck, .heading-att p{ width: 50%; } .attname{ text-align: center; position: relative } .attname p{ float: left; padding: 4% 0 0 38%; } .attenphoto,.attname,.attencheck{ width: 33.33%; } .container{ text-align: center; margin: 0 auto; } .attenphoto img{ max-height: 73px; } .attencheck{ padding: 2% 0; } </style> <div class="contain-atten"> <paper-input hidden value="{{studentid}}"></paper-input> <div class="attenphoto"> <img src="../../images/{{studentid}}.jpg" onerror="this.src='../../images/student_avatar.png'" /> </div> <div class="attname"><p>{{student}}</p></div> <div class="attencheck"><paper-checkbox id="{{studentid}}" on-change="changeHandler"></paper-checkbox></div> </div> </template> <script> (function() { 'use strict'; Polymer({ is: 'addattendance-item-card', changeHandler:function(event){ // alert(document.querySelector("#"+this.studentid)); var studentid = document.querySelector("#"+this.studentid); if(studentid.checked==true) { //alert('hi'); document.querySelector('addattendence-card').FnGetItemsz(this.studentid, this.student); //alert(this.studentid); } else { document.querySelector('addattendence-card').removestud(this.studentid); } } }); })(); </script> </dom-module>
{ "content_hash": "d51ba0c14533625344e6f78143e1d94f", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 117, "avg_line_length": 27.778947368421054, "alnum_prop": 0.5763546798029556, "repo_name": "rmpraba/MLZSTransport", "id": "68f522a81bb0158298ea381c844b468f79f7f1a2", "size": "2639", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/elements/addattendance-item-card/addattendance-item-card.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ActionScript", "bytes": "12703" }, { "name": "CSS", "bytes": "20726" }, { "name": "HTML", "bytes": "2499865" }, { "name": "JavaScript", "bytes": "1685966" }, { "name": "Shell", "bytes": "5106" } ], "symlink_target": "" }
<?xml version="1.0"?> <?dlps id="AnoLast"?> <?dlps page-images="none" figure-images="no"?> <?dlps transcription="other"?> <!DOCTYPE TEI.2 SYSTEM "http://text.lib.virginia.edu/dtd/tei/tei-p4/tei2.dtd" [ <!ENTITY % POSTKB "INCLUDE"> <!ENTITY % TEI.extensions.ent SYSTEM "http://text.lib.virginia.edu/dtd/tei/uva-dl-tei/uva-dl-tei.ent"> <!ENTITY % TEI.extensions.dtd SYSTEM "http://text.lib.virginia.edu/dtd/tei/uva-dl-tei/uva-dl-tei.dtd"> <!ENTITY % ISOnum SYSTEM "http://text.lib.virginia.edu/charent/iso-num.ent"> %ISOnum; <!ENTITY % ISOpub SYSTEM "http://text.lib.virginia.edu/charent/iso-pub.ent"> %ISOpub; ]> <TEI.2 id="AnoLast"> <teiHeader type="migrated" creator="Etext"> <fileDesc> <titleStmt> <title type="main">The Last of Stephen Crane.</title> <title type="sort">last of stephen crane</title> <author>Crane review: Anonymous</author> <respStmt> <resp>Creation of machine-readable version:</resp> <name>Judy Boss</name> <resp>Conversion to TEI.2-conformant markup:</resp> <name>University of Virginia Library Electronic Text Center.</name> </respStmt> </titleStmt> <extent>ca. <num type="kilobytes">9</num> kilobytes</extent> <publicationStmt> <publisher>University of Virginia Library</publisher> <pubPlace>Charlottesville, Virginia</pubPlace> <idno type="ETC">AnoLast</idno> <date value="1996">1996</date> <availability status="public"> <p n="copyright">Copyright &copy; 1996 by the Rector and Visitors of the University of Virginia</p> <p n="access">Publicly accessible</p> </availability> <idno type="uva-pid">uva-lib:475687</idno> </publicationStmt> <seriesStmt> <title>University of Virginia Library, Text collection</title> <idno type="uva-set">UVA-LIB-Text</idno> </seriesStmt> <sourceDesc> <biblFull> <titleStmt> <title type="main">The Last of Stephen Crane.</title> <title>The Literary Digest, no. 21, 1900.</title> <title type="sort">last of stephen crane</title> <author>Crane review: Anonymous</author> </titleStmt> <editionStmt> <p>1st Edition.</p> </editionStmt> <publicationStmt> <publisher>Funk &amp; Wagnalls Company</publisher> <pubPlace>New York</pubPlace> <date value="1900">1900</date> </publicationStmt> <seriesStmt> <p> <hi rend="italic">Literary Digest</hi> 21, 1 Dec. 1900: 647.</p> </seriesStmt> </biblFull> </sourceDesc> </fileDesc> <encodingDesc> <projectDesc> <p>Prepared for the University of Virginia Library Electronic Text Center.</p> </projectDesc> <editorialDecl> <p>All quotation marks retained as data.</p> <p>All unambiguous end-of-line hyphens have been removed, and the trailing part of a word has been joined to the preceding line.</p> <p id="ETC">Keywords in the header are a local Electronic Text Center scheme to aid in establishing analytical groupings.</p> </editorialDecl> <refsDecl> <p>ID elements are given for each page element and are composed of the text's unique cryptogram and the given page number, as in AusEmma1 for page one of Jane Austen's Emma.</p> </refsDecl> </encodingDesc> <profileDesc> <creation> <date value="1900">1900</date> </creation> <langUsage> <language id="eng" usage="main">English</language> </langUsage> <textClass> <keywords> <term>non-fiction; prose</term> </keywords> </textClass> </profileDesc> <revisionDesc> <change> <date value="1996-01">January 1996</date> <respStmt> <resp>corrector</resp> <name>Deirdre Johnson</name> </respStmt> <item>Added header and basic TEI markup.</item> </change> <change> <date value="2005-06">June 2005</date> <respStmt> <resp>corrector</resp> <name>John Ivor Carlson</name> </respStmt> <item>Converted sgml to xml.</item> </change> <change> <date value="2007-09">September 2007</date> <respStmt> <resp>Migration</resp> <name>Ethan Gruber, University of Virginia Library</name> </respStmt> <item>Converted XML markup from TEI Lite to uva-dl-tei (TEI P4 with local customizations).</item> </change> <change> <date value="2008-01">January 2008</date> <respStmt> <resp>Migration</resp> <name>Greg Murray, University of Virginia Library</name> </respStmt> <item>Programmatically updated TEI header markup (but not header content) for minimal compliance with current QA requirements.</item> </change> </revisionDesc> </teiHeader> <text id="d1"> <body id="d2"> <div1 type="essay" id="d3"> <pb n="647" id="AnoLast647"/> <head>THE LAST OF STEPHEN CRANE.</head> <p> THE collection of stories about the Spanish-American war upon which Mr. Crane was engaged at the time of his death, has lately appeared in book form under the title "Wounds in the Rain." <hi rend="italic">The St. James's Gazette</hi> (London, September 27) thinks that in a few of the stories he rises almost, tho not quite, to the level of his masterpiece, "The Red Badge of Courage." It says: </p><p>"The stories are shorter, there is not the same irresistible sequence of things, nor the pauseless, violent sweep of thought and deed which made 'The Red Badge' wonderful. Yet, just as in that book, there are some sentences which only Mr. Crane would, or perhaps could, have written. Take this from 'The Clan of No-Name.' Eight men fire a volley at a Spanish blockhouse: 'Then they laughed and yelled insulting language, for they knew that, as far as the Spaniards were concerned, the surprise was as much as having a diamond bracelet turn to soap.' In some other of his books, Mr. Crane wrote once of a soldier's knees 'turning to bread.' Take another instance: 'On the way he passed many things: bleeding men carried by comrades; others making their way grimly, with encrimsoned arms; then the little settlement of the hospital squad; men on the ground everywhere, many in the path; one young captain dying, with great gasps, his body pale blue and glistening, like the inside of a rabbit's skin.' </p><p>"That is a trick, or call it a habit, of Mr. Crane; a few commonplace sentences, with perhaps a word like 'encrimsoned' gleaming in them; more commonplace words, dull and short; and then the horror of some homely comparison which does its work cleanly and quickly, yet leaves the wound of a queer weapon behind it. Perhaps owing to the fact that Mr. Crane writes of what he saw, not what he imagined, there is less of this kind of work in 'Wounds in the Rain' than in the 'Red Badge of Courage.' But there is the same humor, the same power of making the behavior of his fighting soldiers subjective doings of his own, and the same picturesque language and pithy slang as Mr. Crane set down in so masterly a fashion in his first war story. Here and there he hits his reader too hard. He wishes to insist on the fact that a red-headed Spanish corpse lay near the enemy's trenches. He therefore uses the words 'red-headed' nine times in thirty-three lines. Or he wishes to point out that promotion in the army comes slowly: 'I knew the kind. First lieutenants at forty years of age, captains at fifty, majors at 102, lieutenant-colonels at 620, full colonels at 1,000, and brigadiers at 9,768,295 plus. A man had to live two billion years to gain eminent rank in the regular army at that time.' </p><p>"But of Mr. Crane's other manner, in which, on the whole, he is at his best, is not this excellent?</p> <p>Now Gates had a singular adventure on the second morning after his arrival at Atlanta to take his post as a major in the 307th. </p><p>He was in his tent, writing, when suddenly the flap was flung away and a tall young private stepped inside. </p><p>"Well, Maje," said the newcomer, genially, "how goes it?" </p><p>The major's head flashed up, but he spoke without heat. </p><p>"Come to attention and salute." </p><p>"Huh!" said the private. </p><p>"Come to attention and salute." </p><p>The private looked at him in resentful amazement, and then inquired: </p><p>"Ye ain't mad, are ye? Ain't nothin' to get huffy about, is there?" </p><p>"I&mdash;. Come to attention and salute." </p><p>"Well," drawled the private, as he stared, "seein' as ye are so darn perticular, I don't care if I do&mdash;if it'll make yer meals set on yer stomick any better." </p><p>Drawing a long breath and grinning ironically, he lazily pulled his heels together and saluted with a flourish. </p><p>"There," he said, with a return to his earlier genial manner. "How's that suit ye, Maje?" </p><p>There was a silence which to an impartial observer would have seemed pregnant with dynamite and bloody death. Then the major cleared his throat and coldly said: </p><p>"And now, what is your business?" </p><p>"Who&mdash;me?" asked the private. "Oh, I just sorter dropped in." With a deeper meaning he added: "Sorter dropped in in a friendly way, thinkin' ye was mebbe a different kind of a feller from what ye be." </p><p>The inference was clearly marked. </p><p>It was now Gates's turn to stare, and stare he unfeignedly did. </p><p>"Go back to your quarters," he said at length. </p><p>The volunteer became very angry. </p><p>"Oh, ye needn't be so up-in-th'-air, need ye? Don't know's I'm dead anxious to inflict my company on yer since I've had a good look at ye. There may be men in this here battalion what's had just as much edjewcation as you have, and I'm damned if they ain't got better <hi rend="italic">manners</hi>. Good-mornin'," he said, with dignity; and, passing out of the tent, he flung the flap back in place with an air of slamming it as if it had been a door.</p> <p>"Mr. Crane wrote little that is, in its own way, better than that. The pity is that of all kinds of work which he did we shall see nothing new again." </p> </div1> </body> </text> </TEI.2>
{ "content_hash": "adf561a77c5158c22e7e7d1adfb56324", "timestamp": "", "source": "github", "line_count": 238, "max_line_length": 133, "avg_line_length": 39.819327731092436, "alnum_prop": 0.7401076289965178, "repo_name": "JohannGillium/modern_english_ed", "id": "f195e56e98be62c10e6b360dd3ce81a1252bb61a", "size": "9477", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "XML/AnoLast.xml", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "19931" }, { "name": "HTML", "bytes": "8251" }, { "name": "JavaScript", "bytes": "1711" }, { "name": "Python", "bytes": "3438" }, { "name": "Ruby", "bytes": "75" }, { "name": "XSLT", "bytes": "6581" } ], "symlink_target": "" }
var util = require('util') , api = require('../api') , async = require('async') , archiver = require('archiver') , moment = require('moment') , log = require('winston') , stream = require('stream') , path = require('path') , Exporter = require('./exporter') , geojson = require('../transformers/geojson') , attachmentBase = require('environment').attachmentBaseDirectory; function GeoJson(options) { GeoJson.super_.call(this, options); } util.inherits(GeoJson, Exporter); module.exports = GeoJson; GeoJson.prototype.export = function(streamable) { var self = this; streamable.type('application/zip'); streamable.attachment("mage-geojson.zip"); var archive = archiver('zip'); archive.pipe(streamable); async.parallel([ function(done) { if (!self._filter.exportObservations) return done(); var observationStream = new stream.PassThrough(); archive.append(observationStream, { name:'observations.geojson' }); self.streamObservations(observationStream, archive, function(err) { observationStream.end(); done(err); }); }, function(done) { if (!self._filter.exportLocations) return done(); var locationStream = new stream.PassThrough(); archive.append(locationStream, {name: 'locations.geojson'}); self.streamLocations(locationStream, function(err) { locationStream.end(); done(err); }); } ], function(err) { if (err) { log.info(err); } archive.finalize(); }); }; GeoJson.prototype.streamObservations = function(stream, archive, done) { var self = this; self._filter.states = ['active']; new api.Observation(self._event).getAll({filter: self._filter}, function(err, observations) { if (err) return err; self.mapObservations(observations); observations.forEach(function(o) { o.attachments.forEach(function(attachment) { archive.file(path.join(attachmentBase, attachment.relativePath), {name: attachment.relativePath}); }); }); stream.write(JSON.stringify({ type: 'FeatureCollection', features: geojson.transform(observations) })); // throw in icons archive.bulk([{ cwd: new api.Icon(self._event._id).getBasePath(), src: ['*/**'], dest: 'mage-export/icons', expand: true, data: { date: new Date() } } ]); done(); }); }; GeoJson.prototype.streamLocations = function(stream, done) { log.info('writing locations...'); var self = this; var limit = 2000; var startDate = self._filter.startDate ? moment(self._filter.startDate) : null; var endDate = self._filter.endDate ? moment(self._filter.endDate) : null; var lastLocationId = null; stream.write('{"type": "FeatureCollection", "features": ['); var locations = []; async.doUntil(function(done) { self.requestLocations({startDate: startDate, endDate: endDate, lastLocationId: lastLocationId, limit: limit}, function(err, requestedLocations) { if (err) return done(err); locations = requestedLocations; if (locations.length) { if (lastLocationId) stream.write(","); // not first time through var data = JSON.stringify(locations); stream.write(data.substr(1, data.length - 2)); } else { stream.write(']}'); } log.info('Successfully wrote ' + locations.length + ' locations to GeoJSON'); var last = locations.slice(-1).pop(); if (last) { var locationTime = moment(last.properties.timestamp); lastLocationId = last._id; if (!startDate || startDate.isBefore(locationTime)) { startDate = locationTime; } } done(); }); }, function() { return locations.length === 0; }, function(err) { log.info('done writing locations'); done(err); }); };
{ "content_hash": "ca33f7ee58323bb3b2a154f9a4feb2a9", "timestamp": "", "source": "github", "line_count": 140, "max_line_length": 149, "avg_line_length": 27.52857142857143, "alnum_prop": 0.6312921639854696, "repo_name": "jclark118/mage-server", "id": "52e2866433cc714013db251f4da25e241df65047", "size": "3854", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "export/geojson.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "28390" }, { "name": "HTML", "bytes": "223891" }, { "name": "JavaScript", "bytes": "675165" }, { "name": "Shell", "bytes": "78" } ], "symlink_target": "" }
============= The simple way to use GitHub Pages as your account or project blog and website. ## About ## gh-pages-blog is built upon the existing GitHub:Pages technologies, adding responsive Bootstrap, Font Awesome, JQuery, Disqus, Google Analytics, and some custom javascript to the mix to provide a fairly complete blogging solution. For more information, visit the GitHub Page for the gh-pages-blog project. [http://thedereck.github.io/gh-pages-blog/](http://thedereck.github.io/gh-pages-blog/) ## Credit ## There are definitely a few projects that I need to give credit to: [GitHub:Pages](http://pages.github.com) by GitHub [Bootstrap](http://twitter.github.com/bootstrap/) by Twitter [jQuery](http://jquery.com/) by jQuery Foundation [Font Awesome 3.0](http://fortawesome.github.com/Font-Awesome/) by Dave Gandy Without the above projects, gh-pages-blog probably wouldn't exist. Thanks to everyone working on those projects for all of their hard work and for releasing the code so that the rest of us can focus on other aspects of our sotware. ## License ## Except where noted below and elsewhere in the code and repository, the gh-pages-blog code is &copy; Copyright 2013 by Dereck Curry and is 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](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. [Bootstrap](http://twitter.github.com/bootstrap/) - &copy; Copyright 2012, Twitter, Inc. * Bootstrap code is licensed under Apache License v2.0 - [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0). * Bootstrap documentation is licensed under CC BY 3.0 - [http://creativecommons.org/licenses/by/3.0/](http://creativecommons.org/licenses/by/3.0/). * Glyphicons Free licensed under CC BY 3.0 - [http://creativecommons.org/licenses/by/3.0/](http://creativecommons.org/licenses/by/3.0/). [jQuery](http://jquery.com/) - &copy; Copyright 2013 jQuery Foundation and other contributors * jQuery is licensed under MIT License - [https://github.com/jquery/jquery/blob/master/MIT-LICENSE.txt](https://github.com/jquery/jquery/blob/master/MIT-LICENSE.txt). [Font Awesome](http://fortawesome.github.com/Font-Awesome/) * The Font Awesome font is licensed under the SIL Open Font License - [http://scripts.sil.org/OFL](http://scripts.sil.org/OFL). * Font Awesome CSS, LESS, and SASS files are licensed under the MIT License - [http://opensource.org/licenses/mit-license.html](http://opensource.org/licenses/mit-license.html). * The Font Awesome pictograms are licensed under the CC BY 3.0 License - [http://creativecommons.org/licenses/by/3.0/](http://creativecommons.org/licenses/by/3.0/).
{ "content_hash": "6748c4422735b28903641a0ed813612b", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 305, "avg_line_length": 63.3469387755102, "alnum_prop": 0.7612757731958762, "repo_name": "prasannareddy/prasannareddy.github.io", "id": "95a59cc8e96d1e23c673c2cfc2610afa57de9c73", "size": "3122", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "171334" }, { "name": "JavaScript", "bytes": "61752" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "13bfd3fd41d3133c86fa8a3fa14347b2", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "d5635608513bbeec587215b9e791c6b60702e540", "size": "182", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Phyllanthaceae/Cleistanthus/Cleistanthus venosus/ Syn. Cleistanthus elmeri/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package com.amazonaws.services.iot.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.iot.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * AuthorizerSummary JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class AuthorizerSummaryJsonUnmarshaller implements Unmarshaller<AuthorizerSummary, JsonUnmarshallerContext> { public AuthorizerSummary unmarshall(JsonUnmarshallerContext context) throws Exception { AuthorizerSummary authorizerSummary = new AuthorizerSummary(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("authorizerName", targetDepth)) { context.nextToken(); authorizerSummary.setAuthorizerName(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("authorizerArn", targetDepth)) { context.nextToken(); authorizerSummary.setAuthorizerArn(context.getUnmarshaller(String.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return authorizerSummary; } private static AuthorizerSummaryJsonUnmarshaller instance; public static AuthorizerSummaryJsonUnmarshaller getInstance() { if (instance == null) instance = new AuthorizerSummaryJsonUnmarshaller(); return instance; } }
{ "content_hash": "d56ed91bcf1a3c78759588a1d5428f56", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 136, "avg_line_length": 36.32835820895522, "alnum_prop": 0.6433853738701726, "repo_name": "jentfoo/aws-sdk-java", "id": "6b4e991f82489e1c4849b3b4d41364f236772e6c", "size": "3014", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-iot/src/main/java/com/amazonaws/services/iot/model/transform/AuthorizerSummaryJsonUnmarshaller.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "270" }, { "name": "FreeMarker", "bytes": "173637" }, { "name": "Gherkin", "bytes": "25063" }, { "name": "Java", "bytes": "356214839" }, { "name": "Scilab", "bytes": "3924" }, { "name": "Shell", "bytes": "295" } ], "symlink_target": "" }
Category_matcher = { "salary" => [ /payroll/i ], "groceries" => [ /loblaws/i ], "restaurant" => [ /restaurant/i, /coffee/i, /pizza/i, /subway/i, /souvlaki/i, /tim horton/i, /shawarma/i, /greco/i, /thai/i, /burger/i, /diner/i ], "bar" => [ /royal oak/i, /brew pub/i, /irish pub/i ], "rent" => [ /money order purchase/i ], "cash" => [ /withdrawal/i ], "bank fees" => [ /service charge/i ], "household" => [ /ikea/i, /staples/i, /wal-mart/i, /amazon/i, /target/i ], "entertainment" => [ /cineplex/i, /humblebundle/i ], "alcohol" => [ /wine rack/i, /beer store/i ], "utilities" => [ /hydro/i ], "other bills" => [ /name-cheap/i, /github/i ], "transfer" => [ /customer transfer/i, /mb-credit card/i ] } # merge each category's list of regexes, for simpler matching Category_matcher.each do |category, matchers| Category_matcher[category] = Regexp.union matchers end def categorize (label) match = Category_matcher.find{ |category, matcher| label =~ matcher } return match ? match.first : "uncategorized" end
{ "content_hash": "2bf2fe7c98e9b9b37345b6ebbac6d7f4", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 97, "avg_line_length": 43.03846153846154, "alnum_prop": 0.580875781948168, "repo_name": "wiresnips/ghetto-mint", "id": "2a6758f9aa1f072541d5f8599dc0c17cd8de8603", "size": "1120", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "categorizer.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1017" }, { "name": "JavaScript", "bytes": "267874" }, { "name": "Ruby", "bytes": "8889" } ], "symlink_target": "" }
-- phpMyAdmin SQL Dump -- version 4.5.4.1 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Jan 19, 2017 at 02:45 PM -- Server version: 5.5.53-0ubuntu0.14.04.1 -- PHP Version: 7.0.12-1+deb.sury.org~trusty+1 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `lms` -- -- -------------------------------------------------------- -- -- Table structure for table `author` -- CREATE TABLE `author` ( `aid` smallint(6) NOT NULL COMMENT 'auto incrementing author id', `topic_id` varchar(2) NOT NULL COMMENT 'topic id foreign key', `branch_id` varchar(2) NOT NULL COMMENT 'branch id foreign key', `author_id` varchar(4) NOT NULL COMMENT 'author id based on branch id ', `author_name` varchar(30) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `bloodgroup` -- CREATE TABLE `bloodgroup` ( `blood_id` int(3) NOT NULL, `blood_name` varchar(6) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `bloodgroup` -- INSERT INTO `bloodgroup` (`blood_id`, `blood_name`) VALUES (1, 'A+ve'), (2, 'A-ve'), (5, 'AB+ve'), (6, 'AB-ve'), (3, 'B+ve'), (4, 'B-ve'), (7, 'O+ve'), (8, 'O-ve'); -- -------------------------------------------------------- -- -- Table structure for table `book` -- CREATE TABLE `book` ( `bk_id` mediumint(9) NOT NULL COMMENT 'auto incrementing bookid', `branch_id` varchar(2) NOT NULL COMMENT 'branch_id foreign key', `topic_id` varchar(2) NOT NULL COMMENT 'topic_id foreign key', `author_id` varchar(4) NOT NULL COMMENT 'author_id foreign key', `book_id` varchar(10) NOT NULL COMMENT 'book_id comprising of branch+topic+author+copy_id', `publication_id` tinyint(4) NOT NULL COMMENT 'publication_id foreign key', `copy` tinyint(2) NOT NULL COMMENT 'copy_id foreign key', `book_name` varchar(30) NOT NULL, `book_type` varchar(15) NOT NULL, `cost` varchar(10) NOT NULL, `purchase_date` varchar(15) NOT NULL COMMENT 'describes purchasing date of book' ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `bookold` -- CREATE TABLE `bookold` ( `bkold_id` mediumint(9) NOT NULL COMMENT 'auto incrementing bookoldid', `branch_id` varchar(2) NOT NULL COMMENT 'branch_id foreign key', `topic_id` varchar(2) NOT NULL COMMENT 'topic_id foreign key', `author_id` varchar(4) NOT NULL COMMENT 'author_id foreign key', `bookold_id` varchar(8) NOT NULL COMMENT 'book_id comprising of branch+topic+author+copy_id', `publication_id` tinyint(4) NOT NULL COMMENT 'publication_id foreign key', `copy_id` varchar(2) NOT NULL COMMENT 'copy_id foreign key', `bookold_name` varchar(30) NOT NULL, `cost` varchar(10) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `branch` -- CREATE TABLE `branch` ( `b_id` tinyint(4) NOT NULL COMMENT 'auto incrementing branch id', `branch_id` varchar(2) NOT NULL COMMENT 'same b_id with 0 as a prefix', `branch_name` varchar(40) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `college` -- CREATE TABLE `college` ( `college_id` int(3) NOT NULL, `college_name` varchar(100) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `copy` -- CREATE TABLE `copy` ( `c_id` tinyint(4) NOT NULL, `copy_id` varchar(2) NOT NULL, `copy_value` tinyint(4) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `co_author` -- CREATE TABLE `co_author` ( `ca_id` smallint(6) NOT NULL COMMENT 'auto incrementing co-author id', `topic_id` varchar(2) NOT NULL COMMENT 'topic id foreign key', `branch_id` varchar(2) NOT NULL COMMENT 'branch id foreign key', `co-author_id` varchar(4) NOT NULL COMMENT 'co-author id based on branch id', `co-author_name` varchar(30) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `deposit` -- CREATE TABLE `deposit` ( `deposit_id` mediumint(9) NOT NULL, `member_id` mediumint(9) NOT NULL, `date` varchar(20) NOT NULL, `amount` varchar(5) NOT NULL, `booklet` varchar(10) NOT NULL, `receipt` varchar(10) NOT NULL, `returned` tinyint(4) NOT NULL COMMENT '0=withVSM,1=returned', `return_date` varchar(15) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `fee` -- CREATE TABLE `fee` ( `id` int(11) NOT NULL, `member_id` mediumint(9) NOT NULL, `amount` mediumint(9) NOT NULL, `start_date` varchar(15) NOT NULL COMMENT 'taken by user', `end_date` varchar(15) NOT NULL COMMENT 'calculated by system', `period` tinyint(4) NOT NULL COMMENT 'in months,taken as input', `booklet` varchar(20) NOT NULL, `receipt` varchar(20) NOT NULL, `history` tinyint(4) DEFAULT NULL COMMENT '1=added in fee history on renewal' ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `fee_history` -- CREATE TABLE `fee_history` ( `id` int(11) NOT NULL, `member_id` mediumint(9) NOT NULL, `amount` mediumint(9) NOT NULL, `start_date` varchar(15) NOT NULL COMMENT 'taken by user', `end_date` varchar(15) NOT NULL COMMENT 'calculated by system', `period` tinyint(4) NOT NULL COMMENT 'in months,taken as input', `booklet` varchar(20) NOT NULL, `receipt` varchar(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `fine_record` -- CREATE TABLE `fine_record` ( `id` int(11) NOT NULL, `member_id` int(11) NOT NULL, `amt_paid` smallint(6) NOT NULL, `date` varchar(30) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `magazine` -- CREATE TABLE `magazine` ( `id` tinyint(4) NOT NULL, `magazine_id` varchar(5) NOT NULL, `magazine_name` varchar(100) NOT NULL, `publication_id` tinyint(4) NOT NULL, `author_id` varchar(4) NOT NULL, `cost` varchar(15) NOT NULL, `purchase_date` date NOT NULL, `book_type` varchar(15) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `member` -- CREATE TABLE `member` ( `member_id` smallint(6) NOT NULL, `first_name` varchar(20) NOT NULL, `middle_name` varchar(20) NOT NULL, `last_name` varchar(20) NOT NULL, `date_of_birth` date NOT NULL, `email` varchar(50) NOT NULL, `contact_1` varchar(12) NOT NULL, `contact_2` varchar(12) DEFAULT NULL, `address_building` varchar(50) NOT NULL, `address_street` varchar(50) NOT NULL, `address_city` varchar(25) NOT NULL, `address_state` int(2) NOT NULL, `address_pin` varchar(6) NOT NULL, `date_of_joining` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `type` varchar(10) NOT NULL, `college` int(3) NOT NULL, `company` varchar(50) DEFAULT NULL, `course` varchar(10) NOT NULL, `current_year` smallint(2) DEFAULT NULL, `gender` varchar(6) NOT NULL, `blood_group` int(2) DEFAULT NULL, `university` int(3) NOT NULL, `year_of_passing` varchar(16) DEFAULT NULL, `designation` varchar(30) DEFAULT NULL, `domain_of_work` varchar(30) DEFAULT NULL, `status` tinyint(1) NOT NULL, `branch` tinyint(4) NOT NULL COMMENT 'refers to b_id in branch table' ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `member_fine` -- CREATE TABLE `member_fine` ( `id` int(11) NOT NULL, `member_id` int(11) NOT NULL, `transaction_id` int(11) NOT NULL, `total_fine` smallint(6) NOT NULL, `paid_fine` smallint(6) NOT NULL, `updated_at` varchar(30) NOT NULL, `full_pay` tinyint(4) NOT NULL COMMENT '0=pending, 1=complete' ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `novel` -- CREATE TABLE `novel` ( `id` tinyint(4) NOT NULL, `novel_id` varchar(5) NOT NULL, `novel_name` varchar(100) NOT NULL, `author_id` varchar(4) NOT NULL, `cost` varchar(15) NOT NULL, `purchase_date` date NOT NULL, `publication_id` tinyint(4) NOT NULL, `book_type` varchar(15) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `publication` -- CREATE TABLE `publication` ( `p_id` tinyint(4) NOT NULL COMMENT 'foreign key in book relation', `publication_name` varchar(30) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `settings` -- CREATE TABLE `settings` ( `id` int(11) NOT NULL, `name` varchar(100) NOT NULL, `value` varchar(100) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `settings` -- INSERT INTO `settings` (`id`, `name`, `value`) VALUES (1, 'FEE', '1500'), (2, 'DEPOSIT', '205'); -- -------------------------------------------------------- -- -- Table structure for table `state` -- CREATE TABLE `state` ( `state_id` int(3) NOT NULL, `state_name` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `state` -- INSERT INTO `state` (`state_id`, `state_name`) VALUES (1, 'Andaman and Nicobar Islands'), (2, 'Andhra Pradesh'), (3, 'Arunachal Pradesh'), (4, 'Assam'), (5, 'Bihar'), (6, 'Chandigarh'), (7, 'Chhattisgarh'), (8, 'Dadra and Nagar Haveli'), (9, 'Daman and Diu'), (10, 'Delhi'), (11, 'Goa'), (12, 'Gujarat'), (13, 'Haryana'), (14, 'Himachal Pradesh'), (15, 'Jammu and Kashmir'), (16, 'Jharkhand'), (17, 'Karnataka'), (18, 'Kerala'), (19, 'Lakshadweep'), (20, 'Madhya Pradesh'), (21, 'Maharashtra'), (22, 'Manipur'), (23, 'Meghalaya'), (24, 'Mizoram'), (25, 'Nagaland'), (26, 'Odisha'), (27, 'Puducherry?'), (28, 'Punjab'), (29, 'Rajasthan'), (30, 'Sikkim'), (31, 'Tamil Nadu'), (32, 'Telangana'), (33, 'Tripura'), (34, 'Uttar Pradesh'), (35, 'Uttarakhand'), (36, 'West Bengal'); -- -------------------------------------------------------- -- -- Table structure for table `status` -- CREATE TABLE `status` ( `status_id` tinyint(1) NOT NULL, `status_name` varchar(10) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `status` -- INSERT INTO `status` (`status_id`, `status_name`) VALUES (1, 'Active'), (0, 'Inactive'); -- -------------------------------------------------------- -- -- Table structure for table `topic` -- CREATE TABLE `topic` ( `tid` smallint(6) NOT NULL COMMENT 'autoincrementing id', `topic_id` varchar(2) NOT NULL COMMENT 'topic id based on branch id', `branch_id` varchar(2) NOT NULL COMMENT 'branch id foreign key', `topic_name` varchar(30) NOT NULL COMMENT 'topic name' ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `transaction_issue` -- CREATE TABLE `transaction_issue` ( `t_id` int(10) UNSIGNED NOT NULL, `book_id` varchar(11) NOT NULL, `book_type` tinyint(3) UNSIGNED NOT NULL COMMENT '0=edu, 1=magazine,2=novel', `member_id` varchar(11) NOT NULL, `issue_date` varchar(50) NOT NULL, `return_date` varchar(50) NOT NULL, `returned_on` varchar(30) NOT NULL, `status` tinyint(4) NOT NULL DEFAULT '0' COMMENT '0=not returned | 1=returned' ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `university` -- CREATE TABLE `university` ( `university_id` int(3) NOT NULL, `university_name` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `id` int(10) UNSIGNED NOT NULL, `name` varchar(100) NOT NULL, `email` varchar(100) NOT NULL, `mobile` varchar(11) NOT NULL, `username` varchar(100) NOT NULL, `password` varchar(256) NOT NULL, `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `users` -- INSERT INTO `users` (`id`, `name`, `email`, `mobile`, `username`, `password`, `created_at`) VALUES (2, 'Nilesh Thadani', 'thadaninilesh@gmail.com', '9372111555', 'thadaninilesh', 'e0b7a311043ce8d5c24c3dee0ae23e36ad9342adf3f2d760922128cd55daefb2', '2017-01-16 16:38:17'), (3, 'VSM', 'admin@lms.com', '9323773777', 'admin', '8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918', '2017-01-19 14:37:06'); -- -- Indexes for dumped tables -- -- -- Indexes for table `author` -- ALTER TABLE `author` ADD PRIMARY KEY (`aid`), ADD UNIQUE KEY `aid` (`aid`), ADD KEY `topic_id` (`topic_id`,`branch_id`), ADD KEY `branch_id` (`branch_id`), ADD KEY `author_name` (`author_name`), ADD KEY `author_id` (`author_id`); -- -- Indexes for table `bloodgroup` -- ALTER TABLE `bloodgroup` ADD PRIMARY KEY (`blood_id`), ADD KEY `blood_name` (`blood_name`); -- -- Indexes for table `book` -- ALTER TABLE `book` ADD PRIMARY KEY (`bk_id`), ADD UNIQUE KEY `bk_id` (`bk_id`), ADD KEY `branch_id` (`branch_id`,`topic_id`,`author_id`,`publication_id`,`copy`), ADD KEY `topic_id` (`topic_id`), ADD KEY `author_id` (`author_id`), ADD KEY `publication_id` (`publication_id`), ADD KEY `copy_id` (`copy`), ADD KEY `book_id` (`book_id`); -- -- Indexes for table `bookold` -- ALTER TABLE `bookold` ADD PRIMARY KEY (`bkold_id`), ADD UNIQUE KEY `bk_id` (`bkold_id`), ADD KEY `branch_id` (`branch_id`,`topic_id`,`author_id`,`publication_id`,`copy_id`), ADD KEY `topic_id` (`topic_id`), ADD KEY `author_id` (`author_id`), ADD KEY `publication_id` (`publication_id`), ADD KEY `copy_id` (`copy_id`), ADD KEY `bookold_id` (`bookold_id`); -- -- Indexes for table `branch` -- ALTER TABLE `branch` ADD PRIMARY KEY (`b_id`), ADD UNIQUE KEY `b_id` (`b_id`), ADD KEY `branch_name` (`branch_name`), ADD KEY `branch_name_2` (`branch_name`), ADD KEY `branch_id` (`branch_id`); -- -- Indexes for table `college` -- ALTER TABLE `college` ADD PRIMARY KEY (`college_id`), ADD KEY `college_name` (`college_name`); -- -- Indexes for table `copy` -- ALTER TABLE `copy` ADD PRIMARY KEY (`copy_id`), ADD UNIQUE KEY `c_id` (`c_id`); -- -- Indexes for table `co_author` -- ALTER TABLE `co_author` ADD PRIMARY KEY (`ca_id`), ADD UNIQUE KEY `ca_id` (`ca_id`), ADD KEY `topic_id` (`topic_id`,`branch_id`), ADD KEY `branch_id` (`branch_id`), ADD KEY `co-author_name` (`co-author_name`), ADD KEY `co-author_id` (`co-author_id`); -- -- Indexes for table `deposit` -- ALTER TABLE `deposit` ADD PRIMARY KEY (`deposit_id`), ADD UNIQUE KEY `member_id` (`member_id`); -- -- Indexes for table `fee` -- ALTER TABLE `fee` ADD PRIMARY KEY (`id`); -- -- Indexes for table `fine_record` -- ALTER TABLE `fine_record` ADD PRIMARY KEY (`id`); -- -- Indexes for table `magazine` -- ALTER TABLE `magazine` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `magazineid` (`magazine_id`), ADD KEY `publicationid` (`publication_id`), ADD KEY `author_id` (`author_id`); -- -- Indexes for table `member` -- ALTER TABLE `member` ADD PRIMARY KEY (`member_id`), ADD UNIQUE KEY `member_email` (`email`), ADD KEY `member_bloodgroup` (`blood_group`,`university`,`branch`), ADD KEY `member_branch` (`branch`), ADD KEY `member_university` (`university`), ADD KEY `blood_group` (`blood_group`), ADD KEY `college` (`college`), ADD KEY `address_state` (`address_state`), ADD KEY `type_id` (`type`), ADD KEY `type` (`type`), ADD KEY `status` (`status`), ADD KEY `status_2` (`status`); -- -- Indexes for table `member_fine` -- ALTER TABLE `member_fine` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `transaction_id` (`transaction_id`); -- -- Indexes for table `novel` -- ALTER TABLE `novel` ADD PRIMARY KEY (`id`), ADD KEY `authorid` (`author_id`), ADD KEY `publication_id` (`publication_id`); -- -- Indexes for table `publication` -- ALTER TABLE `publication` ADD PRIMARY KEY (`p_id`), ADD KEY `p_id` (`p_id`); -- -- Indexes for table `settings` -- ALTER TABLE `settings` ADD PRIMARY KEY (`id`); -- -- Indexes for table `state` -- ALTER TABLE `state` ADD PRIMARY KEY (`state_id`), ADD KEY `state_name` (`state_name`), ADD KEY `state_id` (`state_id`); -- -- Indexes for table `status` -- ALTER TABLE `status` ADD PRIMARY KEY (`status_id`), ADD KEY `status_name` (`status_name`); -- -- Indexes for table `topic` -- ALTER TABLE `topic` ADD PRIMARY KEY (`tid`), ADD UNIQUE KEY `tid` (`tid`), ADD KEY `branch_id` (`branch_id`), ADD KEY `topic_id` (`topic_id`); -- -- Indexes for table `transaction_issue` -- ALTER TABLE `transaction_issue` ADD PRIMARY KEY (`t_id`); -- -- Indexes for table `university` -- ALTER TABLE `university` ADD PRIMARY KEY (`university_id`), ADD KEY `university_name` (`university_name`); -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `email` (`email`), ADD UNIQUE KEY `mobile` (`mobile`), ADD UNIQUE KEY `username` (`username`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `author` -- ALTER TABLE `author` MODIFY `aid` smallint(6) NOT NULL AUTO_INCREMENT COMMENT 'auto incrementing author id'; -- -- AUTO_INCREMENT for table `bloodgroup` -- ALTER TABLE `bloodgroup` MODIFY `blood_id` int(3) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9; -- -- AUTO_INCREMENT for table `book` -- ALTER TABLE `book` MODIFY `bk_id` mediumint(9) NOT NULL AUTO_INCREMENT COMMENT 'auto incrementing bookid'; -- -- AUTO_INCREMENT for table `bookold` -- ALTER TABLE `bookold` MODIFY `bkold_id` mediumint(9) NOT NULL AUTO_INCREMENT COMMENT 'auto incrementing bookoldid'; -- -- AUTO_INCREMENT for table `branch` -- ALTER TABLE `branch` MODIFY `b_id` tinyint(4) NOT NULL AUTO_INCREMENT COMMENT 'auto incrementing branch id'; -- -- AUTO_INCREMENT for table `college` -- ALTER TABLE `college` MODIFY `college_id` int(3) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `copy` -- ALTER TABLE `copy` MODIFY `c_id` tinyint(4) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `co_author` -- ALTER TABLE `co_author` MODIFY `ca_id` smallint(6) NOT NULL AUTO_INCREMENT COMMENT 'auto incrementing co-author id'; -- -- AUTO_INCREMENT for table `deposit` -- ALTER TABLE `deposit` MODIFY `deposit_id` mediumint(9) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `fee` -- ALTER TABLE `fee` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `fine_record` -- ALTER TABLE `fine_record` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `magazine` -- ALTER TABLE `magazine` MODIFY `id` tinyint(4) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `member` -- ALTER TABLE `member` MODIFY `member_id` smallint(6) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `member_fine` -- ALTER TABLE `member_fine` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `novel` -- ALTER TABLE `novel` MODIFY `id` tinyint(4) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `publication` -- ALTER TABLE `publication` MODIFY `p_id` tinyint(4) NOT NULL AUTO_INCREMENT COMMENT 'foreign key in book relation'; -- -- AUTO_INCREMENT for table `settings` -- ALTER TABLE `settings` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT for table `state` -- ALTER TABLE `state` MODIFY `state_id` int(3) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=37; -- -- AUTO_INCREMENT for table `topic` -- ALTER TABLE `topic` MODIFY `tid` smallint(6) NOT NULL AUTO_INCREMENT COMMENT 'autoincrementing id'; -- -- AUTO_INCREMENT for table `transaction_issue` -- ALTER TABLE `transaction_issue` MODIFY `t_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `university` -- ALTER TABLE `university` MODIFY `university_id` int(3) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- Constraints for dumped tables -- -- -- Constraints for table `author` -- ALTER TABLE `author` ADD CONSTRAINT `author_ibfk_1` FOREIGN KEY (`topic_id`) REFERENCES `topic` (`topic_id`), ADD CONSTRAINT `author_ibfk_2` FOREIGN KEY (`branch_id`) REFERENCES `branch` (`branch_id`); -- -- Constraints for table `book` -- ALTER TABLE `book` ADD CONSTRAINT `book_ibfk_1` FOREIGN KEY (`branch_id`) REFERENCES `branch` (`branch_id`), ADD CONSTRAINT `book_ibfk_2` FOREIGN KEY (`topic_id`) REFERENCES `topic` (`topic_id`), ADD CONSTRAINT `book_ibfk_3` FOREIGN KEY (`author_id`) REFERENCES `author` (`author_id`), ADD CONSTRAINT `book_ibfk_4` FOREIGN KEY (`publication_id`) REFERENCES `publication` (`p_id`); -- -- Constraints for table `bookold` -- ALTER TABLE `bookold` ADD CONSTRAINT `bookold_ibfk_1` FOREIGN KEY (`branch_id`) REFERENCES `branch` (`branch_id`), ADD CONSTRAINT `bookold_ibfk_2` FOREIGN KEY (`topic_id`) REFERENCES `topic` (`topic_id`), ADD CONSTRAINT `bookold_ibfk_3` FOREIGN KEY (`author_id`) REFERENCES `author` (`author_id`), ADD CONSTRAINT `bookold_ibfk_4` FOREIGN KEY (`publication_id`) REFERENCES `publication` (`p_id`), ADD CONSTRAINT `bookold_ibfk_5` FOREIGN KEY (`copy_id`) REFERENCES `copy` (`copy_id`); -- -- Constraints for table `co_author` -- ALTER TABLE `co_author` ADD CONSTRAINT `co@002dauthor_ibfk_1` FOREIGN KEY (`ca_id`) REFERENCES `author` (`aid`), ADD CONSTRAINT `co@002dauthor_ibfk_2` FOREIGN KEY (`topic_id`) REFERENCES `topic` (`topic_id`), ADD CONSTRAINT `co@002dauthor_ibfk_3` FOREIGN KEY (`co-author_id`) REFERENCES `author` (`author_id`), ADD CONSTRAINT `co@002dauthor_ibfk_4` FOREIGN KEY (`branch_id`) REFERENCES `branch` (`branch_id`), ADD CONSTRAINT `co@002dauthor_ibfk_5` FOREIGN KEY (`co-author_name`) REFERENCES `author` (`author_name`); -- -- Constraints for table `magazine` -- ALTER TABLE `magazine` ADD CONSTRAINT `magazine_ibfk_1` FOREIGN KEY (`publication_id`) REFERENCES `publication` (`p_id`); -- -- Constraints for table `member` -- ALTER TABLE `member` ADD CONSTRAINT `member_ibfk_1` FOREIGN KEY (`address_state`) REFERENCES `state` (`state_id`) ON UPDATE CASCADE, ADD CONSTRAINT `member_ibfk_3` FOREIGN KEY (`university`) REFERENCES `university` (`university_id`) ON UPDATE CASCADE, ADD CONSTRAINT `member_ibfk_5` FOREIGN KEY (`college`) REFERENCES `college` (`college_id`) ON UPDATE CASCADE, ADD CONSTRAINT `member_ibfk_6` FOREIGN KEY (`blood_group`) REFERENCES `bloodgroup` (`blood_id`), ADD CONSTRAINT `member_ibfk_7` FOREIGN KEY (`status`) REFERENCES `status` (`status_id`) ON UPDATE CASCADE, ADD CONSTRAINT `member_ibfk_8` FOREIGN KEY (`branch`) REFERENCES `branch` (`b_id`); -- -- Constraints for table `novel` -- ALTER TABLE `novel` ADD CONSTRAINT `novel_ibfk_1` FOREIGN KEY (`publication_id`) REFERENCES `publication` (`p_id`); -- -- Constraints for table `topic` -- ALTER TABLE `topic` ADD CONSTRAINT `topic_ibfk_1` FOREIGN KEY (`branch_id`) REFERENCES `branch` (`branch_id`); /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
{ "content_hash": "ff8bd3dbbdd9deb2c249e66b4ce17b8a", "timestamp": "", "source": "github", "line_count": 855, "max_line_length": 171, "avg_line_length": 28.139181286549707, "alnum_prop": 0.6375576707261316, "repo_name": "thadaninilesh/library-management-system", "id": "81295cecdcfd2a3509c881496dca30ce6f046028", "size": "24059", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lms.sql", "mode": "33261", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "240" }, { "name": "CSS", "bytes": "122685" }, { "name": "HTML", "bytes": "8413329" }, { "name": "JavaScript", "bytes": "771723" }, { "name": "PHP", "bytes": "2030124" } ], "symlink_target": "" }
import reversion from django.contrib.gis import admin from models import Layer, Map, MapLayer, Feature, FeatureType, GeoeventsSource class MapLayerInline(admin.TabularInline): model = MapLayer extra = 1 class MapAdmin(reversion.VersionAdmin, admin.ModelAdmin): model = Map list_display = ['__unicode__', 'description',] inlines = [MapLayerInline] save_as = True ordering = ['title'] search_fields = ['description', 'title', 'tags', ] class LayerAdmin(reversion.VersionAdmin, admin.OSMGeoAdmin): model = Layer list_display = ['name', 'type', 'url'] list_filter = ['type', 'image_format'] save_as = True search_fields = ['name', 'url', 'type', ] normal_fields = ('name', 'type', 'url', 'layer', 'attribution', 'description', 'image_format') advanced_fields = ( 'disabled', 'styles', 'refreshrate', 'transparent', 'enable_identify', 'token', 'additional_domains', 'constraints', 'extent', 'layer_parsing_function', 'info_format', 'root_field', 'fields_to_show', 'downloadableLink', 'spatial_reference', 'layer_params', 'layer_info_link' ) desc = 'The settings below are advanced. Please contact and admin if you have questions.' fieldsets = ( (None, {'fields': normal_fields}), ('Advanced Settings', {'classes': ('collapse',), 'description': desc, 'fields': advanced_fields, })) class MapLayerAdmin(reversion.VersionAdmin, admin.ModelAdmin): model = MapLayer list_display = ['__unicode__', 'map', 'layer', 'stack_order', 'opacity', 'is_base_layer'] list_filter = ['map', 'layer', 'stack_order', 'is_base_layer'] class FeatureAdmin(reversion.VersionAdmin, admin.OSMGeoAdmin): list_display = ['template', 'status', 'aoi', 'job', 'analyst', 'created_at'] list_filter = ['template', 'status', 'analyst', 'job'] fields = ('template', 'status', 'properties') readonly_fields = ('analyst', 'aoi', 'created_at', 'updated_at') class FeatureTypeAdmin(reversion.VersionAdmin, admin.ModelAdmin): list_display = ['name', 'category', 'type', 'order'] ordering = ('-category', 'order', 'name', 'id') save_as = True class GeoeventsSourceAdmin(admin.ModelAdmin): model = GeoeventsSource list_display = ['name', 'url'] #admin.site.register(Point, FeatureAdmin) #admin.site.register(Polygon, FeatureAdmin) admin.site.register(Feature, FeatureAdmin) admin.site.register(FeatureType, FeatureTypeAdmin) admin.site.register(Layer, LayerAdmin) admin.site.register(Map, MapAdmin) admin.site.register(GeoeventsSource, GeoeventsSourceAdmin)
{ "content_hash": "a16cad73aad3a5500a027d5d198c197d", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 101, "avg_line_length": 38.7536231884058, "alnum_prop": 0.6514584891548242, "repo_name": "Pkthunder/geoq", "id": "646eb007640bb9b3a84e87d6b1714a09df2cb9eb", "size": "2905", "binary": false, "copies": "4", "ref": "refs/heads/develop", "path": "geoq/maps/admin.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "71402" }, { "name": "HTML", "bytes": "203736" }, { "name": "JavaScript", "bytes": "1424580" }, { "name": "Python", "bytes": "727105" } ], "symlink_target": "" }
package org.apache.jena.tdb.store ; import java.util.Iterator ; import java.util.function.Function; import org.apache.jena.atlas.iterator.Iter ; import org.apache.jena.atlas.lib.Closeable ; import org.apache.jena.atlas.lib.Sync ; import org.apache.jena.atlas.lib.tuple.Tuple ; import org.apache.jena.atlas.lib.tuple.TupleFactory ; import org.apache.jena.graph.* ; import org.apache.jena.riot.other.GLib ; import org.apache.jena.shared.PrefixMapping ; import org.apache.jena.sparql.core.GraphView ; import org.apache.jena.sparql.core.Quad ; import org.apache.jena.tdb.TDBException ; import org.apache.jena.tdb.graph.TransactionHandlerTDB ; import org.apache.jena.tdb.store.nodetupletable.NodeTupleTable ; import org.apache.jena.util.iterator.ExtendedIterator ; import org.apache.jena.util.iterator.WrappedIterator ; /** * General operations for TDB graphs (free-standing graph, default graph and * named graphs) */ public class GraphTDB extends GraphView implements Closeable, Sync { private final TransactionHandler transactionHandler = new TransactionHandlerTDB(this) ; // Switch this to DatasetGraphTransaction private final DatasetGraphTDB dataset ; public GraphTDB(DatasetGraphTDB dataset, Node graphName) { super(dataset, graphName) ; this.dataset = dataset ; } /** get the current TDB dataset graph - changes for transactions */ public DatasetGraphTDB getDSG() { return dataset ; } /** The NodeTupleTable for this graph */ public NodeTupleTable getNodeTupleTable() { return getDSG().chooseNodeTupleTable(getGraphName()) ; } @Override protected PrefixMapping createPrefixMapping() { if ( isDefaultGraph() ) return getDSG().getPrefixes().getPrefixMapping() ; if ( isUnionGraph() ) return getDSG().getPrefixes().getPrefixMapping() ; return getDSG().getPrefixes().getPrefixMapping(getGraphName().getURI()) ; } @Override public final void sync() { dataset.sync() ; } @Override final public void close() { sync() ; // Ignore - graphs are projections of the overlying database. // "Close graph" is messy in this projection world. super.close() ; } protected static ExtendedIterator<Triple> graphBaseFindDft(DatasetGraphTDB dataset, Triple triple) { Iterator<Quad> iterQuads = dataset.find(Quad.defaultGraphIRI, triple.getSubject(), triple.getPredicate(), triple.getObject()) ; if ( iterQuads == null ) return org.apache.jena.util.iterator.NullIterator.instance() ; // Can't be duplicates - fixed graph node.. Iterator<Triple> iterTriples = new ProjectQuadsToTriples(Quad.defaultGraphIRI, iterQuads) ; return WrappedIterator.createNoRemove(iterTriples) ; } protected static ExtendedIterator<Triple> graphBaseFindNG(DatasetGraphTDB dataset, Node graphNode, Triple m) { Node gn = graphNode ; // Explicitly named union graph. if ( isUnionGraph(gn) ) gn = Node.ANY ; Iterator<Quad> iter = dataset.getQuadTable().find(gn, m.getMatchSubject(), m.getMatchPredicate(), m.getMatchObject()) ; if ( iter == null ) return org.apache.jena.util.iterator.NullIterator.instance() ; Iterator<Triple> iterTriples = new ProjectQuadsToTriples((gn == Node.ANY ? null : gn), iter) ; if ( gn == Node.ANY ) iterTriples = Iter.distinct(iterTriples) ; return WrappedIterator.createNoRemove(iterTriples) ; } @Override protected ExtendedIterator<Triple> graphUnionFind(Node s, Node p, Node o) { Node g = Quad.unionGraph ; Iterator<Quad> iterQuads = getDSG().find(g, s, p, o) ; Iterator<Triple> iter = GLib.quads2triples(iterQuads) ; // Suppress duplicates after projecting to triples. // TDB guarantees that duplicates are adjacent. // See SolverLib. iter = Iter.distinctAdjacent(iter) ; return WrappedIterator.createNoRemove(iter) ; } @Override protected final int graphBaseSize() { if ( isDefaultGraph() ) return (int)getNodeTupleTable().size() ; Node gn = getGraphName() ; boolean unionGraph = isUnionGraph(gn) ; gn = unionGraph ? Node.ANY : gn ; Iterator<Tuple<NodeId>> iter = getDSG().getQuadTable().getNodeTupleTable().findAsNodeIds(gn, null, null, null) ; if ( unionGraph ) { iter = Iter.map(iter, project4TupleTo3Tuple) ; iter = Iter.distinctAdjacent(iter) ; } return (int)Iter.count(iter) ; } private static Function<Tuple<NodeId>, Tuple<NodeId>> project4TupleTo3Tuple = item -> { if (item.len() != 4) throw new TDBException("Expected a Tuple of 4, got: " + item); return TupleFactory.tuple(item.get(1), item.get(2), item.get(3)); }; // Convert from Iterator<Quad> to Iterator<Triple> static class ProjectQuadsToTriples implements Iterator<Triple> { private final Iterator<Quad> iter ; private final Node graphNode ; /** * Project quads to triples - check the graphNode is as expected if not * null */ ProjectQuadsToTriples(Node graphNode, Iterator<Quad> iter) { this.graphNode = graphNode ; this.iter = iter ; } @Override public boolean hasNext() { return iter.hasNext() ; } @Override public Triple next() { Quad q = iter.next() ; if ( graphNode != null && !q.getGraph().equals(graphNode) ) throw new InternalError("ProjectQuadsToTriples: Quads from unexpected graph (expected=" + graphNode + ", got=" + q.getGraph() + ")") ; return q.asTriple() ; } @Override public void remove() { iter.remove() ; } } @Override public Capabilities getCapabilities() { if ( capabilities == null ) capabilities = new Capabilities() { @Override public boolean sizeAccurate() { return true ; } @Override public boolean addAllowed() { return true ; } @Override public boolean addAllowed(boolean every) { return true ; } @Override public boolean deleteAllowed() { return true ; } @Override public boolean deleteAllowed(boolean every) { return true ; } @Override public boolean canBeEmpty() { return true ; } @Override public boolean iteratorRemoveAllowed() { return false ; } /* ** */ @Override public boolean findContractSafe() { return true ; } @Override public boolean handlesLiteralTyping() { return false ; } /* ** */ } ; return super.getCapabilities() ; } @Override public TransactionHandler getTransactionHandler() { return transactionHandler ; } @Override public void clear() { dataset.deleteAny(getGraphName(), Node.ANY, Node.ANY, Node.ANY) ; getEventManager().notifyEvent(this, GraphEvents.removeAll) ; } @Override public void remove(Node s, Node p, Node o) { if ( getEventManager().listening() ) { // Have to do it the hard way so that triple events happen. super.remove(s, p, o) ; return ; } dataset.deleteAny(getGraphName(), s, p, o) ; // We know no one is listening ... // getEventManager().notifyEvent(this, GraphEvents.remove(s, p, o) ) ; } }
{ "content_hash": "abf46d46aaa742e41b4c676deef94ac4", "timestamp": "", "source": "github", "line_count": 242, "max_line_length": 135, "avg_line_length": 33.83884297520661, "alnum_prop": 0.5906704115276591, "repo_name": "CesarPantoja/jena", "id": "200c99e4f69d4178d93e8b2602de247d90885194", "size": "8994", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jena-tdb/src/main/java/org/apache/jena/tdb/store/GraphTDB.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "145" }, { "name": "AspectJ", "bytes": "3446" }, { "name": "Batchfile", "bytes": "16824" }, { "name": "C++", "bytes": "5037" }, { "name": "CSS", "bytes": "26180" }, { "name": "Elixir", "bytes": "2548" }, { "name": "HTML", "bytes": "100718" }, { "name": "Java", "bytes": "25062598" }, { "name": "JavaScript", "bytes": "918311" }, { "name": "Lex", "bytes": "82672" }, { "name": "Perl", "bytes": "37209" }, { "name": "Ruby", "bytes": "354871" }, { "name": "Shell", "bytes": "223592" }, { "name": "Smarty", "bytes": "17096" }, { "name": "Thrift", "bytes": "3201" }, { "name": "Web Ontology Language", "bytes": "518275" }, { "name": "XSLT", "bytes": "101830" } ], "symlink_target": "" }
package org.encog.mathutil.randomize;
{ "content_hash": "3416e0c353a0ed0c4d8f9e748bafc58d", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 37, "avg_line_length": 13.333333333333334, "alnum_prop": 0.8, "repo_name": "larhoy/SentimentProjectV2", "id": "85b28b66f454ec2304aaa1f82d372c02b36b8db9", "size": "908", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SentimentAnalysisV2/encog-core-3.1.0/src/main/java/org/encog/mathutil/randomize/package-info.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2782" }, { "name": "Java", "bytes": "3482181" } ], "symlink_target": "" }
define(['./module'], function(app) { 'use strict'; var communitiesRepository = function($http) { this.getOne = function(key) { return $http.get("/data/" + key + ".json"); }; this.getAll = function() { return $http.get("/data/communities.json"); }; } app.factory('communitiesRepository', ['$http', function($http) { return new communitiesRepository($http); }]); });
{ "content_hash": "eb22f04c1338adcc7754432dd08a4468", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 68, "avg_line_length": 28.0625, "alnum_prop": 0.5434298440979956, "repo_name": "lilletechhub/lilletechhub.github.io", "id": "875a71ad46c27cf885bd3cb394b9ce9da155d8e4", "size": "449", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "js/communities/communitiesRepository.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2758" }, { "name": "HTML", "bytes": "14179" }, { "name": "JavaScript", "bytes": "12108" } ], "symlink_target": "" }
""" Convert a template emacs JSON keymapping to one for each platform supported by sublime: OS X, Linux, and Windows. """ # Every "move" key binding needs a copy which does the "extend" variant with a # context that checks setting.transient_mode_on. # Every binding in the whole file needs to have a context key that checks # setting.emacs_on. import os __file__ = os.path.abspath(__file__) import json import copy def here(path): return os.path.join(os.path.dirname(__file__), path) def meta(platform): if platform == "OSX": return "super" else: return "alt" def require_setting(mapping, setting): mapping.setdefault("context", []).append( dict(key=setting, operator="equal", operand=True)) def add_arg(mapping, name, value): mapping.setdefault("args", {})[name] = value def new_map(kmap, platform, conditional): new = [] for binding in kmap: new.append(binding) binding['keys'] = [ k.replace( "meta+", meta(platform) + "+" ) for k in binding['keys'] ] if conditional: require_setting(binding, "emax_enabled") if binding.get("command") in ["move", "move_to", "emax_move_sexp"]: clone = copy.deepcopy(binding) require_setting(clone, "setting.emax_region_active") add_arg(clone, "extend", True) new.append(clone) return new def for_platform(platform): return here("Default ({0}).sublime-keymap".format(platform)) def all_maps(conditional=False): template = json.load(open(here("base-keymap.json"))) for platform in "OSX", "Linux", "Windows": cloned = copy.deepcopy(template) doubleclone = new_map(cloned, platform, conditional) doubleclone.append({ "keys": [ meta(platform) + "+ctrl+shift+'", ], "command": "toggle_emax" }) fn = for_platform(platform) tfn = fn + ".new" # atomic but not concurrent with open(tfn, "wb") as f: f.write(json.dumps(doubleclone, indent=2)) f.write("\n") os.rename(tfn, fn) if __name__ == '__main__': # Generating the keymaps from within the editor is more reliable, as that # will honor the globalness setting. all_maps()
{ "content_hash": "dbbf2e90791891c47b978996ed5bac62", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 78, "avg_line_length": 25.397849462365592, "alnum_prop": 0.5893310753598645, "repo_name": "glyph/E-Max", "id": "eda0e1fb1818f98a6a7ce69788f4a3a9761a1bf6", "size": "2432", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "emax_build_keymaps.py", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "784" }, { "name": "Python", "bytes": "40412" } ], "symlink_target": "" }
#include "tensorflow/compiler/jit/encapsulate_subgraphs_pass.h" #include <functional> #include <memory> #include <numeric> #include <string> #include <unordered_map> #include <vector> #include "tensorflow/compiler/jit/graphcycles/graphcycles.h" #include "tensorflow/compiler/jit/mark_for_compilation_pass.h" #include "tensorflow/compiler/jit/shape_inference_helpers.h" #include "tensorflow/compiler/tf2xla/const_analysis.h" #include "tensorflow/compiler/tf2xla/dump_graph.h" #include "tensorflow/compiler/xla/status_macros.h" #include "tensorflow/core/common_runtime/function.h" #include "tensorflow/core/common_runtime/optimization_registry.h" #include "tensorflow/core/common_runtime/shape_refiner.h" #include "tensorflow/core/framework/function.h" #include "tensorflow/core/framework/graph_def_util.h" #include "tensorflow/core/framework/graph_to_functiondef.h" #include "tensorflow/core/framework/node_def_builder.h" #include "tensorflow/core/framework/node_def_util.h" #include "tensorflow/core/graph/algorithm.h" #include "tensorflow/core/graph/control_flow.h" #include "tensorflow/core/graph/graph.h" #include "tensorflow/core/graph/graph_def_builder.h" #include "tensorflow/core/graph/tensor_id.h" #include "tensorflow/core/lib/gtl/flatset.h" #include "tensorflow/core/lib/gtl/map_util.h" #include "tensorflow/core/lib/hash/hash.h" #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/public/session_options.h" #include "tensorflow/core/public/version.h" #include "tensorflow/core/util/device_name_utils.h" namespace tensorflow { const char* const kXlaCompiledKernelAttr = "_XlaCompiledKernel"; const char* const kXlaNumConstantArgsAttr = "_XlaNumConstantArgs"; const char* const kXlaNumResourceArgsAttr = "_XlaNumResourceArgs"; const char* const kXlaHostTransferSequencerAttr = "_xla_host_transfer_sequencer"; namespace { bool AreAllParentsConst(const Node& n, const gtl::FlatSet<const Node*>& runtime_const_nodes) { if (n.type_string() == "GuaranteeConst" || n.type_string() == "Const") { // If the current node is itself a cast-to-const, no need // to look at the incoming edges. return true; } bool all_parents_const = true; bool atleast_one_non_control_edge = false; for (const Edge* in : n.in_edges()) { atleast_one_non_control_edge = atleast_one_non_control_edge || !in->IsControlEdge(); if (!in->IsControlEdge() && runtime_const_nodes.count(in->src()) == 0) { all_parents_const = false; break; } } return all_parents_const && atleast_one_non_control_edge; } void MarkGuaranteedConstants( const Graph& graph, const std::vector<std::pair<const Node*, Node*>>& src_arg_pairs) { gtl::FlatSet<const Node*> guaranteed_const_nodes; std::vector<const Node*> srcs; srcs.reserve(src_arg_pairs.size()); for (const auto& src_arg : src_arg_pairs) { srcs.push_back(src_arg.first); } ReverseDFSFrom(graph, srcs, /*enter=*/nullptr, /*leave=*/[&guaranteed_const_nodes](const Node* n) { // TODO(vinuraja): Doesn't work in the presence of loops. if (AreAllParentsConst(*n, guaranteed_const_nodes)) { guaranteed_const_nodes.insert(n); } }); for (auto& src_arg : src_arg_pairs) { if (guaranteed_const_nodes.count(src_arg.first) != 0) { VLOG(1) << "Guaranteed const found: " << src_arg.first->DebugString(); src_arg.second->AddAttr("_is_guaranteed_constant", true); } } } struct OutputInputTensorPairHasher { uint64 operator()(std::pair<OutputTensor, InputTensor> const& s) const { return Hash64Combine(OutputTensor::Hash()(s.first), InputTensor::Hash()(s.second)); } }; // TODO(phawkins) add a canonical copy of these operator names and refactor // everything to use it. static const char* const kArgOp = "_Arg"; static const char* const kRetValOp = "_Retval"; static const char* const kHostComputeOp = "XlaHostCompute"; static const char* const kSendFromHostOp = "_XlaSendFromHost"; static const char* const kRecvAtHostOp = "_XlaRecvAtHost"; class Encapsulator { public: Encapsulator(string group_attribute, string outside_compilation_attribute, Graph const* graph_in) : group_attribute_(std::move(group_attribute)), outside_compilation_attribute_( std::move(outside_compilation_attribute)), graph_in_(graph_in) {} // Find dependencies between subgraphs and outside_compilation clusters that // only manifest via edges between outside_compilation clusters in the outer // (non-compiled) graph. Status FindClusterDependencies(); // Find subgraphs marked with 'group_attribute', and build a new // subgraph, one for each value of 'group_attribute'. Status SplitIntoSubgraphs(); // Build a FunctionDef for each subgraph, and add it 'library'. The values of // the 'group_attribute' annotations become the function names. // If 'reuse_existing_functions' is set, use an existing function with the // same name, if any. // If 'rewrite_subgraph_fn' is set, it is applied to each subgraph before // function conversion. Status BuildFunctionDefs(const RewriteSubgraphFn& rewrite_subgraph_fn, bool reuse_existing_functions, FunctionLibraryDefinition* library); // Write a copy of the input graph to 'graph_out', where the subgraphs are // replaced with calls to the new functions. Status BuildOutputGraph(Graph* graph_out, FunctionLibraryDefinition* library); private: // A subgraph of the input, all marked with a common 'group_attribute' // value. A subgraph may contain multiple `outside_compilation' clusters. // // In the following simple example, A, B, ..., E are nodes in the original // graph. The group attributes and outside_compilation attributes g and oc are // each shown as either 0 or empty. // // A --> B --> C --> D --> E // g: g:0 g:0 g:0 g: // oc: oc: oc:0 oc: oc: // // The example is rewritten to two graphs; one on the host and one to be // compiled. The host graph is as follows. RAH is a RecvAtHost node receiving // input from the compiled cluster, and SFH is a SendFromHost node sending // input back to the compiled cluster. Dotted edges are control edges. A // 'sequencing' node S is inserted, and both RAH and SFH are connected via S // to E (and in general all nodes that depend on nodes in the compiled // cluster) to ensure that they are not pruned. // // A --> Call --> E // ^ // . // ........> S // .... ^ // .. . // RAH --> C --> SFH // // The compiled cluster is as follows. HC is a HostCompute node which is the // source of a channel to the RAH node above and the destination of a channel // from the SFH node above. // // Arg --> B --> HC --> D --> Retval // // The channels HC/RAH and SFH/HC each transmit multiple tensors, so there is // at most one RAH and SFH in each outside_compilation cluster. This design is // preferred over adding separate Arg/Retval nodes for each transmitted value // because it allows optimizations to the host code that would like to limit // communication between host and device and, e.g., raise only one interrupt // per channel rather than one per transmitted value. // // The shapes of the outputs from the HC node in general cannot be determined // until the shapes of its inputs are known at compile time, since e.g., // above, the shape of C's outputs aren't known until the shape of its inputs // are known. If the shapes of the HC's outputs can be determined during the // rewrite, they are stored in the node's 'shapes' attr. Otherwise a minimal // graph is stored in the shape_inference_graph attr. This graph can be used // when compiling the HC Op to determined the shape of the SFH inputs given // the shapes of any ancestor RAH outputs. If it can be determined that the // shape of the SFH inputs will not be inferrable even once the shapes of the // RAH outputs are known, an error is returned by the rewriter. // // Once edges between compiled and outside_compilation clusters have been // replaced by send/recv ops, some dependencies may no longer be apparent. // A clustering pass finds all the dependencies between HC nodes that are only // present as a result of edges between nodes in outside_compilation clusters. // Suppose there is a path from outside_compilation cluster C in subgraph S // to outside_compilation cluster D in subgraph T. If S != T then a control // edge is added from the call node for S to the call node for T, which // ensures that C will execute before D because S executes before T. If S==T // then a control dependency is added between the HC nodes for C and D in S, // and the HC node for C is added to an 'ancestors' attr in the HC node for D // so that during compilation of the HC node for D, an XLA control dependency // can be added to ensure C's SendToHost executes before D's RecvFromHost. class Subgraph { public: // Creates a graph to build the subgraph in, if it doesn't already exist, // using the same op registry and versions as graph_in. Node* MakeNodeImage(const Graph* graph_in, Node* node); // Returns the graph the subgraph is being built in. Graph* GetGraph() const; // Builds a FunctionDef, and adds it to 'library'. The value of the // 'group_attribute' annotations becomes the function name. If // 'reuse_existing_functions' is set, use an existing function with the same // name, if any. If 'rewrite_subgraph_fn' is set, it is applied to the // subgraph before function conversion. Status BuildFunctionDef(const string& name_in, const RewriteSubgraphFn& rewrite_subgraph_fn, bool reuse_existing_functions, FunctionLibraryDefinition* library); // Adds the function call node to graph_out. Status AddFunctionCallNode( const std::unordered_map<const Node*, Node*>& node_images, Graph* graph_out); // Adds _RecvAtHost and _SendFromHost nodes, where needed, to graph_out. Status AddOutsideCompilationHostIONodes( const string& group_attribute, const string& subgraph_name, const string& outside_compilation_attribute, const std::unordered_map<const Node*, Node*>& node_images, Graph* graph_out); // Returns the names of all the outside_compilation subgraphs in this // Subgraph. void GetOutsideCompilationSubgraphNames(std::vector<string>* names) const; // Returns the Node that the inputs and outputs of the function should be // wired up to. Node* GetCallNode() const; // Returns the index of the arg that the dst of edge should connect to. int GetArgIndexForEdge(const Edge* edge) const; // Returns the index of the result that the src of edge should connect to. int GetResultIndexForEdge(const Edge* edge) const; // Returns the RecvAtHost node for an outside_compilation subgraph. Node* GetRecvAtHostNode( const string& outside_compilation_subgraph_name) const; // Returns the output slot for the RecvAtHost node that corresponds to the // source of edge in an outside_compilation subgraph. int GetRecvAtHostSlot(const string& outside_compilation_subgraph_name, const Edge* edge) const; // Returns the SendFromHost node for an outside_compilation subgraph. Node* GetSendFromHostNode( const string& outside_compilation_subgraph_name) const; // Returns the input slot for the SendFromHost node that corresponds to the // destination of edge in an outside_compilation subgraph. int GetSendFromHostSlot(const string& outside_compilation_subgraph_name, const Edge* edge) const; // Creates an _Arg node for the src node of edge, and add its index to // args_by_src_, if none exists yet. Also adds its index to args_by_dst_, // and adds the edge within the subgraph from the _Arg node to the image of // the dst node. Status RecordArg(const Edge* edge, const std::unordered_map<const Node*, Node*>& node_images, std::vector<std::pair<const Node*, Node*>>* src_arg_pairs); // Creates a _Retval node for the src node of edge, and add it to results_, // if none exists yet. If a new _Retval node is created, also adds the edge // within the subgraph from the src to the _Retval node. Status RecordResult( const Edge* edge, const std::unordered_map<const Node*, Node*>& node_images); // Creates an outside_compilation subgraph for outside_compilation_id if // none exists yet. Creates an entry for the src node of edge in the list of // inputs for the outside_compilation subgraph, if none exists yet. void RecordOutsideCompilationInputOrControl( const string& outside_compilation_id, const Edge* edge); // Creates an outside_compilation subgraph for outside_compilation_id if // none exists yet. Creates an entry for the src node of edge in the list of // outputs by src for the outside_compilation subgraph, if none exists // yet. Creates an entry for the dst node of edge in the list of outputs by // dst for the outside_compilation subgraph. void RecordOutsideCompilationOutputOrControl( const string& outside_compilation_id, const Edge* edge); // Records the fact that there is a path from a node in outside_compilation // cluster ancestor to node in cluster successor that does not go through // the subgraph. void RecordOutsideCompilationDependency(const string& successor, const string& ancestor); // Returns the mapping from outside_compilation cluster C to the set of // outside_compilation clusters that have a path to C entirely outside // compiled subgraphs. const std::unordered_map<string, std::unordered_set<string>> OutsideCompilationAncestorMap() const; // Adds the HostCompute nodes for each outside_compilation subgraph. Status AddHostComputes( const string& subgraph_name, const std::unordered_map<const Node*, Node*>& node_images); // Creates the sequencer node if it doesn't exist, adding it to graph_out. Status MakeSequencingNode(const string& subgraph_name, Graph* graph_out); // If there is a sequencer node, adds a control edge from the sequencer to // the call node. void ConnectSequencerToCallNode(Graph* graph_out); Status AddShapeInferenceInfo( const string& subgraph_name, const string& outside_compilation_subgraph_name, const std::vector<TensorShapeProto>& shapes, Graph* inference_graph, FunctionLibraryDefinition* library); Status ReplaceFunctionDef(FunctionLibraryDefinition* library); private: struct OutsideCompilationSubgraph { // Map from source (producer node/slot) tensors in the original graph to // input index (slot number in the HostCompute/RecvAtHost nodes that will // be created) for the outside_compilation subgraph. std::unordered_map<OutputTensor, int, OutputTensor::Hash> inputs; // Set of nodes in the original graph that are the source of control edges // that cross from the containing compiled subgraph into the // outside_compilation subgraph. These are recorded by // RecordOutsideCompilationInputOrControl while walking all the subgraph // edges, and lifted control edges within the subgraph are added by // AddSendsToOutsideCompilation once the _HostCompute node has been // created. The matching control edge from _RecvAtHost to the // destination is added by CopyEdgeToOutputGraph. std::unordered_set<const Node*> control_inputs; // Maps from source (producer node/slot) and destination (consumer // node/slot) tensors in the original graph to output index (slot number // in the SendFromHost/HostCompute nodes that will be created) for the // outside_compilation subgraph. struct ArgNumAndType { int index; DataType dtype; ArgNumAndType(int i, DataType t) : index(i), dtype(t) {} }; std::unordered_map<OutputTensor, ArgNumAndType, OutputTensor::Hash> outputs_by_src; std::unordered_map<InputTensor, int, InputTensor::Hash> outputs_by_dst; // Set of nodes in the original graph that are the destination of control // edges that cross from the outside_compilation subgraph into the // containing compiled subgraph. These are recorded by // RecordOutsideCompilationOutputOrControl while walking all the subgraph // edges, and lifted control edges within the subgraph are added by // AddRecvsFromToOutsideCompilation once the _HostCompute node has been // created. The matching control edge from the source to _SendFromHost to // the destination is added by CopyEdgeToOutputGraph. std::unordered_set<const Node*> control_outputs; // Name of the _HostCompute node in the subgraph. string host_compute_name; // _RecvAtHost node in the output graph. Not owned. Node* recv_at_host = nullptr; // _SendFromHost node in the output graph. Not owned. Node* send_from_host = nullptr; }; // Creates an outside_compilation subgraph for outside_compilation_id if // none exists yet. Returns the (possible newly created) subgraph for // outside_compilation_id. OutsideCompilationSubgraph* LookupOrCreateOutsideCompilationSubgraph( const string& outside_compilation_id); // Builds a placeholder node used to provide the key input to a RecvAtHost // or SendFromHost node. This placeholder node will be removed by a later // pass. Status AddHostComputeKeyPlaceholder(OutsideCompilationSubgraph* oc_subgraph, Graph* graph_out); // Get the set of outside_compilation clusters and the dependency edges // between them. void GetActiveClusterDependencyGraph( std::unordered_set<string>* clusters, std::unordered_set<string>* has_successor, std::unordered_map<string, std::unordered_set<string>>* ancestors_map); // Builds a _RecvAtHost node producing all the inputs of an // outside_compilation subgraph and stores it in oc_subgraph.recv_at_host. Status AddRecvAtHostNode(const string& group_attribute, const string& subgraph_name, const string& outside_compilation_attribute, const string& oc_subgraph_name, OutsideCompilationSubgraph* oc_subgraph, Graph* graph_out); // Builds a _SendFromHost node consuming all the outputs of an // outside_compilation subgraph and stores it in oc_subgraph.send_from_host. Status AddSendFromHostNode( const std::unordered_map<const Node*, Node*>& node_images, const string& group_attribute, const string& subgraph_name, const string& outside_compilation_attribute, const string& oc_subgraph_name, OutsideCompilationSubgraph* oc_subgraph, Graph* graph_out); // The subgraph extracted from the input graph, suitable for being turned // into a FunctionDef. Inputs are fed by _Arg nodes, and outputs are // returned by _Retval nodes. std::unique_ptr<Graph> graph_; // Which device are these nodes on? Used to assign a device to the call // node. string device_; // NodeDef for the function call node. NodeDef call_node_def_; // Name that is used for the call node. This may not be // call_node_def_.name() if the client supplies a rewrite lambda. string function_def_name_; // Placeholder node simulating the host compute key in the output graph. // Not owned. Node* host_compute_key_placeholder_ = nullptr; // Function call node in the output graph. Not owned. Node* call_node_; // Maps from source (producer node/slot) and destination // (consumer node/slot) tensors in the input graph to _Arg numbers in // the subgraph. The source map is one-to-one, whereas the dest map may be // many-to-one. std::unordered_map<OutputTensor, int, OutputTensor::Hash> args_by_src_; std::unordered_map<InputTensor, int, InputTensor::Hash> args_by_dst_; // The arguments to the subgraph, in order. std::vector<Node*> args_; // Map from source tensor in the input graph to result #. std::unordered_map<OutputTensor, int, OutputTensor::Hash> results_; // The outside_compilation clusters in this subgraph. std::unordered_map<string, OutsideCompilationSubgraph> outside_compilation_subgraphs_; // For each outside_compilation cluster C, the outside_compilation clusters // that have a path to C outside the compiled graph. std::unordered_map<string, std::unordered_set<string>> outside_compilation_ancestors_; // For each outside_compilation cluster C, the outside_compilation clusters // that have a path from C outside the compiled graph. std::unordered_map<string, std::unordered_set<string>> outside_compilation_successors_; // NoOp node in the output graph that is sequenced after the call node and // used to prevent host-side outside_compilation sends and recvs from being // pruned. Node* sequencer_ = nullptr; }; // Returns the key attribute and outside_compilation attribute associated // with a node in attr, and outside_compilation_attr, respectively. Sets // either result to the empty string if the respective attribute is not // found. Returns error status if there is an outside_compilation attribute // and no key attribute, Status GetFunctionNameAttr(Node const* node, string* attr, string* outside_compilation_attr) const; // Copies edges local to a subgraph. Adds _Arg and _Retval nodes to // subgraphs for data edges that cross subgraph boundaries. Status CopySubgraphEdges( const std::unordered_map<const Node*, Node*>& node_images, std::vector<std::pair<const Node*, Node*>>* src_arg_pairs); // Copies all marked nodes to a subgraph. Does nothing for unmarked nodes, // or nodes marked outside_compilation. Status CopySubgraphNodes(std::unordered_map<const Node*, Node*>* node_images); // Copies all nodes that aren't in a compiled subgraph to the output graph. Status CopyNodesToOutputGraph( Graph* graph_out, std::unordered_map<const Node*, Node*>* node_images); // Adds function call nodes for each compiled subgraph. Status AddFunctionCallNodes( const std::unordered_map<const Node*, Node*>& node_images, Graph* graph_out); // Adds _RecvAtHost and _SendFromHost nodes, where needed, for all // outside_compilation subgraphs. Status AddOutsideCompilationHostIONodes( const std::unordered_map<const Node*, Node*>& node_images, Graph* graph_out); // Finds the image of an edge source in the output graph. If the edge crosses // a subgraph boundary it is the output of a call node, otherwise it is a node // in the output graph. Status FindOutputImageOfEdgeSrc( const string& src_func_id, const string& src_outside_compilation_id, const string& dst_func_id, const string& dst_outside_compilation_id, const std::unordered_map<const Node*, Node*>& node_images, const Node* original_src_node, Node** src_image); // Finds an edge source slot in the output graph. If the edge crosses a // subgraph boundary it is a slot on the output of a call node or a // _RecvAtHost node, otherwise it is a slot on a node in the output graph. int FindOutputSlotOfEdgeSrc(const string& src_func_id, const string& src_outside_compilation_id, const string& dst_func_id, const string& dst_outside_compilation_id, const Edge* edge); // Finds the image of an edge destination in the output graph. If the edge // crosses a subgraph boundary it is the input of a call node or a // _SendFromHost node, otherwise it is a node in the output graph. Status FindOutputImageOfEdgeDst( const string& src_func_id, const string& src_outside_compilation_id, const string& dst_func_id, const string& dst_outside_compilation_id, const std::unordered_map<const Node*, Node*>& node_images, const Node* original_dst_node, Node** dst_image); // Finds an edge destination slot in the output graph. If the edge crosses a // subgraph boundary it is a slot on the input of a call node or a // _SendFromHost node, otherwise it is a slot on a node in the output graph. int FindOutputSlotOfEdgeDst(const string& src_func_id, const string& src_outside_compilation_id, const string& dst_func_id, const string& dst_outside_compilation_id, const Edge* edge); // Copies a single edge to the output graph. The edge is either entirely // within the output graph, or crosses into or out of a compiled subgraph. Status CopyEdgeToOutputGraph( const Edge* edge, const string& src_func_id, const string& src_outside_compilation_id, const string& dst_func_id, const string& dst_outside_compilation_id, const std::unordered_map<const Node*, Node*>& node_images, Graph* graph_out, std::unordered_set<std::pair<OutputTensor, InputTensor>, OutputInputTensorPairHasher>* edges_added); // Adds control dependencies between subgraph call nodes that have // dependencies via outside_compilation edges. Status AddCallNodeDependencies(Graph* graph_out); // Adds all edges to the output graph. Status AddEdgesToOutputGraph( const std::unordered_map<const Node*, Node*>& node_images, Graph* graph_out); // Constructs a minimal shape inference graph that can be used to determine // the shape of send_node at the time that the subgraph is compiled. // recv_at_host_nodes contains the names of all the recv_at_host nodes that // send_node might depend on. These recv_at_host nodes have shapes that are // not known during the rewrite pass, but will be known at compile time. // // If the shapes of all the inputs to send_node can be determined during the // rewrite pass, on exit graphdef_out is empty and the shapes are returned in // static_shape_out. Otherwise graphdef_out contains a graph that can be used // for shape inference at compile time, where all the source nodes of the // graph are either constants with known shapes, or nodes named in // recv_at_host_nodes. // // A non-OK status is returned if neither of the above conditions can be // satisfied, e.g., because send_node depends on a node that doesn't have a // registered shape inference function. Status DoStaticShapeInferenceForOutsideCompilationSend( const Graph& graph_in, const BackEdgeHelper& back_edge_helper, const ShapeRefiner& shape_refiner, const std::unordered_set<string>& recv_at_host_nodes, Node* send_node, FunctionLibraryDefinition* library, std::vector<TensorShapeProto>* static_shape_out, std::unique_ptr<Graph>* graph_out); // Makes a copy of graph containing only nodes that are ancestors of at least // one node in send_from_host_nodes and store it in pruned_graph. On exit // nodes_images contains a mapping from nodes in graph to nodes in // pruned_graph. All functions in the copied graph are inlined. Status MakePrunedGraphCopyAndInline( const Graph& graph, const std::vector<Node*>& sink_nodes, std::unique_ptr<Graph>* pruned_graph, std::unordered_map<const Node*, Node*>* node_images, FunctionLibraryDefinition* library); // Makes a copy of graph containing only nodes that are ancestors of a // send_from_host node in an outside_compilation subgraph, and store it in // pruned_graph. Also perform shape inference on the pruned graph, using // shape_refiner. On exit node_images contains a mapping from nodes in graph // to nodes in pruned_graph. Status MakeGraphForOutsideCompilationSends( const Graph& graph, std::unique_ptr<Graph>* pruned_graph, BackEdgeHelper* back_edge_helper, ShapeRefiner* shape_refiner, std::unordered_map<const Node*, Node*>* node_images, FunctionLibraryDefinition* library); // Performs static shape inference, as far as possible, for the send_from_host // nodes in each outside_compilation subgraph. Where it is not possible to // determine the shape statically, stores a serialized GraphDef in the // HostCompute 'shape_inference_graph' attr, to be used at compile time for // final inference. If the shapes are known statically they are stored in the // HostCompute 'shapes' attr. Status GetShapeInfoForOutsideCompilationSends( Graph* graph_out, FunctionLibraryDefinition* library); const string group_attribute_; const string outside_compilation_attribute_; const Graph* graph_in_; std::unordered_map<string, Subgraph> subgraphs_; // For each subgraph S the subgraphs S' such that there is a path in some // outside_compilation cluster C in S to some outside_compilation cluster C' // in S', that goes only through the uncompiled graph. std::unordered_map<string, std::unordered_set<string>> subgraph_ancestors_; TF_DISALLOW_COPY_AND_ASSIGN(Encapsulator); }; namespace { // Return in 'sorted' a topological sort of clusters according to the // dependencies encoded in ancestors. clusters is the list of all clusters // including clusters that are not present in the ancestors map. has_successors // is the set of clusters that are ancestors of some other cluster. void TopologicalClusterSort( const std::unordered_set<string>& clusters, const std::unordered_set<string>& has_successors, const std::unordered_map<string, std::unordered_set<string>>& ancestors, std::vector<string>* sorted) { // The nodes are placed in 'sorted' in topological order. sorted->clear(); // We don't use the standard DFS because we are not operating on Node* // objects. struct Work { string cluster; bool leave; }; std::set<string> visited; std::vector<Work> stack; // Seed the processing list with clusters that have no successors. for (const auto& cluster : clusters) { if (has_successors.find(cluster) == has_successors.end()) { stack.push_back({cluster, false}); } } while (!stack.empty()) { const Work item = stack.back(); stack.pop_back(); if (item.leave) { sorted->push_back(item.cluster); continue; } if (visited.find(item.cluster) != visited.end()) continue; visited.insert(item.cluster); stack.push_back({item.cluster, true}); const auto& iter = ancestors.find(item.cluster); if (iter != ancestors.end()) { for (const auto& ancestor : iter->second) { stack.push_back({ancestor, false}); } } } CHECK(sorted->size() == clusters.size()); } } // namespace Node* Encapsulator::Subgraph::GetCallNode() const { return call_node_; } int Encapsulator::Subgraph::GetArgIndexForEdge(const Edge* edge) const { return args_by_dst_.at(InputTensor(edge->dst(), edge->dst_input())); } int Encapsulator::Subgraph::GetResultIndexForEdge(const Edge* edge) const { return results_.at(OutputTensor(edge->src(), edge->src_output())); } Node* Encapsulator::Subgraph::GetRecvAtHostNode( const string& outside_compilation_subgraph_name) const { return outside_compilation_subgraphs_.at(outside_compilation_subgraph_name) .recv_at_host; } int Encapsulator::Subgraph::GetRecvAtHostSlot( const string& outside_compilation_subgraph_name, const Edge* edge) const { return outside_compilation_subgraphs_.at(outside_compilation_subgraph_name) .inputs.at(OutputTensor(edge->src(), edge->src_output())); } Node* Encapsulator::Subgraph::GetSendFromHostNode( const string& outside_compilation_subgraph_name) const { return outside_compilation_subgraphs_.at(outside_compilation_subgraph_name) .send_from_host; } int Encapsulator::Subgraph::GetSendFromHostSlot( const string& outside_compilation_subgraph_name, const Edge* edge) const { return outside_compilation_subgraphs_.at(outside_compilation_subgraph_name) .outputs_by_dst.at(InputTensor(edge->dst(), edge->dst_input())); } Node* Encapsulator::Subgraph::MakeNodeImage(const Graph* graph_in, Node* node) { if (!graph_) { graph_.reset(new Graph(graph_in->op_registry())); graph_->set_versions(graph_in->versions()); } if (device_.empty()) { device_ = node->assigned_device_name().empty() ? node->requested_device() : node->assigned_device_name(); } return graph_->CopyNode(node); } Graph* Encapsulator::Subgraph::GetGraph() const { return graph_.get(); } Status Encapsulator::Subgraph::RecordArg( const Edge* edge, const std::unordered_map<const Node*, Node*>& node_images, std::vector<std::pair<const Node*, Node*>>* src_arg_pairs) { Node* src_node = edge->src(); int src_slot = edge->src_output(); std::unordered_map<OutputTensor, int, OutputTensor::Hash>::iterator iter; bool inserted; std::tie(iter, inserted) = args_by_src_.emplace( OutputTensor(src_node, src_slot), args_by_src_.size()); int arg_index = iter->second; if (inserted) { NodeDef arg_def; NodeDefBuilder builder( strings::StrCat(src_node->name(), "_", src_slot, "_arg"), kArgOp); DataType dtype = edge->dst()->input_type(edge->dst_input()); builder.Attr("T", dtype); builder.Attr("index", arg_index); Status s = builder.Finalize(&arg_def); if (!s.ok()) return s; Node* arg = graph_->AddNode(arg_def, &s); if (!s.ok()) return s; src_arg_pairs->push_back({src_node, arg}); args_.push_back(arg); } Node* dst_node = edge->dst(); Node* dst_image = node_images.at(dst_node); int dst_slot = edge->dst_input(); args_by_dst_[InputTensor(dst_node, dst_slot)] = arg_index; graph_->AddEdge(args_[arg_index], 0, dst_image, dst_slot); return Status::OK(); } Status Encapsulator::Subgraph::RecordResult( const Edge* edge, const std::unordered_map<const Node*, Node*>& node_images) { Node* src_node = edge->src(); Node* src_image = node_images.at(src_node); int src_slot = edge->src_output(); std::unordered_map<OutputTensor, int, OutputTensor::Hash>::iterator iter; bool inserted; std::tie(iter, inserted) = results_.emplace(OutputTensor(src_node, src_slot), results_.size()); int ret_index = iter->second; if (inserted) { NodeDef ret_def; NodeDefBuilder builder( strings::StrCat(src_node->name(), "_", src_slot, "_retval"), kRetValOp); DataType dtype = src_node->output_type(src_slot); builder.Attr("T", dtype); builder.Attr("index", ret_index); builder.Input(src_image->name(), src_slot, dtype); Status s = builder.Finalize(&ret_def); if (!s.ok()) return s; Node* ret = graph_->AddNode(ret_def, &s); if (!s.ok()) return s; graph_->AddEdge(src_image, src_slot, ret, 0); } return Status::OK(); } Encapsulator::Subgraph::OutsideCompilationSubgraph* Encapsulator::Subgraph::LookupOrCreateOutsideCompilationSubgraph( const string& outside_compilation_id) { auto iter = outside_compilation_subgraphs_ .emplace(outside_compilation_id, OutsideCompilationSubgraph()) .first; OutsideCompilationSubgraph* outside_subgraph = &iter->second; return outside_subgraph; } void Encapsulator::Subgraph::RecordOutsideCompilationInputOrControl( const string& outside_compilation_id, const Edge* edge) { OutsideCompilationSubgraph* outside_subgraph = LookupOrCreateOutsideCompilationSubgraph(outside_compilation_id); if (edge->IsControlEdge()) { outside_subgraph->control_inputs.insert(edge->src()); } else { int input_index = outside_subgraph->inputs.size(); outside_subgraph->inputs.emplace( OutputTensor(edge->src(), edge->src_output()), input_index); } } void Encapsulator::Subgraph::RecordOutsideCompilationOutputOrControl( const string& outside_compilation_id, const Edge* edge) { OutsideCompilationSubgraph* outside_subgraph = LookupOrCreateOutsideCompilationSubgraph(outside_compilation_id); if (edge->IsControlEdge()) { outside_subgraph->control_outputs.insert(edge->dst()); } else { DataType dtype = edge->dst()->input_type(edge->dst_input()); auto output_iter = outside_subgraph->outputs_by_src .emplace(OutputTensor(edge->src(), edge->src_output()), OutsideCompilationSubgraph::ArgNumAndType( outside_subgraph->outputs_by_src.size(), dtype)) .first; const int output_index = output_iter->second.index; outside_subgraph ->outputs_by_dst[InputTensor(edge->dst(), edge->dst_input())] = output_index; } } void Encapsulator::Subgraph::RecordOutsideCompilationDependency( const string& successor, const string& ancestor) { outside_compilation_ancestors_[successor].insert(ancestor); outside_compilation_successors_[ancestor].insert(successor); } const std::unordered_map<string, std::unordered_set<string>> Encapsulator::Subgraph::OutsideCompilationAncestorMap() const { return outside_compilation_ancestors_; } void Encapsulator::Subgraph::GetActiveClusterDependencyGraph( std::unordered_set<string>* clusters, std::unordered_set<string>* has_successor, std::unordered_map<string, std::unordered_set<string>>* ancestors_map) { // During initial clustering the ancestor and successor datastructures may // have been built including oc_cluster names that never turned into subgraphs // because they had no edges into or out of the compiled cluster. Remove them // before proceeding to simplify the logic. Get the set of clusters that was // actually added, then remove references to the others. for (const auto& oc_subgraph : outside_compilation_subgraphs_) { clusters->insert(oc_subgraph.first); } for (const auto& cluster : outside_compilation_successors_) { if (clusters->find(cluster.first) != clusters->end()) { for (const auto& successor : cluster.second) { if (clusters->find(successor) != clusters->end()) { has_successor->insert(cluster.first); break; } } } } for (const auto& cluster : outside_compilation_ancestors_) { if (clusters->find(cluster.first) != clusters->end()) { std::unordered_set<string>& ancestors = (*ancestors_map)[cluster.first]; for (const auto& ancestor : cluster.second) { if (clusters->find(ancestor) != clusters->end()) { ancestors.insert(ancestor); } } } } } Status Encapsulator::Subgraph::AddHostComputes( const string& subgraph_name, const std::unordered_map<const Node*, Node*>& node_images) { // Get the set of outside_compilation clusters and the dependency edges // between them. std::unordered_set<string> clusters; std::unordered_set<string> has_successor; std::unordered_map<string, std::unordered_set<string>> ancestors_map; GetActiveClusterDependencyGraph(&clusters, &has_successor, &ancestors_map); // Topologically sort the outside_compilation clusters according to their // dependency relation. std::vector<string> sorted_clusters; TopologicalClusterSort(clusters, has_successor, ancestors_map, &sorted_clusters); // The host compute nodes added for each outside_compilation_cluster; std::unordered_map<string, Node*> host_compute_node; for (const string& oc_subgraph_name : sorted_clusters) { OutsideCompilationSubgraph& oc_subgraph = outside_compilation_subgraphs_[oc_subgraph_name]; if (!oc_subgraph.inputs.empty() || !oc_subgraph.control_inputs.empty() || !oc_subgraph.outputs_by_src.empty() || !oc_subgraph.control_outputs.empty()) { // Build a _HostCompute node. std::vector<NodeDefBuilder::NodeOut> inputs(oc_subgraph.inputs.size()); std::vector<DataType> input_dtypes(oc_subgraph.inputs.size(), DT_INVALID); std::vector<DataType> output_dtypes(oc_subgraph.outputs_by_src.size(), DT_INVALID); for (const auto& input_src : oc_subgraph.inputs) { const Node* src_node = input_src.first.node; Node* src_image = node_images.at(src_node); int src_slot = input_src.first.index; int input_index = input_src.second; DataType dtype = src_node->output_type(src_slot); inputs[input_index].Reset(src_image->name(), src_slot, dtype); input_dtypes[input_index] = dtype; } for (const auto& output : oc_subgraph.outputs_by_src) { DataType dtype = output.second.dtype; int output_index = output.second.index; output_dtypes[output_index] = dtype; } std::vector<string> host_compute_ancestors; const auto iter = ancestors_map.find(oc_subgraph_name); if (iter != ancestors_map.end()) { for (const string& ancestor_cluster : iter->second) { host_compute_ancestors.push_back( outside_compilation_subgraphs_[ancestor_cluster] .host_compute_name); } } NodeDef host_compute_def; NodeDefBuilder builder(strings::StrCat("outside_compilation_", oc_subgraph_name, "_host_compute"), kHostComputeOp); builder.Input(inputs); builder.Attr("Tinputs", input_dtypes); builder.Attr("Toutputs", output_dtypes); builder.Attr("ancestors", host_compute_ancestors); builder.Attr("key", strings::StrCat("host_compute_channel_", subgraph_name, "_", oc_subgraph_name)); builder.Attr("_outside_compilation_subgraph", oc_subgraph_name); Status s = builder.Finalize(&host_compute_def); if (!s.ok()) return s; Node* host_compute = graph_->AddNode(host_compute_def, &s); if (!s.ok()) return s; host_compute_node[host_compute->name()] = host_compute; oc_subgraph.host_compute_name = host_compute->name(); // Connect the _HostCompute node to its producers in the subgraph. for (auto& input_src : oc_subgraph.inputs) { const Node* src_node = input_src.first.node; Node* src_image = node_images.at(src_node); int src_slot = input_src.first.index; int input_index = input_src.second; graph_->AddEdge(src_image, src_slot, host_compute, input_index); } // Connect the _HostCompute node to its control edge producers in the // subgraph. for (const auto& src_node : oc_subgraph.control_inputs) { Node* src_image = node_images.at(src_node); graph_->AddControlEdge(src_image, host_compute); } // Connect the _HostCompute node to its ancestor host compute nodes. for (const auto& ancestor_name : host_compute_ancestors) { Node* ancestor = host_compute_node[ancestor_name]; graph_->AddControlEdge(ancestor, host_compute); } // Connect the consumers in the subgraph to the _HostCompute node. for (const auto& output : oc_subgraph.outputs_by_dst) { const Node* dst_node = output.first.node; Node* dst_image = node_images.at(dst_node); int dst_slot = output.first.index; int output_index = output.second; graph_->AddEdge(host_compute, output_index, dst_image, dst_slot); } // Connect the control edge consumers in the subgraph to the _HostCompute // node. for (const auto& dst_node : oc_subgraph.control_outputs) { Node* dst_image = node_images.at(dst_node); graph_->AddControlEdge(host_compute, dst_image); } } } return Status::OK(); } Status Encapsulator::Subgraph::MakeSequencingNode(const string& subgraph_name, Graph* graph_out) { if (sequencer_ == nullptr) { NodeDef seq_def; NodeDefBuilder builder(strings::StrCat(subgraph_name, "_sequencer"), "NoOp"); builder.Attr(kXlaHostTransferSequencerAttr, subgraph_name); builder.Device(device_); Status s = builder.Finalize(&seq_def); if (!s.ok()) return s; sequencer_ = graph_out->AddNode(seq_def, &s); if (!s.ok()) return s; } return Status::OK(); } void Encapsulator::Subgraph::ConnectSequencerToCallNode(Graph* graph_out) { if (sequencer_ != nullptr) { VLOG(2) << "ConnectSequencerToCallNode"; graph_out->AddControlEdge(sequencer_, call_node_); } } Status Encapsulator::Subgraph::BuildFunctionDef( const string& name_in, const RewriteSubgraphFn& rewrite_subgraph_fn, bool reuse_existing_functions, FunctionLibraryDefinition* library) { // name_in is copied here because name may be modified below if // rewrite_subgraph_fn is true. string name = name_in; call_node_def_.set_op(name); call_node_def_.set_name(name); call_node_def_.set_device(device_); if (rewrite_subgraph_fn) { std::vector<OutputTensor> arg_source_tensors(args_by_src_.size()); for (const auto& arg : args_by_src_) { arg_source_tensors.at(arg.second) = arg.first; } // Initialize the input and output permutations to the identity. std::vector<int> input_permutation(args_by_src_.size()); std::iota(input_permutation.begin(), input_permutation.end(), 0); std::vector<int> output_permutation(results_.size()); std::iota(output_permutation.begin(), output_permutation.end(), 0); TF_RETURN_IF_ERROR( rewrite_subgraph_fn(arg_source_tensors, &graph_, &input_permutation, &output_permutation, &call_node_def_)); // Apply the input/output permutations to the 'args_by_...' and 'results_' // mappings, so when we build edges in BuildOutputGraph() we // connect them to the right input/output positions. if (input_permutation.size() != args_by_src_.size()) { return errors::InvalidArgument("Input permutation has incorrect size."); } if (output_permutation.size() != results_.size()) { return errors::InvalidArgument("Output permutation has incorrect size."); } for (auto& arg : args_by_src_) { arg.second = input_permutation[arg.second]; } for (auto& arg : args_by_dst_) { arg.second = input_permutation[arg.second]; } for (auto& result : results_) { result.second = output_permutation[result.second]; } name = call_node_def_.op(); } function_def_name_ = name; FunctionDef fdef; TF_RETURN_IF_ERROR(GraphToFunctionDef(*graph_, name, &fdef)); if (VLOG_IS_ON(1)) { VLOG(2) << "Build function def " << name; dump_graph::DumpGraphToFile( strings::StrCat("encapsulate_fdef_graph_", name), *graph_, library); dump_graph::DumpFunctionDefToFile( strings::StrCat("encapsulate_fdef_", name), fdef); } if (!reuse_existing_functions || library->Find(name) == nullptr) { TF_RETURN_IF_ERROR(library->AddFunctionDef(fdef)); } return Status::OK(); } Status Encapsulator::Subgraph::AddShapeInferenceInfo( const string& subgraph_name, const string& outside_compilation_subgraph_name, const std::vector<TensorShapeProto>& shapes, Graph* inference_graph, FunctionLibraryDefinition* library) { OutsideCompilationSubgraph& oc_subgraph = outside_compilation_subgraphs_.at(outside_compilation_subgraph_name); Node* host_compute = nullptr; for (Node* n : graph_->nodes()) { if (n->name() == oc_subgraph.host_compute_name) { host_compute = n; break; } } if (host_compute == nullptr) { return errors::InvalidArgument( "After rewriting subgraph ", outside_compilation_subgraph_name, " there is no HostCompute Op for outside compilation subgraph ", oc_subgraph.host_compute_name); } if (inference_graph == nullptr) { host_compute->AddAttr("shape_inference_graph", ""); host_compute->AddAttr("shapes", shapes); } else { string inference_graph_name = strings::StrCat("_outside_compilation_shape_inference_", subgraph_name, "_", outside_compilation_subgraph_name); FunctionDef fdef; TF_RETURN_IF_ERROR( GraphToFunctionDef(*inference_graph, inference_graph_name, &fdef)); host_compute->AddAttr("shape_inference_graph", inference_graph_name); host_compute->AddAttr("shapes", std::vector<TensorShapeProto>()); // TODO(sibyl-Aix6ihai): Understand why there are multiple calls to Encapsulator. if (library->Find(inference_graph_name) == nullptr) { TF_RETURN_IF_ERROR(library->AddFunctionDef(fdef)); } } return Status::OK(); } Status Encapsulator::Subgraph::ReplaceFunctionDef( FunctionLibraryDefinition* library) { const string& name = function_def_name_; FunctionDef fdef; TF_RETURN_IF_ERROR(GraphToFunctionDef(*graph_, name, &fdef)); if (VLOG_IS_ON(1)) { VLOG(2) << "Replace function def " << name; dump_graph::DumpGraphToFile( strings::StrCat("replace_encapsulate_fdef_graph_", name), *graph_, library); dump_graph::DumpFunctionDefToFile( strings::StrCat("replace_encapsulate_fdef_", name), fdef); } TF_RETURN_IF_ERROR(library->RemoveFunction(name)); TF_RETURN_IF_ERROR(library->AddFunctionDef(fdef)); return Status::OK(); } Status Encapsulator::Subgraph::AddFunctionCallNode( const std::unordered_map<const Node*, Node*>& node_images, Graph* graph_out) { Status s; call_node_ = graph_out->AddNode(call_node_def_, &s); if (!s.ok()) return s; // Copy the assigned device and the key_annotation over. call_node_->set_assigned_device_name(device_); return Status::OK(); } Status Encapsulator::Subgraph::AddHostComputeKeyPlaceholder( OutsideCompilationSubgraph* oc_subgraph, Graph* graph_out) { TensorShapeProto shape_proto; TensorShape shape({2}); shape.AsProto(&shape_proto); GraphDefBuilder::Options options(graph_out, /*status=*/nullptr); NodeDef key_def; NodeDefBuilder builder( strings::StrCat(call_node_def_.name(), "_key_placeholder"), "Placeholder"); builder.Attr("dtype", DT_STRING); builder.Attr("shape", shape_proto); builder.Attr("_host_compute_call_node", call_node_def_.name()); Status s = builder.Finalize(&key_def); if (!s.ok()) return s; host_compute_key_placeholder_ = graph_out->AddNode(key_def, &s); if (!s.ok()) return s; host_compute_key_placeholder_->set_assigned_device_name(device_); return Status::OK(); } Status Encapsulator::Subgraph::AddRecvAtHostNode( const string& group_attribute, const string& subgraph_name, const string& outside_compilation_attribute, const string& oc_subgraph_name, OutsideCompilationSubgraph* oc_subgraph, Graph* graph_out) { if (host_compute_key_placeholder_ == nullptr) { TF_RETURN_IF_ERROR(AddHostComputeKeyPlaceholder(oc_subgraph, graph_out)); } std::vector<DataType> dtypes(oc_subgraph->inputs.size(), DT_INVALID); for (const auto& input : oc_subgraph->inputs) { const Node* src_node = input.first.node; int src_slot = input.first.index; int input_index = input.second; DataType dtype = src_node->output_type(src_slot); dtypes[input_index] = dtype; } NodeDef recv_def; NodeDefBuilder builder(strings::StrCat("outside_compilation_", subgraph_name, "_", oc_subgraph_name, "_recv"), kRecvAtHostOp); builder.Device(device_); builder.Attr("Toutputs", dtypes); // The correct device_ordinal will be inserted during replication in a // subsequent rewrite. builder.Attr("device_ordinal", 0); builder.Attr("key", strings::StrCat("host_compute_channel_", subgraph_name, "_", oc_subgraph_name)); builder.Attr(group_attribute, subgraph_name); builder.Attr(outside_compilation_attribute, oc_subgraph_name); builder.Input(host_compute_key_placeholder_->name(), 0, DT_STRING); Status s = builder.Finalize(&recv_def); if (!s.ok()) return s; oc_subgraph->recv_at_host = graph_out->AddNode(recv_def, &s); if (!s.ok()) return s; graph_out->AddEdge(host_compute_key_placeholder_, 0, oc_subgraph->recv_at_host, 0); // Add a control dependency forcing the RecvAtHost to run before the subgraph // completes. This has no effect on execution order but prevents the // RecvAtHost being pruned. TF_RETURN_IF_ERROR(MakeSequencingNode(subgraph_name, graph_out)); graph_out->AddControlEdge(oc_subgraph->recv_at_host, sequencer_); return Status::OK(); } Status Encapsulator::Subgraph::AddSendFromHostNode( const std::unordered_map<const Node*, Node*>& node_images, const string& group_attribute, const string& subgraph_name, const string& outside_compilation_attribute, const string& oc_subgraph_name, OutsideCompilationSubgraph* oc_subgraph, Graph* graph_out) { if (host_compute_key_placeholder_ == nullptr) { TF_RETURN_IF_ERROR(AddHostComputeKeyPlaceholder(oc_subgraph, graph_out)); } std::vector<DataType> dtypes(oc_subgraph->outputs_by_src.size(), DT_INVALID); std::vector<NodeDefBuilder::NodeOut> inputs( oc_subgraph->outputs_by_src.size()); for (const auto& output : oc_subgraph->outputs_by_src) { const Node* src_node = output.first.node; Node* src_image = node_images.at(src_node); int src_slot = output.first.index; int output_index = output.second.index; DataType dtype = src_node->output_type(src_slot); dtypes[output_index] = dtype; inputs[output_index].Reset(src_image->name(), src_slot, dtype); } NodeDef send_def; NodeDefBuilder builder(strings::StrCat("outside_compilation_", subgraph_name, "_", oc_subgraph_name, "_send"), kSendFromHostOp); builder.Device(device_); builder.Attr("Tinputs", dtypes); builder.Attr("key", strings::StrCat("host_compute_channel_", subgraph_name, "_", oc_subgraph_name)); // The correct device_ordinal will be inserted during replication in a // subsequent rewrite. builder.Attr("device_ordinal", 0); builder.Attr(group_attribute, subgraph_name); builder.Attr(outside_compilation_attribute, oc_subgraph_name); builder.Input(inputs); builder.Input(host_compute_key_placeholder_->name(), 0, DT_STRING); Status s = builder.Finalize(&send_def); if (!s.ok()) return s; oc_subgraph->send_from_host = graph_out->AddNode(send_def, &s); if (!s.ok()) return s; graph_out->AddEdge(host_compute_key_placeholder_, 0, oc_subgraph->send_from_host, inputs.size()); // Add a control dependency forcing the SendFromHost to run before the // subgraph completes. This has no effect on execution order but prevents the // RecvAtHost being pruned. TF_RETURN_IF_ERROR(MakeSequencingNode(subgraph_name, graph_out)); graph_out->AddControlEdge(oc_subgraph->send_from_host, sequencer_); return Status::OK(); } Status Encapsulator::Subgraph::AddOutsideCompilationHostIONodes( const string& group_attribute, const string& subgraph_name, const string& outside_compilation_attribute, const std::unordered_map<const Node*, Node*>& node_images, Graph* graph_out) { for (auto& outside_compilation_subgraph_entry : outside_compilation_subgraphs_) { const string& oc_name = outside_compilation_subgraph_entry.first; OutsideCompilationSubgraph& oc_subgraph = outside_compilation_subgraph_entry.second; if (!oc_subgraph.inputs.empty() || !oc_subgraph.control_inputs.empty()) { TF_RETURN_IF_ERROR(AddRecvAtHostNode(group_attribute, subgraph_name, outside_compilation_attribute, oc_name, &oc_subgraph, graph_out)); } if (!oc_subgraph.outputs_by_src.empty() || !oc_subgraph.control_outputs.empty()) { TF_RETURN_IF_ERROR(AddSendFromHostNode( node_images, group_attribute, subgraph_name, outside_compilation_attribute, oc_name, &oc_subgraph, graph_out)); } } return Status::OK(); } void Encapsulator::Subgraph::GetOutsideCompilationSubgraphNames( std::vector<string>* names) const { for (auto& entry : outside_compilation_subgraphs_) { names->push_back(entry.first); } } Status Encapsulator::GetFunctionNameAttr( Node const* node, string* attr, string* outside_compilation_attr) const { Status s = GetNodeAttr(node->attrs(), group_attribute_, attr); if (s.code() == error::Code::NOT_FOUND) { // Return empty attr if there's no group_attribute. attr->clear(); } else { TF_RETURN_IF_ERROR(s); } bool has_group_attr = s.ok(); s = GetNodeAttr(node->attrs(), outside_compilation_attribute_, outside_compilation_attr); if (s.code() == error::Code::NOT_FOUND) { // Return empty attr if there's no outside_compilation attribute. outside_compilation_attr->clear(); } else { TF_RETURN_IF_ERROR(s); if (!has_group_attr) { return errors::InvalidArgument( "Node ", node->name(), " has ", outside_compilation_attribute_, " attribute but no ", group_attribute_, " attribute."); } } return Status::OK(); } bool IsInSubgraph(const string& func_id, const string& outside_compilation_id) { return !func_id.empty() && outside_compilation_id.empty(); } Status Encapsulator::CopySubgraphNodes( std::unordered_map<const Node*, Node*>* node_images) { for (Node* node : graph_in_->op_nodes()) { string func_id; string outside_compilation_id; TF_RETURN_IF_ERROR( GetFunctionNameAttr(node, &func_id, &outside_compilation_id)); if (!IsInSubgraph(func_id, outside_compilation_id)) continue; Subgraph& subgraph = subgraphs_[func_id]; Node* image = subgraph.MakeNodeImage(graph_in_, node); image->ClearAttr(group_attribute_); (*node_images)[node] = image; } return Status::OK(); } Status Encapsulator::CopySubgraphEdges( const std::unordered_map<const Node*, Node*>& node_images, std::vector<std::pair<const Node*, Node*>>* src_arg_pairs) { for (const Edge* edge : graph_in_->edges()) { string src_func_id; string src_outside_compilation_id; TF_RETURN_IF_ERROR(GetFunctionNameAttr(edge->src(), &src_func_id, &src_outside_compilation_id)); string dst_func_id; string dst_outside_compilation_id; TF_RETURN_IF_ERROR(GetFunctionNameAttr(edge->dst(), &dst_func_id, &dst_outside_compilation_id)); Node* src_image = gtl::FindWithDefault(node_images, edge->src(), nullptr); Node* dst_image = gtl::FindWithDefault(node_images, edge->dst(), nullptr); // Copy edges that are local to a subgraph. if (IsInSubgraph(src_func_id, src_outside_compilation_id) && IsInSubgraph(dst_func_id, dst_outside_compilation_id) && src_func_id == dst_func_id) { Graph* g = subgraphs_[src_func_id].GetGraph(); if (edge->IsControlEdge()) { g->AddControlEdge(src_image, dst_image); } else { g->AddEdge(src_image, edge->src_output(), dst_image, edge->dst_input()); } continue; } // Record 'src' as an output of its subgraph, if applicable. if (IsInSubgraph(src_func_id, src_outside_compilation_id)) { if (!edge->IsControlEdge()) { DataType dtype = edge->src()->output_type(edge->src_output()); if (IsRefType(dtype)) { return errors::InvalidArgument( "Ref Tensors (e.g., Variables) are not supported as results: " "tensor ", edge->src()->name(), ":", edge->src_output()); } } Subgraph& src_subgraph = subgraphs_[src_func_id]; if (src_func_id == dst_func_id) { // src is in the subgraph and dst is outside_compilation in the same // subgraph. src_subgraph.RecordOutsideCompilationInputOrControl( dst_outside_compilation_id, edge); } else { // Ignore control edges leaving the subgraph. We will lift them onto the // enclosing call operators in BuildOutputGraph(). if (!edge->IsControlEdge()) { TF_RETURN_IF_ERROR(src_subgraph.RecordResult(edge, node_images)); } } } // Record 'dst' as an input of its subgraph, if applicable. if (IsInSubgraph(dst_func_id, dst_outside_compilation_id)) { // Look at the type of the destination not the source, since Ref output // Tensors can be automatically cast to non-Ref Tensors at the // destination. if (!edge->IsControlEdge()) { DataType dtype = edge->dst()->input_type(edge->dst_input()); if (IsRefType(dtype)) { return errors::InvalidArgument( "Ref Tensors (e.g., Variables) are not supported as args: " "tensor ", edge->src()->name(), ":", edge->src_output()); } } Subgraph& dst_subgraph = subgraphs_[dst_func_id]; if (src_func_id == dst_func_id) { // dst is in the subgraph and src is outside_compilation in the same // subgraph. dst_subgraph.RecordOutsideCompilationOutputOrControl( src_outside_compilation_id, edge); } else { // Ignore control edges entering the subgraph. We will lift them onto // the enclosing call operators in BuildOutputGraph(). if (!edge->IsControlEdge()) { TF_RETURN_IF_ERROR( dst_subgraph.RecordArg(edge, node_images, src_arg_pairs)); } } } } return Status::OK(); } Status Encapsulator::SplitIntoSubgraphs() { Status s; // Map from input graph nodes to subgraph nodes. std::unordered_map<const Node*, Node*> node_images; // Each entry of src_arg_pairs is a pair whose first element is a node in the // original graph that has an output edge in the subgraph, and whose second // element is the arg node in the subgraph that it sends to. The vector will // be filled in below in AddArgs. std::vector<std::pair<const Node*, Node*>> src_arg_pairs; TF_RETURN_IF_ERROR(CopySubgraphNodes(&node_images)); TF_RETURN_IF_ERROR(CopySubgraphEdges(node_images, &src_arg_pairs)); // For each subgraph, add the nodes that deal with inputs and outputs its // nested outside_compilation subgraphs. These could not be added earlier // during CopySubgraphEdges since we need to discover all the types of the // inputs and outputs for an outside_compilation subgraph before creating a // single input and output node for it. for (auto& entry : subgraphs_) { Subgraph& subgraph = entry.second; TF_RETURN_IF_ERROR(subgraph.AddHostComputes(entry.first, node_images)); } MarkGuaranteedConstants(*graph_in_, src_arg_pairs); for (auto& entry : subgraphs_) { Subgraph& subgraph = entry.second; FixupSourceAndSinkEdges(subgraph.GetGraph()); // Verify that the graph has well-formed control flow structure. std::vector<ControlFlowInfo> dummy; TF_RETURN_IF_ERROR(BuildControlFlowInfo(subgraph.GetGraph(), &dummy)); } return s; } Status Encapsulator::BuildFunctionDefs( const RewriteSubgraphFn& rewrite_subgraph_fn, bool reuse_existing_functions, FunctionLibraryDefinition* library) { for (auto& subgraph_entry : subgraphs_) { string name = subgraph_entry.first; Subgraph& subgraph = subgraph_entry.second; TF_RETURN_IF_ERROR(subgraph.BuildFunctionDef( name, rewrite_subgraph_fn, reuse_existing_functions, library)); } return Status::OK(); } Status Encapsulator::CopyNodesToOutputGraph( Graph* graph_out, std::unordered_map<const Node*, Node*>* node_images) { for (Node* node : graph_in_->op_nodes()) { string func_id; string outside_compilation_id; TF_RETURN_IF_ERROR( GetFunctionNameAttr(node, &func_id, &outside_compilation_id)); // Don't copy nodes that are going to be encapsulated. if (IsInSubgraph(func_id, outside_compilation_id)) continue; Node* image = graph_out->CopyNode(node); (*node_images)[node] = image; } (*node_images)[graph_in_->source_node()] = graph_out->source_node(); (*node_images)[graph_in_->sink_node()] = graph_out->sink_node(); return Status::OK(); } Status Encapsulator::AddFunctionCallNodes( const std::unordered_map<const Node*, Node*>& node_images, Graph* graph_out) { for (auto& subgraph_entry : subgraphs_) { TF_RETURN_IF_ERROR( subgraph_entry.second.AddFunctionCallNode(node_images, graph_out)); } return Status::OK(); } Status Encapsulator::AddOutsideCompilationHostIONodes( const std::unordered_map<const Node*, Node*>& node_images, Graph* graph_out) { for (auto& subgraph_entry : subgraphs_) { const string& subgraph_name = subgraph_entry.first; Subgraph& subgraph = subgraph_entry.second; TF_RETURN_IF_ERROR(subgraph.AddOutsideCompilationHostIONodes( group_attribute_, subgraph_name, outside_compilation_attribute_, node_images, graph_out)); } return Status::OK(); } Status Encapsulator::FindOutputImageOfEdgeSrc( const string& src_func_id, const string& src_outside_compilation_id, const string& dst_func_id, const string& dst_outside_compilation_id, const std::unordered_map<const Node*, Node*>& node_images, const Node* original_src_node, Node** src_image) { if (IsInSubgraph(src_func_id, src_outside_compilation_id)) { if (dst_func_id == src_func_id) { // The edge is from a subgraph to an outside_compilation cluster in the // same subgraph so use the appropriate _RecvAtHost node in the output // graph. TF_RET_CHECK(!dst_outside_compilation_id.empty()); *src_image = subgraphs_.at(src_func_id) .GetRecvAtHostNode(dst_outside_compilation_id); } else { // The edge is from a subgraph to a regular node in the output graph so // use the subgraph's call node output. *src_image = subgraphs_.at(src_func_id).GetCallNode(); } } else { // The source of the edge is in the output graph so use the node image in // the output graph. *src_image = node_images.at(original_src_node); } return Status::OK(); } int Encapsulator::FindOutputSlotOfEdgeSrc( const string& src_func_id, const string& src_outside_compilation_id, const string& dst_func_id, const string& dst_outside_compilation_id, const Edge* edge) { if (IsInSubgraph(src_func_id, src_outside_compilation_id)) { const Subgraph& src_subgraph = subgraphs_.at(src_func_id); if (src_func_id == dst_func_id) { // 'src' is in a subgraph and 'dst' is outside_compilation in the same // subgraph. Use the corresponding _RecvAtHost output instead. return src_subgraph.GetRecvAtHostSlot(dst_outside_compilation_id, edge); } else { // 'src' is in a subgraph and 'dst' is a regular node in the output // graph. Use the corresponding call output instead. return src_subgraph.GetResultIndexForEdge(edge); } } else { // The source of the edge is in the output graph so use the regular edge // slot. return edge->src_output(); } } Status Encapsulator::FindOutputImageOfEdgeDst( const string& src_func_id, const string& src_outside_compilation_id, const string& dst_func_id, const string& dst_outside_compilation_id, const std::unordered_map<const Node*, Node*>& node_images, const Node* original_dst_node, Node** dst_image) { if (IsInSubgraph(dst_func_id, dst_outside_compilation_id)) { if (src_func_id == dst_func_id) { // The edge is to a subgraph from an outside_compilation cluster in the // same subgraph so use the appropriate _SendFromHost node in the output // graph. TF_RET_CHECK(!src_outside_compilation_id.empty()); *dst_image = subgraphs_.at(dst_func_id) .GetSendFromHostNode(src_outside_compilation_id); } else { // The edge is to a subgraph from a regular node in the output graph so // use the subgraph's call node input. *dst_image = subgraphs_.at(dst_func_id).GetCallNode(); } } else { // The destination of the edge is in the output graph so use the node image // in the output graph. *dst_image = node_images.at(original_dst_node); } return Status::OK(); } int Encapsulator::FindOutputSlotOfEdgeDst( const string& src_func_id, const string& src_outside_compilation_id, const string& dst_func_id, const string& dst_outside_compilation_id, const Edge* edge) { if (IsInSubgraph(dst_func_id, dst_outside_compilation_id)) { const Subgraph& dst_subgraph = subgraphs_.at(dst_func_id); if (dst_func_id == src_func_id) { // 'dst' is in a subgraph and 'src' is outside_compilation in the same // subgraph. Use the corresponding _SendFromHost input instead. return dst_subgraph.GetSendFromHostSlot(src_outside_compilation_id, edge); } else { // 'dst' is in a subgraph and 'src' is a regular node in the output // graph. Use the corresponding call input instead. return dst_subgraph.GetArgIndexForEdge(edge); } } else { // The destination of the edge is in the output graph so use the regular // edge slot. return edge->dst_input(); } } Status Encapsulator::CopyEdgeToOutputGraph( const Edge* edge, const string& src_func_id, const string& src_outside_compilation_id, const string& dst_func_id, const string& dst_outside_compilation_id, const std::unordered_map<const Node*, Node*>& node_images, Graph* graph_out, std::unordered_set<std::pair<OutputTensor, InputTensor>, OutputInputTensorPairHasher>* edges_added) { Node* src_image; TF_RETURN_IF_ERROR(FindOutputImageOfEdgeSrc( src_func_id, src_outside_compilation_id, dst_func_id, dst_outside_compilation_id, node_images, edge->src(), &src_image)); Node* dst_image; TF_RETURN_IF_ERROR(FindOutputImageOfEdgeDst( src_func_id, src_outside_compilation_id, dst_func_id, dst_outside_compilation_id, node_images, edge->dst(), &dst_image)); // If this is a control edge then copy it and return. Lift control edges onto // the enclosing call operator. if (edge->IsControlEdge()) { // Add the control edge, if we have not already added it, using the images // determined above (potentially call operators or RecvAtHost/SendFromHost). if (edges_added ->emplace(OutputTensor(src_image, -1), InputTensor(dst_image, -1)) .second) { graph_out->AddControlEdge(src_image, dst_image); } return Status::OK(); } int src_output = FindOutputSlotOfEdgeSrc(src_func_id, src_outside_compilation_id, dst_func_id, dst_outside_compilation_id, edge); int dst_input = FindOutputSlotOfEdgeDst(src_func_id, src_outside_compilation_id, dst_func_id, dst_outside_compilation_id, edge); // Add the edge, if we have not already added it. if (edges_added ->emplace(OutputTensor(src_image, src_output), InputTensor(dst_image, dst_input)) .second) { graph_out->AddEdge(src_image, src_output, dst_image, dst_input); } return Status::OK(); } Status Encapsulator::AddCallNodeDependencies(Graph* graph_out) { for (const auto& ancestors : subgraph_ancestors_) { const string& subgraph = ancestors.first; for (const string& ancestor : ancestors.second) { graph_out->AddControlEdge(subgraphs_[ancestor].GetCallNode(), subgraphs_[subgraph].GetCallNode()); } } return Status::OK(); } Status Encapsulator::AddEdgesToOutputGraph( const std::unordered_map<const Node*, Node*>& node_images, Graph* graph_out) { // Set of edges already added to the output graph, represented as (src, dst) // pairs. We use the set to deduplicate edges; multiple edges in the input // graph may map to one edge in the output graph. std::unordered_set<std::pair<OutputTensor, InputTensor>, OutputInputTensorPairHasher> edges_added; for (const Edge* edge : graph_in_->edges()) { string src_func_id; string src_outside_compilation_id; TF_RETURN_IF_ERROR(GetFunctionNameAttr(edge->src(), &src_func_id, &src_outside_compilation_id)); string dst_func_id; string dst_outside_compilation_id; TF_RETURN_IF_ERROR(GetFunctionNameAttr(edge->dst(), &dst_func_id, &dst_outside_compilation_id)); // Ignore edges that are strictly contained within one subgraph, unless // we are constructing parallel check graphs. if (IsInSubgraph(src_func_id, src_outside_compilation_id) && IsInSubgraph(dst_func_id, dst_outside_compilation_id) && src_func_id == dst_func_id) { continue; } // We have an edge that crosses a cluster boundary or is entirely within the // unclustered graph. TF_RETURN_IF_ERROR(CopyEdgeToOutputGraph( edge, src_func_id, src_outside_compilation_id, dst_func_id, dst_outside_compilation_id, node_images, graph_out, &edges_added)); } for (auto& subgraph_entry : subgraphs_) { Subgraph& subgraph = subgraph_entry.second; subgraph.ConnectSequencerToCallNode(graph_out); } TF_RETURN_IF_ERROR(AddCallNodeDependencies(graph_out)); return Status::OK(); } namespace { // Adds a dummy Const node to graph_out. The "constant" has the type of // data_type and the shape indicated in 'shape'. The dummy node is not a valid // Const node because it does not have any value defined, but this doesn't // matter because it will only be used subsequently for shape inference. (It // would be possible to add a switch statement over data_type to create a value // for the constant, but that would entail maintaining the logic as new types // are added, and is not necessary.) If the node being replaced was within a // control flow frame, adds appropriate Enter nodes so that the use of the Const // is well-formed. Node* AddDummyShapedNode(const Node* src_node, int src_port, const std::vector<ControlFlowInfo>& control_flow_info, const TensorShapeProto& shape, Graph* graph_out) { DataType data_type = src_node->output_type(src_port); TensorProto dummy_proto; dummy_proto.set_dtype(data_type); *dummy_proto.mutable_tensor_shape() = shape; // Don't set any value field in the proto, since it is only going to be used // for shape inference. GraphDefBuilder::Options options(graph_out, /*status=*/nullptr); NodeBuilder node_builder(options.GetNameForOp("KnownShape"), "Const", options.op_registry()); node_builder.Attr("dtype", data_type).Attr("value", dummy_proto); Node* node = options.FinalizeBuilder(&node_builder); // Add any Enter nodes required to bring the constant to the correct control // flow frame. while (!control_flow_info[src_node->id()].frame_name.empty()) { NodeBuilder enter_builder(options.GetNameForOp("Enter"), "Enter", options.op_registry()); enter_builder.Attr("frame_name", control_flow_info[src_node->id()].frame_name); enter_builder.Attr("is_constant", true); enter_builder.Input(node, 0); Node* enter_node = options.FinalizeBuilder(&enter_builder); // Adopt the new Enter node as the value in the current frame. node = enter_node; // Recurse to the parent frame to see if more Enter nodes need to be added. src_node = control_flow_info[src_node->id()].parent_frame; } return node; } // Adds a copy of node_in to graph_out and adds the mapping to // copied_node_images. Status CopyShapeInferenceNodeToGraph( Node* node_in, const Node* send_node, const std::unordered_map<Node*, Node*>& dummy_node_images, FunctionLibraryDefinition* library, std::unordered_map<Node*, Node*>* copied_node_images, Graph* graph_out) { // Once all the ancestor nodes have been added to graph_out, add this node // and connect it to its ancestors. Node* node_out = graph_out->CopyNode(node_in); (*copied_node_images)[node_in] = node_out; // Don't bother to build the shape inference graph if there's a node with no // shape inference function, since it would just result in an error later at // compile time. const OpRegistrationData* op_reg_data; TF_RETURN_IF_ERROR(library->LookUp(node_in->type_string(), &op_reg_data)); if (op_reg_data->shape_inference_fn == nullptr) { return errors::InvalidArgument( "Shape inference is not possible for outside_compilation " "SendFromHost node ", send_node->name(), " because it depends on node ", node_in->name(), " which does not have a shape inference function registered."); } // Add all the edges to the newly copied node. for (const Edge* in_edge : node_in->in_edges()) { if (!in_edge->IsControlEdge()) { Node* src = in_edge->src(); const auto iter = dummy_node_images.find(src); if (iter == dummy_node_images.end()) { // The src is a copied node so use the original output port. graph_out->AddEdge((*copied_node_images)[in_edge->src()], in_edge->src_output(), node_out, in_edge->dst_input()); } else { // The src is a dummy node so use output port 0. graph_out->AddEdge(iter->second, 0, node_out, in_edge->dst_input()); } } } // Work around the fact that Enter nodes refuse to propagate shape information // unless they are marked loop invariant. Since we are never going to execute // this graph, marking them all loop invariant is fine. if (node_out->type_string() == "Enter") { node_out->ClearAttr("is_constant"); node_out->AddAttr("is_constant", true); } return Status::OK(); } } // namespace Status Encapsulator::DoStaticShapeInferenceForOutsideCompilationSend( const Graph& graph_in, const BackEdgeHelper& back_edge_helper, const ShapeRefiner& shape_refiner, const std::unordered_set<string>& recv_at_host_nodes, Node* send_node, FunctionLibraryDefinition* library, std::vector<TensorShapeProto>* static_shape_out, std::unique_ptr<Graph>* graph_out) { // Get the control flow structure of the input graph so we can build // well-formed output graphs. std::vector<ControlFlowInfo> control_flow_info; TF_RETURN_IF_ERROR(BuildControlFlowInfo(&graph_in, &control_flow_info)); // Maps from nodes in graph_in to nodes in graph_out. // // When an edge has fully defined shape the source node in graph_in is // replaced in graph_out by a dummy constant node. The mapping from nodes // in graph_in to dummy nodes is stored in dummy_node_images. // // When a node in graph_in has at least one ancestor that doesn't have fully // defined shape, it is copied into graph_out. The mapping from nodes in // graph_in to copied nodes is stored in copied_node_images. // // The two types of node are treated differently because, when adding edges to // graph_out, an output from a dummy node always uses port 0, whereas an // output from a copied node uses the same port that was used in graph_in. std::unordered_map<Node*, Node*> dummy_node_images; std::unordered_map<Node*, Node*> copied_node_images; graph_out->reset(new Graph(graph_in.op_registry())); (*graph_out)->set_versions(graph_in.versions()); // The final input to the send node is the dynamic key, which we don't include // in the static shapes. static_shape_out->resize(send_node->num_inputs() - 1); // We don't use the standard ReverseDFS because we want to cut off traversal // whenever we find an output with fully defined shape. struct Work { Node* node; bool leave; // Are we entering or leaving node? }; std::vector<Work> stack({{send_node, false}}); std::vector<bool> visited(graph_in.num_node_ids(), false); while (!stack.empty()) { Work w = stack.back(); stack.pop_back(); Node* n = w.node; if (w.leave) { TF_RETURN_IF_ERROR(CopyShapeInferenceNodeToGraph( n, send_node, dummy_node_images, library, &copied_node_images, graph_out->get())); } else { if (visited[n->id()]) continue; visited[n->id()] = true; // Arrange to revisit when all done with all inputs. stack.push_back(Work{n, true}); bool has_parent_with_unknown_shape = false; for (const Edge* in_edge : n->in_edges()) { if (!in_edge->IsControlEdge()) { Node* src_node = in_edge->src(); int src_port = in_edge->src_output(); shape_inference::InferenceContext* context = shape_refiner.GetContext(src_node); shape_inference::ShapeHandle shape = context->output(src_port); if (context->FullyDefined(shape)) { // This ancestor has known shape, so instead of adding it to the // stack, add a dummy node with that shape to graph_out and // continue. TensorShapeProto proto; context->ShapeHandleToProto(shape, &proto); if (dummy_node_images.find(src_node) == dummy_node_images.end()) { dummy_node_images[src_node] = AddDummyShapedNode(src_node, src_port, control_flow_info, proto, graph_out->get()); } // The final input to the send node is the dynamic key, which we // don't include in the static shapes. if (n == send_node && in_edge->dst_input() < static_shape_out->size()) { (*static_shape_out)[in_edge->dst_input()] = proto; } } else { has_parent_with_unknown_shape = true; if (!visited[src_node->id()]) { if (VLOG_IS_ON(2)) { TensorShapeProto proto; context->ShapeHandleToProto(shape, &proto); } stack.push_back({src_node, false}); } } } } if (!has_parent_with_unknown_shape) { if (n == send_node) { // The shapes of all the inputs to send_node are statically known. We // won't have to do any inference at compile time so return now: the // shapes were stored in static_shape_out above. graph_out->reset(); return Status::OK(); } else { // Any shape that is being processed is either the original send node // or has at least one output with statically-unknown shape. If the // latter and it doesn't have any inputs with statically-unknown // shape, then check that it is of the recv nodes that we can fill in // the shape of at run-time later. If it isn't one of those, then we // won't have any additional knowledge at compile time, so we already // know we won't be able to do shape inference and we can return an // error now. if (recv_at_host_nodes.find(n->name()) == recv_at_host_nodes.end()) { return errors::InvalidArgument( "Shape inference is not possible for outside_compilation " "SendFromHost node ", send_node->name(), " because shape of node ", n->name(), " will not be known at compilation time."); } } } } } for (const auto edge : back_edge_helper.RemovedEdges()) { if (copied_node_images.find(edge.dst) != copied_node_images.end()) { // The destination of this back edge was added to the inference graph, so // fix it up. Node* dst = copied_node_images[edge.dst]; if (dst->type_string() != "Merge") { return errors::InvalidArgument( "outside_compilation cluster contains a back-edge to node ", dst->name(), " of type ", dst->type_string(), ". The analysis pass only supports back-edges to Merge nodes."); } const Edge* existing_input_edge; if (edge.dst_input != 1 || dst->num_inputs() != 2 || !dst->input_edge(0, &existing_input_edge).ok()) { // TODO(misard) if we see graphs built with a different structure, relax // this constraint. Leaving it here for now to avoid writing unnecessary // complex code since we believe graphs generated by front ends all have // the back edge as the second input to the merge node. return errors::Internal( "Internal assumption failed while rewriting an outside_compilation " "cluster that contains a while loop. Logic assumes back-edge is to " "port 1 of a 2-input " "Merge node."); } // Connect the existing edge to both inputs of the Merge node so that the // graph will be well-formed. (*graph_out) ->AddEdge(existing_input_edge->src(), existing_input_edge->src_output(), dst, edge.dst_input); } } return Status::OK(); } namespace { // Helper struct for building cluster dependencies and also debugging cycles in // the dependencies. While computing dependencies we construct a mapping from // Node* to PathDetails. struct PathDetails { struct SubgraphAndCluster { string subgraph; string outside_compilation_cluster; bool operator==(const SubgraphAndCluster& other) const { return subgraph == other.subgraph && outside_compilation_cluster == other.outside_compilation_cluster; } }; struct SubgraphAndClusterHash { inline std::size_t operator()(const SubgraphAndCluster& v) const { return hash<string>()( strings::StrCat(v.subgraph, v.outside_compilation_cluster)); } }; typedef std::unordered_set<SubgraphAndCluster, SubgraphAndClusterHash> SubgraphAndClusterSet; // Returns the set of (subgraph, oc_cluster) pairs that should be recorded as // ancestors for any successor of this node. If the node is in the outer // graph, it returns the transitive union of the ancestors of the node's // inputs. If the node is in an outside_compilation cluster, it returns just // that cluster. If the node is compiled, it returns the empty set. SubgraphAndClusterSet AncestorsForSuccessor() { if (subgraph.empty()) { return ancestor_clusters; } else if (outside_compilation_cluster.empty()) { return SubgraphAndClusterSet(); } else { SubgraphAndCluster entry; entry.subgraph = subgraph; entry.outside_compilation_cluster = outside_compilation_cluster; return SubgraphAndClusterSet({entry}); } } // The transitive union of the ancestor's of this node's inputs. This is only // saved for debugging in order to print out enough information to debug a // discovered cycle. SubgraphAndClusterSet ancestor_clusters; // The subgraph attr on this node. string subgraph; // The outside_compilation attr on this node. string outside_compilation_cluster; }; // Adds an edge from ancestor to successor to the cycle detector, and returns an // error if that edge causes the formation of a cycle. In the error case, logs // the contents of the node_ancestors_map to facilitate debugging. Status CheckClusterDependencyForCycles( const string& ancestor, const string& successor, const std::unordered_map<string, std::unordered_set<string>>& ancestors, const std::unordered_map<Node*, PathDetails>& node_ancestors_map, GraphCycles* cycle_detector, std::map<string, int>* cycle_detector_map) { if (cycle_detector_map->find(ancestor) == cycle_detector_map->end()) { (*cycle_detector_map)[ancestor] = cycle_detector->NewNode(); } if (cycle_detector_map->find(successor) == cycle_detector_map->end()) { (*cycle_detector_map)[successor] = cycle_detector->NewNode(); } if (!cycle_detector->InsertEdge((*cycle_detector_map)[ancestor], (*cycle_detector_map)[successor])) { LOG(ERROR) << "Cycle in outside_compilation clusters"; for (const auto& cluster : ancestors) { LOG(ERROR) << "Cluster " << cluster.first << " depends on:"; for (const auto& ancestor : cluster.second) { LOG(ERROR) << " " << ancestor; } } for (const auto& node_ancestors : node_ancestors_map) { LOG(ERROR) << "Node " << node_ancestors.first->name() << " (" << node_ancestors.second.subgraph << ";" << node_ancestors.second.outside_compilation_cluster << ") has ancestor clusters:"; for (const auto& ancestor : node_ancestors.second.ancestor_clusters) { LOG(ERROR) << " " << ancestor.subgraph << ";" << ancestor.outside_compilation_cluster; } } return errors::InvalidArgument( "Can't compile outside_compilation clusters because there is a " "dependency cycle: see error log for details."); } return Status::OK(); } } // namespace Status Encapsulator::FindClusterDependencies() { // Map from nodes to ancestor details. A node is entered into the map if it is // in a compilation subgraph, and outside_compilation cluster, or appears on a // path in the outer graph leading from an outside_compilation subgraph. std::unordered_map<Node*, PathDetails> node_ancestors_map; // We check that clusters are acyclic using this cycle detector. GraphCycles cycle_detector; // Map from cluster name to cycle detector node id. std::map<string, int> cycle_detector_map; // Process the nodes in topologically-sorted order. std::vector<Node*> nodes; GetReversePostOrder(*graph_in_, &nodes); for (Node* node : nodes) { string subgraph_name; string oc_cluster; TF_RETURN_IF_ERROR(GetFunctionNameAttr(node, &subgraph_name, &oc_cluster)); // First create an entry in the ancestors map if the node is in a compiled // subgraph or outside_compilation cluster, or if any incoming edge is from // a node with an ancestor map entry; and find the union of all the // ancestors. if (!subgraph_name.empty()) { node_ancestors_map[node].subgraph = subgraph_name; node_ancestors_map[node].outside_compilation_cluster = oc_cluster; } for (Node* src : node->in_nodes()) { const auto iter = node_ancestors_map.find(src); if (iter != node_ancestors_map.end()) { const auto& ancestors_to_follow = iter->second.AncestorsForSuccessor(); for (const auto& ancestor : ancestors_to_follow) { if (ancestor.subgraph != subgraph_name || ancestor.outside_compilation_cluster != oc_cluster) { node_ancestors_map[node].ancestor_clusters.insert(ancestor); } } } } if (!subgraph_name.empty()) { // The node is in a compiled subgraph or an outside_compilation cluster. if (oc_cluster.empty()) { // The node is not in an outside_compilation cluster. Record the // subgraph's ancestor dependencies. for (const auto& cluster : node_ancestors_map[node].ancestor_clusters) { if (cluster.subgraph != subgraph_name) { subgraph_ancestors_[subgraph_name].insert(cluster.subgraph); TF_RETURN_IF_ERROR(CheckClusterDependencyForCycles( cluster.subgraph, subgraph_name, subgraph_ancestors_, node_ancestors_map, &cycle_detector, &cycle_detector_map)); } } } else { Subgraph& subgraph = subgraphs_[subgraph_name]; // The node is in an outside_compilation cluster. Record the cluster // and/or subgraph ancestor dependencies. for (const auto& cluster : node_ancestors_map[node].ancestor_clusters) { if (cluster.subgraph == subgraph_name) { // The ancestor is in the same subgraph. if (cluster.outside_compilation_cluster != oc_cluster) { // But not in the same oc_cluster, so record the dependency. subgraph.RecordOutsideCompilationDependency( oc_cluster, cluster.outside_compilation_cluster); TF_RETURN_IF_ERROR(CheckClusterDependencyForCycles( cluster.outside_compilation_cluster, oc_cluster, subgraph.OutsideCompilationAncestorMap(), node_ancestors_map, &cycle_detector, &cycle_detector_map)); } } else { // The ancestor is in a different subgraph, so record the // dependency. subgraph_ancestors_[subgraph_name].insert(cluster.subgraph); TF_RETURN_IF_ERROR(CheckClusterDependencyForCycles( cluster.subgraph, subgraph_name, subgraph_ancestors_, node_ancestors_map, &cycle_detector, &cycle_detector_map)); } } } } } return Status::OK(); } Status Encapsulator::MakePrunedGraphCopyAndInline( const Graph& graph, const std::vector<Node*>& sink_nodes, std::unique_ptr<Graph>* pruned_graph, std::unordered_map<const Node*, Node*>* node_images, FunctionLibraryDefinition* library) { // First copy all ancestor nodes of sink_nodes into a new graph. pruned_graph->reset(new Graph(library)); (*pruned_graph)->set_versions(graph.versions()); ReverseDFSFrom(graph, sink_nodes, /*enter=*/nullptr, /*leave=*/[&](Node* n) { if (!n->IsSource()) { Node* copied = (*pruned_graph)->CopyNode(n); node_images->emplace(n, copied); } }); // Add all the edges between copied nodes. for (auto entry : *node_images) { const Node* orig = entry.first; Node* image = entry.second; for (const Edge* out_edge : orig->out_edges()) { auto iter = node_images->find(out_edge->dst()); if (iter != node_images->end()) { // The source and destination are both in the copied graph. (*pruned_graph) ->AddEdge(image, out_edge->src_output(), iter->second, out_edge->dst_input()); } } } // Find all the function call nodes, and inline them. std::vector<Node*> function_nodes; for (auto node : (*pruned_graph)->nodes()) { const OpRegistrationData* op_reg_data; TF_RETURN_IF_ERROR(library->LookUp(node->type_string(), &op_reg_data)); if (op_reg_data->is_function_op) { function_nodes.push_back(node); } } for (auto node : function_nodes) { VLOG(2) << "Inlining function " << node->name(); const FunctionDef* fdef = library->Find(node->type_string()); if (fdef == nullptr) { return errors::Internal("Failed to find function ", node->type_string(), " in function library."); } FunctionBody* fbody = nullptr; TF_RETURN_IF_ERROR( FunctionDefToBodyHelper(*fdef, node->attrs(), library, [library](const string& op, const OpDef** sig) { return library->LookUpOpDef(op, sig); }, &fbody)); InlineFunctionBody(*library, pruned_graph->get(), node, fbody); delete fbody; } return Status::OK(); } Status Encapsulator::MakeGraphForOutsideCompilationSends( const Graph& graph, std::unique_ptr<Graph>* pruned_graph, BackEdgeHelper* back_edge_helper, ShapeRefiner* shape_refiner, std::unordered_map<const Node*, Node*>* node_images, FunctionLibraryDefinition* library) { // Find all the send_from_host nodes in all subgraphs, to use as roots for the // pruning. std::vector<Node*> send_from_host_nodes; for (auto& subgraph_entry : subgraphs_) { Subgraph& subgraph = subgraph_entry.second; std::vector<string> outside_compilation_names; subgraph.GetOutsideCompilationSubgraphNames(&outside_compilation_names); for (const auto& name : outside_compilation_names) { Node* send_node = subgraph.GetSendFromHostNode(name); if (send_node != nullptr) { send_from_host_nodes.push_back(send_node); } } } // Make a copy of all the graph nodes needed to evaluate the send_from_host // nodes, inlining any functions as needed. TF_RETURN_IF_ERROR(MakePrunedGraphCopyAndInline( graph, send_from_host_nodes, pruned_graph, node_images, library)); FixupSourceAndSinkEdges(pruned_graph->get()); // Remove back edges from any cycles in the pruned graph to simplify shape // inference traversal. They will be fixed up in the per-subgraph shape // inference graphs stored in the function library. TF_RETURN_IF_ERROR(back_edge_helper->Remove(pruned_graph->get())); // Perform shape inference on the pruned graph. shape_refiner->set_require_shape_inference_fns(false); std::vector<Node*> post_order; GetReversePostOrder(*(*pruned_graph), &post_order); for (auto node : post_order) { // Ignore the status returned by the shape_refiner. At this point we want // the best effort shapes, even if no shape function is registered for a // node. Status status = shape_refiner->AddNode(node); if (!status.ok()) { VLOG(1) << "Shape inference failed for node: " << status; } } return Status::OK(); } Status Encapsulator::GetShapeInfoForOutsideCompilationSends( Graph* graph_out, FunctionLibraryDefinition* library) { BackEdgeHelper back_edge_helper; std::unique_ptr<Graph> pruned_graph; ShapeRefiner shape_refiner(graph_out->versions(), graph_out->op_registry()); std::unordered_map<const Node*, Node*> node_images; TF_RETURN_IF_ERROR(MakeGraphForOutsideCompilationSends( *graph_out, &pruned_graph, &back_edge_helper, &shape_refiner, &node_images, library)); if (VLOG_IS_ON(1)) { dump_graph::DumpGraphToFile("pruned_graph_for_shape_inference", *pruned_graph, library); } for (auto& subgraph_entry : subgraphs_) { const string& subgraph_name = subgraph_entry.first; Subgraph& subgraph = subgraph_entry.second; // Find all the recv_at_host nodes in this subgraph. std::vector<string> outside_compilation_names; subgraph.GetOutsideCompilationSubgraphNames(&outside_compilation_names); std::unordered_set<string> recv_at_host_names; for (const auto& oc_name : outside_compilation_names) { Node* recv_node = subgraph.GetRecvAtHostNode(oc_name); if (recv_node != nullptr) { recv_at_host_names.insert(recv_node->name()); } } // For each send_from_host node, do as much shape inference as possible // without knowing the shape of the recv_at_host nodes, and store the // result, along with enough information to complete the job at compile time // once the recv_at_host shapes are known. for (const auto& oc_name : outside_compilation_names) { Node* send_node = subgraph.GetSendFromHostNode(oc_name); std::vector<TensorShapeProto> static_shape; std::unique_ptr<Graph> graph; if (send_node != nullptr) { TF_RETURN_IF_ERROR(DoStaticShapeInferenceForOutsideCompilationSend( *pruned_graph, back_edge_helper, shape_refiner, recv_at_host_names, node_images[send_node], library, &static_shape, &graph)); if (graph == nullptr) { VLOG(2) << "Send node " << send_node->name() << " shapes"; for (int i = 0; i < static_shape.size(); ++i) { VLOG(2) << static_shape[i].DebugString(); } } else { if (VLOG_IS_ON(2)) { GraphDef graphdef; graph->ToGraphDef(&graphdef); VLOG(2) << "Send node " << send_node->name() << " graph\n" << graphdef.DebugString(); } } } TF_RETURN_IF_ERROR(subgraph.AddShapeInferenceInfo( subgraph_name, oc_name, static_shape, graph.get(), library)); } if (!outside_compilation_names.empty()) { TF_RETURN_IF_ERROR(subgraph.ReplaceFunctionDef(library)); } } return Status::OK(); } Status Encapsulator::BuildOutputGraph(Graph* graph_out, FunctionLibraryDefinition* library) { // Map from nodes in the input graph to nodes in the output graph. std::unordered_map<const Node*, Node*> node_images; TF_RETURN_IF_ERROR(CopyNodesToOutputGraph(graph_out, &node_images)); TF_RETURN_IF_ERROR(AddFunctionCallNodes(node_images, graph_out)); TF_RETURN_IF_ERROR(AddOutsideCompilationHostIONodes(node_images, graph_out)); TF_RETURN_IF_ERROR(AddEdgesToOutputGraph(node_images, graph_out)); TF_RETURN_IF_ERROR( GetShapeInfoForOutsideCompilationSends(graph_out, library)); return Status::OK(); } } // anonymous namespace Status EncapsulateSubgraphsInFunctions( string group_attribute, string outside_compilation_attribute, const Graph& graph_in, const RewriteSubgraphFn& rewrite_subgraph_fn, bool reuse_existing_functions, std::unique_ptr<Graph>* graph_out, FunctionLibraryDefinition* library) { Status s; Encapsulator encapsulator(std::move(group_attribute), std::move(outside_compilation_attribute), &graph_in); TF_RETURN_IF_ERROR(encapsulator.FindClusterDependencies()); TF_RETURN_IF_ERROR(encapsulator.SplitIntoSubgraphs()); TF_RETURN_IF_ERROR(encapsulator.BuildFunctionDefs( rewrite_subgraph_fn, reuse_existing_functions, library)); std::unique_ptr<Graph> out(new Graph(library)); out->set_versions(graph_in.versions()); TF_RETURN_IF_ERROR(encapsulator.BuildOutputGraph(out.get(), library)); *graph_out = std::move(out); return Status::OK(); } // Finds the types of the _Arg nodes, indexed by position. static Status GetArgTypes(const Graph& graph, DataTypeVector* types) { for (Node* n : graph.op_nodes()) { if (n->type_string() == kArgOp) { int index; TF_RETURN_IF_ERROR(GetNodeAttr(n->attrs(), "index", &index)); if (index < 0 || index >= types->size()) { return errors::InvalidArgument("Invalid argument number"); } (*types)[index] = n->output_type(0); } } return Status::OK(); } // Renumber the indices of _Arg nodes in a graph, according to // 'permutation' that maps old indices to new indices. static Status RenumberArguments(Graph* graph, const std::vector<int>& permutation) { for (Node* n : graph->op_nodes()) { if (n->type_string() == kArgOp) { int index; TF_RETURN_IF_ERROR(GetNodeAttr(n->attrs(), "index", &index)); if (index < 0 || index >= permutation.size()) { return errors::InvalidArgument("Invalid argument number"); } n->AddAttr("index", permutation[index]); } } return Status::OK(); } Status EncapsulateSubgraphsPass::Run( const GraphOptimizationPassOptions& options) { VLOG(1) << "EncapsulateSubgraphsPass::Run"; if (VLOG_IS_ON(1)) { dump_graph::DumpGraphToFile("before_encapsulate_subgraphs", **options.graph, options.flib_def); } std::unique_ptr<Graph> graph_out; FunctionLibraryDefinition* const library = options.flib_def; OptimizerOptions opts; std::unique_ptr<ProcessFunctionLibraryRuntime> pflr( new ProcessFunctionLibraryRuntime(nullptr, options.session_options->env, TF_GRAPH_DEF_VERSION, library, opts)); FunctionLibraryRuntime* flr = pflr->GetFLR(ProcessFunctionLibraryRuntime::kDefaultFLRDevice); auto rewrite_subgraph = [flr](const std::vector<OutputTensor>& arg_source_tensors, std::unique_ptr<Graph>* subgraph, std::vector<int>* input_permutation, std::vector<int>* output_permutation, NodeDef* node) { // Optimize the subgraph. OptimizeGraph(flr, subgraph); const int num_args = input_permutation->size(); std::vector<bool> const_args(num_args); TF_RETURN_IF_ERROR(BackwardsConstAnalysis(**subgraph, &const_args)); DataTypeVector arg_types(num_args); TF_RETURN_IF_ERROR(GetArgTypes(**subgraph, &arg_types)); // Compute a permutation of the arguments such that the constant // arguments are first. const int num_consts = std::count(const_args.begin(), const_args.end(), true); const int num_resources = std::count(arg_types.begin(), arg_types.end(), DT_RESOURCE); const int num_nonconsts = num_args - num_resources - num_consts; if (num_nonconsts < 0) { return errors::Internal("num_nonconsts should be >= 0, was ", num_nonconsts); } int const_pos = 0; int arg_pos = num_consts; int resource_pos = num_consts + num_nonconsts; for (int i = 0; i < num_args; ++i) { if (const_args[i]) { if (arg_types[i] == DT_RESOURCE) { return errors::Internal( "Resource arguments cannot be constant (argument ", i, ")"); } (*input_permutation)[i] = const_pos; ++const_pos; } else if (arg_types[i] == DT_RESOURCE) { (*input_permutation)[i] = resource_pos; ++resource_pos; } else { (*input_permutation)[i] = arg_pos; ++arg_pos; } } // Renumber argument nodes in the graph. TF_RETURN_IF_ERROR( RenumberArguments(subgraph->get(), *input_permutation)); // TODO(phawkins): add a forward is-constant analysis, similarly split // outputs into host-memory constants and device-memory non-constants. AddNodeAttr(kXlaCompiledKernelAttr, true, node); AddNodeAttr(kXlaNumConstantArgsAttr, num_consts, node); AddNodeAttr(kXlaNumResourceArgsAttr, num_resources, node); return Status::OK(); }; TF_RETURN_WITH_CONTEXT_IF_ERROR( EncapsulateSubgraphsInFunctions( kXlaClusterAttr, kXlaOutsideCompilationAttr, **options.graph, rewrite_subgraph, /*reuse_existing_functions=*/false, &graph_out, library), "EncapsulateSubgraphsPass failed"); if (VLOG_IS_ON(1)) { dump_graph::DumpGraphToFile("after_encapsulate_subgraphs", *graph_out, options.flib_def); } *options.graph = std::move(graph_out); return Status::OK(); } bool IsXlaCompiledKernel(const Node& node) { bool is_compiled = false; bool has_compilation_attr = GetNodeAttr(node.attrs(), kXlaCompiledKernelAttr, &is_compiled).ok() && is_compiled; return has_compilation_attr ? is_compiled : false; } } // namespace tensorflow
{ "content_hash": "c1e8517c231ac0cda7965190902e8fe9", "timestamp": "", "source": "github", "line_count": 2539, "max_line_length": 85, "avg_line_length": 42.34186687672312, "alnum_prop": 0.6634141350250219, "repo_name": "caisq/tensorflow", "id": "b3a1c19c9e555161ec64aae46bfd4deb6b05e9ff", "size": "108174", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tensorflow/compiler/jit/encapsulate_subgraphs_pass.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "9258" }, { "name": "C", "bytes": "309340" }, { "name": "C++", "bytes": "44750055" }, { "name": "CMake", "bytes": "206817" }, { "name": "Go", "bytes": "1163781" }, { "name": "HTML", "bytes": "4680032" }, { "name": "Java", "bytes": "795866" }, { "name": "Jupyter Notebook", "bytes": "2266715" }, { "name": "LLVM", "bytes": "6536" }, { "name": "Makefile", "bytes": "52050" }, { "name": "Objective-C", "bytes": "15650" }, { "name": "Objective-C++", "bytes": "99265" }, { "name": "PHP", "bytes": "2140" }, { "name": "Perl", "bytes": "7536" }, { "name": "PureBasic", "bytes": "25356" }, { "name": "Python", "bytes": "38665761" }, { "name": "Ruby", "bytes": "533" }, { "name": "Shell", "bytes": "447966" }, { "name": "Smarty", "bytes": "6870" } ], "symlink_target": "" }
export as namespace cloudinary; /****************************** Constants *************************************/ type CropMode = string | "scale" | "fit" | "limit" | "mfit" | "fill" | "lfill" | "pad" | "lpad" | "mpad" | "crop" | "thumb" | "imagga_crop" | "imagga_scale"; type Gravity = string | "north_west" | "north" | "north_east" | "west" | "center" | "east" | "south_west" | "south" | "south_east" | "xy_center" | "face" | "face:center" | "face:auto" | "faces" | "faces:center" | "faces:auto" | "body" | "body:face" | "adv_face" | "adv_faces" | "adv_eyes" | "custom" | "custom:face" | "custom:faces" | "custom:adv_face" | "custom:adv_faces" | "auto" | "auto:adv_face" | "auto:adv_faces" | "auto:adv_eyes" | "auto:body" | "auto:face" | "auto:faces" | "auto:custom_no_override" | "auto:none"; type ImageFileExtension = string | "jpg" | "jpe" | "jpeg" | "jpc" | "jp2" | "j2k" | "wdp" | "jxr" | "hdp" | "png" | "gif" | "webp" | "bmp" | "tif" | "tiff" | "ico" | "pdf" | "ps" | "ept" | "eps" | "eps3" | "psd" | "svg" | "ai" | "djvu" | "flif"; type VideoFileExtension = string | "webm" | "mp4" | "ogv" | "flv" | "m3u8"; type Angle = number | string | Array<number | string> | "auto_right" | "auto_left" | "ignore" | "vflip" | "hflip"; type ColorSpace = string | "srgb" | "no_cmyk"; type ImageFlags = string | Array<string> | "any_format" | "attachment" | "awebp" | "clip" | "cutter" | "force_strip" | "ignore_aspect_ratio" | "keep_iptc" | "layer_apply" | "lossy" | "preserve_transparency" | "png8" | "progressive" | "rasterize" | "region_relative" | "relative" | "strip_profile" | "text_no_trim" | "no_overflow" | "tiled"; type VideoFlags = string | Array<string> | "splice" | "layer_apply" | "no_stream" | "truncate_ts" | "waveform"; type AudioCodec = string | "none" | "aac" | "vorbis" | "mp3"; type AudioFrequency = number | 8000 | 11025 | 16000 | 22050 | 32000 | 37800 | 44056 | 44100 | 47250 | 48000 | 88200 | 96000 | 176400 | 192000; type StreamingProfiles = string | "4k" | "full_hd" | "hd" | "sd" | "full_hd_wifi" | "full_hd_lean" | "hd_lean"; export function crc32(str: string): any; export function utf8_encode(argString: string): any; export class Util { static allStrings(list: Array<any>): boolean; static camelCase(text: string): string; static convertKeys(source: Object, converter?: (value: any) => any): Object; static defaults(target: Object, object1?: any, ...objectN: any[]): Object; static snakeCase(source: string): string; static without(array: Array<any>, item: any): Array<any>; static isNumberLike(value: any): boolean; static withCamelCaseKeys(source: Object): Object; static smartEscape(text: string, unsafe: string | RegExp): string; static withSnakeCaseKeys(source: Object): Object; static hasClass(element: Element, name: string): boolean; static addClass(element: Element, name: string): void; static getAttribute(element: Element, name: string): string; static setAttribute(element: Element, name: string, value: any): void; static removeAttribute(element: Element, name: string): void; static setAttributes(element: Element, attributes: Array<any>): any; static getData(element: Element, name: string): any; static setData(element: Element, name: string, value: any): void; static width(element: Element): number; static isString(value: any): boolean; static isArray(obj: any): boolean; static isEmpty(value: any): boolean; static assign(target: Object, object1?: any, ...objectN: any[]): any; static merge(target: Object, object1?: any, ...objectN: any[]): any; static cloneDeep(value: any): any; static compact(array: Array<any>): Array<any>; static contains(collection: Array<any>, item: any): boolean; static difference(array: Array<any>, values: Array<any>): Array<any>; static isFunction(value: any): boolean; static functions(object: any): Array<any>; static identity(value: any): any; static isPlainObject(value: any): boolean; static trim(text: string): string; } /** * Represents a single transformation. * @class Transformation * @example * t = new cloudinary.Transformation(); * t.angle(20).crop("scale").width("auto"); * * // or * * t = new cloudinary.Transformation( {angle: 20, crop: "scale", width: "auto"}); */ export class Transformation { constructor(options?: Transformation.Options); static "new"(options?: Transformation.Options): Transformation; /** * Return an options object that can be used to create an identical Transformation * @function Transformation#toOptions * @return {Object} Returns a plain object representing this transformation */ toOptions(): Object; /** * Get the value associated with the given name. * @function Transformation#getValue * @param {string} name - the name of the parameter * @return {*} the processed value associated with the given name * @description Use {@link get}.origValue for the value originally provided for the parameter */ getValue(name: string): any; /** * Get the parameter object for the given parameter name * @function Transformation#get * @param {string} name the name of the transformation parameter * @returns {Param} the param object for the given name, or undefined */ get(name: string): any; /** * Remove a transformation option from the transformation. * @function Transformation#remove * @param {string} name - the name of the option to remove * @return {*} Returns the option that was removed or null if no option by that name was found. The type of the * returned value depends on the value. */ remove(name: string): any; /** * Return an array of all the keys (option names) in the transformation. * @return {Array<string>} the keys in snakeCase format */ keys(): Array<string>; /** * Returns a plain object representation of the transformation. Values are processed. * @function Transformation#toPlainObject * @return {Object} the transformation options as plain object */ toPlainObject(): Object; /** * Returns the value of "overlay" if it exists, otherwise returns the value of "underlay" */ hasLayer(): any; /** * Generate a string representation of the transformation. * @return {string } Returns the transformation as a string */ serialize(): string; /** * Combines all propoerties from source transformation into this one * @param source transformation to copy * @return this transforamtion */ fromTransformation(source: Transformation): Transformation; /** * Returns attributes for an HTML tag. * @return PlainObject */ toHtmlAttributes(): Object; /** * Complete the current transformation and chain to a new one. * In the URL, transformations are chained together by slashes. * @function Transformation#chain * @return {Transformation} Returns this transformation for chaining * @example * var tr = cloudinary.Transformation.new(); * tr.width(10).crop('fit').chain().angle(15).serialize() * // produces "c_fit,w_10/a_15" */ chain(): Transformation; /** * Resets this transformation to an empty one */ resetTransformations(): Transformation; "if"(): Condition; // Create a condition "if"(condition?: string): Transformation; // Create a condition "else"(): Transformation; // Separator for setting the desired transformation for an "if" branch in case of falsy condition endIf(): Transformation; // End condition /** * Transformation methods */ angle(value: Angle): Transformation; // degrees or mode audioCodec(value: AudioCodec): Transformation; audioFrequency(value: AudioFrequency): Transformation; aspectRatio(value: string | number): Transformation; // ratio or percent, e.g. 1.5 or 16:9 background(value: string): Transformation; // color, e.g. "blue" or "rgb:9090ff" border(value: string): Transformation; // style, e.g. "6px_solid_rgb:00390b60" color(value: string): Transformation; // e.g. "red" or "rgb:20a020" colorSpace(value: ColorSpace): Transformation; crop(value: CropMode): Transformation; defaultImage(value: string): Transformation; // public id of an uploaded image delay(value: string): Transformation; density(value: number): Transformation; // Control the density to use while converting a PDF document to images. (range: 50-300, default: 150) dpr(value: "auto" | number): Transformation; // Deliver the image in the specified device pixel ratio. The parameter accepts any positive float value effect(value: string | Array<string | number>): Transformation; // name and value, e.g. hue:40 fetchFormat(value: "auto" | ImageFileExtension): Transformation; format(value: ImageFileExtension): Transformation; flags(value: ImageFlags | string): Transformation; // Set one or more flags that alter the default transformation behavior. Separate multiple flags with a dot (`.`). gravity(value: Gravity): Transformation; // The last any covers auto:50 which is cropping algorithm aggresiveness and future proofing height(value: number): Transformation; // Number of pixels or height % htmlHeight(value: string): Transformation; htmlWidth(value: string): Transformation; opacity(value: number): Transformation; // percent, 0-100 overlay(value: string): Transformation; // Identifier, e.g. "text:Arial_50:Smile!", or public id of a different resource page(value: number): Transformation; // Given a multi-page file (PDF, animated GIF, TIFF), generate an image of a single page using the given index. prefix(value: string): Transformation; quality(value: string | number): Transformation; // percent or percent[:chroma_subsampling] or auto[:quality_level] radius(value: "max" | number): Transformation; // pixels or max rawTransformation(value: any): Transformation; size(value: string): Transformation; sourceTypes(value: VideoFileExtension | Array<VideoFileExtension>): Transformation; sourceTransformation(value: Object): Transformation; // Set the transformation to apply on each source by an object with pairs of source type and source transformations to apply startOffset(value: number | string): Transformation; streamingProfile(value: string): Transformation; transformation(value: string | Array<Transformation.Options>): Transformation; // Apply a pre-defined named transformation of the given name. When using Cloudinary's client integration libraries, the 'transformation' parameter accepts an array of transformation parameters to be chained together. underlay(value: string): Transformation; // public id of an uploaded image variables(value: [[string]]): Transformation; videoCodec(value: string | Object): Transformation; // Select the video codec and control the video content of the profile used. Can be provided in the form <codec>[:<profile>:[<level>]] to specify specific values to apply for video codec, profile and level, e.g. "h264:baseline:3.1". Also accepts a hash of values such as { codec: 'h264', profile: 'basic', level: '3.1' } videoSampling(value: number | string): Transformation; // Integer - The total number of frames to sample from the original video. String - The number of seconds between each frame to sample from the original video. e.g. 2.3s takes one frame every 2.3 seconds. width(value: string | number): Transformation; // Number of pixels, width % or "auto" with rounding step x(value: number): Transformation; // pixels or percent y(value: number): Transformation; // pixels or percent zoom(value: number): Transformation; // percent toHtml(): string; // Returns the string representation of this transformation // Video options bitRate(value: number | string): Transformation; // Advanced control of video bitrate in bits per second. By default the video uses a variable bitrate (VBR), with this value indicating the maximum bitrate. If constant is specified, the video plays with a constant bitrate (CBR). // Supported codecs: h264, h265(MPEG - 4); vp8, vp9(WebM). duration(value :number | string): Transformation; // Float or string endOffset(value: number | string): Transformation; // Float or string fallbackContent(value: string): Transformation; keyframeInterval(value: number): Transformation; offset(value: string): Transformation; // [float, float] or [string, string] or a range. Shortcut to set video cutting using a combination of start_offset and end_offset values poster(value: string | Object): Transformation; sourceType(value: string): Transformation; } export class Condition { /** * Represents a transformation condition * @param {string} conditionStr - a condition in string format * @class Condition * @example * // normally this class is not instantiated directly */ constructor(conditionStr: string); static "new"(conditionStr: string): Condition; "and"(): Condition; // Add terms to the condition "or"(): Condition; // Add terms to the condition "then"(): Transformation; // Separator for setting the desired transformation for an "if" branch in case of truthy condition /** * @function Condition#height * @param {string} operator the comparison operator (e.g. "<", "lt") * @param {string|number} value the right hand side value * @return {Condition} this condition */ height(operator: string, value: string | number): Condition; /** * @function Condition#width * @param {string} operator the comparison operator (e.g. "<", "lt") * @param {string|number} value the right hand side value * @return {Condition} this condition */ width(operator: string, value: string | number): Condition; /** * @function Condition#aspectRatio * @param {string} operator the comparison operator (e.g. "<", "lt") * @param {string|number} value the right hand side value * @return {Condition} this condition */ aspectRatio(operator: string, value: string | number): Condition; /** * @function Condition#pageCount * @param {string} operator the comparison operator (e.g. "<", "lt") * @param {string|number} value the right hand side value * @return {Condition} this condition */ pageCount(operator: string, value: string | number): Condition; /** * @function Condition#faceCount * @param {string} operator the comparison operator (e.g. "<", "lt") * @param {string|number} value the right hand side value * @return {Condition} this condition */ faceCount(operator: string, value: string | number): Condition; } export namespace Transformation { export interface Options extends Configuration.Options { angle?: Angle; // degrees or mode aspectRatio?: string | number | string; // ratio or percent, e.g. 1.5 or 16:9 background?: string; // color, e.g. "blue" or "rgb:9090ff" border?: string; // style, e.g. "6px_solid_rgb:00390b60" color?: string; // e.g. "red" or "rgb:20a020" colorSpace?: ColorSpace; crop?: CropMode, defaultImage?: string; // public id of an uploaded image delay?: string; density?: number | string; // Control the density to use while converting a PDF document to images. (range: 50-300, default: 150) dpr?: number | string; // Deliver the image in the specified device pixel ratio. The parameter accepts any positive float value effect?: string | Array<string | number>; // name and value, e.g. hue:40 fetchFormat?: ImageFileExtension; format?: ImageFileExtension; flags?: ImageFlags | string; // Set one or more flags that alter the default transformation behavior. Separate multiple flags with a dot (`.`). gravity?: Gravity; // The last any covers auto:50 which is cropping algorithm aggresiveness and future proofing height?: number | string; // Number of pixels or height % htmlHeight?: string; htmlWidth?: string; "if"?: string; // Apply a transformation only if a specified condition is met (see the conditional transformations documentation). "else"?: string; endIf?: string; opacity?: number | string; // percent, 0-100 overlay?: string | string; // Identifier, e.g. "text:Arial_50:Smile!", or public id of a different resource page?: number | string; // Given a multi-page file (PDF, animated GIF, TIFF), generate an image of a single page using the given index. prefix?: string; quality?: string | number; // percent or percent[:chroma_subsampling] or auto[:quality_level] radius?: number | string; // pixels or max rawTransformation?: any; size?: string; transformation?: string | Array<Transformation.Options>; // Apply a pre-defined named transformation of the given name. When using Cloudinary's client integration libraries, the 'transformation' parameter accepts an array of transformation parameters to be chained together. underlay?: string; // public id of an uploaded image variables?: [[string, any]]; width?: string | number; // Number of pixels, width % or "auto" with rounding step x?: number | string; // pixels or percent y?: number | string; // pixels or percent zoom?: number | string; // percent [futureKey: string]: any; } interface VideoOptions extends Transformation.Options { audioCodec?: AudioCodec; audioFrequency?: AudioFrequency; bitRate?: number | string; // Advanced control of video bitrate in bits per second. By default the video uses a variable bitrate (VBR), with this value indicating the maximum bitrate. If constant is specified, the video plays with a constant bitrate (CBR). // Supported codecs: h264, h265(MPEG - 4); vp8, vp9(WebM). duration?: number | string; // Float or string endOffset?: number | string; // Float or string fallbackContent?: string; flags?: VideoFlags; keyframeInterval?: number; offset?: string, // [float, float] or [string, string] or a range. Shortcut to set video cutting using a combination of start_offset and end_offset values poster?: string | Object, sourceType?: string; sourceTransformation?: string; startOffset?: number | string; // Float or string streamingProfile?: StreamingProfiles videoCodec?: string | Object; // Select the video codec and control the video content of the profile used. Can be provided in the form <codec>[:<profile>:[<level>]] to specify specific values to apply for video codec, profile and level, e.g. "h264:baseline:3.1". Also accepts a hash of values such as { codec: 'h264', profile: 'basic', level: '3.1' } videoSampling?: number | string; // Integer - The total number of frames to sample from the original video. The frames are spread out over the length of the video, e.g. 20 takes one frame every 5% -- OR -- String - The number of seconds between each frame to sample from the original video. e.g. 2.3s takes one frame every 2.3 seconds. } } /** * Cloudinary configuration class * @constructor Configuration * @param {Object} options - configuration parameters */ export class Configuration { constructor(options?: Configuration.Options); init(): Configuration; set(name: string, value?: any): Configuration; get(name: string): any; merge(config?: Object): Configuration; /** * Initialize Cloudinary from HTML meta tags. * @function Configuration#fromDocument * @return {Configuration} * @example <meta name="cloudinary_cloud_name" content="mycloud"> * */ fromDocument(): Configuration; fromEnvironment(): Configuration; toOptions(): Object; } /** * Represents an HTML (DOM) tag * @constructor HtmlTag * @param {string} name - the name of the tag * @param {string} [publicId] * @param {Object} options * @example tag = new HtmlTag( 'div', { 'width': 10}) */ export class HtmlTag { constructor(name: string, publicId?: string, options?: Transformation.Options); constructor(name: string, options?: Transformation.Options); static "new"(name: string, publicId?: string, options?: Transformation.Options): HtmlTag; static "new"(name: string, options?: Transformation.Options): HtmlTag; getOptions(): Object; getOption(name: string): any; attributes(): Object; setAttr(name: string, value: string): void; getAttr(name: string): string; removeAttr(name: string): string; content(): string; openTag(): string; closeTag(): string; toHtml(): string; toDOM(): Element; isResponsive(): boolean; transformation(): Transformation; } /** * Creates an HTML (DOM) Image tag using Cloudinary as the source. * @constructor ImageTag * @extends HtmlTag * @param {string} [publicId] * @param {Object} [options] */ export class ImageTag extends HtmlTag { static "new"(publicId: string, options?: Transformation.Options): ImageTag; static "new"(name: string, publicId: string, options?: Transformation.Options): ImageTag; } /** * Creates an HTML (DOM) Video tag using Cloudinary as the source. * @constructor VideoTag * @extends HtmlTag * @param {string} [publicId] * @param {Object} [options] */ export class VideoTag extends HtmlTag { static "new"(publicId: string, options?: Transformation.VideoOptions): VideoTag; static "new"(name: string, publicId: string, options?: Transformation.Options): VideoTag; /** * Set the transformation to apply on each source * @function VideoTag#setSourceTransformation * @param {Object} value an object with pairs of source type and source transformation * @returns {VideoTag} Returns this instance for chaining purposes. */ setSourceTransformation(value: Object): VideoTag; /** * Set the source types to include in the video tag * @function VideoTag#setSourceTypes * @param {Array<string>} sourceTypes an array of source types * @returns {VideoTag} Returns this instance for chaining purposes. */ setSourceTypes(sourceTypes: VideoFileExtension | Array<VideoFileExtension>): VideoTag; /** * Set the poster to be used in the video tag * @function VideoTag#setPoster * @param {string|Object} poster * - string: a URL to use for the poster * - Object: transformation parameters to apply to the poster. May optionally include a public_id to use instead of the video public_id. * @returns {VideoTag} Returns this instance for chaining purposes. */ setPoster(poster: string | Object): VideoTag; /** * Set the content to use as fallback in the video tag * @function VideoTag#setFallbackContent * @param {string} fallbackContent - the content to use, in HTML format * @returns {VideoTag} Returns this instance for chaining purposes. */ setFallbackContent(fallbackContent: string): VideoTag; /** * Returns the HTML for the child <source> elements of this video */ content(): string; } /** * Creates an HTML (DOM) Meta tag that enables client-hints. * @constructor ClientHintsMetaTag * @extends HtmlTag */ export class ClientHintsMetaTag extends HtmlTag { constructor (options?: Transformation.Options); } /**************************************** Layers section ************************************/ export class Layer { /** * Layer * @constructor Layer * @param {Object} options - layer parameters */ constructor(options?: Layer.Options); /** Setters */ resourceType(value: string): Layer; type(value: string): Layer; publicId(value: string): Layer; format(value: string): Layer; /** Getters */ getPublicId(): string; getFullPublicId(): string; toString(): string; } export namespace Layer { export interface Options { resourceType?: string; type?: string; publicId?: string; format?: string; } } /** * @constructor TextLayer * @param {Object} options - layer parameters */ export class TextLayer extends Layer { constructor (options?: TextLayer.Options); /** Setters */ fontFamily(value: string): TextLayer; fontSize(value: number): TextLayer; fontWeight(value: string): TextLayer; fontStyle(value: string): TextLayer; textDecoration(value: string): TextLayer; textAlign(value: string): TextLayer; stroke(value: string): TextLayer; letterSpacing(value: number): TextLayer; lineSpacing(value: number): TextLayer; text(value: string): TextLayer; /** Getters */ toString(): string; textStyleIdentifier(): Array<string>; } export namespace TextLayer { export interface Options { resourceType?: string; fontFamily?: string; fontSize?: number; fontWeight?: string; fontStyle?: string; textDecoration?: string; textAlign?: string; stroke?: string; letterSpacing?: number; lineSpacing?: number; text?: string; } } /** * Represent a subtitles layer * @constructor SubtitlesLayer * @param {Object} options - layer parameters */ export class SubtitlesLayer extends TextLayer { constructor (options: TextLayer.Options); } export class Param { constructor (name: string, shortName?: string, process?: (value: any) => any); /** * Set a (unprocessed) value for this parameter * @function Param#set * @param {*} origValue - the value of the parameter * @return {Param} self for chaining */ set(origValue: any): Param; /** * Generate the serialized form of the parameter * @function Param#serialize * @return {string} the serialized form of the parameter */ serialize(): string; /** * Return the processed value of the parameter * @function Param#value */ value(): any; /** * Replaces '#' symbols with 'rgb:' */ norm_color(): string; /** * Wraps this param in an array if it isn't already an array */ build_array(): Array<any> } /** * Main Cloudinary class * @class Cloudinary * @param {Object} options - options to configure Cloudinary * @see Configuration for more details * @example * var cl = new cloudinary.Cloudinary( { cloud_name: "mycloud"}); * var imgTag = cl.image("myPicID"); */ export class Cloudinary { constructor(options: Configuration.Options); static "new"(options: Configuration.Options): Cloudinary; /** * Generate an resource URL. * @function Cloudinary#url * @param {string} publicId - the public ID of the resource * @param {Object} [options] - options for the tag and transformations, possible values include all {@link Transformation} parameters * and {@link Configuration} parameters * @param {string} [options.type='upload'] - the classification of the resource * @param {Object} [options.resource_type='image'] - the type of the resource * @return {string} The resource URL */ url(publicId: string, options?: Transformation | Transformation.Options): string; /** * Generate an video resource URL. * @function Cloudinary#video_url * @param {string} publicId - the public ID of the resource * @param {Object} [options] - options for the tag and transformations, possible values include all {@link Transformation} parameters * and {@link Configuration} parameters * @param {string} [options.type='upload'] - the classification of the resource * @return {string} The video URL */ video_url(publicId: string, options?: Transformation | Transformation.VideoOptions): string; /** * Generate an image tag. * @function Cloudinary#image * @param {string} publicId - the public ID of the image * @param {Object} [options] - options for the tag and transformations * @return {HTMLImageElement} an image tag element */ image(publicId: string, options?: Transformation | Transformation.Options): HTMLImageElement; /** * Generate an video thumbnail URL. * @function Cloudinary#video_thumbnail_url * @param {string} publicId - the public ID of the resource * @param {Object} [options] - options for the tag and transformations, possible values include all {@link Transformation} parameters * and {@link Configuration} parameters * @param {string} [options.type='upload'] - the classification of the resource * @return {string} The video thumbnail URL */ video_thumbnail_url(publicId: string, options?: Transformation | Transformation.VideoOptions): string; /** * Generate a string representation of the provided transformation options. * @function Cloudinary#transformation_string * @param {Object} options - the transformation options * @returns {string} The transformation string */ transformation_string(options: Transformation | Transformation.Options): string; /** * Generate an image tag. * @function Cloudinary#image * @param {string} publicId - the public ID of the image * @param {Object} [options] - options for the tag and transformations * @return {HTMLImageElement} an image tag element */ image(publicId: string, options?: Transformation | Transformation.Options): HTMLImageElement; /** * Creates a new ImageTag instance, configured using this own's configuration. * @function Cloudinary#imageTag * @param {string} publicId - the public ID of the resource * @param {Object} options - additional options to pass to the new ImageTag instance * @return {ImageTag} An ImageTag that is attached (chained) to this Cloudinary instance */ imageTag(publicId: string, options?: Transformation | Transformation.Options): ImageTag; /** * Generate an image tag for the video thumbnail. * @function Cloudinary#video_thumbnail * @param {string} publicId - the public ID of the video * @param {Object} [options] - options for the tag and transformations * @return {HTMLImageElement} An image tag element */ video_thumbnail(publicId: string, options?: Transformation | Transformation.Options): HTMLImageElement; /** * @function Cloudinary#facebook_profile_image * @param {string} publicId - the public ID of the image * @param {Object} [options] - options for the tag and transformations * @return {HTMLImageElement} an image tag element */ facebook_profile_image(publicId: string, options?: Transformation | Transformation.Options): HTMLImageElement; /** * @function Cloudinary#twitter_profile_image * @param {string} publicId - the public ID of the image * @param {Object} [options] - options for the tag and transformations * @return {HTMLImageElement} an image tag element */ twitter_profile_image(publicId: string, options?: Transformation | Transformation.Options): HTMLImageElement; /** * @function Cloudinary#twitter_name_profile_image * @param {string} publicId - the public ID of the image * @param {Object} [options] - options for the tag and transformations * @return {HTMLImageElement} an image tag element */ twitter_name_profile_image(publicId: string, options?: Transformation | Transformation.Options): HTMLImageElement; /** * @function Cloudinary#gravatar_image * @param {string} publicId - the public ID of the image * @param {Object} [options] - options for the tag and transformations * @return {HTMLImageElement} an image tag element */ gravatar_image(publicId: string, options?: Transformation | Transformation.Options): HTMLImageElement; /** * @function Cloudinary#fetch_image * @param {string} publicId - the public ID of the image * @param {Object} [options] - options for the tag and transformations * @return {HTMLImageElement} an image tag element */ fetch_image(publicId: string, options?: Transformation | Transformation.Options): HTMLImageElement; /** * @function Cloudinary#video * @param {string} publicId - the public ID of the video * @param {Object} [options] - options for the tag and transformations * @return {string} The generated <video> tag and its descendants */ video(publicId: string, options?: Transformation | Transformation.VideoOptions): string; /** * Creates a new VideoTag instance, configured using this own's configuration. * @function Cloudinary#videoTag * @param {string} publicId - the public ID of the resource * @param {Object} options - additional options to pass to the new VideoTag instance * @return {VideoTag} A VideoTag that is attached (chained) to this Cloudinary instance */ videoTag(publicId: string, options?: Transformation | Transformation.VideoOptions): VideoTag; /** * Generate the URL of the sprite image * @function Cloudinary#sprite_css * @param {string} publicId - the public ID of the resource * @param {Object} [options] - options for the tag and transformations * @see {@link http://cloudinary.com/documentation/sprite_generation Sprite generation} */ sprite_css(publicId: string, options?: Transformation | Transformation.Options): string; /** * Initialize the responsive behaviour.<br> * Calls {@link Cloudinary#cloudinary_update} to modify image tags. * @function Cloudinary#responsive * @param {Object} options * @param {String} [options.responsive_class='cld-responsive'] - provide an alternative class used to locate img tags * @param {number} [options.responsive_debounce=100] - the debounce interval in milliseconds. * @param {boolean} [bootstrap=true] if true processes the img tags by calling cloudinary_update. When false the tags will be processed only after a resize event. * @see {@link Cloudinary#cloudinary_update} for additional configuration parameters */ responsive(options?: Transformation | Transformation.Options, bootstrap?: boolean): void; /** * Update hidpi (dpr_auto) and responsive (w_auto) fields according to the current container size and the device pixel ratio. * Only images marked with the cld-responsive class have w_auto updated. * @function Cloudinary#cloudinary_update * @param {(Array|string|NodeList)} elements - the elements to modify * @param {Object} options * @param {boolean|string} [options.responsive_use_breakpoints=true] * - when `true`, always use breakpoints for width * - when `"resize"` use exact width on first render and breakpoints on resize * - when `false` always use exact width * @param {boolean} [options.responsive] - if `true`, enable responsive on this element. Can be done by adding cld-responsive. * @param {boolean} [options.responsive_preserve_height] - if set to true, original css height is preserved. * Should only be used if the transformation supports different aspect ratios. */ cloudinary_update(elements: Array<string> | NodeList, options?: Transformation | Transformation.Options): Cloudinary; /** * Provide a transformation object, initialized with own's options, for chaining purposes. * @function Cloudinary#transformation * @param {Object} options * @return {Transformation} */ transformation(options?: Transformation | Transformation.Options): Transformation; } export const VERSION: string; export namespace Configuration { export interface Options { responsive_class?: string; responsive_use_breakpoints?: boolean; responsive_debounce?: number; // The debounce interval in milliseconds, default is 100 round_dpr?: boolean; secure?: boolean; // Default value is based on window.location.protocol api_key?: string; api_secret?: string; cdn_subdomain?: boolean; cloud_name?: string; cname?: string; private_cdn?: boolean; protocol?: string; resource_type?: string; responsive?: boolean; responsive_width?: string; secure_cdn_subdomain?: boolean; secure_distribution?: boolean; shorten?: string; type?: string; url_suffix?: string; use_root_path?: boolean; version?: string; static_image_support?: string; enhance_image_tag?: boolean; [futureKey: string]: any; } }
{ "content_hash": "9b97fcd2043178b2969bd0f6a431dbd8", "timestamp": "", "source": "github", "line_count": 808, "max_line_length": 376, "avg_line_length": 45.78217821782178, "alnum_prop": 0.6733618079584776, "repo_name": "phannh58/project", "id": "6093b138bf4fa922e368c4fbb029ac84974d3f01", "size": "36992", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/components/cloudinary-core/cloudinary-core.d.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "147184" }, { "name": "HTML", "bytes": "104989" }, { "name": "JavaScript", "bytes": "2914604" }, { "name": "PowerShell", "bytes": "471" }, { "name": "Ruby", "bytes": "1030" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using Newtonsoft.Json; using SkyScanner.Services.Base; using System.Threading; namespace SkyScanner.Services { internal class Market : Requester<List<Data.Market>> { private readonly Data.Locale _locale; public Market(string apiKey, Data.Locale locale) : base(apiKey) { _locale = locale; } protected override Func<HttpClient, CancellationToken, Task<HttpResponseMessage>> HttpMethod { get { return (client, token) => client.GetAsync( $"http://partners.api.skyscanner.net/apiservices/reference/v1.0/countries/{_locale}?apiKey={ApiKey}", token); } } protected override List<Data.Market> CreateResponse(string content) { return JsonConvert.DeserializeObject<Response>(content, Scanner.JsonSerializerSettings).Countries; } internal class Response { internal List<Data.Market> Countries { get; set; } } } }
{ "content_hash": "aabdf15982028da2be7f90a09e28a4c0", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 121, "avg_line_length": 29.05, "alnum_prop": 0.612736660929432, "repo_name": "tamasvajk/SkyScanner", "id": "be5b1f47c77773bf25bcb58fe64a212eaa0a13ce", "size": "1316", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/SkyScanner/Services/Market.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "167" }, { "name": "C#", "bytes": "153511" } ], "symlink_target": "" }
<div class="commune_descr limited"> <p> Le&nbsp;Renouard est un village situé dans le département de l'Orne en Basse-Normandie. On dénombrait 189 habitants en 2008.</p> <p>La ville propose quelques équipements, elle propose entre autres un terrain de tennis.</p> <p>Le nombre de logements, à Le&nbsp;Renouard, se décomposait en 2011 en un appartements et 157 maisons soit un marché plutôt équilibré.</p> <p>Si vous envisagez de emmenager à Le&nbsp;Renouard, vous pourrez aisément trouver une maison à acheter. </p> <p>À coté de Le&nbsp;Renouard sont positionnées géographiquement les communes de <a href="{{VLROOT}}/immobilier/tortisambert_14696/">Tortisambert</a> à 5&nbsp;km, 141 habitants, <a href="{{VLROOT}}/immobilier/champeaux_61086/">Les&nbsp;Champeaux</a> à 3&nbsp;km, 123 habitants, <a href="{{VLROOT}}/immobilier/saint-gervais-des-sablons_61399/">Saint-Gervais-des-Sablons</a> à 2&nbsp;km, 68 habitants, <a href="{{VLROOT}}/immobilier/ecorches_61152/">Écorches</a> située à 5&nbsp;km, 98 habitants, <a href="{{VLROOT}}/immobilier/crouttes_61139/">Crouttes</a> à 2&nbsp;km, 285 habitants, <a href="{{VLROOT}}/immobilier/autels-saint-bazile_14029/">Les&nbsp;Autels-Saint-Bazile</a> située à 3&nbsp;km, 45 habitants, entre autres. De plus, Le&nbsp;Renouard est située à seulement 26&nbsp;km de <a href="{{VLROOT}}/immobilier/lisieux_14366/">Lisieux</a>.</p> </div>
{ "content_hash": "1aeab32056770e1db567a113d9c1535e", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 141, "avg_line_length": 77.33333333333333, "alnum_prop": 0.7392241379310345, "repo_name": "donaldinou/frontend", "id": "60ab98a641534b1db37857b4cf3e99150a4150d6", "size": "1420", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Viteloge/CoreBundle/Resources/descriptions/61346.html", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3073" }, { "name": "CSS", "bytes": "111338" }, { "name": "HTML", "bytes": "58634405" }, { "name": "JavaScript", "bytes": "88564" }, { "name": "PHP", "bytes": "841919" } ], "symlink_target": "" }
package com.baidu.disconf.web.web.auth; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.baidu.disconf.web.service.sign.form.SigninForm; import com.baidu.disconf.web.service.sign.service.SignMgr; import com.baidu.disconf.web.service.user.bo.User; import com.baidu.disconf.web.service.user.dto.Visitor; import com.baidu.disconf.web.service.user.form.PasswordModifyForm; import com.baidu.disconf.web.service.user.service.UserMgr; import com.baidu.disconf.web.service.user.vo.VisitorVo; import com.baidu.disconf.web.web.auth.constant.LoginConstant; import com.baidu.disconf.web.web.auth.login.RedisLogin; import com.baidu.disconf.web.web.auth.validator.AuthValidator; import com.baidu.dsp.common.annotation.NoAuth; import com.baidu.dsp.common.constant.ErrorCode; import com.baidu.dsp.common.constant.WebConstants; import com.baidu.dsp.common.controller.BaseController; import com.baidu.dsp.common.vo.JsonObjectBase; import com.baidu.ub.common.commons.ThreadContext; /** * @author liaoqiqi * @version 2014-1-20 */ @Controller @RequestMapping(WebConstants.API_PREFIX + "/account") public class UserController extends BaseController { protected static final Logger LOG = LoggerFactory.getLogger(UserController.class); @Autowired private UserMgr userMgr; @Autowired private AuthValidator authValidator; @Autowired private SignMgr signMgr; @Autowired private RedisLogin redisLogin; /** * GET 获取 * * @param * * @return */ @NoAuth @RequestMapping(value = "/session", method = RequestMethod.GET) @ResponseBody public JsonObjectBase get() { VisitorVo visitorVo = userMgr.getCurVisitor(); if (visitorVo != null) { return buildSuccess("visitor", visitorVo); } else { // 没有登录啊 return buildGlobalError("syserror.inner", ErrorCode.GLOBAL_ERROR); } } /** * 登录 * * @param signin * @param request * * @return */ @NoAuth @RequestMapping(value = "/signin", method = RequestMethod.POST) @ResponseBody public JsonObjectBase signin(@Valid SigninForm signin, HttpServletRequest request) { LOG.info(signin.toString()); //先通过LADP验证登录 if(!authValidator.validateLADPLogin(signin)) { // 验证 authValidator.validateLogin(signin); } // 数据库登录 User user = signMgr.signin(signin.getName()); // 过期时间 int expireTime = LoginConstant.SESSION_EXPIRE_TIME; if (signin.getRemember().equals(1)) { expireTime = LoginConstant.SESSION_EXPIRE_TIME2; } // redis login redisLogin.login(request, user, expireTime); VisitorVo visitorVo = userMgr.getCurVisitor(); return buildSuccess("visitor", visitorVo); } /** * 登出 * * @param request * * @return */ @NoAuth @RequestMapping(value = "/signout", method = RequestMethod.GET) @ResponseBody public JsonObjectBase signout(HttpServletRequest request) { redisLogin.logout(request); return buildSuccess("ok", "ok"); } /** * 修改密码 * * @param * * @return */ @RequestMapping(value = "/password", method = RequestMethod.PUT) @ResponseBody public JsonObjectBase password(@Valid PasswordModifyForm passwordModifyForm, HttpServletRequest request) { // 校验 authValidator.validatePasswordModify(passwordModifyForm); // 修改 Visitor visitor = ThreadContext.getSessionVisitor(); userMgr.modifyPassword(visitor.getLoginUserId(), passwordModifyForm.getNew_password()); // re login redisLogin.logout(request); return buildSuccess("修改成功,请重新登录"); } }
{ "content_hash": "efbfeaf0a98e79124b4c10f0be9b292f", "timestamp": "", "source": "github", "line_count": 155, "max_line_length": 110, "avg_line_length": 27.019354838709678, "alnum_prop": 0.6833810888252149, "repo_name": "markyao/disconf", "id": "7004697787b928865e2f753942e45b933e523067", "size": "4282", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "disconf-web/src/main/java/com/baidu/disconf/web/web/auth/UserController.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "38" }, { "name": "CSS", "bytes": "17318" }, { "name": "HTML", "bytes": "157466" }, { "name": "Java", "bytes": "870541" }, { "name": "JavaScript", "bytes": "164332" }, { "name": "Python", "bytes": "5180" }, { "name": "Shell", "bytes": "3929" }, { "name": "Smarty", "bytes": "7662" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>mathcomp-finmap: 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.14.0 / mathcomp-finmap - 1.1.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> mathcomp-finmap <small> 1.1.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-06-03 04:13:51 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-06-03 04:13:51 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 conf-gmp 4 Virtual package relying on a GMP lib system installation coq 8.14.0 Formal proof management system dune 3.2.0 Fast, portable, and opinionated build system ocaml 4.10.2 The OCaml compiler (virtual package) ocaml-base-compiler 4.10.2 Official release 4.10.2 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.3 A library manager for OCaml zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Cyril Cohen &lt;cyril.cohen@inria.fr&gt;&quot; homepage: &quot;http://www.cyrilcohen.fr&quot; bug-reports: &quot;Cyril Cohen &lt;cyril.cohen@inria.fr&gt;&quot; license: &quot;CeCILL-B&quot; build: [ make &quot;-j&quot; &quot;%{jobs}%&quot; ] install: [ make &quot;install&quot; ] depends: [ &quot;coq-mathcomp-ssreflect&quot; {&gt;= &quot;1.7.0&quot; &amp; &lt; &quot;1.8~&quot;} ] tags: [ &quot;keyword:finmap&quot; &quot;keyword:finset&quot; &quot;keyword:multiset&quot; &quot;keyword:order&quot; &quot;logpath:mathcomp.finmap&quot; ] authors: [ &quot;Cyril Cohen &lt;cyril.cohen@inria.fr&gt;&quot; ] synopsis: &quot;Finite sets, finite maps, finitely supported functions, orders&quot; description: &quot;&quot;&quot; This library is an extension of mathematical component in order to support finite sets and finite maps on choicetypes (rather that finite types). This includes support for functions with finite support and multisets. The library also contains a generic order and set libary, which will be used to subsume notations for finite sets, eventually.&quot;&quot;&quot; url { src: &quot;https://github.com/math-comp/finmap/archive/1.1.0.tar.gz&quot; checksum: &quot;md5=f8bca7e64d16fdc61bf6b09af5e0b99b&quot; } </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-mathcomp-finmap.1.1.0 coq.8.14.0</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.14.0). The following dependencies couldn&#39;t be met: - coq-mathcomp-finmap -&gt; coq-mathcomp-ssreflect &lt; 1.8~ -&gt; coq &lt; 8.10~ -&gt; ocaml &lt; 4.10 base of this switch (use `--unlock-base&#39; 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-mathcomp-finmap.1.1.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": "68ac4805ae4adeff766a3c1ae894c9b6", "timestamp": "", "source": "github", "line_count": 169, "max_line_length": 159, "avg_line_length": 41.79289940828402, "alnum_prop": 0.5473594789749399, "repo_name": "coq-bench/coq-bench.github.io", "id": "70d345e55e88b5a5efe684c5e0aea377ad2a39b9", "size": "7088", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.10.2-2.0.6/released/8.14.0/mathcomp-finmap/1.1.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<!--A Design by W3layouts Author: W3layout Author URL: http://w3layouts.com License: Creative Commons Attribution 3.0 Unported License URL: http://creativecommons.org/licenses/by/3.0/ --> <!DOCTYPE HTML> <html ng-app="yopi"> <head> <title>Yopevent - Let's watch TV together</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script> <script src="https://cdn.firebase.com/js/client/2.0.4/firebase.js"></script> <script src="https://cdn.firebase.com/libs/angularfire/0.9.0/angularfire.min.js"></script> <script type="text/javascript" src="js/app.js"></script> <link href="css/bootstrap.css" rel='stylesheet' type='text/css' /> <link rel="stylesheet" type="text/css" href="css/jquery.datetimepicker.css"/ > <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <!-- Custom Theme files --> <link href="css/style.css" rel='stylesheet' type='text/css' /> <link rel="shortcut icon" href="ico/favicon.png"> <link href="css/carousel.css" rel="stylesheet"> <!-- Custom Theme files --> <meta name="viewport" content="width=device-width, initial-scale=1"> <script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script> <!--webfont--> <link href='http://fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'> <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Ek+Mukta"> <script type="text/javascript" src="js/jquery-1.11.1.min.js"></script> <script type="text/javascript" src="js/bootstrap.js"></script> <script src="js/jquery.easydropdown.js"></script> <script src="js/wow.min.js"></script> <link href="css/animate.css" rel='stylesheet' type='text/css' /> <script> new WOW().init(); </script> </head> <body ng-controller="EventCtrl"> <div> <div ng-include src="'header.html'"></div> <div ng-include src="'faq-body.html'"></div> <div ng-include src="'footer.html'"></div> </div>
{ "content_hash": "3a3cf2c27b1ad72369a5c0adaa1eb762", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 173, "avg_line_length": 44.86666666666667, "alnum_prop": 0.7013372956909361, "repo_name": "akamaotto/yopeventweb", "id": "1cf5f464cdba789efbc78d84e903fdf5faf7e1fb", "size": "2019", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "faq.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "78986" }, { "name": "JavaScript", "bytes": "104017" } ], "symlink_target": "" }
using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using RiotSharp.Caching; using RiotSharp.Endpoints.Interfaces; using RiotSharp.Endpoints.MatchEndpoint; using RiotSharp.Http.Interfaces; using RiotSharp.Misc; using System; using System.Collections.Generic; using System.IO; using System.Text; namespace RiotSharp.Test.EndpointTests { [TestClass] public class MatchEndpointTests { private Mock<IRateLimitedRequester> _rateLimitedRequester; private IMatchEndpoint _matchEndpoint; private const string ResponsePath = "./Resources/MatchEndpoint/MatchList_EUW_Response.txt"; [TestInitialize] public void Initialize() { _rateLimitedRequester = new Mock<IRateLimitedRequester>(); _matchEndpoint = new MatchEndpoint(_rateLimitedRequester.Object, new PassThroughCache()); } [TestMethod] [Ignore] // TODO: out-of-date. public void GetMatchListAsync_GetTheListOfMatchesOfASpecificSummonerAsync_ReturnMatchList() { _rateLimitedRequester.Setup(moq => moq.CreateGetRequestAsync(It.IsAny<string>(), It.IsAny<Region>(), It.IsAny<List<string>>(), It.IsAny<bool>())).ReturnsAsync(File.ReadAllText(ResponsePath)); var matchList = _matchEndpoint.GetMatchListAsync(Region.Euw, "SummonerId").Result; Assert.IsNotNull(matchList); foreach(var matchId in matchList) { Assert.IsTrue(matchId.StartsWith("EUW1_")); } } } }
{ "content_hash": "fa8c5dca87dbff4c21687b00ebf6047d", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 112, "avg_line_length": 33.255319148936174, "alnum_prop": 0.6775431861804223, "repo_name": "JanOuborny/RiotSharp", "id": "6c8241dc6bb975a1a8090092f49a9b6da42fa33d", "size": "1565", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "RiotSharp.Test/EndpointTests/MatchEndpointTests.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "562703" } ], "symlink_target": "" }
This package ensures that your application doesn't have installed dependencies with known security vulnerabilities. ## Installation ```sh ~$ composer require roave/security-advisories:dev-master@DEV ``` ## Usage This package does not provide any API or usable classes: its only purpose is to prevent installation of software with known and documented security issues. Simply add `"roave/security-advisories": "dev-master@DEV"` to your `composer.json` `"require"` section and you will not be able to harm yourself with software with known security vulnerabilities. For example, try following: ```sh ~$ composer require roave/security-advisories:dev-master@DEV ~$ # following commands will fail: ~$ composer require symfony/symfony:2.5.2 ~$ composer require zendframework/zendframework:2.3.1 ``` ## Stability This package can only be required in its `dev-master@DEV` version: there will never be stable/tagged versions because of the nature of the problem being targeted. Security issues are in fact a moving target, and locking your project to a specific tagged version of the package would not make any sense. This package is therefore only suited for installation in the root of your deployable project. ## Sources This package extracts information about existing security issues in various composer projects from the [FriendsOfPHP/security-advisories](https://github.com/FriendsOfPHP/security-advisories) repository.
{ "content_hash": "0c53157ee83dcb9d78d644bd0308a620", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 120, "avg_line_length": 39.80555555555556, "alnum_prop": 0.7941381716678297, "repo_name": "stof/SecurityAdvisories", "id": "007c3dea33eac22b2a1f1779122a7c2e5de7ce4c", "size": "1462", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "15447" } ], "symlink_target": "" }
export = _; export as namespace _; declare const _: _.LoDashStatic; declare namespace _ { // tslint:disable-next-line no-empty-interface (This will be augmented) interface LoDashStatic {} } // Backward compatibility with --target es5 declare global { // tslint:disable-next-line:no-empty-interface interface Set<T> { } // tslint:disable-next-line:no-empty-interface interface Map<K, V> { } // tslint:disable-next-line:no-empty-interface interface WeakSet<T> { } // tslint:disable-next-line:no-empty-interface interface WeakMap<K extends object, V> { } }
{ "content_hash": "51988eb12ba2bca756c5f8bdfecd2074", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 75, "avg_line_length": 29.8, "alnum_prop": 0.6879194630872483, "repo_name": "markogresak/DefinitelyTyped", "id": "1fa09484625c1062a9f23708b52dcbbbdc808ee2", "size": "1848", "binary": false, "copies": "24", "ref": "refs/heads/master", "path": "types/lodash/index.d.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "15" }, { "name": "Protocol Buffer", "bytes": "678" }, { "name": "TypeScript", "bytes": "17426898" } ], "symlink_target": "" }
package org.hsqldb.store; import java.sql.Date; /* * implementation notes: * * NB: As of this version this class cannot be used for mixed object types * It is relativly easy to support this by adding an 'instanceof' test inside * each getOrAddXxxx method before casting the Set values to the target type * for comparison purposes. * * superclass is used as an Object Set * getOrAddXxxx methods are implemented directly for speed * the superclass infrastructure is otherwise used */ /** * Subclass of BaseHashMap for maintaining a pool of objects. Supports a * range of java.lang.* objects. * * @author fredt@users * @version 1.8.0 * @since 1.7.2 * */ public class ValuePoolHashMap extends BaseHashMap { public ValuePoolHashMap(int initialCapacity, int maxCapacity, int purgePolicy) throws IllegalArgumentException { super(initialCapacity, 1, BaseHashMap.objectKeyOrValue, BaseHashMap.noKeyOrValue, true); this.maxCapacity = maxCapacity; this.purgePolicy = purgePolicy; } /** * In rare circumstances resetCapacity may not succeed, in which case * capacity remains unchanged but purge policy is set to newPolicy */ public void resetCapacity(int newCapacity, int newPolicy) throws IllegalArgumentException { if (newCapacity != 0 && hashIndex.elementCount > newCapacity) { int surplus = hashIndex.elementCount - newCapacity; surplus += (surplus >> 5); if (surplus > hashIndex.elementCount) { surplus = hashIndex.elementCount; } clear(surplus, (surplus >> 6)); } if (newCapacity != 0 && newCapacity < threshold) { rehash(newCapacity); if (newCapacity < hashIndex.elementCount) { newCapacity = maxCapacity; } } this.maxCapacity = newCapacity; this.purgePolicy = newPolicy; } protected Integer getOrAddInteger(int intKey) { Integer testValue; int index = hashIndex.getHashIndex(intKey); int lookup = hashIndex.hashTable[index]; int lastLookup = -1; for (; lookup >= 0; lastLookup = lookup, lookup = hashIndex.getNextLookup(lookup)) { testValue = (Integer) objectKeyTable[lookup]; if (testValue.intValue() == intKey) { if (accessCount == Integer.MAX_VALUE) { resetAccessCount(); } accessTable[lookup] = accessCount++; return testValue; } } if (hashIndex.elementCount >= threshold) { reset(); return getOrAddInteger(intKey); } lookup = hashIndex.linkNode(index, lastLookup); testValue = new Integer(intKey); objectKeyTable[lookup] = testValue; if (accessCount == Integer.MAX_VALUE) { resetAccessCount(); } accessTable[lookup] = accessCount++; return testValue; } protected Long getOrAddLong(long longKey) { Long testValue; int index = hashIndex.getHashIndex((int) (longKey ^ (longKey >>> 32))); int lookup = hashIndex.hashTable[index]; int lastLookup = -1; for (; lookup >= 0; lastLookup = lookup, lookup = hashIndex.getNextLookup(lookup)) { testValue = (Long) objectKeyTable[lookup]; if (testValue.longValue() == longKey) { if (accessCount == Integer.MAX_VALUE) { resetAccessCount(); } accessTable[lookup] = accessCount++; return testValue; } } if (hashIndex.elementCount >= threshold) { reset(); return getOrAddLong(longKey); } lookup = hashIndex.linkNode(index, lastLookup); testValue = new Long(longKey); objectKeyTable[lookup] = testValue; if (accessCount == Integer.MAX_VALUE) { resetAccessCount(); } accessTable[lookup] = accessCount++; return testValue; } /** * This is dissimilar to normal hash map get() methods. The key Object * should have an equals(String) method which should return true if the * key.toString.equals(String) is true. Also the key.hashCode() method * must return the same value as key.toString.hashCode().<p> * * The above is always true when the key is a String. But it means it is * possible to submit special keys that fulfill the contract. For example * a wrapper around a byte[] can be submitted as key to retrieve either * a new String, which is the toString() method of the wrapper, or return * an existing String which would be equal to the product of toString(). * * @param key String or other Object with compatible equals(String) * and hashCode(). * @return String from map or a new String */ protected String getOrAddString(Object key) { String testValue; int index = hashIndex.getHashIndex(key.hashCode()); int lookup = hashIndex.hashTable[index]; int lastLookup = -1; for (; lookup >= 0; lastLookup = lookup, lookup = hashIndex.getNextLookup(lookup)) { testValue = (String) objectKeyTable[lookup]; if (key.equals(testValue)) { if (accessCount == Integer.MAX_VALUE) { resetAccessCount(); } accessTable[lookup] = accessCount++; return testValue; } } if (hashIndex.elementCount >= threshold) { reset(); return getOrAddString(key); } testValue = key.toString(); lookup = hashIndex.linkNode(index, lastLookup); objectKeyTable[lookup] = testValue; if (accessCount == Integer.MAX_VALUE) { resetAccessCount(); } accessTable[lookup] = accessCount++; return testValue; } protected Date getOrAddDate(long longKey) { Date testValue; int hash = (int) longKey ^ (int) (longKey >>> 32); int index = hashIndex.getHashIndex(hash); int lookup = hashIndex.hashTable[index]; int lastLookup = -1; for (; lookup >= 0; lastLookup = lookup, lookup = hashIndex.getNextLookup(lookup)) { testValue = (Date) objectKeyTable[lookup]; if (testValue.getTime() == longKey) { if (accessCount == Integer.MAX_VALUE) { resetAccessCount(); } accessTable[lookup] = accessCount++; return testValue; } } if (hashIndex.elementCount >= threshold) { reset(); return getOrAddDate(longKey); } lookup = hashIndex.linkNode(index, lastLookup); testValue = new Date(longKey); objectKeyTable[lookup] = testValue; if (accessCount == Integer.MAX_VALUE) { resetAccessCount(); } accessTable[lookup] = accessCount++; return testValue; } protected Double getOrAddDouble(long longKey) { Double testValue; int index = hashIndex.getHashIndex((int) (longKey ^ (longKey >>> 32))); int lookup = hashIndex.hashTable[index]; int lastLookup = -1; for (; lookup >= 0; lastLookup = lookup, lookup = hashIndex.getNextLookup(lookup)) { testValue = (Double) objectKeyTable[lookup]; if (Double.doubleToLongBits(testValue.doubleValue()) == longKey) { if (accessCount == Integer.MAX_VALUE) { resetAccessCount(); } accessTable[lookup] = accessCount++; return testValue; } } if (hashIndex.elementCount >= threshold) { reset(); return getOrAddDouble(longKey); } lookup = hashIndex.linkNode(index, lastLookup); testValue = new Double(Double.longBitsToDouble(longKey)); objectKeyTable[lookup] = testValue; if (accessCount == Integer.MAX_VALUE) { resetAccessCount(); } accessTable[lookup] = accessCount++; return testValue; } protected Object getOrAddObject(Object key) { Object testValue; int index = hashIndex.getHashIndex(key.hashCode()); int lookup = hashIndex.hashTable[index]; int lastLookup = -1; for (; lookup >= 0; lastLookup = lookup, lookup = hashIndex.getNextLookup(lookup)) { testValue = objectKeyTable[lookup]; if (testValue.equals(key)) { if (accessCount == Integer.MAX_VALUE) { resetAccessCount(); } accessTable[lookup] = accessCount++; return testValue; } } if (hashIndex.elementCount >= threshold) { reset(); return getOrAddObject(key); } lookup = hashIndex.linkNode(index, lastLookup); objectKeyTable[lookup] = key; if (accessCount == Integer.MAX_VALUE) { resetAccessCount(); } accessTable[lookup] = accessCount++; return key; } /* public static void main(String[] argv) { int BIGRANGE = 100000; int SMALLRANGE = 50000; int POOLSIZE = 100000; java.util.Random randomgen = new java.util.Random(); org.hsqldb.lib.StopWatch sw = new org.hsqldb.lib.StopWatch(); ValuePoolHashMap map = new ValuePoolHashMap(POOLSIZE, POOLSIZE, BaseHashMap.PURGE_HALF); int maxCount = 5000000; try { for (int rounds = 0; rounds < 3; rounds++) { sw.zero(); // timing for ValuePool retreival for (int i = 0; i < maxCount; i++) { boolean bigrange = (i % 2) == 0; int intValue = randomgen.nextInt(bigrange ? BIGRANGE : SMALLRANGE); Integer intObject = map.getOrAddInteger(intValue); if (intObject.intValue() != intValue) { throw new Exception("Value mismatch"); } // System.out.print(intValue); // System.out.print(' '); } System.out.println("Count " + maxCount + " " + sw.elapsedTime()); sw.zero(); // timing for Integer creation for (int i = 0; i < maxCount; i++) { boolean bigrange = (i % 2) == 0; int intValue = randomgen.nextInt(bigrange ? BIGRANGE : SMALLRANGE); Integer intObject = new Integer(intValue); if (intObject.intValue() != intValue) { throw new Exception("Value mismatch"); } } System.out.println("Count new Integer() " + maxCount + " " + sw.elapsedTime()); } } catch (Exception e) { e.printStackTrace(); } } */ }
{ "content_hash": "1251c51e0c899dc14dab4767255dc757", "timestamp": "", "source": "github", "line_count": 397, "max_line_length": 81, "avg_line_length": 30.397984886649873, "alnum_prop": 0.520633079217766, "repo_name": "minghao7896321/canyin", "id": "bc317bc8155cf41d381fbc23c68d26a1011e5cf0", "size": "13664", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "hsqldb/src/org/hsqldb/store/ValuePoolHashMap.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "9258" }, { "name": "CSS", "bytes": "6677" }, { "name": "HTML", "bytes": "3379482" }, { "name": "Java", "bytes": "5469249" }, { "name": "PLSQL", "bytes": "4437" }, { "name": "PLpgSQL", "bytes": "3783" }, { "name": "Protocol Buffer", "bytes": "53031" }, { "name": "Puppet", "bytes": "442" }, { "name": "SQLPL", "bytes": "14759" }, { "name": "Shell", "bytes": "39471" } ], "symlink_target": "" }
namespace Geekhub.Modules.Meetings.Models { public partial class Tag { public string Name { get; set; } } }
{ "content_hash": "d75ce3c5853b979c2084d5fb4e7611ec", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 41, "avg_line_length": 18.142857142857142, "alnum_prop": 0.6299212598425197, "repo_name": "geekhubdk/geekhub", "id": "0ea02fadc58c41202c11dde229dfcee3664eefc2", "size": "127", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Geekhub/Modules/Meetings/Models/Tag.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "90" }, { "name": "C#", "bytes": "133505" }, { "name": "CSS", "bytes": "63469" }, { "name": "HTML", "bytes": "4654" }, { "name": "JavaScript", "bytes": "175118" }, { "name": "Shell", "bytes": "1383" } ], "symlink_target": "" }
Add this line to your application's Gemfile: ```ruby gem 'sharedcount' ``` And then execute: ```bash bundle install ``` ## Setup Setup configuration parameters ```ruby require "sharedcount" Sharedcount.configure do |c| c.apikey = "your-api-key" c.endpoint = "http://free.sharedcount.com/" end ``` ## Usage ```ruby api = Sharedcount::API.new response = api.fetch("http://www.example.com/some-page.html") # Raw response from SharedCount response.raw_data => {"StumbleUpon"=>0, "Reddit"=>0, "Facebook"=>{ "commentsbox_count"=>0, "click_count"=>0, "total_count"=>35, "comment_count"=>4, "like_count"=>6, "share_count"=>25}, "Delicious"=>0, "GooglePlusOne"=>7, "Buzz"=>0, "Twitter"=>0, "Diggs"=>0, "Pinterest"=>0, "LinkedIn"=>0} # Sum of all social actions response.total_actions => 42 # Other methods response.stumble_upon_shares response.reddit_shares response.delicious_shares response.google_plus_one response.google_buzzs response.twitter_shares response.digg_shares response.pinterest_shares response.linkedin_shares response.facebook_commentsbox response.facebook_clicks response.facebook_total response.facebook_comments response.facebook_likes response.facebook_shares ```
{ "content_hash": "42459e9bff518744cd1c690fb2c3bfa1", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 61, "avg_line_length": 17.295774647887324, "alnum_prop": 0.7141693811074918, "repo_name": "zenkay/sharedcount-ruby", "id": "6c053733301743bcfa3bc72fe76f24c41c629f5c", "size": "1269", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "5396" }, { "name": "Shell", "bytes": "115" } ], "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> <!-- Generated by javadoc (1.8.0_161-google-v7) on Fri Nov 09 17:55:36 PST 2018 --> <title>RoundRectangle</title> <meta name="date" content="2018-11-09"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="RoundRectangle"; } } catch(err) { } //--> var methods = {"i0":10,"i1":10,"i2":10,"i3":10,"i4":10,"i5":10,"i6":10,"i7":10,"i8":10,"i9":10,"i10":10}; var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../org/robolectric/shadows/RoboLayoutInflater.html" title="class in org.robolectric.shadows"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../org/robolectric/shadows/ShadowAbsListView.html" title="class in org.robolectric.shadows"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?org/robolectric/shadows/RoundRectangle.html" target="_top">Frames</a></li> <li><a href="RoundRectangle.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.robolectric.shadows</div> <h2 title="Class RoundRectangle" class="title">Class RoundRectangle</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>java.awt.geom.RectangularShape</li> <li> <ul class="inheritance"> <li>org.robolectric.shadows.RoundRectangle</li> </ul> </li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd>java.awt.Shape, java.lang.Cloneable</dd> </dl> <hr> <br> <pre>public class <span class="typeNameLabel">RoundRectangle</span> extends java.awt.geom.RectangularShape</pre> <div class="block"><p>Defines a rectangle with rounded corners, where the sizes of the corners are potentially different.</p> <p><p>Copied from <a href="https://github.com/aosp-mirror/platform_frameworks_base/blob/oreo-release/tools/layoutlib/bridge/src/android/graphics/RoundRectangle.java">https://github.com/aosp-mirror/platform_frameworks_base/blob/oreo-release/tools/layoutlib/bridge/src/android/graphics/RoundRectangle.java</a></p></div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field.summary"> <!-- --> </a> <h3>Field Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation"> <caption><span>Fields</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>double</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/shadows/RoundRectangle.html#height">height</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>double</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/shadows/RoundRectangle.html#llHeight">llHeight</a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>double</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/shadows/RoundRectangle.html#llWidth">llWidth</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>double</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/shadows/RoundRectangle.html#lrHeight">lrHeight</a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>double</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/shadows/RoundRectangle.html#lrWidth">lrWidth</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>double</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/shadows/RoundRectangle.html#ulHeight">ulHeight</a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>double</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/shadows/RoundRectangle.html#ulWidth">ulWidth</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>double</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/shadows/RoundRectangle.html#urHeight">urHeight</a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>double</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/shadows/RoundRectangle.html#urWidth">urWidth</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>double</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/shadows/RoundRectangle.html#width">width</a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>double</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/shadows/RoundRectangle.html#x">x</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>double</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/shadows/RoundRectangle.html#y">y</a></span></code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../org/robolectric/shadows/RoundRectangle.html#RoundRectangle-float-float-float-float-float:A-">RoundRectangle</a></span>(float&nbsp;x, float&nbsp;y, float&nbsp;width, float&nbsp;height, float[]&nbsp;cornerDimensions)</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/shadows/RoundRectangle.html#contains-double-double-">contains</a></span>(double&nbsp;x, double&nbsp;y)</code>&nbsp;</td> </tr> <tr id="i1" class="rowColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/shadows/RoundRectangle.html#contains-double-double-double-double-">contains</a></span>(double&nbsp;x, double&nbsp;y, double&nbsp;w, double&nbsp;h)</code>&nbsp;</td> </tr> <tr id="i2" class="altColor"> <td class="colFirst"><code>java.awt.geom.Rectangle2D</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/shadows/RoundRectangle.html#getBounds2D--">getBounds2D</a></span>()</code>&nbsp;</td> </tr> <tr id="i3" class="rowColor"> <td class="colFirst"><code>double</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/shadows/RoundRectangle.html#getHeight--">getHeight</a></span>()</code>&nbsp;</td> </tr> <tr id="i4" class="altColor"> <td class="colFirst"><code>java.awt.geom.PathIterator</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/shadows/RoundRectangle.html#getPathIterator-java.awt.geom.AffineTransform-">getPathIterator</a></span>(java.awt.geom.AffineTransform&nbsp;at)</code>&nbsp;</td> </tr> <tr id="i5" class="rowColor"> <td class="colFirst"><code>double</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/shadows/RoundRectangle.html#getWidth--">getWidth</a></span>()</code>&nbsp;</td> </tr> <tr id="i6" class="altColor"> <td class="colFirst"><code>double</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/shadows/RoundRectangle.html#getX--">getX</a></span>()</code>&nbsp;</td> </tr> <tr id="i7" class="rowColor"> <td class="colFirst"><code>double</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/shadows/RoundRectangle.html#getY--">getY</a></span>()</code>&nbsp;</td> </tr> <tr id="i8" class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/shadows/RoundRectangle.html#intersects-double-double-double-double-">intersects</a></span>(double&nbsp;x, double&nbsp;y, double&nbsp;w, double&nbsp;h)</code>&nbsp;</td> </tr> <tr id="i9" class="rowColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/shadows/RoundRectangle.html#isEmpty--">isEmpty</a></span>()</code>&nbsp;</td> </tr> <tr id="i10" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/shadows/RoundRectangle.html#setFrame-double-double-double-double-">setFrame</a></span>(double&nbsp;x, double&nbsp;y, double&nbsp;w, double&nbsp;h)</code>&nbsp;</td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.awt.geom.RectangularShape"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.awt.geom.RectangularShape</h3> <code>clone, contains, contains, getBounds, getCenterX, getCenterY, getFrame, getMaxX, getMaxY, getMinX, getMinY, getPathIterator, intersects, setFrame, setFrame, setFrameFromCenter, setFrameFromCenter, setFrameFromDiagonal, setFrameFromDiagonal</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ FIELD DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="field.detail"> <!-- --> </a> <h3>Field Detail</h3> <a name="x"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>x</h4> <pre>public&nbsp;double x</pre> </li> </ul> <a name="y"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>y</h4> <pre>public&nbsp;double y</pre> </li> </ul> <a name="width"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>width</h4> <pre>public&nbsp;double width</pre> </li> </ul> <a name="height"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>height</h4> <pre>public&nbsp;double height</pre> </li> </ul> <a name="ulWidth"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>ulWidth</h4> <pre>public&nbsp;double ulWidth</pre> </li> </ul> <a name="ulHeight"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>ulHeight</h4> <pre>public&nbsp;double ulHeight</pre> </li> </ul> <a name="urWidth"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>urWidth</h4> <pre>public&nbsp;double urWidth</pre> </li> </ul> <a name="urHeight"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>urHeight</h4> <pre>public&nbsp;double urHeight</pre> </li> </ul> <a name="lrWidth"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>lrWidth</h4> <pre>public&nbsp;double lrWidth</pre> </li> </ul> <a name="lrHeight"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>lrHeight</h4> <pre>public&nbsp;double lrHeight</pre> </li> </ul> <a name="llWidth"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>llWidth</h4> <pre>public&nbsp;double llWidth</pre> </li> </ul> <a name="llHeight"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>llHeight</h4> <pre>public&nbsp;double llHeight</pre> </li> </ul> </li> </ul> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="RoundRectangle-float-float-float-float-float:A-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>RoundRectangle</h4> <pre>public&nbsp;RoundRectangle(float&nbsp;x, float&nbsp;y, float&nbsp;width, float&nbsp;height, float[]&nbsp;cornerDimensions)</pre> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>cornerDimensions</code> - array of 8 floating-point number corresponding to the width and the height of each corner in the following order: upper-left, upper-right, lower-right, lower-left. It assumes for the size the same convention as <code>RoundRectangle2D</code>, that is that the width and height of a corner correspond to the total width and height of the ellipse that corner is a quarter of.</dd> </dl> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="getX--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getX</h4> <pre>public&nbsp;double&nbsp;getX()</pre> <dl> <dt><span class="overrideSpecifyLabel">Specified by:</span></dt> <dd><code>getX</code>&nbsp;in class&nbsp;<code>java.awt.geom.RectangularShape</code></dd> </dl> </li> </ul> <a name="getY--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getY</h4> <pre>public&nbsp;double&nbsp;getY()</pre> <dl> <dt><span class="overrideSpecifyLabel">Specified by:</span></dt> <dd><code>getY</code>&nbsp;in class&nbsp;<code>java.awt.geom.RectangularShape</code></dd> </dl> </li> </ul> <a name="getWidth--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getWidth</h4> <pre>public&nbsp;double&nbsp;getWidth()</pre> <dl> <dt><span class="overrideSpecifyLabel">Specified by:</span></dt> <dd><code>getWidth</code>&nbsp;in class&nbsp;<code>java.awt.geom.RectangularShape</code></dd> </dl> </li> </ul> <a name="getHeight--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getHeight</h4> <pre>public&nbsp;double&nbsp;getHeight()</pre> <dl> <dt><span class="overrideSpecifyLabel">Specified by:</span></dt> <dd><code>getHeight</code>&nbsp;in class&nbsp;<code>java.awt.geom.RectangularShape</code></dd> </dl> </li> </ul> <a name="isEmpty--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>isEmpty</h4> <pre>public&nbsp;boolean&nbsp;isEmpty()</pre> <dl> <dt><span class="overrideSpecifyLabel">Specified by:</span></dt> <dd><code>isEmpty</code>&nbsp;in class&nbsp;<code>java.awt.geom.RectangularShape</code></dd> </dl> </li> </ul> <a name="setFrame-double-double-double-double-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setFrame</h4> <pre>public&nbsp;void&nbsp;setFrame(double&nbsp;x, double&nbsp;y, double&nbsp;w, double&nbsp;h)</pre> <dl> <dt><span class="overrideSpecifyLabel">Specified by:</span></dt> <dd><code>setFrame</code>&nbsp;in class&nbsp;<code>java.awt.geom.RectangularShape</code></dd> </dl> </li> </ul> <a name="getBounds2D--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getBounds2D</h4> <pre>public&nbsp;java.awt.geom.Rectangle2D&nbsp;getBounds2D()</pre> </li> </ul> <a name="contains-double-double-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>contains</h4> <pre>public&nbsp;boolean&nbsp;contains(double&nbsp;x, double&nbsp;y)</pre> </li> </ul> <a name="intersects-double-double-double-double-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>intersects</h4> <pre>public&nbsp;boolean&nbsp;intersects(double&nbsp;x, double&nbsp;y, double&nbsp;w, double&nbsp;h)</pre> </li> </ul> <a name="contains-double-double-double-double-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>contains</h4> <pre>public&nbsp;boolean&nbsp;contains(double&nbsp;x, double&nbsp;y, double&nbsp;w, double&nbsp;h)</pre> </li> </ul> <a name="getPathIterator-java.awt.geom.AffineTransform-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>getPathIterator</h4> <pre>public&nbsp;java.awt.geom.PathIterator&nbsp;getPathIterator(java.awt.geom.AffineTransform&nbsp;at)</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><script type="text/javascript" src="../../../highlight.pack.js"></script> <script type="text/javascript"><!-- hljs.initHighlightingOnLoad(); //--></script></div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../org/robolectric/shadows/RoboLayoutInflater.html" title="class in org.robolectric.shadows"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../org/robolectric/shadows/ShadowAbsListView.html" title="class in org.robolectric.shadows"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?org/robolectric/shadows/RoundRectangle.html" target="_top">Frames</a></li> <li><a href="RoundRectangle.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "c59a5c788d7593b796e577121f823ccf", "timestamp": "", "source": "github", "line_count": 656, "max_line_length": 417, "avg_line_length": 34.832317073170735, "alnum_prop": 0.6469146608315098, "repo_name": "robolectric/robolectric.github.io", "id": "16c35bf2fb5ce7df980147b37388d842d66f831d", "size": "22850", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "javadoc/4.0/org/robolectric/shadows/RoundRectangle.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "132673" }, { "name": "HTML", "bytes": "277730" }, { "name": "JavaScript", "bytes": "24371" }, { "name": "Ruby", "bytes": "1051" }, { "name": "SCSS", "bytes": "64100" }, { "name": "Shell", "bytes": "481" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "57a8d1c34627d93fdb45fffa348c59be", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "b881a80cfd498bc1fcd3e9fd61ae0b8cf76f12a7", "size": "181", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Pteridophyta/Polypodiopsida/Polypodiales/Polypodiaceae/Arthromeris/Arthromeris mairei/ Syn. Polypodium mairei/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<html lang="en"> <head> <title>title</title> <script type="text/javascript" src="reqlite.js"></script> <script type="text/javascript" src="rethinkdbdash.js"></script> <script type="text/javascript" src="example.js"></script> </head> <body> <h1>Quick run</h1> <ol> <li>Run `node browserify.js` in the reqlite repository</li> <li>Run `npm run browserify` in the rethinkdbdash repository</li> <li>Copy `rethinkdbdash.js` in browser/</li> <li>Run `python -m SimpleHTTPServer`</li> <li>Open http://localhost:8000</li> </ol> </body> </html>
{ "content_hash": "ee4f09a1359e32bc48f5170d9ed42fd8", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 71, "avg_line_length": 28.857142857142858, "alnum_prop": 0.6204620462046204, "repo_name": "neumino/reqlite", "id": "a2fd0b15a5ea435b44900321b7422421b0ee636d", "size": "606", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "browser/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "606" }, { "name": "JavaScript", "bytes": "809568" } ], "symlink_target": "" }
""" Python Markdown A Python implementation of John Gruber's Markdown. Documentation: https://python-markdown.github.io/ GitHub: https://github.com/Python-Markdown/markdown/ PyPI: https://pypi.org/project/Markdown/ Started by Manfred Stienstra (http://www.dwerg.net/). Maintained for a few years by Yuri Takhteyev (http://www.freewisdom.org). Currently maintained by Waylan Limberg (https://github.com/waylan), Dmitry Shachnev (https://github.com/mitya57) and Isaac Muse (https://github.com/facelessuser). Copyright 2007-2018 The Python Markdown Project (v. 1.7 and later) Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b) Copyright 2004 Manfred Stienstra (the original version) License: BSD (see LICENSE.md for details). """ import warnings from ..util import parseBoolValue class Extension: """ Base class for extensions to subclass. """ # Default config -- to be overriden by a subclass # Must be of the following format: # { # 'key': ['value', 'description'] # } # Note that Extension.setConfig will raise a KeyError # if a default is not set here. config = {} def __init__(self, **kwargs): """ Initiate Extension and set up configs. """ self.setConfigs(kwargs) def getConfig(self, key, default=''): """ Return a setting for the given key or an empty string. """ if key in self.config: return self.config[key][0] else: return default def getConfigs(self): """ Return all configs settings as a dict. """ return {key: self.getConfig(key) for key in self.config.keys()} def getConfigInfo(self): """ Return all config descriptions as a list of tuples. """ return [(key, self.config[key][1]) for key in self.config.keys()] def setConfig(self, key, value): """ Set a config setting for `key` with the given `value`. """ if isinstance(self.config[key][0], bool): value = parseBoolValue(value) if self.config[key][0] is None: value = parseBoolValue(value, preserve_none=True) self.config[key][0] = value def setConfigs(self, items): """ Set multiple config settings given a dict or list of tuples. """ if hasattr(items, 'items'): # it's a dict items = items.items() for key, value in items: self.setConfig(key, value) def _extendMarkdown(self, *args): """ Private wrapper around extendMarkdown. """ md = args[0] try: self.extendMarkdown(md) except TypeError as e: if "missing 1 required positional argument" in str(e): # Must be a 2.x extension. Pass in a dumby md_globals. self.extendMarkdown(md, {}) warnings.warn( "The 'md_globals' parameter of '{}.{}.extendMarkdown' is " "deprecated.".format(self.__class__.__module__, self.__class__.__name__), category=DeprecationWarning, stacklevel=2 ) else: raise def extendMarkdown(self, md): """ Add the various proccesors and patterns to the Markdown Instance. This method must be overriden by every extension. Keyword arguments: * md: The Markdown instance. * md_globals: Global variables in the markdown module namespace. """ raise NotImplementedError( 'Extension "%s.%s" must define an "extendMarkdown"' 'method.' % (self.__class__.__module__, self.__class__.__name__) )
{ "content_hash": "33a49f5daf66f05a3c658441d99607c1", "timestamp": "", "source": "github", "line_count": 107, "max_line_length": 94, "avg_line_length": 34.21495327102804, "alnum_prop": 0.601748156241464, "repo_name": "dmilith/SublimeText3-dmilith", "id": "9428a2a21204b902513184dd8630769ef39edbd8", "size": "3685", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Packages/mdpopups/st3/mdpopups/markdown/extensions/__init__.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "659" }, { "name": "C", "bytes": "3406335" }, { "name": "C++", "bytes": "532143" }, { "name": "CSS", "bytes": "8658" }, { "name": "DTrace", "bytes": "12324" }, { "name": "Elixir", "bytes": "346" }, { "name": "Go", "bytes": "282" }, { "name": "HTML", "bytes": "123" }, { "name": "JavaScript", "bytes": "119153" }, { "name": "Makefile", "bytes": "242" }, { "name": "PHP", "bytes": "4545" }, { "name": "Python", "bytes": "9755009" }, { "name": "Roff", "bytes": "20024" }, { "name": "Ruby", "bytes": "45" }, { "name": "Shell", "bytes": "7754" } ], "symlink_target": "" }
%% BTH Dissertation Style 2 (see https://github.com/CaterHatterPillar/bth-dissertation-style-2) %% Blekinge Institute of Technology alternative dissertation/thesis template. See https://github.com/CaterHatterPillar/bth-dissertation-style for a style resembling the official, close-source, dissertation template commonly used in BTH computer science theses. %% %% Based on the ILLC Dissertation Style by the Institute for Logic, Language and Computation, University of Amsterdam (used with permission). %% Licensed under the BSD 3-Clause License. See adjoined LICENSE for more information. %% Currently maintained by Eric Nilsson. %% %% Version: June 29, 2014. %% \begin{thesymbols} This is an optional chapter containing a list of symbols that you use. It is specified by:\\[2ex] \verb| \begin{thesymbols}|\\ \verb| <your list of symbols>|\\ \verb| \end{thesymbols}| \end{thesymbols}
{ "content_hash": "51f8f80d7c9e2e1f789037d5b64cac92", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 260, "avg_line_length": 52.35294117647059, "alnum_prop": 0.7719101123595505, "repo_name": "CaterHatterPillar/bth-dissertation-style-2", "id": "10bd222a2c7453ac4f14044cf89541cc0daa545b", "size": "890", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bthdiss_symbols.tex", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
osx_defaults "TimeMachine should NOT ask to use every new disk" do domain 'com.apple.TimeMachine' key 'DoNotOfferNewDisksForBackup' boolean true end old_menu_extras = `sudo -u #{node['current_user']} defaults read com.apple.systemuiserver menuExtras` new_menu_extras = old_menu_extras.split("\n").select { |line| line !~ /TimeMachine.menu/ }.join("\n") execute "TimeMachine should NOT appear in the status bar" do command "defaults write com.apple.systemuiserver menuExtras \'#{new_menu_extras}\'" user node['current_user'] only_if { new_menu_extras != old_menu_extras } notifies :run, "execute[restart SystemUIServer]" end execute "restart SystemUIServer" do command "killall -HUP SystemUIServer" action :nothing ignore_failure true # SystemUIServer is not running if not logged in end execute "make sure it doesn't exist" do command "! defaults read com.apple.systemuiserver menuExtras | grep TimeMachine.menu" user node['current_user'] end
{ "content_hash": "8e21610730dc9d8c3b5a3fb19929f116", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 101, "avg_line_length": 37.5, "alnum_prop": 0.7456410256410256, "repo_name": "Yesware/sprout", "id": "e0b83492e49c74ef0f8ca8049998fdb4574c72bb", "size": "975", "binary": false, "copies": "1", "ref": "refs/heads/yesware", "path": "pivotal_workstation/recipes/timemachine_preferences.rb", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "39278" }, { "name": "Ruby", "bytes": "157652" }, { "name": "Shell", "bytes": "1337" } ], "symlink_target": "" }
//IBM_PROLOG_BEGIN_TAG //IBM_PROLOG_END_TAG #ifndef cipInterpreter_h #define cipInterpreter_h /** @file cipInterpreter.H @brief eCMD CIP Extension Command Interpreter function prototypes */ //-------------------------------------------------------------------- // Includes //-------------------------------------------------------------------- #include <inttypes.h> #define ECMD_MAX_DATA_BITS 800000 //-------------------------------------------------------------------- // Forward References //-------------------------------------------------------------------- /** @brief Process user args and execute command requested @param argc Command line arguments @param argv Command line arguments @retval ECMD_SUCCESS On successful command @retval ECMD_INT_UNKNOWN_COMMAND If command is not valid @retval nonzero On command failure @pre Dll must be loaded - if applicable NOTE - should only be called for cip extension functions */ uint32_t cipCommandInterpreter(int argc, char* argv[]); /** @name User Functions */ //@{ /* cipProcUser.C */ #ifndef CIP_REMOVE_INSTRUCTION_FUNCTIONS uint32_t cipInstructUser(int argc, char* argv[]); #endif // CIP_REMOVE_INSTRUCTION_FUNCTIONS #ifndef CIP_REMOVE_BREAKPOINT_FUNCTIONS uint32_t cipBreakpointUser(int argc, char* argv[]); uint32_t cipBrkptUser(int argc, char* argv[]); #endif // CIP_REMOVE_BREAKPOINT_FUNCTIONS #ifndef CIP_REMOVE_VR_FUNCTIONS uint32_t cipGetVrUser(int argc, char * argv[]); uint32_t cipPutVrUser(int argc, char * argv[]); #endif // CIP_REMOVE_VR_FUNCTIONS #ifndef CIP_REMOVE_MEMORY_FUNCTIONS uint32_t ecmdCipGetMemProcUser(int argc, char * argv[]); uint32_t ecmdCipPutMemProcUser(int argc, char * argv[]); uint32_t cipGetMemPbaUser(int argc, char * argv[]); uint32_t cipPutMemPbaUser(int argc, char * argv[]); uint32_t cipGetMemProcVarUser(int argc, char * argv[]); uint32_t cipPutMemProcVarUser(int argc, char * argv[]); #endif // CIP_REMOVE_MEMORY_FUNCTIONS #ifndef CIP_REMOVE_VSR_FUNCTIONS uint32_t cipGetVsrUser(int argc, char * argv[]); uint32_t cipPutVsrUser(int argc, char * argv[]); #endif // CIP_REMOVE_VSR_FUNCTIONS /* cipPoreUser.C */ #ifndef CIP_REMOVE_PORE_FUNCTIONS uint32_t cipPorePutScomUser(int argc, char * argv[]); uint32_t cipPorePutSpyUser(int argc, char * argv[]); uint32_t cipPorePutSprUser(int argc, char * argv[]); uint32_t cipPoreQueryImageUser(int argc, char * argv[]); uint32_t cipPoreLoadImageUser(int argc, char * argv[]); #endif // CIP_REMOVE_PORE_FUNCTIONS /* cipProcUser.C */ #ifndef CIP_REMOVE_RW_FUNCTIONS uint32_t cipRWReadCacheUser(int argc, char * argv[]); uint32_t cipRWReadTLBUser(int argc, char * argv[]); uint32_t cipRWReadMemUser(int argc, char * argv[]); uint32_t cipRWWriteMemUser(int argc, char * argv[]); uint32_t cipRWGetDcrUser(int argc, char * argv[]); uint32_t cipRWPutDcrUser(int argc, char * argv[]); uint32_t cipRWProcStatusUser(int argc, char * argv[]); #endif // CIP_REMOVE_RW_FUNCTIONS /* cipProcUser.C */ #ifndef CIP_REMOVE_PMC_VOLTAGE_FUNCTIONS uint32_t cipGetPmcVoltageUser(int argc, char * argv[]); uint32_t cipPutPmcVoltageUser(int argc, char * argv[]); #endif // CIP_REMOVE_PMC_VOLTAGE_FUNCTIONS //@} #endif /* cipInterpreter_h */
{ "content_hash": "c709d8890a66fc1cae8d5695875e927b", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 70, "avg_line_length": 32.42, "alnum_prop": 0.6662553979025293, "repo_name": "mklight/eCMD", "id": "4b2488d62711543d1ac87ac5f694900639fbdbba", "size": "3872", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ecmd-core/ext/cip/cmd/cipInterpreter.H", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "3678" }, { "name": "C", "bytes": "3304707" }, { "name": "C++", "bytes": "1439660" }, { "name": "Makefile", "bytes": "71142" }, { "name": "Objective-C", "bytes": "1308" }, { "name": "Perl", "bytes": "172072" }, { "name": "Python", "bytes": "249967" }, { "name": "SWIG", "bytes": "60267" }, { "name": "Shell", "bytes": "20249" } ], "symlink_target": "" }
import matplotlib.pyplot as plt import pandas as pd from sklearn.cluster import KMeans plt.style.use('ggplot') # Look Pretty # TODO: To procure the dataset, follow these steps: # 1. Navigate to: https://data.cityofchicago.org/Public-Safety/Crimes-2001-to-present/ijzp-q8t2 # 2. In the 'Primary Type' column, click on the 'Menu' button next to the info button, # and select 'Filter This Column'. It might take a second for the filter option to # show up, since it has to load the entire list first. # 3. Scroll down to 'GAMBLING' # 4. Click the light blue 'Export' button next to the 'Filter' button, and select 'Download As CSV' def doKMeans(df): # INFO: Plot your data with a '.' marker, with 0.3 alpha at the Longitude, # and Latitude locations in your dataset. Longitude = x, Latitude = y fig = plt.figure() ax = fig.add_subplot(111) ax.scatter(df.Latitude, df.Longitude, marker='.', alpha=0.3) # TODO: Filter df so that you're only looking at Longitude and Latitude, # since the remaining columns aren't really applicable for this purpose. df_filtered = df[['Latitude', 'Longitude']] # TODO: Use K-Means to try and find seven cluster centers in this df. kmeans_model = KMeans(n_clusters=7) kmeans_model.fit(df_filtered) # INFO: Print and plot the centroids... centroids = kmeans_model.cluster_centers_ ax.scatter(centroids[:, 0], centroids[:, 1], marker='x', c='red', alpha=0.5, linewidths=3, s=169) print(centroids) # TODO: Load your dataset after importing Pandas df = pd.read_csv('Datasets/crimes.csv') # TODO: Drop any ROWs with nans in them df.dropna(axis=0, inplace=True) # TODO: Print out the dtypes of your dset print(df.dtypes) print('========') # Coerce the 'Date' feature (which is currently a string object) into real date, # and confirm by re-printing the dtypes. NOTE: This is a slow process... df['Date'] = pd.to_datetime(df['Date'], errors='coerce') print(df.dtypes) # INFO: Print & Plot your data doKMeans(df) # TODO: Filter out the data so that it only contains samples that have # a Date > '2011-01-01', using indexing. Then, in a new figure, plot the # crime incidents, as well as a new K-Means run's centroids. df = df[df.Date > '2011-01-01'] doKMeans(df) # INFO: Print & Plot your data doKMeans(df) plt.show()
{ "content_hash": "6418f077b1fab3c8910026322e281c65", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 101, "avg_line_length": 35.69230769230769, "alnum_prop": 0.7008620689655173, "repo_name": "Wittlich/DAT210x-Python", "id": "4e754a6ef65ca62038875d0c723006575255deef", "size": "2383", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Module5/assignment1.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "118755" } ], "symlink_target": "" }
package com.iwc.shop.common.persistence; import java.util.HashMap; /** * 查询参数类 * @author Tony Wong * @version 2013-8-23 */ public class Parameter extends HashMap<String, Object> { private static final long serialVersionUID = 1L; /** * 构造类,例:new Parameter(id, parentIds) * @param values 参数值 */ public Parameter(Object... values) { if (values != null){ for (int i=0; i<values.length; i++){ put("p"+(i+1), values[i]); } } } /** * 构造类,例:new Parameter(new Object[][]{{"id", id}, {"parentIds", parentIds}}) * @param parameters 参数二维数组 */ public Parameter(Object[][] parameters) { if (parameters != null){ for (Object[] os : parameters){ if (os.length == 2){ put((String)os[0], os[1]); } } } } }
{ "content_hash": "9511e5d12e51094edec86d2fefc1fa5c", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 77, "avg_line_length": 18.51219512195122, "alnum_prop": 0.5942028985507246, "repo_name": "newmann/shop", "id": "64afe1395705d4d540722b1ac9d04fed29f188e2", "size": "928", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/iwc/shop/common/persistence/Parameter.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "129713197" } ], "symlink_target": "" }
// page initialization $(document).ready(function () { getExposureLevel(); }); $("#update-default-version").click(function () { var versionName = $("#default-version option:selected").val(); jagg.post("../blocks/settings/settings.jag", { action: "updateDefaultVersion", applicationName: applicationName, defaultVersion: versionName },function defaultVersionUpdatedSuccess(result) { //alert(result); var defaultVersion = "Default version is set to " + $("#default-version option:selected").val(); $("#lbl-default-version").text(defaultVersion); jagg.message({content: "Default version is successfully updated.", type: 'success', id: 'view_log'}); setTimeout(redirectAppHome, 3000); function redirectAppHome(){ window.location.replace("home.jag?applicationKey=" + result); } },function (jqXHR, textStatus, errorThrown) { jagg.message({content: jqXHR.responseText, type: 'error', id: 'view_log'}); }); }); $("#update-exposure-level").click(function () { var versionName = $("#exposure-level-version-list option:selected").val(); jagg.post("../blocks/application/application.jag", { action: "updateVersionExposureLevel", applicationName: applicationName, versionName: versionName, exposureLevel: $("input:radio[name='security-radio']:checked").val() },function exposureLevelUpdatedSuccess(result) { jagg.message({content: "Exposure level is successfully updated.", type: 'success', id: 'view_log'}); },function (jqXHR, textStatus, errorThrown) { jagg.message({content: jqXHR.responseText, type: 'error', id: 'view_log'}); }); }); $("#exposure-level-version-list").change(function () { getExposureLevel(); }); function getExposureLevel() { var versionName = $("#exposure-level-version-list option:selected").val(); jagg.post("../blocks/application/application.jag", { action:"getExposureLevel", versionName:versionName, applicationName:applicationName },function (result) { $("#security-" + result).prop("checked", true); },function (jqXHR, textStatus, errorThrown) { jagg.message({content: "Error occurred while retrieving the endpoint security level of the selected " + cloudSpecificApplicationRepresentation.toLowerCase() + " version", type: 'error', id:'view_log'}); }); }
{ "content_hash": "c86e917b545a61cdac5b81a0addb6729", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 120, "avg_line_length": 38.421875, "alnum_prop": 0.6522976819845465, "repo_name": "jagathsisira/app-cloud", "id": "f83eaa2393890bcdb8179ae61e5b65e853691d5f", "size": "3155", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/jaggeryapps/appmgt/src/site/themes/default/templates/settings/js/settings.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "225619" }, { "name": "Go", "bytes": "40336" }, { "name": "Groff", "bytes": "10514" }, { "name": "HTML", "bytes": "44051" }, { "name": "Java", "bytes": "624149" }, { "name": "JavaScript", "bytes": "2495729" }, { "name": "Makefile", "bytes": "630" }, { "name": "PHP", "bytes": "4186" }, { "name": "Python", "bytes": "3499" }, { "name": "Shell", "bytes": "86013" } ], "symlink_target": "" }
**Considerations:** - To change from `prod` the `dev` environment, change all instances of `app.php` to `app_dev.php` - You may need to change the `fastcgi` endpoint to the listen address of your `php-fpm` instance - Make sure that the user that Caddy is running under has permissions to to `php-fpm` - Make sure that the user that `php-fpm` is running under has permissions to the `root` directory
{ "content_hash": "94cb3061b659ca18519e01ddf14a4d4b", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 97, "avg_line_length": 79.8, "alnum_prop": 0.7493734335839599, "repo_name": "caddyserver/examples", "id": "d757b9440129dd2707183dfb449bf82fc9758d18", "size": "434", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "symfony/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "116" }, { "name": "CSS", "bytes": "3217" }, { "name": "HTML", "bytes": "1300" }, { "name": "PHP", "bytes": "21" }, { "name": "Python", "bytes": "524" } ], "symlink_target": "" }
{% extends 'lotes/index.html' %} {% block title.content %}{{ titulo }} - {{ block.super }}{% endblock title.content %} {% block header.content %}{{ titulo }} - <a href="{% url 'producao:index' %}">{{ block.super }}</a>{% endblock header.content %} {% block stylesheet %} <style> {% include 'layout/simple_table.css' %} </style> {% endblock %} {% block content %} <form action="{% url 'producao:lote' %}" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Busca"/> </form> {% if erro %} <h3>Lote não encontrado</h3> {% elif lote %} <br/> <p> Lote selecionado: <b>{{lote}}</b> ( <b>{{ nloted.NLOTE }}</b> de {{ nloted.TOTLOTES }} )<br/> {% url 'cd:historico_lote' lote as hist_lote %} {% include "layout/link.html" with link=hist_lote text='Histórico do lote '|add:lote|add:' no CD' only %} </p> <table> {% include "layout/html_thead.html" with data=i_headers only %} {% include "layout/html_tbody_link.html" with fields=i_fields data=i_data link=i_link only %} </table> <table class="layout"> <tr> <td style="vertical-align: top;"> <table> {% include "layout/thead_generic.html" with data=p_headers style=p_style only %} {% include "layout/tbody_generic.html" with fields=p_fields data=p_data link=p_link style=p_style only %} </table> </td> <td></td> <td style="border-left: thin solid lightgrey;"></td> <td style="vertical-align: top;"> <table> {% include "layout/html_thead.html" with data=l_headers only %} {% include "layout/html_tbody.html" with fields=l_fields data=l_data only %} </table> </td> </tr> </table> <br /> <table> {% include "layout/html_thead.html" with data=o_headers only %} {% include "layout/html_tbody_link.html" with fields=o_fields data=o_data link=o_link only %} </table> {% if os_data %} <table> {% include "layout/html_thead.html" with data=os_headers only %} {% include "layout/html_tbody_link.html" with fields=os_fields data=os_data link=os_link only %} </table> {% endif %} <br /> <table> {% include "layout/thead_generic.html" with data=se_headers style=se_style only %} {% include "layout/tbody_generic.html" with fields=se_fields data=se_data style=se_style only %} </table> <br /> <table> {% include "layout/thead_generic.html" with data=hh_headers only %} {% include "layout/tbody_generic.html" with fields=hh_fields data=hh_data only %} </table> <br /> {% if h_data %} <table> {% include "layout/thead_generic.html" with data=h_headers style=h_style only %} {% include "layout/tbody_generic.html" with fields=h_fields data=h_data safe=h_safe style=h_style only %} </table> {% endif %} <br /> <table> {% include "layout/html_thead.html" with data=e_headers only %} {% include "layout/html_tbody_group.html" with fields=e_fields data=e_data group=e_group only %} </table> {% if slq_data %} <h3>Solicitações</h3> <div class="text-align:right;"> <a href="{% url 'cd:solicitacao_detalhe__get3' solicit_id 'dl' lote %}" target="_blank" onclick="if(confirm('Confirma cancelamento?')){return true}else{return false};" >Cancela solicitação de toda quantidade disponível no lote <span id="booom" class="glyphicon glyphicon-ban-circle" aria-hidden="true"></span></a> </div> <table> {% include "layout/thead_generic.html" with data=slq_headers style=slq_style only %} {% include "layout/tbody_generic.html" with fields=slq_fields data=slq_data link=slq_link style=slq_style only %} </table> {% endif %} {% endif %} {% endblock content %} {% block javascript %} <script> var inp = document.getElementById('id_lote'); inp.select(); </script> {% endblock javascript %}
{ "content_hash": "0398a202c8aa6abe2aeb9f1916b9bf43", "timestamp": "", "source": "github", "line_count": 101, "max_line_length": 173, "avg_line_length": 37.97029702970297, "alnum_prop": 0.6221642764015646, "repo_name": "anselmobd/fo2", "id": "4ae49f49a4eb49acae53d589acf937ad6c30fdfe", "size": "3842", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/template/lotes/posicao.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "160899" }, { "name": "HTML", "bytes": "855985" }, { "name": "JavaScript", "bytes": "203109" }, { "name": "PLSQL", "bytes": "2762" }, { "name": "Python", "bytes": "3228268" }, { "name": "Shell", "bytes": "2161" } ], "symlink_target": "" }
package com.ihidea.as.citypicker; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import com.ihidea.as.citypicker.activity.CitypickerListActivity; import com.ihidea.as.citypicker.activity.CitypickerWheelActivity; import com.ihidea.as.citypicker.adapter.CityPickerAdapter; import com.ihidea.as.citypicker.model.CityPickerStyleBean; import com.ihidea.as.citypicker.utils.ActivityUtils; import com.ihidea.as.citypicker.widget.DividerGridItemDecoration; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { RecyclerView mCitypickerRv; CityPickerAdapter mCityPickerAdapter; String[] mTitle = new String[] { "城市列表", "滚轮实现" }; Integer[] mIcon = new Integer[] { R.drawable.ic_list, R.drawable.ic_wheel }; private List<CityPickerStyleBean> mCityPickerStyleBeanList = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findView(); setData(); initRecyclerView(); } private void findView() { mCitypickerRv=(RecyclerView)findViewById(R.id.citypicker_rv); } private void setData() { for (int i = 0; i < mTitle.length; i++) { CityPickerStyleBean cityPickerStyleBean = new CityPickerStyleBean(); cityPickerStyleBean.setTitle(mTitle[i]); cityPickerStyleBean.setResourId(mIcon[i]); mCityPickerStyleBeanList.add(cityPickerStyleBean); } } private void initRecyclerView() { mCitypickerRv.addItemDecoration(new DividerGridItemDecoration(this)); mCitypickerRv.setLayoutManager(new GridLayoutManager(this, 3)); mCityPickerAdapter = new CityPickerAdapter(MainActivity.this, mCityPickerStyleBeanList); mCitypickerRv.setAdapter(mCityPickerAdapter); mCityPickerAdapter.setmOnItemClickListener(new CityPickerAdapter.OnItemClickListener() { @Override public void onItemClick(View view, int position) { if (null != mCityPickerAdapter && null != mCityPickerAdapter.getData() && !mCityPickerAdapter.getData().isEmpty() && null != mCityPickerAdapter.getData().get(position)) { gotoDetail(mCityPickerAdapter.getData().get(position).getResourId()); } } }); } /** * 选择相关样式 * @param resourId */ private void gotoDetail(int resourId) { switch (resourId) { case R.drawable.ic_list: ActivityUtils.getInstance().showActivity(MainActivity.this, CitypickerListActivity.class); break; case R.drawable.ic_wheel: ActivityUtils.getInstance().showActivity(MainActivity.this, CitypickerWheelActivity.class); break; default: break; } } }
{ "content_hash": "5f83cfc76faf542cb6bf080da968a1d3", "timestamp": "", "source": "github", "line_count": 94, "max_line_length": 129, "avg_line_length": 34.12765957446808, "alnum_prop": 0.6561720698254364, "repo_name": "weiwenqiang/GitHub", "id": "7b00a23979da9c3c4b389eb4da6adcc9b97cb771", "size": "3236", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SelectWidget/city/CityPicker2/citypicker/app/src/main/java/com/ihidea/as/citypicker/MainActivity.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "87" }, { "name": "C", "bytes": "42062" }, { "name": "C++", "bytes": "12137" }, { "name": "CMake", "bytes": "202" }, { "name": "CSS", "bytes": "75087" }, { "name": "Clojure", "bytes": "12036" }, { "name": "FreeMarker", "bytes": "21704" }, { "name": "Groovy", "bytes": "55083" }, { "name": "HTML", "bytes": "61549" }, { "name": "Java", "bytes": "42222825" }, { "name": "JavaScript", "bytes": "216823" }, { "name": "Kotlin", "bytes": "24319" }, { "name": "Makefile", "bytes": "19490" }, { "name": "Perl", "bytes": "280" }, { "name": "Prolog", "bytes": "1030" }, { "name": "Python", "bytes": "13032" }, { "name": "Scala", "bytes": "310450" }, { "name": "Shell", "bytes": "27802" } ], "symlink_target": "" }
""" Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.8.2 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys import unittest import kubernetes.client from kubernetes.client.rest import ApiException from kubernetes.client.apis.core_v1_api import CoreV1Api class TestCoreV1Api(unittest.TestCase): """ CoreV1Api unit test stubs """ def setUp(self): self.api = kubernetes.client.apis.core_v1_api.CoreV1Api() def tearDown(self): pass def test_connect_delete_namespaced_pod_proxy(self): """ Test case for connect_delete_namespaced_pod_proxy """ pass def test_connect_delete_namespaced_pod_proxy_with_path(self): """ Test case for connect_delete_namespaced_pod_proxy_with_path """ pass def test_connect_delete_namespaced_service_proxy(self): """ Test case for connect_delete_namespaced_service_proxy """ pass def test_connect_delete_namespaced_service_proxy_with_path(self): """ Test case for connect_delete_namespaced_service_proxy_with_path """ pass def test_connect_delete_node_proxy(self): """ Test case for connect_delete_node_proxy """ pass def test_connect_delete_node_proxy_with_path(self): """ Test case for connect_delete_node_proxy_with_path """ pass def test_connect_get_namespaced_pod_attach(self): """ Test case for connect_get_namespaced_pod_attach """ pass def test_connect_get_namespaced_pod_exec(self): """ Test case for connect_get_namespaced_pod_exec """ pass def test_connect_get_namespaced_pod_portforward(self): """ Test case for connect_get_namespaced_pod_portforward """ pass def test_connect_get_namespaced_pod_proxy(self): """ Test case for connect_get_namespaced_pod_proxy """ pass def test_connect_get_namespaced_pod_proxy_with_path(self): """ Test case for connect_get_namespaced_pod_proxy_with_path """ pass def test_connect_get_namespaced_service_proxy(self): """ Test case for connect_get_namespaced_service_proxy """ pass def test_connect_get_namespaced_service_proxy_with_path(self): """ Test case for connect_get_namespaced_service_proxy_with_path """ pass def test_connect_get_node_proxy(self): """ Test case for connect_get_node_proxy """ pass def test_connect_get_node_proxy_with_path(self): """ Test case for connect_get_node_proxy_with_path """ pass def test_connect_head_namespaced_pod_proxy(self): """ Test case for connect_head_namespaced_pod_proxy """ pass def test_connect_head_namespaced_pod_proxy_with_path(self): """ Test case for connect_head_namespaced_pod_proxy_with_path """ pass def test_connect_head_namespaced_service_proxy(self): """ Test case for connect_head_namespaced_service_proxy """ pass def test_connect_head_namespaced_service_proxy_with_path(self): """ Test case for connect_head_namespaced_service_proxy_with_path """ pass def test_connect_head_node_proxy(self): """ Test case for connect_head_node_proxy """ pass def test_connect_head_node_proxy_with_path(self): """ Test case for connect_head_node_proxy_with_path """ pass def test_connect_options_namespaced_pod_proxy(self): """ Test case for connect_options_namespaced_pod_proxy """ pass def test_connect_options_namespaced_pod_proxy_with_path(self): """ Test case for connect_options_namespaced_pod_proxy_with_path """ pass def test_connect_options_namespaced_service_proxy(self): """ Test case for connect_options_namespaced_service_proxy """ pass def test_connect_options_namespaced_service_proxy_with_path(self): """ Test case for connect_options_namespaced_service_proxy_with_path """ pass def test_connect_options_node_proxy(self): """ Test case for connect_options_node_proxy """ pass def test_connect_options_node_proxy_with_path(self): """ Test case for connect_options_node_proxy_with_path """ pass def test_connect_patch_namespaced_pod_proxy(self): """ Test case for connect_patch_namespaced_pod_proxy """ pass def test_connect_patch_namespaced_pod_proxy_with_path(self): """ Test case for connect_patch_namespaced_pod_proxy_with_path """ pass def test_connect_patch_namespaced_service_proxy(self): """ Test case for connect_patch_namespaced_service_proxy """ pass def test_connect_patch_namespaced_service_proxy_with_path(self): """ Test case for connect_patch_namespaced_service_proxy_with_path """ pass def test_connect_patch_node_proxy(self): """ Test case for connect_patch_node_proxy """ pass def test_connect_patch_node_proxy_with_path(self): """ Test case for connect_patch_node_proxy_with_path """ pass def test_connect_post_namespaced_pod_attach(self): """ Test case for connect_post_namespaced_pod_attach """ pass def test_connect_post_namespaced_pod_exec(self): """ Test case for connect_post_namespaced_pod_exec """ pass def test_connect_post_namespaced_pod_portforward(self): """ Test case for connect_post_namespaced_pod_portforward """ pass def test_connect_post_namespaced_pod_proxy(self): """ Test case for connect_post_namespaced_pod_proxy """ pass def test_connect_post_namespaced_pod_proxy_with_path(self): """ Test case for connect_post_namespaced_pod_proxy_with_path """ pass def test_connect_post_namespaced_service_proxy(self): """ Test case for connect_post_namespaced_service_proxy """ pass def test_connect_post_namespaced_service_proxy_with_path(self): """ Test case for connect_post_namespaced_service_proxy_with_path """ pass def test_connect_post_node_proxy(self): """ Test case for connect_post_node_proxy """ pass def test_connect_post_node_proxy_with_path(self): """ Test case for connect_post_node_proxy_with_path """ pass def test_connect_put_namespaced_pod_proxy(self): """ Test case for connect_put_namespaced_pod_proxy """ pass def test_connect_put_namespaced_pod_proxy_with_path(self): """ Test case for connect_put_namespaced_pod_proxy_with_path """ pass def test_connect_put_namespaced_service_proxy(self): """ Test case for connect_put_namespaced_service_proxy """ pass def test_connect_put_namespaced_service_proxy_with_path(self): """ Test case for connect_put_namespaced_service_proxy_with_path """ pass def test_connect_put_node_proxy(self): """ Test case for connect_put_node_proxy """ pass def test_connect_put_node_proxy_with_path(self): """ Test case for connect_put_node_proxy_with_path """ pass def test_create_namespace(self): """ Test case for create_namespace """ pass def test_create_namespaced_binding(self): """ Test case for create_namespaced_binding """ pass def test_create_namespaced_config_map(self): """ Test case for create_namespaced_config_map """ pass def test_create_namespaced_endpoints(self): """ Test case for create_namespaced_endpoints """ pass def test_create_namespaced_event(self): """ Test case for create_namespaced_event """ pass def test_create_namespaced_limit_range(self): """ Test case for create_namespaced_limit_range """ pass def test_create_namespaced_persistent_volume_claim(self): """ Test case for create_namespaced_persistent_volume_claim """ pass def test_create_namespaced_pod(self): """ Test case for create_namespaced_pod """ pass def test_create_namespaced_pod_binding(self): """ Test case for create_namespaced_pod_binding """ pass def test_create_namespaced_pod_eviction(self): """ Test case for create_namespaced_pod_eviction """ pass def test_create_namespaced_pod_template(self): """ Test case for create_namespaced_pod_template """ pass def test_create_namespaced_replication_controller(self): """ Test case for create_namespaced_replication_controller """ pass def test_create_namespaced_resource_quota(self): """ Test case for create_namespaced_resource_quota """ pass def test_create_namespaced_secret(self): """ Test case for create_namespaced_secret """ pass def test_create_namespaced_service(self): """ Test case for create_namespaced_service """ pass def test_create_namespaced_service_account(self): """ Test case for create_namespaced_service_account """ pass def test_create_node(self): """ Test case for create_node """ pass def test_create_persistent_volume(self): """ Test case for create_persistent_volume """ pass def test_delete_collection_namespaced_config_map(self): """ Test case for delete_collection_namespaced_config_map """ pass def test_delete_collection_namespaced_endpoints(self): """ Test case for delete_collection_namespaced_endpoints """ pass def test_delete_collection_namespaced_event(self): """ Test case for delete_collection_namespaced_event """ pass def test_delete_collection_namespaced_limit_range(self): """ Test case for delete_collection_namespaced_limit_range """ pass def test_delete_collection_namespaced_persistent_volume_claim(self): """ Test case for delete_collection_namespaced_persistent_volume_claim """ pass def test_delete_collection_namespaced_pod(self): """ Test case for delete_collection_namespaced_pod """ pass def test_delete_collection_namespaced_pod_template(self): """ Test case for delete_collection_namespaced_pod_template """ pass def test_delete_collection_namespaced_replication_controller(self): """ Test case for delete_collection_namespaced_replication_controller """ pass def test_delete_collection_namespaced_resource_quota(self): """ Test case for delete_collection_namespaced_resource_quota """ pass def test_delete_collection_namespaced_secret(self): """ Test case for delete_collection_namespaced_secret """ pass def test_delete_collection_namespaced_service_account(self): """ Test case for delete_collection_namespaced_service_account """ pass def test_delete_collection_node(self): """ Test case for delete_collection_node """ pass def test_delete_collection_persistent_volume(self): """ Test case for delete_collection_persistent_volume """ pass def test_delete_namespace(self): """ Test case for delete_namespace """ pass def test_delete_namespaced_config_map(self): """ Test case for delete_namespaced_config_map """ pass def test_delete_namespaced_endpoints(self): """ Test case for delete_namespaced_endpoints """ pass def test_delete_namespaced_event(self): """ Test case for delete_namespaced_event """ pass def test_delete_namespaced_limit_range(self): """ Test case for delete_namespaced_limit_range """ pass def test_delete_namespaced_persistent_volume_claim(self): """ Test case for delete_namespaced_persistent_volume_claim """ pass def test_delete_namespaced_pod(self): """ Test case for delete_namespaced_pod """ pass def test_delete_namespaced_pod_template(self): """ Test case for delete_namespaced_pod_template """ pass def test_delete_namespaced_replication_controller(self): """ Test case for delete_namespaced_replication_controller """ pass def test_delete_namespaced_resource_quota(self): """ Test case for delete_namespaced_resource_quota """ pass def test_delete_namespaced_secret(self): """ Test case for delete_namespaced_secret """ pass def test_delete_namespaced_service(self): """ Test case for delete_namespaced_service """ pass def test_delete_namespaced_service_account(self): """ Test case for delete_namespaced_service_account """ pass def test_delete_node(self): """ Test case for delete_node """ pass def test_delete_persistent_volume(self): """ Test case for delete_persistent_volume """ pass def test_get_api_resources(self): """ Test case for get_api_resources """ pass def test_list_component_status(self): """ Test case for list_component_status """ pass def test_list_config_map_for_all_namespaces(self): """ Test case for list_config_map_for_all_namespaces """ pass def test_list_endpoints_for_all_namespaces(self): """ Test case for list_endpoints_for_all_namespaces """ pass def test_list_event_for_all_namespaces(self): """ Test case for list_event_for_all_namespaces """ pass def test_list_limit_range_for_all_namespaces(self): """ Test case for list_limit_range_for_all_namespaces """ pass def test_list_namespace(self): """ Test case for list_namespace """ pass def test_list_namespaced_config_map(self): """ Test case for list_namespaced_config_map """ pass def test_list_namespaced_endpoints(self): """ Test case for list_namespaced_endpoints """ pass def test_list_namespaced_event(self): """ Test case for list_namespaced_event """ pass def test_list_namespaced_limit_range(self): """ Test case for list_namespaced_limit_range """ pass def test_list_namespaced_persistent_volume_claim(self): """ Test case for list_namespaced_persistent_volume_claim """ pass def test_list_namespaced_pod(self): """ Test case for list_namespaced_pod """ pass def test_list_namespaced_pod_template(self): """ Test case for list_namespaced_pod_template """ pass def test_list_namespaced_replication_controller(self): """ Test case for list_namespaced_replication_controller """ pass def test_list_namespaced_resource_quota(self): """ Test case for list_namespaced_resource_quota """ pass def test_list_namespaced_secret(self): """ Test case for list_namespaced_secret """ pass def test_list_namespaced_service(self): """ Test case for list_namespaced_service """ pass def test_list_namespaced_service_account(self): """ Test case for list_namespaced_service_account """ pass def test_list_node(self): """ Test case for list_node """ pass def test_list_persistent_volume(self): """ Test case for list_persistent_volume """ pass def test_list_persistent_volume_claim_for_all_namespaces(self): """ Test case for list_persistent_volume_claim_for_all_namespaces """ pass def test_list_pod_for_all_namespaces(self): """ Test case for list_pod_for_all_namespaces """ pass def test_list_pod_template_for_all_namespaces(self): """ Test case for list_pod_template_for_all_namespaces """ pass def test_list_replication_controller_for_all_namespaces(self): """ Test case for list_replication_controller_for_all_namespaces """ pass def test_list_resource_quota_for_all_namespaces(self): """ Test case for list_resource_quota_for_all_namespaces """ pass def test_list_secret_for_all_namespaces(self): """ Test case for list_secret_for_all_namespaces """ pass def test_list_service_account_for_all_namespaces(self): """ Test case for list_service_account_for_all_namespaces """ pass def test_list_service_for_all_namespaces(self): """ Test case for list_service_for_all_namespaces """ pass def test_patch_namespace(self): """ Test case for patch_namespace """ pass def test_patch_namespace_status(self): """ Test case for patch_namespace_status """ pass def test_patch_namespaced_config_map(self): """ Test case for patch_namespaced_config_map """ pass def test_patch_namespaced_endpoints(self): """ Test case for patch_namespaced_endpoints """ pass def test_patch_namespaced_event(self): """ Test case for patch_namespaced_event """ pass def test_patch_namespaced_limit_range(self): """ Test case for patch_namespaced_limit_range """ pass def test_patch_namespaced_persistent_volume_claim(self): """ Test case for patch_namespaced_persistent_volume_claim """ pass def test_patch_namespaced_persistent_volume_claim_status(self): """ Test case for patch_namespaced_persistent_volume_claim_status """ pass def test_patch_namespaced_pod(self): """ Test case for patch_namespaced_pod """ pass def test_patch_namespaced_pod_status(self): """ Test case for patch_namespaced_pod_status """ pass def test_patch_namespaced_pod_template(self): """ Test case for patch_namespaced_pod_template """ pass def test_patch_namespaced_replication_controller(self): """ Test case for patch_namespaced_replication_controller """ pass def test_patch_namespaced_replication_controller_scale(self): """ Test case for patch_namespaced_replication_controller_scale """ pass def test_patch_namespaced_replication_controller_status(self): """ Test case for patch_namespaced_replication_controller_status """ pass def test_patch_namespaced_resource_quota(self): """ Test case for patch_namespaced_resource_quota """ pass def test_patch_namespaced_resource_quota_status(self): """ Test case for patch_namespaced_resource_quota_status """ pass def test_patch_namespaced_secret(self): """ Test case for patch_namespaced_secret """ pass def test_patch_namespaced_service(self): """ Test case for patch_namespaced_service """ pass def test_patch_namespaced_service_account(self): """ Test case for patch_namespaced_service_account """ pass def test_patch_namespaced_service_status(self): """ Test case for patch_namespaced_service_status """ pass def test_patch_node(self): """ Test case for patch_node """ pass def test_patch_node_status(self): """ Test case for patch_node_status """ pass def test_patch_persistent_volume(self): """ Test case for patch_persistent_volume """ pass def test_patch_persistent_volume_status(self): """ Test case for patch_persistent_volume_status """ pass def test_proxy_delete_namespaced_pod(self): """ Test case for proxy_delete_namespaced_pod """ pass def test_proxy_delete_namespaced_pod_with_path(self): """ Test case for proxy_delete_namespaced_pod_with_path """ pass def test_proxy_delete_namespaced_service(self): """ Test case for proxy_delete_namespaced_service """ pass def test_proxy_delete_namespaced_service_with_path(self): """ Test case for proxy_delete_namespaced_service_with_path """ pass def test_proxy_delete_node(self): """ Test case for proxy_delete_node """ pass def test_proxy_delete_node_with_path(self): """ Test case for proxy_delete_node_with_path """ pass def test_proxy_get_namespaced_pod(self): """ Test case for proxy_get_namespaced_pod """ pass def test_proxy_get_namespaced_pod_with_path(self): """ Test case for proxy_get_namespaced_pod_with_path """ pass def test_proxy_get_namespaced_service(self): """ Test case for proxy_get_namespaced_service """ pass def test_proxy_get_namespaced_service_with_path(self): """ Test case for proxy_get_namespaced_service_with_path """ pass def test_proxy_get_node(self): """ Test case for proxy_get_node """ pass def test_proxy_get_node_with_path(self): """ Test case for proxy_get_node_with_path """ pass def test_proxy_head_namespaced_pod(self): """ Test case for proxy_head_namespaced_pod """ pass def test_proxy_head_namespaced_pod_with_path(self): """ Test case for proxy_head_namespaced_pod_with_path """ pass def test_proxy_head_namespaced_service(self): """ Test case for proxy_head_namespaced_service """ pass def test_proxy_head_namespaced_service_with_path(self): """ Test case for proxy_head_namespaced_service_with_path """ pass def test_proxy_head_node(self): """ Test case for proxy_head_node """ pass def test_proxy_head_node_with_path(self): """ Test case for proxy_head_node_with_path """ pass def test_proxy_options_namespaced_pod(self): """ Test case for proxy_options_namespaced_pod """ pass def test_proxy_options_namespaced_pod_with_path(self): """ Test case for proxy_options_namespaced_pod_with_path """ pass def test_proxy_options_namespaced_service(self): """ Test case for proxy_options_namespaced_service """ pass def test_proxy_options_namespaced_service_with_path(self): """ Test case for proxy_options_namespaced_service_with_path """ pass def test_proxy_options_node(self): """ Test case for proxy_options_node """ pass def test_proxy_options_node_with_path(self): """ Test case for proxy_options_node_with_path """ pass def test_proxy_patch_namespaced_pod(self): """ Test case for proxy_patch_namespaced_pod """ pass def test_proxy_patch_namespaced_pod_with_path(self): """ Test case for proxy_patch_namespaced_pod_with_path """ pass def test_proxy_patch_namespaced_service(self): """ Test case for proxy_patch_namespaced_service """ pass def test_proxy_patch_namespaced_service_with_path(self): """ Test case for proxy_patch_namespaced_service_with_path """ pass def test_proxy_patch_node(self): """ Test case for proxy_patch_node """ pass def test_proxy_patch_node_with_path(self): """ Test case for proxy_patch_node_with_path """ pass def test_proxy_post_namespaced_pod(self): """ Test case for proxy_post_namespaced_pod """ pass def test_proxy_post_namespaced_pod_with_path(self): """ Test case for proxy_post_namespaced_pod_with_path """ pass def test_proxy_post_namespaced_service(self): """ Test case for proxy_post_namespaced_service """ pass def test_proxy_post_namespaced_service_with_path(self): """ Test case for proxy_post_namespaced_service_with_path """ pass def test_proxy_post_node(self): """ Test case for proxy_post_node """ pass def test_proxy_post_node_with_path(self): """ Test case for proxy_post_node_with_path """ pass def test_proxy_put_namespaced_pod(self): """ Test case for proxy_put_namespaced_pod """ pass def test_proxy_put_namespaced_pod_with_path(self): """ Test case for proxy_put_namespaced_pod_with_path """ pass def test_proxy_put_namespaced_service(self): """ Test case for proxy_put_namespaced_service """ pass def test_proxy_put_namespaced_service_with_path(self): """ Test case for proxy_put_namespaced_service_with_path """ pass def test_proxy_put_node(self): """ Test case for proxy_put_node """ pass def test_proxy_put_node_with_path(self): """ Test case for proxy_put_node_with_path """ pass def test_read_component_status(self): """ Test case for read_component_status """ pass def test_read_namespace(self): """ Test case for read_namespace """ pass def test_read_namespace_status(self): """ Test case for read_namespace_status """ pass def test_read_namespaced_config_map(self): """ Test case for read_namespaced_config_map """ pass def test_read_namespaced_endpoints(self): """ Test case for read_namespaced_endpoints """ pass def test_read_namespaced_event(self): """ Test case for read_namespaced_event """ pass def test_read_namespaced_limit_range(self): """ Test case for read_namespaced_limit_range """ pass def test_read_namespaced_persistent_volume_claim(self): """ Test case for read_namespaced_persistent_volume_claim """ pass def test_read_namespaced_persistent_volume_claim_status(self): """ Test case for read_namespaced_persistent_volume_claim_status """ pass def test_read_namespaced_pod(self): """ Test case for read_namespaced_pod """ pass def test_read_namespaced_pod_log(self): """ Test case for read_namespaced_pod_log """ pass def test_read_namespaced_pod_status(self): """ Test case for read_namespaced_pod_status """ pass def test_read_namespaced_pod_template(self): """ Test case for read_namespaced_pod_template """ pass def test_read_namespaced_replication_controller(self): """ Test case for read_namespaced_replication_controller """ pass def test_read_namespaced_replication_controller_scale(self): """ Test case for read_namespaced_replication_controller_scale """ pass def test_read_namespaced_replication_controller_status(self): """ Test case for read_namespaced_replication_controller_status """ pass def test_read_namespaced_resource_quota(self): """ Test case for read_namespaced_resource_quota """ pass def test_read_namespaced_resource_quota_status(self): """ Test case for read_namespaced_resource_quota_status """ pass def test_read_namespaced_secret(self): """ Test case for read_namespaced_secret """ pass def test_read_namespaced_service(self): """ Test case for read_namespaced_service """ pass def test_read_namespaced_service_account(self): """ Test case for read_namespaced_service_account """ pass def test_read_namespaced_service_status(self): """ Test case for read_namespaced_service_status """ pass def test_read_node(self): """ Test case for read_node """ pass def test_read_node_status(self): """ Test case for read_node_status """ pass def test_read_persistent_volume(self): """ Test case for read_persistent_volume """ pass def test_read_persistent_volume_status(self): """ Test case for read_persistent_volume_status """ pass def test_replace_namespace(self): """ Test case for replace_namespace """ pass def test_replace_namespace_finalize(self): """ Test case for replace_namespace_finalize """ pass def test_replace_namespace_status(self): """ Test case for replace_namespace_status """ pass def test_replace_namespaced_config_map(self): """ Test case for replace_namespaced_config_map """ pass def test_replace_namespaced_endpoints(self): """ Test case for replace_namespaced_endpoints """ pass def test_replace_namespaced_event(self): """ Test case for replace_namespaced_event """ pass def test_replace_namespaced_limit_range(self): """ Test case for replace_namespaced_limit_range """ pass def test_replace_namespaced_persistent_volume_claim(self): """ Test case for replace_namespaced_persistent_volume_claim """ pass def test_replace_namespaced_persistent_volume_claim_status(self): """ Test case for replace_namespaced_persistent_volume_claim_status """ pass def test_replace_namespaced_pod(self): """ Test case for replace_namespaced_pod """ pass def test_replace_namespaced_pod_status(self): """ Test case for replace_namespaced_pod_status """ pass def test_replace_namespaced_pod_template(self): """ Test case for replace_namespaced_pod_template """ pass def test_replace_namespaced_replication_controller(self): """ Test case for replace_namespaced_replication_controller """ pass def test_replace_namespaced_replication_controller_scale(self): """ Test case for replace_namespaced_replication_controller_scale """ pass def test_replace_namespaced_replication_controller_status(self): """ Test case for replace_namespaced_replication_controller_status """ pass def test_replace_namespaced_resource_quota(self): """ Test case for replace_namespaced_resource_quota """ pass def test_replace_namespaced_resource_quota_status(self): """ Test case for replace_namespaced_resource_quota_status """ pass def test_replace_namespaced_secret(self): """ Test case for replace_namespaced_secret """ pass def test_replace_namespaced_service(self): """ Test case for replace_namespaced_service """ pass def test_replace_namespaced_service_account(self): """ Test case for replace_namespaced_service_account """ pass def test_replace_namespaced_service_status(self): """ Test case for replace_namespaced_service_status """ pass def test_replace_node(self): """ Test case for replace_node """ pass def test_replace_node_status(self): """ Test case for replace_node_status """ pass def test_replace_persistent_volume(self): """ Test case for replace_persistent_volume """ pass def test_replace_persistent_volume_status(self): """ Test case for replace_persistent_volume_status """ pass if __name__ == '__main__': unittest.main()
{ "content_hash": "bb58b036a0db37482f7fa50b8b32fc7a", "timestamp": "", "source": "github", "line_count": 1954, "max_line_length": 105, "avg_line_length": 19.180655066530193, "alnum_prop": 0.5290696123162304, "repo_name": "mbohlool/client-python", "id": "f84c56ea31159f6f77c88f040b3fe9bb3ffe5fd2", "size": "37496", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "kubernetes/test/test_core_v1_api.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "8417639" }, { "name": "Shell", "bytes": "16830" } ], "symlink_target": "" }
/* * Plugins */ var gulp = require('gulp'); var plumber = require('gulp-plumber'); var sass = require('gulp-sass'); var browserSync = require('browser-sync'); /* * Configuration */ var pathConfig = require('../config/gulp').paths; var sassConfig = require('../config/gulp').sass; /* * Pipe */ module.exports = { getPipe: function() { return gulp.src(pathConfig.styles) .pipe(plumber()) .pipe(sass(sassConfig)) .pipe(gulp.dest(pathConfig.dest.development)) .pipe(browserSync.stream()); } };
{ "content_hash": "2857db1358cfbd9707460a55d67d0cc4", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 51, "avg_line_length": 15.823529411764707, "alnum_prop": 0.6263940520446096, "repo_name": "t-mon/guh-webinterface", "id": "44661304df3da990b9f77c0ffb523e7ff3c3e52a", "size": "2585", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "gulp/pipes/built-app-styles-development.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "86972" }, { "name": "HTML", "bytes": "100238" }, { "name": "JavaScript", "bytes": "371574" }, { "name": "Shell", "bytes": "352" } ], "symlink_target": "" }
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.continuous_search; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.content.Context; import android.content.res.Resources; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestRule; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import org.mockito.quality.Strictness; import org.chromium.base.test.BaseRobolectricTestRunner; import org.chromium.chrome.browser.flags.ChromeFeatureList; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.test.util.browser.Features; import org.chromium.chrome.test.util.browser.Features.DisableFeatures; import org.chromium.chrome.test.util.browser.Features.EnableFeatures; /** * Test of {@link ContinuousSearchTabHelper}. */ @RunWith(BaseRobolectricTestRunner.class) public class ContinuousSearchTabHelperJUnitTest { @Mock private Tab mTabMock; @Rule public MockitoRule mMockitoRule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS); @Rule public TestRule mProcessor = new Features.JUnitProcessor(); @Before public void setUp() { Context context = mock(Context.class); Resources resources = mock(Resources.class); when(mTabMock.getContext()).thenReturn(context); when(context.getResources()).thenReturn(resources); when(resources.getInteger(anyInt())).thenReturn(0); } /** * Tests successful initialization of the tab observer. */ @Test @EnableFeatures({ChromeFeatureList.CONTINUOUS_SEARCH}) public void testInitializeSuccess() { when(mTabMock.isIncognito()).thenReturn(false); ContinuousSearchTabHelper.createForTab(mTabMock); verify(mTabMock).addObserver(any()); } /** * Tests initialization is skipped for incognito tabs even if the feature is on. */ @Test @EnableFeatures({ChromeFeatureList.CONTINUOUS_SEARCH}) public void testNoInitializeIfIncognito() { when(mTabMock.isIncognito()).thenReturn(true); ContinuousSearchTabHelper.createForTab(mTabMock); verify(mTabMock, never()).addObserver(any()); } /** * Tests skip initialization if the feature flag is off. */ @Test @DisableFeatures({ChromeFeatureList.CONTINUOUS_SEARCH}) public void testFeatureDisabled() { when(mTabMock.isIncognito()).thenReturn(false); ContinuousSearchTabHelper.createForTab(mTabMock); verify(mTabMock, never()).addObserver(any()); } }
{ "content_hash": "3039ab307cf3b346a787cc924cf9f987", "timestamp": "", "source": "github", "line_count": 94, "max_line_length": 94, "avg_line_length": 31.829787234042552, "alnum_prop": 0.7386363636363636, "repo_name": "scheib/chromium", "id": "287eb37b1fd2a4371f3403c8d79b25942ddf4397", "size": "2992", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "chrome/browser/continuous_search/android/junit/src/org/chromium/chrome/browser/continuous_search/ContinuousSearchTabHelperJUnitTest.java", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package org.codemucker.lang; public class BeanNameUtil { public static String toSetterName(String name) { return addPrefixName("set",name); } public static String toGetterName(String name, java.lang.reflect.Type type) { boolean isBool = "boolean".equals(type.toString())|| "java.lang.Boolean".equals(type.toString()); return toGetterName(name, isBool); } public static String toGetterName(String name, Class<?> type) { return toGetterName(name, boolean.class.equals(type) || Boolean.class.equals(type)); } public static String toGetterName(String name, boolean isBoolean) { name = stripPrefix(name); return addPrefixName((isBoolean ? "is" : "get"),name); } public static String addPrefixName(String prefix,String name) { name = stripPrefix(name); return prefix + ClassNameUtil.upperFirstChar(name); } /** * Best effort basis to convert the given method name to a property name * * <p> * <ul> * <li>setFoo --&gt; foo</li> * <li>Foo --&gt; foo</li> * <li>F --&gt; f</li> * <li>setFOO --&gt; fOO</li> * </ul> * </p> */ public static String methodToPropertyName(String name) { return lowerFirst(stripPrefix(name)); } /** * Best effort basis to convert the given method name to a property name */ public static String fieldToPropertyName(String name) { return lowerFirst(name); } public static String lowerFirst(String name) { if(name.length() > 1){ name = Character.toLowerCase(name.charAt(0)) + name.substring(1); } else if(name.length() == 1){ name = Character.toLowerCase(name.charAt(0)) + ""; } return name; } /** * Strips the get/set/is prefix from a method name * * <p>Handles the case where the prefix get/set/is is actually part of a name by ensuring that the letter after the prefix is in uppercase</p> * * <p>Examples: * <ul> * <li>getFoo,setFoo,isFoo --&gt; 'Foo' * <li>gettyburg --&gt; gettyburg (unchanged) * <li>iso --&gt; iso (unchanged) * <li>getIso--&gt; iso * <li>isIso--&gt; iso * <li>isolated --&gt; isolated (unchanged) * <li>isIsolated --&gt; isolated * </p> * @param name * @return */ public static String stripPrefix(String name) { if ((name.startsWith("get") || name.startsWith("set")) && (name.length() > 3 && Character.isUpperCase(name.charAt(3)))) { return name.substring(3); } if (name.startsWith("is") && name.length() > 2 && Character.isUpperCase(name.charAt(2))) { return name.substring(2); } return name; } public static String extractIndexedKeyType(String fullType) { //eg ..Map or ..Map<String,Bar> or ..Map<String,Bar<T,Foo>> //return the 2nd generic arg int first = fullType.indexOf('<'); if (first != -1) { int last = fullType.indexOf(',', first); if(last !=-1){ return fullType.substring(first + 1, last); } else { return null;//have a generic part but not enough generic params for a key } } else { return "java.lang.Object"; } } public static String extractIndexedValueType(String fullType) { //eg .. List or ..List<String> or ..List<Bar<T,Foo>> or ..Map or ..Map<String,Bar> or ..Map<String,Bar<T,Foo>> int first = fullType.indexOf('<'); if (first != -1) { int angle = fullType.indexOf('<', first+1); int comma = fullType.indexOf(',', first+1); if( angle !=-1 || comma != -1){ if(angle == -1){ first = comma; } else if( comma == -1){ first = angle; } else if( angle < comma){ first = angle; } else { first = comma; } } int last = fullType.lastIndexOf('>'); return fullType.substring(first + 1, last); } return "java.lang.Object"; } }
{ "content_hash": "26561c2063da0690a037222325cc349b", "timestamp": "", "source": "github", "line_count": 129, "max_line_length": 143, "avg_line_length": 28.4031007751938, "alnum_prop": 0.6350982532751092, "repo_name": "codemucker/codemucker-lang", "id": "e4fe33fa99d16c6fc684f0412caa6eb4ae26f0db", "size": "3664", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/codemucker/lang/BeanNameUtil.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "42351" } ], "symlink_target": "" }
Online at https://googlechrome.github.io/lighthouse/viewer/ ## Development Run the following in the root folder of a Lighthouse checkout: * `yarn` * `yarn build-viewer` * `yarn serve-gh-pages` * `open http://localhost:8000/viewer/` This compiles and minifies `app/src/main.js`. Results are written to `dist/gh-pages/viewer/`. ## Deploy Deploys should be done as part of the Lighthouse release process. To push the viewer to the `gh-pages` branch under `viewer/`, run the following in the root folder of a Lighthouse checkout: ```sh yarn deploy-viewer ``` For more information on deployment, see `releasing.md`. ## Usage ### Load JSON from Gist Pass the GitHub Gist identifier as `gist` query parameter. e.g., `http://localhost:8000/?gist=bd1779783a5bbcb348564a58f80f7099` ### Load JSON from URL Pass the absolute URL as `jsonurl` query parameter. e.g., `http://localhost:8000/?jsonurl=https://gist.githubusercontent.com/Kikobeats/d570a1aa285c5d1d97bbda10b92fb97f/raw/4b0f14a5914edd25c95b4bd9d09728ab42181c3e/lighthouse.json` ### Run and load from PageSpeed Insights Pass target URL `psiurl` query parameter. e.g., `http://localhost:8000/?psiurl=https://www.example.com&category=pwa&category=seo` The following query parameters are also supported as options: `category` - Category to enable. One per category. `strategy` - mobile, desktop `locale` - locale to render report with `utm_source` - id that identifies the tool using the viewer
{ "content_hash": "0a1e0ff58cafd498d1d2842184950c1d", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 189, "avg_line_length": 29.755102040816325, "alnum_prop": 0.7606310013717421, "repo_name": "ev1stensberg/lighthouse", "id": "ab24478072af2fa6660947295695cc8f3bdc28ef", "size": "1479", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lighthouse-viewer/README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "39729" }, { "name": "HTML", "bytes": "116705" }, { "name": "JavaScript", "bytes": "1821251" }, { "name": "Ruby", "bytes": "7024" }, { "name": "Shell", "bytes": "12285" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "c9a1e1a64a1e58ea089f531ee53cea71", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "c4e52adff15c7d66229ead7b00963152e508d2e0", "size": "174", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Urticaceae/Urtica/Urtica roxburghii/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
namespace { SkColor kBGColor = SkColorSetARGB(255, 52, 52, 50); } // namespace namespace xwalk { TizenSystemIndicator::TizenSystemIndicator() : watcher_(new TizenSystemIndicatorWatcher(this)) { if (!watcher_->Connect()) { watcher_.reset(); return; } set_background(views::Background::CreateSolidBackground(kBGColor)); content::BrowserThread::PostTask( content::BrowserThread::IO, FROM_HERE, base::Bind(&TizenSystemIndicatorWatcher::StartWatching, base::Unretained(watcher_.get()))); } TizenSystemIndicator::~TizenSystemIndicator() { } bool TizenSystemIndicator::IsConnected() const { return watcher_; } void TizenSystemIndicator::OnPaint(gfx::Canvas* canvas) { View::OnPaint(canvas); if (image_.isNull()) return; canvas->DrawImageInt(image_, 0, 0); } gfx::Size TizenSystemIndicator::GetPreferredSize() { return watcher_->GetSize(); } void TizenSystemIndicator::SetImage(const gfx::ImageSkia& img) { image_ = img; SchedulePaint(); } bool TizenSystemIndicator::OnMousePressed(const ui::MouseEvent& event) { watcher_->OnMouseDown(); return true; } void TizenSystemIndicator::OnMouseReleased(const ui::MouseEvent& event) { watcher_->OnMouseUp(); } void TizenSystemIndicator::OnTouchEvent(ui::TouchEvent* event) { const gfx::Point position = event->location(); switch (event->type()) { case ui::ET_UNKNOWN: case ui::ET_MOUSE_PRESSED: case ui::ET_MOUSE_DRAGGED: case ui::ET_MOUSE_RELEASED: case ui::ET_MOUSE_MOVED: case ui::ET_MOUSE_ENTERED: case ui::ET_MOUSE_EXITED: case ui::ET_KEY_PRESSED: case ui::ET_KEY_RELEASED: case ui::ET_MOUSEWHEEL: case ui::ET_MOUSE_CAPTURE_CHANGED: case ui::ET_TOUCH_RELEASED: watcher_->OnMouseUp(); break; case ui::ET_TOUCH_PRESSED: watcher_->OnMouseDown(); break; case ui::ET_TOUCH_MOVED: watcher_->OnMouseMove(position.x(), position.y()); break; case ui::ET_TOUCH_STATIONARY: case ui::ET_TOUCH_CANCELLED: case ui::ET_DROP_TARGET_EVENT: case ui::ET_TRANSLATED_KEY_PRESS: case ui::ET_TRANSLATED_KEY_RELEASE: case ui::ET_GESTURE_SCROLL_BEGIN: case ui::ET_GESTURE_SCROLL_END: case ui::ET_GESTURE_SCROLL_UPDATE: case ui::ET_GESTURE_TAP: case ui::ET_GESTURE_TAP_DOWN: case ui::ET_GESTURE_TAP_CANCEL: case ui::ET_GESTURE_BEGIN: case ui::ET_GESTURE_END: case ui::ET_GESTURE_TWO_FINGER_TAP: case ui::ET_GESTURE_PINCH_BEGIN: case ui::ET_GESTURE_PINCH_END: case ui::ET_GESTURE_PINCH_UPDATE: case ui::ET_GESTURE_LONG_PRESS: case ui::ET_GESTURE_LONG_TAP: case ui::ET_GESTURE_MULTIFINGER_SWIPE: case ui::ET_SCROLL: case ui::ET_SCROLL_FLING_START: case ui::ET_SCROLL_FLING_CANCEL: case ui::ET_CANCEL_MODE: case ui::ET_UMA_DATA: case ui::ET_LAST: break; } event->SetHandled(); } void TizenSystemIndicator::OnMouseMoved(const ui::MouseEvent& event) { const gfx::Point position = event.location(); watcher_->OnMouseMove(position.x(), position.y()); } } // namespace xwalk
{ "content_hash": "f12071a6d96ee9711f04013052437cb0", "timestamp": "", "source": "github", "line_count": 117, "max_line_length": 73, "avg_line_length": 26.384615384615383, "alnum_prop": 0.6747651441528992, "repo_name": "Shouqun/crosswalk", "id": "6e55318f58f7af25f543f2b727c0ca1f7d58e1e9", "size": "3580", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "runtime/browser/ui/tizen_system_indicator.cc", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "29648" }, { "name": "C++", "bytes": "769508" }, { "name": "Java", "bytes": "214330" }, { "name": "JavaScript", "bytes": "3286" }, { "name": "Objective-C", "bytes": "17188" }, { "name": "Python", "bytes": "80956" }, { "name": "Shell", "bytes": "1984" } ], "symlink_target": "" }
package com.dataartisans.flink.dataflow.translation.types; import com.dataartisans.flink.dataflow.translation.wrappers.DataInputViewWrapper; import com.dataartisans.flink.dataflow.translation.wrappers.DataOutputViewWrapper; import com.google.cloud.dataflow.sdk.coders.Coder; import com.google.cloud.dataflow.sdk.coders.CoderException; import org.apache.flink.api.common.typeutils.TypeSerializer; import org.apache.flink.core.memory.DataInputView; import org.apache.flink.core.memory.DataOutputView; import java.io.ByteArrayInputStream; import java.io.EOFException; import java.io.IOException; import java.io.ObjectInputStream; /** * Flink {@link org.apache.flink.api.common.typeutils.TypeSerializer} for * Dataflow {@link com.google.cloud.dataflow.sdk.coders.Coder}s */ public class CoderTypeSerializer<T> extends TypeSerializer<T> { private Coder<T> coder; private transient DataInputViewWrapper inputWrapper; private transient DataOutputViewWrapper outputWrapper; // We use this for internal encoding/decoding for creating copies using the Coder. private transient InspectableByteArrayOutputStream buffer; public CoderTypeSerializer(Coder<T> coder) { this.coder = coder; this.inputWrapper = new DataInputViewWrapper(null); this.outputWrapper = new DataOutputViewWrapper(null); buffer = new InspectableByteArrayOutputStream(); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); this.inputWrapper = new DataInputViewWrapper(null); this.outputWrapper = new DataOutputViewWrapper(null); buffer = new InspectableByteArrayOutputStream(); } @Override public boolean isImmutableType() { return false; } @Override public CoderTypeSerializer<T> duplicate() { return new CoderTypeSerializer<>(coder); } @Override public T createInstance() { return null; } @Override public T copy(T t) { buffer.reset(); try { coder.encode(t, buffer, Coder.Context.OUTER); } catch (IOException e) { throw new RuntimeException("Could not copy.", e); } try { return coder.decode(new ByteArrayInputStream(buffer.getBuffer(), 0, buffer .size()), Coder.Context.OUTER); } catch (IOException e) { throw new RuntimeException("Could not copy.", e); } } @Override public T copy(T t, T reuse) { return copy(t); } @Override public int getLength() { return 0; } @Override public void serialize(T t, DataOutputView dataOutputView) throws IOException { outputWrapper.setOutputView(dataOutputView); coder.encode(t, outputWrapper, Coder.Context.NESTED); } @Override public T deserialize(DataInputView dataInputView) throws IOException { try { inputWrapper.setInputView(dataInputView); return coder.decode(inputWrapper, Coder.Context.NESTED); } catch (CoderException e) { Throwable cause = e.getCause(); if (cause instanceof EOFException) { throw (EOFException) cause; } else { throw e; } } } @Override public T deserialize(T t, DataInputView dataInputView) throws IOException { return deserialize(dataInputView); } @Override public void copy(DataInputView dataInputView, DataOutputView dataOutputView) throws IOException { serialize(deserialize(dataInputView), dataOutputView); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CoderTypeSerializer that = (CoderTypeSerializer) o; if (!coder.equals(that.coder)) { return false; } return true; } @Override public int hashCode() { return coder.hashCode(); } }
{ "content_hash": "3262b926ad816c482becab0bb0f66c68", "timestamp": "", "source": "github", "line_count": 140, "max_line_length": 98, "avg_line_length": 25.857142857142858, "alnum_prop": 0.7488950276243094, "repo_name": "mbalassi/flink-dataflow", "id": "6a12e83557b11d5c6436c67806bff99efe34a7ed", "size": "4227", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/dataartisans/flink/dataflow/translation/types/CoderTypeSerializer.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "270660" } ], "symlink_target": "" }
'use strict'; /* eslint prefer-arrow-callback: 0 */ const app = require('../app'); const request = require('supertest'); const expect = require('chai').expect; describe('Thing API:', function () { let newThing; describe('GET /api/things', function () { let things; beforeEach(function (done) { request(app) .get('/api/things') .expect(200) .expect('Content-Type', /json/) .end((err, res) => { if (err) return done(err); things = res.body; return done(); }); }); it('should respond with JSON array', function () { expect(things).to.be.instanceOf(Array); }); }); describe('POST /api/things', function () { beforeEach(function (done) { request(app) .post('/api/things') .send({ name: 'New Thing', info: 'This is the brand new thing!!!', }) .expect(201) .expect('Content-Type', /json/) .end((err, res) => { if (err) return done(err); newThing = res.body; return done(); }); }); it('should respond with the newly created thing', function () { expect(newThing.name).to.equal('New Thing'); expect(newThing.info).to.equal('This is the brand new thing!!!'); }); }); describe('GET /api/things/:id', function () { let thing; beforeEach(function (done) { request(app) .get('/api/things/' + newThing.id) .expect(200) .expect('Content-Type', /json/) .end((err, res) => { if (err) return done(err); thing = res.body; return done(); }); }); afterEach(function () { thing = {}; }); it('should respond with the requested thing', function () { expect(thing.name).to.equal('New Thing'); expect(thing.info).to.equal('This is the brand new thing!!!'); }); }); describe('PUT /api/things/:id', function () { let updatedThing; beforeEach(function (done) { request(app) .put('/api/things/' + newThing.id) .send({ name: 'Updated Thing', info: 'This is the updated thing!!!', }) .expect(200) .expect('Content-Type', /json/) .end((err, res) => { if (err) return done(err); updatedThing = res.body; return done(); }); }); afterEach(function () { updatedThing = {}; }); it('should respond with the updated thing', function () { expect(updatedThing.name).to.equal('Updated Thing'); expect(updatedThing.info).to.equal('This is the updated thing!!!'); }); }); describe('DELETE /api/things/:id', function () { it('should respond with 204 on successful removal', function (done) { request(app) .delete('/api/things/' + newThing.id) .expect(204) .end((err, res) => { if (err) return done(err); return done(); }); }); it('should respond with 404 when thing does not exist', function (done) { request(app) .delete('/api/things/' + newThing.id) .expect(404) .end((err, res) => { if (err) return done(err); return done(); }); }); }); });
{ "content_hash": "7fd9fc5e820cf48f44b2a3b98e4f9724", "timestamp": "", "source": "github", "line_count": 128, "max_line_length": 77, "avg_line_length": 25.703125, "alnum_prop": 0.517629179331307, "repo_name": "chunkai1312/ng6-fullstack", "id": "d1c1f3789c1fa4ea1646eba18f4293abb923eaf1", "size": "3290", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/server/test/thing.test.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2584" }, { "name": "HTML", "bytes": "12563" }, { "name": "JavaScript", "bytes": "63800" } ], "symlink_target": "" }
<?php require_once dirname(__FILE__) . "/../Query/Student.php"; require_once dirname(__FILE__) . "/../API/Utility.php"; // Database connection if (!($CONNECTION = fido_db_connect())) { echo "<p>Connection Failed</p>\n"; exit(); } //check if user is in the database, if not insert them if (!($result = get_student_id_by_username($_SERVER['PHP_AUTH_USER']))) { echo "Could not determine if user is in database or not"; } else if (pg_num_rows($result) == 0) { $new_user = $_SERVER['PHP_AUTH_USER']; $join_date = new Datetime("now"); if (!add_student($new_user, $join_date)) { echo "ERROR: Logged in student not in database and insertion failed"; } } else { } //check if the user is an admin or not $admin = false; $admins = array( 'bowzr', 'shrugz4life', 'dog01', 'unix4life', 'princessz', 'koopaking' ); //TODO: when LDAP is intigrated, change logic to set $admin flag if (in_array($_SERVER['PHP_AUTH_USER'], $admins)) { $admin = true; } ?>
{ "content_hash": "932f7c0ab8bd805923bd1ab1a5b356d0", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 77, "avg_line_length": 25.25, "alnum_prop": 0.6118811881188119, "repo_name": "The-Duchess/CAT-Scheduler", "id": "eedca9bd91475999f33cf3ecbc54890b45247602", "size": "1010", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Source/Pages/login_handler.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "376" }, { "name": "CSS", "bytes": "3295" }, { "name": "HTML", "bytes": "118891" }, { "name": "JavaScript", "bytes": "53925" }, { "name": "PHP", "bytes": "158834" }, { "name": "Shell", "bytes": "202" } ], "symlink_target": "" }
/** * @flow */ import type {ExtendedModule} from '../types/Stats'; export type SortableFields = $Keys<ExtendedModule>; export type SortDirection = 'ASC' | 'DESC'; export type SortProps = { field: SortableFields, direction: SortDirection, }; type SortResult = -1 | 0 | 1; function checkDirection( direction: SortDirection, sort: SortResult, ): SortResult { if (sort === 0 || direction === 'ASC') { return sort; } else { return sort > 0 ? -1 : 1; } } // flowlint-next-line unclear-type:off function compare(a: any, b: any): SortResult { return (a === b ? 0 : (a > b ? 1 : -1)); } export default function sortModules( extendedModules: Array<ExtendedModule>, sort: SortProps, ): Array<ExtendedModule> { return extendedModules .sort((a: ExtendedModule, b: ExtendedModule) => { const {field, direction} = sort; return checkDirection(direction, compare(a[field], b[field])); }); }
{ "content_hash": "fc3fc43a44069b7fc4e7971d43f3ed5e", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 68, "avg_line_length": 21.72093023255814, "alnum_prop": 0.6477516059957173, "repo_name": "pinterest/bonsai", "id": "4c15ccd9bdcbf0db464b417edb037f2dbd3b1686", "size": "934", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/stats/sortModules.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1068" }, { "name": "HTML", "bytes": "1482" }, { "name": "JavaScript", "bytes": "220432" }, { "name": "Shell", "bytes": "1909" } ], "symlink_target": "" }
#include "common/log.h" #include "TradeDbBean.h" namespace hku { std::vector<XueqiuAccountModel> TradeDbBean::queryAllXueqiuAccount() { std::vector<XueqiuAccountModel> result; std::string sql( fmt::format("select a.id, a.td_id, a.cookies, a.portfolio_code, a.portfolio_market, b.name, " "b.userid from " "td_account_xq a, td_account b where a.td_id=b.td_id and b.type='{}'", XueqiuAccountModel::ACCOUNT_TYPE)); auto con = TradeDbBean::getConnect(); SQLStatementPtr st = con->getStatement(sql); st->exec(); while (st->moveNext()) { XueqiuAccountModel mo; st->getColumn(0, mo.m_id, mo.td_id, mo.cookies, mo.portfolio_code, mo.portfolio_market, mo.m_name, mo.m_userid); result.push_back(mo); } return result; } bool TradeDbBean::queryXueqiuAccountsByTdId(int64_t id, XueqiuAccountModel& out_mo) { std::string sql(fmt::format( "select a.id, a.td_id, a.cookies, a.portfolio_code, a.portfolio_market, b.name, " "b.userid from " "td_account_xq a, td_account b where a.td_id=b.td_id and b.type='{}' and a.td_id={}", XueqiuAccountModel::ACCOUNT_TYPE, id)); auto con = TradeDbBean::getConnect(); SQLStatementPtr st = con->getStatement(sql); st->exec(); if (st->moveNext()) { st->getColumn(0, out_mo.m_id, out_mo.td_id, out_mo.cookies, out_mo.portfolio_code, out_mo.portfolio_market, out_mo.m_name, out_mo.m_userid); return true; } return false; } } // namespace hku
{ "content_hash": "61477b34926096be3302938e631106a3", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 99, "avg_line_length": 35.355555555555554, "alnum_prop": 0.612193588937775, "repo_name": "fasiondog/hikyuu", "id": "f0224531262263ee9c87bc6db04a3f86cb1140a3", "size": "1684", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "hikyuu_cpp/hikyuu_server/service/trade/bean/TradeDbBean.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "422" }, { "name": "C++", "bytes": "3954032" }, { "name": "Jupyter Notebook", "bytes": "2063922" }, { "name": "Lua", "bytes": "28945" } ], "symlink_target": "" }
<?php declare(strict_types=1); namespace Zend\Diactoros; use function Laminas\Diactoros\marshalUriFromSapi as laminas_marshalUriFromSapi; /** * @deprecated Use Laminas\Diactoros\marshalUriFromSapi instead */ function marshalUriFromSapi(array $server, array $headers) : Uri { return laminas_marshalUriFromSapi(...func_get_args()); }
{ "content_hash": "6f29fb0c6062c47143521ecb83f700f4", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 80, "avg_line_length": 22.8, "alnum_prop": 0.7719298245614035, "repo_name": "deforay/odkdash", "id": "f121f23fe457756fd338a8e9152f544296413143", "size": "342", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "vendor/laminas/laminas-diactoros/src/functions/marshal_uri_from_sapi.legacy.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "2671717" }, { "name": "HTML", "bytes": "974515" }, { "name": "JavaScript", "bytes": "2257422" }, { "name": "Makefile", "bytes": "285" }, { "name": "PHP", "bytes": "644826" }, { "name": "Python", "bytes": "16281" }, { "name": "Shell", "bytes": "1061" } ], "symlink_target": "" }
This project serves as a starting base for the CS Games 2016 Mobile Competition. You may edit it as much as you like (or start completely from scratch if you prefer) – as long as you make something awesome! ## Prerequisites Make sure you have the following software installed before beginning: - Latest version of Android Studio (1.5.1) - Recent version of the Android SDK (at least API 21) You can download these from the [Android Developer website](http://developer.android.com/sdk/index.html). > **NOTE:** If you have a Mac computer running OS X 10.10 or later, you may also be interested in our [Android app](https://github.com/mirego/csgames16-competition/tree/master/ios), which uses Xcode and the latest iOS SDK. ## Getting started First, make sure you have cloned the project from Github: ``` git clone http://github.com/mirego/csgames16-competition.git ``` Then, in Android Studio: - Select **Import project (Eclipse, ADT, Gradle, etc.)** in the Welcome Screen, go find the `android` folder in the repository you just cloned, and click **OK**. - Once the project is open, click on **Sync Project with Gradle Files** in the main toolbar (or navigate to `Tools -> Android` in the application menu and select the same option). <p align="center"><img src="https://cloud.githubusercontent.com/assets/4378424/13450169/9f925920-e000-11e5-999a-464b9949ee9a.png" width="199"></p> Once you see a `BUILD SUCCESSFUL` notice in the Gradle Console, your environment should be ready to build and run the project. ### Web server For the app to communicate with the local web server, you must set your local IP address in the project configuration file. In `res/vales/config.xml`: - Change the value of `service_host` to the IP address of your computer on the local network (you cannot set `localhost` or `127.0.0.1` because it will use the loopback of the Android device). ## Building the project The project should have already been configured as an Android project in Android Studio, therefore you should see a target named `app` in the main toolbar, with **Play** and **Debug** buttons on its right. Press on the **Debug** icon, and if you don't already have one, [create a new Android Virtual Device](http://developer.android.com/tools/devices/managing-avds.html), then select it to run the project. Once the app appears running in your Virtual Device, your environment is ready for the competition. ## How it works **Rebel Chat** is a small application that imitates the popular messaging application [Snapchat](https://www.snapchat.com/). It is very basic however, as it can only send random message strings and a fixed image. It should be fairly straightforward to use and customize, but if you want to know more about it, you can read on. > **NOTE:** Before you begin, make sure the web server is up and running (see the [server page](https://github.com/mirego/csgames16-competition/tree/master/server)). ### Activities The app contains three main activities: - `HomeActivity`: The **home screen**, with *login* and *registration* buttons - `LoginActivity`: The **login screen**, with is used for both *sign up* and *sign in* - `MessageActivity`: The **messaging screen**, with random text strings and a fixed image You will customize mostly the latter, where you can add real messaging functionalities. You are free to change the project structure and add as many activities as you want, but keep in mind that 3 hours go very fast. ### Dependencies As you will see from the `build.gradle`, this project uses a couple of public libraries: - **[Butterknife](http://jakewharton.github.io/butterknife/)**: View injection library, for easier usage of views inside activities - **[Calligraphy](https://github.com/chrisjenx/Calligraphy)**: Small utility to load custom fonts easily, for the _Rebellion_ style of the app - **[OkHttp](https://github.com/square/okhttp)**: Simple HTTP client for Android, to easily send requests to the web server These make up the project as it is, but you may add or remove dependencies as much as you like. ### Controllers The app contains two data sources: - `LoginController`: For user login and registration - `MessageController`: For messages sent through the app They offer very basic support for two routes available in the [server](https://github.com/mirego/csgames16-competition/tree/master/server). The data is not validated, except for the user login, where only existing users are authorized. ### Next steps So, what's the room for improvement? Here are some features you could add to this app: - Customization of the text message (various fonts, colors or layouts) - Customization of the background image (from the library or from other apps) - Drawing tools (various brushes sizes or colors) - Message encryption - Real-time chat messaging - Video messaging (simple camera stream, video effects) The list is non-exhaustive, feel free to do anything you can think of! ## License This competition is © 2016 [Mirego](http://www.mirego.com) and may be freely distributed under the [New BSD license](http://opensource.org/licenses/BSD-3-Clause). See the [`LICENSE.md`](https://github.com/mirego/csgames16-competition/blob/master/LICENSE.md) file. ## About Mirego [Mirego](http://mirego.com) is a team of passionate people who believe that work is a place where you can innovate and have fun. We're a team of [talented people](http://life.mirego.com) who imagine and build beautiful Web and mobile applications. We come together to share ideas and [change the world](http://mirego.org). We also [love open-source software](http://open.mirego.com) and we try to give back to the community as much as we can.
{ "content_hash": "b7236af8c8b1cbc36207b941edad2968", "timestamp": "", "source": "github", "line_count": 111, "max_line_length": 322, "avg_line_length": 51.26126126126126, "alnum_prop": 0.7606326889279438, "repo_name": "TyMarc/turbo-spork", "id": "1ef6c388191224be82b0011da2c5091f5616a5e8", "size": "5733", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "android/README.md", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "1019" }, { "name": "HTML", "bytes": "2357" }, { "name": "Java", "bytes": "79450" }, { "name": "JavaScript", "bytes": "14125" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in Mushrooms of Cape Cod and the National Seashore (Syracuse) 32 (2001) #### Original name Boletus edulis subsp. aurantioruber E.A. Dick & Snell ### Remarks null
{ "content_hash": "59ffdb32a4457090f269bb51083e2559", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 68, "avg_line_length": 17.076923076923077, "alnum_prop": 0.7297297297297297, "repo_name": "mdoering/backbone", "id": "ac38cf8bc8c28a5bf07951a6bd419c46fe18a8cf", "size": "315", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Basidiomycota/Agaricomycetes/Boletales/Boletaceae/Boletus/Boletus aurantioruber/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import PropTypes from 'prop-types'; const propTypes = { className: PropTypes.string, children: PropTypes.node.isRequired }; class Dropdown extends Component { constructor(props) { super(props); if (props.children.length !== 2) { throw new Error('Dropdown component requires exactly 2 children'); } this.onOutsideClick = this.onOutsideClick.bind(this); this.toggleIsOpen = this.toggleIsOpen.bind(this); this.state = { isOpen: false }; } componentDidMount() { document.addEventListener('mousedown', this.onOutsideClick); } componentWillUnmount() { document.removeEventListener('mousedown', this.onOutsideClick); } onOutsideClick(e) { if (!this.state.isOpen) { return; } if (!this.dropdown.contains(e.target)) { this.setState({ isOpen: false }) } } toggleIsOpen() { this.setState({ isOpen: !this.state.isOpen }); } render() { const { isOpen } = this.state; const { className, children } = this.props; return ( <div ref={(dropdown) => { this.dropdown = dropdown; }} className={`${className} dropdown ${(isOpen ? ' open': '')}`} onClick={this.toggleIsOpen} > {children[0]} {isOpen ? children[1] : null} </div> ); } } Dropdown.propTypes = propTypes; export default Dropdown;
{ "content_hash": "9986f87d2545890eed5b6ea8cd7154a1", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 72, "avg_line_length": 22.303030303030305, "alnum_prop": 0.6100543478260869, "repo_name": "fangweb/tmdb-redux", "id": "8d51dfcd90fa480c395412e55914a2f69a180372", "size": "1472", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "client/components/Dropdown.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "8485" }, { "name": "HTML", "bytes": "335" }, { "name": "JavaScript", "bytes": "33649" } ], "symlink_target": "" }
<?php namespace Magento\SalesRule\Controller\Adminhtml\Promo\Quote; class NewActionHtml extends \Magento\SalesRule\Controller\Adminhtml\Promo\Quote { /** * New action html action * * @return void */ public function execute() { $id = $this->getRequest()->getParam('id'); $typeArr = explode('|', str_replace('-', '/', $this->getRequest()->getParam('type'))); $type = $typeArr[0]; $model = $this->_objectManager->create( $type )->setId( $id )->setType( $type )->setRule( $this->_objectManager->create('Magento\SalesRule\Model\Rule') )->setPrefix( 'actions' ); if (!empty($typeArr[1])) { $model->setAttribute($typeArr[1]); } if ($model instanceof \Magento\Rule\Model\Condition\AbstractCondition) { $model->setJsFormObject($this->getRequest()->getParam('form')); $html = $model->asHtmlRecursive(); } else { $html = ''; } $this->getResponse()->setBody($html); } }
{ "content_hash": "c95912cbc411c6fc82a55fbede6bbec3", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 94, "avg_line_length": 27.463414634146343, "alnum_prop": 0.5230905861456483, "repo_name": "tarikgwa/test", "id": "cf383bfed2d0c28b46e728a2bdc40425458018f3", "size": "1227", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "html/app/code/Magento/SalesRule/Controller/Adminhtml/Promo/Quote/NewActionHtml.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "26588" }, { "name": "CSS", "bytes": "4874492" }, { "name": "HTML", "bytes": "8635167" }, { "name": "JavaScript", "bytes": "6810903" }, { "name": "PHP", "bytes": "55645559" }, { "name": "Perl", "bytes": "7938" }, { "name": "Shell", "bytes": "4505" }, { "name": "XSLT", "bytes": "19889" } ], "symlink_target": "" }
<?php namespace ngresttest\controllers; /** * Table Controller. * * File has been created with `crud/create` command on LUYA version 1.0.0-RC2-dev. */ class TableController extends \luya\admin\ngrest\base\Controller { /** * @var string The path to the model which is the provider for the rules and fields. */ public $modelClass = 'ngresttest\models\Table'; }
{ "content_hash": "4ab4236ab9445b3b7428ee58ff121803", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 88, "avg_line_length": 23.9375, "alnum_prop": 0.6945169712793734, "repo_name": "vuongminh/luya", "id": "1a4004b2bc5170cf9175a20d157960bb1199a73a", "size": "383", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "envs/dev/modules/ngresttest/controllers/TableController.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "1509" }, { "name": "CSS", "bytes": "229397" }, { "name": "HTML", "bytes": "45192" }, { "name": "JavaScript", "bytes": "205670" }, { "name": "PHP", "bytes": "2509552" }, { "name": "Shell", "bytes": "3746" } ], "symlink_target": "" }
<!DOCTYPE html><html><head><meta charset="utf-8" /> <meta http-equiv="refresh" content="0;url=/place/sweden/water/" /> </head></html>
{ "content_hash": "c6f2779a31081c49d5257ebfc58c30a7", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 66, "avg_line_length": 44.333333333333336, "alnum_prop": 0.6691729323308271, "repo_name": "okfn/opendataindex-2015", "id": "4e5d62fb2e81f982f7290275e05bb16768142685", "size": "133", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "country/overview/Sweden/water/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "277465" }, { "name": "HTML", "bytes": "169425658" }, { "name": "JavaScript", "bytes": "37060" } ], "symlink_target": "" }
<p align="left">You can't have great software without a great team, and most software teams behave like dysfunctional families. <br> <i>--Jim McCarthy </i><em>[<a target="_blank" href="http://www.eskimo.com/~hottub/software/programming_quotes.html"> source</a>]</em></p>
{ "content_hash": "dbecc268bb080a36c1debb3c4d8985c7", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 117, "avg_line_length": 55.2, "alnum_prop": 0.7101449275362319, "repo_name": "Hackafe/lp-intro", "id": "7d1f525b8255b37405430521d3d276f2ebc7e68f", "size": "276", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/quotes/damithch173.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1082" }, { "name": "HTML", "bytes": "89768" }, { "name": "JavaScript", "bytes": "4245" } ], "symlink_target": "" }
using System; namespace MicroFx { public class ResourceNotFoundException : Exception { public ResourceNotFoundException(string msg):base(msg) { } } }
{ "content_hash": "95259ab1a706e15f2c03f8ddc7029183", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 62, "avg_line_length": 16.583333333333332, "alnum_prop": 0.5979899497487438, "repo_name": "NinjaRocks/MicroFX", "id": "c52c83660a89507c2df6135e3a55ded365c6bae7", "size": "199", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/MicroFx/ResourceNotFoundException.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "75163" } ], "symlink_target": "" }
package cmcc.iot.onenet.javasdk.api.bindata; import java.util.HashMap; import java.util.Map; import org.apache.http.HttpResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.ObjectMapper; import cmcc.iot.onenet.javasdk.api.AbstractAPI; import cmcc.iot.onenet.javasdk.exception.OnenetApiException; import cmcc.iot.onenet.javasdk.http.HttpPostMethod; import cmcc.iot.onenet.javasdk.request.RequestInfo.Method; import cmcc.iot.onenet.javasdk.response.BasicResponse; import cmcc.iot.onenet.javasdk.response.bindata.NewBindataResponse; import cmcc.iot.onenet.javasdk.utils.Config; public class AddBindataApi extends AbstractAPI{ private final Logger logger = LoggerFactory.getLogger(this.getClass()); private String devId; private String datastreamId; private String filename; private String filepath; private HttpPostMethod HttpMethod; /** * @param devId:数据所属设备(必选),String * @param datastreamId:该数据所属已经存在的数据流(必选),String * @param key:masterkey 或者 该设备的设备key * @param filename:文件名,String * @param filepath:路径,String */ public AddBindataApi(String devId, String datastreamId,String key, String filename,String filepath) { this.devId = devId; this.datastreamId = datastreamId; this.key=key; this.filename=filename; this.filepath=filepath; this.method=Method.POST; Map<String, Object> headmap = new HashMap<String, Object>(); HttpMethod= new HttpPostMethod(method); headmap.put("api-key", key); HttpMethod.setHeader(headmap); this.url=Config.getString("test.url")+"/bindata"; Map<String, Object> urlmap = new HashMap<String, Object>(); if(devId!=null){ urlmap.put("device_id", devId); } if(datastreamId!=null){ urlmap.put("datastream_id", datastreamId); } Map<String, String> fileMap=new HashMap<String, String>(); fileMap.put(filename, filepath); ((HttpPostMethod)HttpMethod).setEntity(null,fileMap); HttpMethod.setcompleteUrl(url,urlmap); } public BasicResponse<NewBindataResponse> executeApi(){ BasicResponse response=null; try { HttpResponse httpResponse=HttpMethod.execute(); response = mapper.readValue(httpResponse.getEntity().getContent(),BasicResponse.class); response.setJson(mapper.writeValueAsString(response)); Object newData = mapper.readValue(mapper.writeValueAsString(response.getDataInternal()), NewBindataResponse.class); response.setData(newData); return response; } catch (Exception e) { logger.error("json error {}", e.getMessage()); throw new OnenetApiException(e.getMessage()); }finally { try { HttpMethod.httpClient.close(); } catch (Exception e) { logger.error("http close error: {}", e.getMessage()); throw new OnenetApiException(e.getMessage()); } } } }
{ "content_hash": "79c652d84a5b7bb056d9e85a4aeb9086", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 118, "avg_line_length": 34.154761904761905, "alnum_prop": 0.7253398396653886, "repo_name": "cm-heclouds/JAVA-HTTP-SDK", "id": "4a3017922c1696a5b70469a2f5920012d37208ae", "size": "2951", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "javaSDK/src/main/java/cmcc/iot/onenet/javasdk/api/bindata/AddBindataApi.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "228928" } ], "symlink_target": "" }
this["wp"] = this["wp"] || {}; this["wp"]["coreData"] = /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 309); /******/ }) /************************************************************************/ /******/ ({ /***/ 120: /***/ (function(module, exports) { module.exports = function(originalModule) { if (!originalModule.webpackPolyfill) { var module = Object.create(originalModule); // module.parent = undefined by default if (!module.children) module.children = []; Object.defineProperty(module, "loaded", { enumerable: true, get: function() { return module.l; } }); Object.defineProperty(module, "id", { enumerable: true, get: function() { return module.i; } }); Object.defineProperty(module, "exports", { enumerable: true }); module.webpackPolyfill = 1; } return module; }; /***/ }), /***/ 15: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return _defineProperty; }); function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } /***/ }), /***/ 19: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; // CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/arrayWithoutHoles.js function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/iterableToArray.js var iterableToArray = __webpack_require__(33); // CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/nonIterableSpread.js function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } // CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/toConsumableArray.js /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return _toConsumableArray; }); function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || Object(iterableToArray["a" /* default */])(arr) || _nonIterableSpread(); } /***/ }), /***/ 2: /***/ (function(module, exports) { (function() { module.exports = this["lodash"]; }()); /***/ }), /***/ 24: /***/ (function(module, exports) { (function() { module.exports = this["wp"]["url"]; }()); /***/ }), /***/ 25: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/arrayWithHoles.js var arrayWithHoles = __webpack_require__(35); // CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/iterableToArrayLimit.js function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/nonIterableRest.js var nonIterableRest = __webpack_require__(36); // CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/slicedToArray.js /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return _slicedToArray; }); function _slicedToArray(arr, i) { return Object(arrayWithHoles["a" /* default */])(arr) || _iterableToArrayLimit(arr, i) || Object(nonIterableRest["a" /* default */])(); } /***/ }), /***/ 30: /***/ (function(module, exports) { (function() { module.exports = this["wp"]["apiFetch"]; }()); /***/ }), /***/ 309: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); var build_module_actions_namespaceObject = {}; __webpack_require__.r(build_module_actions_namespaceObject); __webpack_require__.d(build_module_actions_namespaceObject, "receiveUserQuery", function() { return receiveUserQuery; }); __webpack_require__.d(build_module_actions_namespaceObject, "addEntities", function() { return addEntities; }); __webpack_require__.d(build_module_actions_namespaceObject, "receiveEntityRecords", function() { return receiveEntityRecords; }); __webpack_require__.d(build_module_actions_namespaceObject, "receiveThemeSupports", function() { return receiveThemeSupports; }); __webpack_require__.d(build_module_actions_namespaceObject, "receiveEmbedPreview", function() { return receiveEmbedPreview; }); __webpack_require__.d(build_module_actions_namespaceObject, "saveEntityRecord", function() { return saveEntityRecord; }); __webpack_require__.d(build_module_actions_namespaceObject, "receiveUploadPermissions", function() { return receiveUploadPermissions; }); var build_module_selectors_namespaceObject = {}; __webpack_require__.r(build_module_selectors_namespaceObject); __webpack_require__.d(build_module_selectors_namespaceObject, "isRequestingEmbedPreview", function() { return isRequestingEmbedPreview; }); __webpack_require__.d(build_module_selectors_namespaceObject, "getAuthors", function() { return getAuthors; }); __webpack_require__.d(build_module_selectors_namespaceObject, "getUserQueryResults", function() { return getUserQueryResults; }); __webpack_require__.d(build_module_selectors_namespaceObject, "getEntitiesByKind", function() { return getEntitiesByKind; }); __webpack_require__.d(build_module_selectors_namespaceObject, "getEntity", function() { return getEntity; }); __webpack_require__.d(build_module_selectors_namespaceObject, "getEntityRecord", function() { return getEntityRecord; }); __webpack_require__.d(build_module_selectors_namespaceObject, "getEntityRecords", function() { return getEntityRecords; }); __webpack_require__.d(build_module_selectors_namespaceObject, "getThemeSupports", function() { return getThemeSupports; }); __webpack_require__.d(build_module_selectors_namespaceObject, "getEmbedPreview", function() { return getEmbedPreview; }); __webpack_require__.d(build_module_selectors_namespaceObject, "isPreviewEmbedFallback", function() { return isPreviewEmbedFallback; }); __webpack_require__.d(build_module_selectors_namespaceObject, "hasUploadPermissions", function() { return selectors_hasUploadPermissions; }); var resolvers_namespaceObject = {}; __webpack_require__.r(resolvers_namespaceObject); __webpack_require__.d(resolvers_namespaceObject, "getAuthors", function() { return resolvers_getAuthors; }); __webpack_require__.d(resolvers_namespaceObject, "getEntityRecord", function() { return resolvers_getEntityRecord; }); __webpack_require__.d(resolvers_namespaceObject, "getEntityRecords", function() { return resolvers_getEntityRecords; }); __webpack_require__.d(resolvers_namespaceObject, "getThemeSupports", function() { return resolvers_getThemeSupports; }); __webpack_require__.d(resolvers_namespaceObject, "getEmbedPreview", function() { return resolvers_getEmbedPreview; }); __webpack_require__.d(resolvers_namespaceObject, "hasUploadPermissions", function() { return resolvers_hasUploadPermissions; }); // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/objectSpread.js var objectSpread = __webpack_require__(8); // EXTERNAL MODULE: external {"this":["wp","data"]} var external_this_wp_data_ = __webpack_require__(5); // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/slicedToArray.js + 1 modules var slicedToArray = __webpack_require__(25); // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/toConsumableArray.js + 2 modules var toConsumableArray = __webpack_require__(19); // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/esm/defineProperty.js var defineProperty = __webpack_require__(15); // EXTERNAL MODULE: external "lodash" var external_lodash_ = __webpack_require__(2); // CONCATENATED MODULE: ./node_modules/@wordpress/core-data/build-module/utils/if-matching-action.js /** * A higher-order reducer creator which invokes the original reducer only if * the dispatching action matches the given predicate, **OR** if state is * initializing (undefined). * * @param {Function} isMatch Function predicate for allowing reducer call. * * @return {Function} Higher-order reducer. */ var ifMatchingAction = function ifMatchingAction(isMatch) { return function (reducer) { return function (state, action) { if (state === undefined || isMatch(action)) { return reducer(state, action); } return state; }; }; }; /* harmony default export */ var if_matching_action = (ifMatchingAction); // CONCATENATED MODULE: ./node_modules/@wordpress/core-data/build-module/utils/on-sub-key.js /** * Higher-order reducer creator which creates a combined reducer object, keyed * by a property on the action object. * * @param {string} actionProperty Action property by which to key object. * * @return {Function} Higher-order reducer. */ var on_sub_key_onSubKey = function onSubKey(actionProperty) { return function (reducer) { return function () { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var action = arguments.length > 1 ? arguments[1] : undefined; // Retrieve subkey from action. Do not track if undefined; useful for cases // where reducer is scoped by action shape. var key = action[actionProperty]; if (key === undefined) { return state; } // Avoid updating state if unchanged. Note that this also accounts for a // reducer which returns undefined on a key which is not yet tracked. var nextKeyState = reducer(state[key], action); if (nextKeyState === state[key]) { return state; } return Object(objectSpread["a" /* default */])({}, state, Object(defineProperty["a" /* default */])({}, key, nextKeyState)); }; }; }; /* harmony default export */ var on_sub_key = (on_sub_key_onSubKey); // CONCATENATED MODULE: ./node_modules/@wordpress/core-data/build-module/utils/replace-action.js /** * Higher-order reducer creator which substitutes the action object before * passing to the original reducer. * * @param {Function} replacer Function mapping original action to replacement. * * @return {Function} Higher-order reducer. */ var replaceAction = function replaceAction(replacer) { return function (reducer) { return function (state, action) { return reducer(state, replacer(action)); }; }; }; /* harmony default export */ var replace_action = (replaceAction); // CONCATENATED MODULE: ./node_modules/@wordpress/core-data/build-module/utils/with-weak-map-cache.js /** * External dependencies */ /** * Given a function, returns an enhanced function which caches the result and * tracks in WeakMap. The result is only cached if the original function is * passed a valid object-like argument (requirement for WeakMap key). * * @param {Function} fn Original function. * * @return {Function} Enhanced caching function. */ function withWeakMapCache(fn) { var cache = new WeakMap(); return function (key) { var value; if (cache.has(key)) { value = cache.get(key); } else { value = fn(key); // Can reach here if key is not valid for WeakMap, since `has` // will return false for invalid key. Since `set` will throw, // ensure that key is valid before setting into cache. if (Object(external_lodash_["isObjectLike"])(key)) { cache.set(key, value); } } return value; }; } /* harmony default export */ var with_weak_map_cache = (withWeakMapCache); // CONCATENATED MODULE: ./node_modules/@wordpress/core-data/build-module/utils/index.js // CONCATENATED MODULE: ./node_modules/@wordpress/core-data/build-module/queried-data/actions.js /** * External dependencies */ /** * Returns an action object used in signalling that items have been received. * * @param {Array} items Items received. * * @return {Object} Action object. */ function receiveItems(items) { return { type: 'RECEIVE_ITEMS', items: Object(external_lodash_["castArray"])(items) }; } /** * Returns an action object used in signalling that queried data has been * received. * * @param {Array} items Queried items received. * @param {?Object} query Optional query object. * * @return {Object} Action object. */ function receiveQueriedItems(items) { var query = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return Object(objectSpread["a" /* default */])({}, receiveItems(items), { query: query }); } // EXTERNAL MODULE: ./node_modules/rememo/es/rememo.js var rememo = __webpack_require__(31); // EXTERNAL MODULE: ./node_modules/equivalent-key-map/equivalent-key-map.js var equivalent_key_map = __webpack_require__(66); var equivalent_key_map_default = /*#__PURE__*/__webpack_require__.n(equivalent_key_map); // EXTERNAL MODULE: external {"this":["wp","url"]} var external_this_wp_url_ = __webpack_require__(24); // CONCATENATED MODULE: ./node_modules/@wordpress/core-data/build-module/queried-data/get-query-parts.js /** * WordPress dependencies */ /** * Internal dependencies */ /** * An object of properties describing a specific query. * * @typedef {WPQueriedDataQueryParts} * * @property {number} page The query page (1-based index, default 1). * @property {number} perPage Items per page for query (default 10). * @property {string} stableKey An encoded stable string of all non-pagination * query parameters. */ /** * Given a query object, returns an object of parts, including pagination * details (`page` and `perPage`, or default values). All other properties are * encoded into a stable (idempotent) `stableKey` value. * * @param {Object} query Optional query object. * * @return {WPQueriedDataQueryParts} Query parts. */ function getQueryParts(query) { /** * @type {WPQueriedDataQueryParts} */ var parts = { stableKey: '', page: 1, perPage: 10 }; // Ensure stable key by sorting keys. Also more efficient for iterating. var keys = Object.keys(query).sort(); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = query[key]; switch (key) { case 'page': parts[key] = Number(value); break; case 'per_page': parts.perPage = Number(value); break; default: // While it could be any deterministic string, for simplicity's // sake mimic querystring encoding for stable key. // // TODO: For consistency with PHP implementation, addQueryArgs // should accept a key value pair, which may optimize its // implementation for our use here, vs. iterating an object // with only a single key. parts.stableKey += (parts.stableKey ? '&' : '') + Object(external_this_wp_url_["addQueryArgs"])('', Object(defineProperty["a" /* default */])({}, key, value)).slice(1); } } return parts; } /* harmony default export */ var get_query_parts = (with_weak_map_cache(getQueryParts)); // CONCATENATED MODULE: ./node_modules/@wordpress/core-data/build-module/queried-data/selectors.js /** * External dependencies */ /** * Internal dependencies */ /** * Cache of state keys to EquivalentKeyMap where the inner map tracks queries * to their resulting items set. WeakMap allows garbage collection on expired * state references. * * @type {WeakMap<Object,EquivalentKeyMap>} */ var queriedItemsCacheByState = new WeakMap(); /** * Returns items for a given query, or null if the items are not known. * * @param {Object} state State object. * @param {?Object} query Optional query. * * @return {?Array} Query items. */ function getQueriedItemsUncached(state, query) { var _getQueryParts = get_query_parts(query), stableKey = _getQueryParts.stableKey, page = _getQueryParts.page, perPage = _getQueryParts.perPage; if (!state.queries[stableKey]) { return null; } var itemIds = state.queries[stableKey]; if (!itemIds) { return null; } var startOffset = perPage === -1 ? 0 : (page - 1) * perPage; var endOffset = perPage === -1 ? itemIds.length : Math.min(startOffset + perPage, itemIds.length); var items = []; for (var i = startOffset; i < endOffset; i++) { var itemId = itemIds[i]; items.push(state.items[itemId]); } return items; } /** * Returns items for a given query, or null if the items are not known. Caches * result both per state (by reference) and per query (by deep equality). * The caching approach is intended to be durable to query objects which are * deeply but not referentially equal, since otherwise: * * `getQueriedItems( state, {} ) !== getQueriedItems( state, {} )` * * @param {Object} state State object. * @param {?Object} query Optional query. * * @return {?Array} Query items. */ var getQueriedItems = Object(rememo["a" /* default */])(function (state) { var query = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var queriedItemsCache = queriedItemsCacheByState.get(state); if (queriedItemsCache) { var queriedItems = queriedItemsCache.get(query); if (queriedItems !== undefined) { return queriedItems; } } else { queriedItemsCache = new equivalent_key_map_default.a(); queriedItemsCacheByState.set(state, queriedItemsCache); } var items = getQueriedItemsUncached(state, query); queriedItemsCache.set(query, items); return items; }); // EXTERNAL MODULE: ./node_modules/redux/es/redux.js var redux = __webpack_require__(62); // EXTERNAL MODULE: external {"this":["wp","apiFetch"]} var external_this_wp_apiFetch_ = __webpack_require__(30); var external_this_wp_apiFetch_default = /*#__PURE__*/__webpack_require__.n(external_this_wp_apiFetch_); // CONCATENATED MODULE: ./node_modules/@wordpress/core-data/build-module/controls.js /** * WordPress dependencies */ /** * Trigger an API Fetch request. * * @param {Object} request API Fetch Request Object. * @return {Object} control descriptor. */ function apiFetch(request) { return { type: 'API_FETCH', request: request }; } /** * Calls a selector using the current state. * @param {string} selectorName Selector name. * @param {Array} args Selector arguments. * * @return {Object} control descriptor. */ function controls_select(selectorName) { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } return { type: 'SELECT', selectorName: selectorName, args: args }; } var controls = { API_FETCH: function API_FETCH(_ref) { var request = _ref.request; return external_this_wp_apiFetch_default()(request); }, SELECT: function SELECT(_ref2) { var _selectData; var selectorName = _ref2.selectorName, args = _ref2.args; return (_selectData = Object(external_this_wp_data_["select"])('core'))[selectorName].apply(_selectData, Object(toConsumableArray["a" /* default */])(args)); } }; /* harmony default export */ var build_module_controls = (controls); // CONCATENATED MODULE: ./node_modules/@wordpress/core-data/build-module/actions.js var _marked = /*#__PURE__*/ regeneratorRuntime.mark(saveEntityRecord); /** * External dependencies */ /** * Internal dependencies */ /** * Returns an action object used in signalling that authors have been received. * * @param {string} queryID Query ID. * @param {Array|Object} users Users received. * * @return {Object} Action object. */ function receiveUserQuery(queryID, users) { return { type: 'RECEIVE_USER_QUERY', users: Object(external_lodash_["castArray"])(users), queryID: queryID }; } /** * Returns an action object used in adding new entities. * * @param {Array} entities Entities received. * * @return {Object} Action object. */ function addEntities(entities) { return { type: 'ADD_ENTITIES', entities: entities }; } /** * Returns an action object used in signalling that entity records have been received. * * @param {string} kind Kind of the received entity. * @param {string} name Name of the received entity. * @param {Array|Object} records Records received. * @param {?Object} query Query Object. * @param {?boolean} invalidateCache Should invalidate query caches * * @return {Object} Action object. */ function receiveEntityRecords(kind, name, records, query) { var invalidateCache = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; var action; if (query) { action = receiveQueriedItems(records, query); } else { action = receiveItems(records); } return Object(objectSpread["a" /* default */])({}, action, { kind: kind, name: name, invalidateCache: invalidateCache }); } /** * Returns an action object used in signalling that the index has been received. * * @param {Object} themeSupports Theme support for the current theme. * * @return {Object} Action object. */ function receiveThemeSupports(themeSupports) { return { type: 'RECEIVE_THEME_SUPPORTS', themeSupports: themeSupports }; } /** * Returns an action object used in signalling that the preview data for * a given URl has been received. * * @param {string} url URL to preview the embed for. * @param {Mixed} preview Preview data. * * @return {Object} Action object. */ function receiveEmbedPreview(url, preview) { return { type: 'RECEIVE_EMBED_PREVIEW', url: url, preview: preview }; } /** * Action triggered to save an entity record. * * @param {string} kind Kind of the received entity. * @param {string} name Name of the received entity. * @param {Object} record Record to be saved. * * @return {Object} Updated record. */ function saveEntityRecord(kind, name, record) { var entities, entity, key, recordId, updatedRecord; return regeneratorRuntime.wrap(function saveEntityRecord$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return getKindEntities(kind); case 2: entities = _context.sent; entity = Object(external_lodash_["find"])(entities, { kind: kind, name: name }); if (entity) { _context.next = 6; break; } return _context.abrupt("return"); case 6: key = entity.key || DEFAULT_ENTITY_KEY; recordId = record[key]; _context.next = 10; return apiFetch({ path: "".concat(entity.baseURL).concat(recordId ? '/' + recordId : ''), method: recordId ? 'PUT' : 'POST', data: record }); case 10: updatedRecord = _context.sent; _context.next = 13; return receiveEntityRecords(kind, name, updatedRecord, undefined, true); case 13: return _context.abrupt("return", updatedRecord); case 14: case "end": return _context.stop(); } } }, _marked, this); } /** * Returns an action object used in signalling that Upload permissions have been received. * * @param {boolean} hasUploadPermissions Does the user have permission to upload files? * * @return {Object} Action object. */ function receiveUploadPermissions(hasUploadPermissions) { return { type: 'RECEIVE_UPLOAD_PERMISSIONS', hasUploadPermissions: hasUploadPermissions }; } // CONCATENATED MODULE: ./node_modules/@wordpress/core-data/build-module/entities.js var entities_marked = /*#__PURE__*/ regeneratorRuntime.mark(loadPostTypeEntities), _marked2 = /*#__PURE__*/ regeneratorRuntime.mark(loadTaxonomyEntities), _marked3 = /*#__PURE__*/ regeneratorRuntime.mark(getKindEntities); /** * External dependencies */ /** * Internal dependencies */ var DEFAULT_ENTITY_KEY = 'id'; var defaultEntities = [{ name: 'postType', kind: 'root', key: 'slug', baseURL: '/wp/v2/types' }, { name: 'media', kind: 'root', baseURL: '/wp/v2/media', plural: 'mediaItems' }, { name: 'taxonomy', kind: 'root', key: 'slug', baseURL: '/wp/v2/taxonomies', plural: 'taxonomies' }]; var kinds = [{ name: 'postType', loadEntities: loadPostTypeEntities }, { name: 'taxonomy', loadEntities: loadTaxonomyEntities }]; /** * Returns the list of post type entities. * * @return {Promise} Entities promise */ function loadPostTypeEntities() { var postTypes; return regeneratorRuntime.wrap(function loadPostTypeEntities$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return apiFetch({ path: '/wp/v2/types?context=edit' }); case 2: postTypes = _context.sent; return _context.abrupt("return", Object(external_lodash_["map"])(postTypes, function (postType, name) { return { kind: 'postType', baseURL: '/wp/v2/' + postType.rest_base, name: name }; })); case 4: case "end": return _context.stop(); } } }, entities_marked, this); } /** * Returns the list of the taxonomies entities. * * @return {Promise} Entities promise */ function loadTaxonomyEntities() { var taxonomies; return regeneratorRuntime.wrap(function loadTaxonomyEntities$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: _context2.next = 2; return apiFetch({ path: '/wp/v2/taxonomies?context=edit' }); case 2: taxonomies = _context2.sent; return _context2.abrupt("return", Object(external_lodash_["map"])(taxonomies, function (taxonomy, name) { return { kind: 'taxonomy', baseURL: '/wp/v2/' + taxonomy.rest_base, name: name }; })); case 4: case "end": return _context2.stop(); } } }, _marked2, this); } /** * Returns the entity's getter method name given its kind and name. * * @param {string} kind Entity kind. * @param {string} name Entity name. * @param {string} prefix Function prefix. * @param {boolean} usePlural Whether to use the plural form or not. * * @return {string} Method name */ var entities_getMethodName = function getMethodName(kind, name) { var prefix = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'get'; var usePlural = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; var entity = Object(external_lodash_["find"])(defaultEntities, { kind: kind, name: name }); var kindPrefix = kind === 'root' ? '' : Object(external_lodash_["upperFirst"])(Object(external_lodash_["camelCase"])(kind)); var nameSuffix = Object(external_lodash_["upperFirst"])(Object(external_lodash_["camelCase"])(name)) + (usePlural ? 's' : ''); var suffix = usePlural && entity.plural ? Object(external_lodash_["upperFirst"])(Object(external_lodash_["camelCase"])(entity.plural)) : nameSuffix; return "".concat(prefix).concat(kindPrefix).concat(suffix); }; /** * Loads the kind entities into the store. * * @param {string} kind Kind * * @return {Array} Entities */ function getKindEntities(kind) { var entities, kindConfig; return regeneratorRuntime.wrap(function getKindEntities$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: _context3.next = 2; return controls_select('getEntitiesByKind', kind); case 2: entities = _context3.sent; if (!(entities && entities.length !== 0)) { _context3.next = 5; break; } return _context3.abrupt("return", entities); case 5: kindConfig = Object(external_lodash_["find"])(kinds, { name: kind }); if (kindConfig) { _context3.next = 8; break; } return _context3.abrupt("return", []); case 8: _context3.next = 10; return kindConfig.loadEntities(); case 10: entities = _context3.sent; _context3.next = 13; return addEntities(entities); case 13: return _context3.abrupt("return", entities); case 14: case "end": return _context3.stop(); } } }, _marked3, this); } // CONCATENATED MODULE: ./node_modules/@wordpress/core-data/build-module/queried-data/reducer.js /** * External dependencies */ /** * Internal dependencies */ /** * Returns a merged array of item IDs, given details of the received paginated * items. The array is sparse-like with `undefined` entries where holes exist. * * @param {?Array<number>} itemIds Original item IDs (default empty array). * @param {number[]} nextItemIds Item IDs to merge. * @param {number} page Page of items merged. * @param {number} perPage Number of items per page. * * @return {number[]} Merged array of item IDs. */ function getMergedItemIds(itemIds, nextItemIds, page, perPage) { var nextItemIdsStartIndex = (page - 1) * perPage; // If later page has already been received, default to the larger known // size of the existing array, else calculate as extending the existing. var size = Math.max(itemIds.length, nextItemIdsStartIndex + nextItemIds.length); // Preallocate array since size is known. var mergedItemIds = new Array(size); for (var i = 0; i < size; i++) { // Preserve existing item ID except for subset of range of next items. var isInNextItemsRange = i >= nextItemIdsStartIndex && i < nextItemIdsStartIndex + nextItemIds.length; mergedItemIds[i] = isInNextItemsRange ? nextItemIds[i - nextItemIdsStartIndex] : itemIds[i]; } return mergedItemIds; } /** * Reducer tracking items state, keyed by ID. Items are assumed to be normal, * where identifiers are common across all queries. * * @param {Object} state Current state. * @param {Object} action Dispatched action. * * @return {Object} Next state. */ function reducer_items() { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var action = arguments.length > 1 ? arguments[1] : undefined; switch (action.type) { case 'RECEIVE_ITEMS': return Object(objectSpread["a" /* default */])({}, state, Object(external_lodash_["keyBy"])(action.items, action.key || DEFAULT_ENTITY_KEY)); } return state; } /** * Reducer tracking queries state, keyed by stable query key. Each reducer * query object includes `itemIds` and `requestingPageByPerPage`. * * @param {Object} state Current state. * @param {Object} action Dispatched action. * * @return {Object} Next state. */ var queries = Object(external_lodash_["flowRight"])([// Limit to matching action type so we don't attempt to replace action on // an unhandled action. if_matching_action(function (action) { return 'query' in action; }), // Inject query parts into action for use both in `onSubKey` and reducer. replace_action(function (action) { // `ifMatchingAction` still passes on initialization, where state is // undefined and a query is not assigned. Avoid attempting to parse // parts. `onSubKey` will omit by lack of `stableKey`. if (action.query) { return Object(objectSpread["a" /* default */])({}, action, get_query_parts(action.query)); } return action; }), // Queries shape is shared, but keyed by query `stableKey` part. Original // reducer tracks only a single query object. on_sub_key('stableKey')])(function () { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; var action = arguments.length > 1 ? arguments[1] : undefined; var type = action.type, page = action.page, perPage = action.perPage, _action$key = action.key, key = _action$key === void 0 ? DEFAULT_ENTITY_KEY : _action$key; if (type !== 'RECEIVE_ITEMS') { return state; } return getMergedItemIds(state || [], Object(external_lodash_["map"])(action.items, key), page, perPage); }); /* harmony default export */ var queried_data_reducer = (Object(redux["b" /* combineReducers */])({ items: reducer_items, queries: queries })); // CONCATENATED MODULE: ./node_modules/@wordpress/core-data/build-module/queried-data/index.js // CONCATENATED MODULE: ./node_modules/@wordpress/core-data/build-module/reducer.js /** * External dependencies */ /** * WordPress dependencies */ /** * Internal dependencies */ /** * Reducer managing terms state. Keyed by taxonomy slug, the value is either * undefined (if no request has been made for given taxonomy), null (if a * request is in-flight for given taxonomy), or the array of terms for the * taxonomy. * * @param {Object} state Current state. * @param {Object} action Dispatched action. * * @return {Object} Updated state. */ function terms() { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var action = arguments.length > 1 ? arguments[1] : undefined; switch (action.type) { case 'RECEIVE_TERMS': return Object(objectSpread["a" /* default */])({}, state, Object(defineProperty["a" /* default */])({}, action.taxonomy, action.terms)); } return state; } /** * Reducer managing authors state. Keyed by id. * * @param {Object} state Current state. * @param {Object} action Dispatched action. * * @return {Object} Updated state. */ function reducer_users() { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : { byId: {}, queries: {} }; var action = arguments.length > 1 ? arguments[1] : undefined; switch (action.type) { case 'RECEIVE_USER_QUERY': return { byId: Object(objectSpread["a" /* default */])({}, state.byId, Object(external_lodash_["keyBy"])(action.users, 'id')), queries: Object(objectSpread["a" /* default */])({}, state.queries, Object(defineProperty["a" /* default */])({}, action.queryID, Object(external_lodash_["map"])(action.users, function (user) { return user.id; }))) }; } return state; } /** * Reducer managing taxonomies. * * @param {Object} state Current state. * @param {Object} action Dispatched action. * * @return {Object} Updated state. */ function reducer_taxonomies() { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var action = arguments.length > 1 ? arguments[1] : undefined; switch (action.type) { case 'RECEIVE_TAXONOMIES': return action.taxonomies; } return state; } /** * Reducer managing theme supports data. * * @param {Object} state Current state. * @param {Object} action Dispatched action. * * @return {Object} Updated state. */ function themeSupports() { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var action = arguments.length > 1 ? arguments[1] : undefined; switch (action.type) { case 'RECEIVE_THEME_SUPPORTS': return Object(objectSpread["a" /* default */])({}, state, action.themeSupports); } return state; } /** * Higher Order Reducer for a given entity config. It supports: * * - Fetching a record by primary key * * @param {Object} entityConfig Entity config. * * @return {Function} Reducer. */ function reducer_entity(entityConfig) { return Object(external_lodash_["flowRight"])([// Limit to matching action type so we don't attempt to replace action on // an unhandled action. if_matching_action(function (action) { return action.name && action.kind && action.name === entityConfig.name && action.kind === entityConfig.kind; }), // Inject the entity config into the action. replace_action(function (action) { return Object(objectSpread["a" /* default */])({}, action, { key: entityConfig.key || DEFAULT_ENTITY_KEY }); })])(queried_data_reducer); } /** * Reducer keeping track of the registered entities. * * @param {Object} state Current state. * @param {Object} action Dispatched action. * * @return {Object} Updated state. */ function entitiesConfig() { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultEntities; var action = arguments.length > 1 ? arguments[1] : undefined; switch (action.type) { case 'ADD_ENTITIES': return Object(toConsumableArray["a" /* default */])(state).concat(Object(toConsumableArray["a" /* default */])(action.entities)); } return state; } /** * Reducer keeping track of the registered entities config and data. * * @param {Object} state Current state. * @param {Object} action Dispatched action. * * @return {Object} Updated state. */ var reducer_entities = function entities() { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var action = arguments.length > 1 ? arguments[1] : undefined; var newConfig = entitiesConfig(state.config, action); // Generates a dynamic reducer for the entities var entitiesDataReducer = state.reducer; if (!entitiesDataReducer || newConfig !== state.config) { var entitiesByKind = Object(external_lodash_["groupBy"])(newConfig, 'kind'); entitiesDataReducer = Object(external_this_wp_data_["combineReducers"])(Object.entries(entitiesByKind).reduce(function (memo, _ref) { var _ref2 = Object(slicedToArray["a" /* default */])(_ref, 2), kind = _ref2[0], subEntities = _ref2[1]; var kindReducer = Object(external_this_wp_data_["combineReducers"])(subEntities.reduce(function (kindMemo, entityConfig) { return Object(objectSpread["a" /* default */])({}, kindMemo, Object(defineProperty["a" /* default */])({}, entityConfig.name, reducer_entity(entityConfig))); }, {})); memo[kind] = kindReducer; return memo; }, {})); } var newData = entitiesDataReducer(state.data, action); if (newData === state.data && newConfig === state.config && entitiesDataReducer === state.reducer) { return state; } return { reducer: entitiesDataReducer, data: newData, config: newConfig }; }; /** * Reducer managing embed preview data. * * @param {Object} state Current state. * @param {Object} action Dispatched action. * * @return {Object} Updated state. */ function embedPreviews() { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var action = arguments.length > 1 ? arguments[1] : undefined; switch (action.type) { case 'RECEIVE_EMBED_PREVIEW': var url = action.url, preview = action.preview; return Object(objectSpread["a" /* default */])({}, state, Object(defineProperty["a" /* default */])({}, url, preview)); } return state; } /** * Reducer managing Upload permissions. * * @param {Object} state Current state. * @param {Object} action Dispatched action. * * @return {Object} Updated state. */ function hasUploadPermissions() { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var action = arguments.length > 1 ? arguments[1] : undefined; switch (action.type) { case 'RECEIVE_UPLOAD_PERMISSIONS': return action.hasUploadPermissions; } return state; } /* harmony default export */ var build_module_reducer = (Object(external_this_wp_data_["combineReducers"])({ terms: terms, users: reducer_users, taxonomies: reducer_taxonomies, themeSupports: themeSupports, entities: reducer_entities, embedPreviews: embedPreviews, hasUploadPermissions: hasUploadPermissions })); // CONCATENATED MODULE: ./node_modules/@wordpress/core-data/build-module/name.js /** * The reducer key used by core data in store registration. * This is defined in a separate file to avoid cycle-dependency * * @type {string} */ var REDUCER_KEY = 'core'; // CONCATENATED MODULE: ./node_modules/@wordpress/core-data/build-module/selectors.js /** * External dependencies */ /** * WordPress dependencies */ /** * Internal dependencies */ /** * Returns true if resolution is in progress for the core selector of the given * name and arguments. * * @param {string} selectorName Core data selector name. * @param {...*} args Arguments passed to selector. * * @return {boolean} Whether resolution is in progress. */ function isResolving(selectorName) { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } return Object(external_this_wp_data_["select"])('core/data').isResolving(REDUCER_KEY, selectorName, args); } /** * Returns true if a request is in progress for embed preview data, or false * otherwise. * * @param {Object} state Data state. * @param {string} url URL the preview would be for. * * @return {boolean} Whether a request is in progress for an embed preview. */ function isRequestingEmbedPreview(state, url) { return isResolving('getEmbedPreview', url); } /** * Returns all available authors. * * @param {Object} state Data state. * * @return {Array} Authors list. */ function getAuthors(state) { return getUserQueryResults(state, 'authors'); } /** * Returns all the users returned by a query ID. * * @param {Object} state Data state. * @param {string} queryID Query ID. * * @return {Array} Users list. */ var getUserQueryResults = Object(rememo["a" /* default */])(function (state, queryID) { var queryResults = state.users.queries[queryID]; return Object(external_lodash_["map"])(queryResults, function (id) { return state.users.byId[id]; }); }, function (state, queryID) { return [state.users.queries[queryID], state.users.byId]; }); /** * Returns whether the entities for the give kind are loaded. * * @param {Object} state Data state. * @param {string} kind Entity kind. * * @return {boolean} Whether the entities are loaded */ function getEntitiesByKind(state, kind) { return Object(external_lodash_["filter"])(state.entities.config, { kind: kind }); } /** * Returns the entity object given its kind and name. * * @param {Object} state Data state. * @param {string} kind Entity kind. * @param {string} name Entity name. * * @return {Object} Entity */ function getEntity(state, kind, name) { return Object(external_lodash_["find"])(state.entities.config, { kind: kind, name: name }); } /** * Returns the Entity's record object by key. * * @param {Object} state State tree * @param {string} kind Entity kind. * @param {string} name Entity name. * @param {number} key Record's key * * @return {Object?} Record. */ function getEntityRecord(state, kind, name, key) { return Object(external_lodash_["get"])(state.entities.data, [kind, name, 'items', key]); } /** * Returns the Entity's records. * * @param {Object} state State tree * @param {string} kind Entity kind. * @param {string} name Entity name. * @param {?Object} query Optional terms query. * * @return {Array} Records. */ function getEntityRecords(state, kind, name, query) { var queriedState = Object(external_lodash_["get"])(state.entities.data, [kind, name]); if (!queriedState) { return []; } return getQueriedItems(queriedState, query); } /** * Return theme supports data in the index. * * @param {Object} state Data state. * * @return {*} Index data. */ function getThemeSupports(state) { return state.themeSupports; } /** * Returns the embed preview for the given URL. * * @param {Object} state Data state. * @param {string} url Embedded URL. * * @return {*} Undefined if the preview has not been fetched, otherwise, the preview fetched from the embed preview API. */ function getEmbedPreview(state, url) { return state.embedPreviews[url]; } /** * Determines if the returned preview is an oEmbed link fallback. * * WordPress can be configured to return a simple link to a URL if it is not embeddable. * We need to be able to determine if a URL is embeddable or not, based on what we * get back from the oEmbed preview API. * * @param {Object} state Data state. * @param {string} url Embedded URL. * * @return {booleans} Is the preview for the URL an oEmbed link fallback. */ function isPreviewEmbedFallback(state, url) { var preview = state.embedPreviews[url]; var oEmbedLinkCheck = '<a href="' + url + '">' + url + '</a>'; if (!preview) { return false; } return preview.html === oEmbedLinkCheck; } /** * Return Upload Permissions. * * @param {Object} state State tree. * * @return {boolean} Upload Permissions. */ function selectors_hasUploadPermissions(state) { return state.hasUploadPermissions; } // CONCATENATED MODULE: ./node_modules/@wordpress/core-data/build-module/resolvers.js var resolvers_marked = /*#__PURE__*/ regeneratorRuntime.mark(resolvers_getAuthors), resolvers_marked2 = /*#__PURE__*/ regeneratorRuntime.mark(resolvers_getEntityRecord), resolvers_marked3 = /*#__PURE__*/ regeneratorRuntime.mark(resolvers_getEntityRecords), _marked4 = /*#__PURE__*/ regeneratorRuntime.mark(resolvers_getThemeSupports), _marked5 = /*#__PURE__*/ regeneratorRuntime.mark(resolvers_getEmbedPreview), _marked6 = /*#__PURE__*/ regeneratorRuntime.mark(resolvers_hasUploadPermissions); /** * External dependencies */ /** * WordPress dependencies */ /** * Internal dependencies */ /** * Requests authors from the REST API. */ function resolvers_getAuthors() { var users; return regeneratorRuntime.wrap(function getAuthors$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return apiFetch({ path: '/wp/v2/users/?who=authors&per_page=-1' }); case 2: users = _context.sent; _context.next = 5; return receiveUserQuery('authors', users); case 5: case "end": return _context.stop(); } } }, resolvers_marked, this); } /** * Requests an entity's record from the REST API. * * @param {string} kind Entity kind. * @param {string} name Entity name. * @param {number} key Record's key */ function resolvers_getEntityRecord(kind, name, key) { var entities, entity, record; return regeneratorRuntime.wrap(function getEntityRecord$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: _context2.next = 2; return getKindEntities(kind); case 2: entities = _context2.sent; entity = Object(external_lodash_["find"])(entities, { kind: kind, name: name }); if (entity) { _context2.next = 6; break; } return _context2.abrupt("return"); case 6: _context2.next = 8; return apiFetch({ path: "".concat(entity.baseURL, "/").concat(key, "?context=edit") }); case 8: record = _context2.sent; _context2.next = 11; return receiveEntityRecords(kind, name, record); case 11: case "end": return _context2.stop(); } } }, resolvers_marked2, this); } /** * Requests the entity's records from the REST API. * * @param {string} kind Entity kind. * @param {string} name Entity name. * @param {Object?} query Query Object. */ function resolvers_getEntityRecords(kind, name) { var query, entities, entity, path, records, _args3 = arguments; return regeneratorRuntime.wrap(function getEntityRecords$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: query = _args3.length > 2 && _args3[2] !== undefined ? _args3[2] : {}; _context3.next = 3; return getKindEntities(kind); case 3: entities = _context3.sent; entity = Object(external_lodash_["find"])(entities, { kind: kind, name: name }); if (entity) { _context3.next = 7; break; } return _context3.abrupt("return"); case 7: path = Object(external_this_wp_url_["addQueryArgs"])(entity.baseURL, Object(objectSpread["a" /* default */])({}, query, { context: 'edit' })); _context3.next = 10; return apiFetch({ path: path }); case 10: records = _context3.sent; _context3.next = 13; return receiveEntityRecords(kind, name, Object.values(records), query); case 13: case "end": return _context3.stop(); } } }, resolvers_marked3, this); } resolvers_getEntityRecords.shouldInvalidate = function (action, kind, name) { return action.type === 'RECEIVE_ITEMS' && action.invalidateCache && kind === action.kind && name === action.name; }; /** * Requests theme supports data from the index. */ function resolvers_getThemeSupports() { var activeThemes; return regeneratorRuntime.wrap(function getThemeSupports$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: _context4.next = 2; return apiFetch({ path: '/wp/v2/themes?status=active' }); case 2: activeThemes = _context4.sent; _context4.next = 5; return receiveThemeSupports(activeThemes[0].theme_supports); case 5: case "end": return _context4.stop(); } } }, _marked4, this); } /** * Requests a preview from the from the Embed API. * * @param {string} url URL to get the preview for. */ function resolvers_getEmbedPreview(url) { var embedProxyResponse; return regeneratorRuntime.wrap(function getEmbedPreview$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: _context5.prev = 0; _context5.next = 3; return apiFetch({ path: Object(external_this_wp_url_["addQueryArgs"])('/oembed/1.0/proxy', { url: url }) }); case 3: embedProxyResponse = _context5.sent; _context5.next = 6; return receiveEmbedPreview(url, embedProxyResponse); case 6: _context5.next = 12; break; case 8: _context5.prev = 8; _context5.t0 = _context5["catch"](0); _context5.next = 12; return receiveEmbedPreview(url, false); case 12: case "end": return _context5.stop(); } } }, _marked5, this, [[0, 8]]); } /** * Requests Upload Permissions from the REST API. */ function resolvers_hasUploadPermissions() { var response, allowHeader; return regeneratorRuntime.wrap(function hasUploadPermissions$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: _context6.next = 2; return apiFetch({ path: '/wp/v2/media', method: 'OPTIONS', parse: false }); case 2: response = _context6.sent; if (Object(external_lodash_["hasIn"])(response, ['headers', 'get'])) { // If the request is fetched using the fetch api, the header can be // retrieved using the 'get' method. allowHeader = response.headers.get('allow'); } else { // If the request was preloaded server-side and is returned by the // preloading middleware, the header will be a simple property. allowHeader = Object(external_lodash_["get"])(response, ['headers', 'Allow'], ''); } _context6.next = 6; return receiveUploadPermissions(Object(external_lodash_["includes"])(allowHeader, 'POST')); case 6: case "end": return _context6.stop(); } } }, _marked6, this); } // CONCATENATED MODULE: ./node_modules/@wordpress/core-data/build-module/index.js /** * WordPress dependencies */ /** * Internal dependencies */ // The entity selectors/resolvers and actions are shortcuts to their generic equivalents // (getEntityRecord, getEntityRecords, updateEntityRecord, updateEntityRecordss) // Instead of getEntityRecord, the consumer could use more user-frieldly named selector: getPostType, getTaxonomy... // The "kind" and the "name" of the entity are combined to generate these shortcuts. var entitySelectors = defaultEntities.reduce(function (result, entity) { var kind = entity.kind, name = entity.name; result[entities_getMethodName(kind, name)] = function (state, key) { return getEntityRecord(state, kind, name, key); }; result[entities_getMethodName(kind, name, 'get', true)] = function (state) { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } return getEntityRecords.apply(build_module_selectors_namespaceObject, [state, kind, name].concat(args)); }; return result; }, {}); var entityResolvers = defaultEntities.reduce(function (result, entity) { var kind = entity.kind, name = entity.name; result[entities_getMethodName(kind, name)] = function (key) { return resolvers_getEntityRecord(kind, name, key); }; var pluralMethodName = entities_getMethodName(kind, name, 'get', true); result[pluralMethodName] = function () { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } return resolvers_getEntityRecords.apply(resolvers_namespaceObject, [kind, name].concat(args)); }; result[pluralMethodName].shouldInvalidate = function (action) { var _resolvers$getEntityR; for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { args[_key3 - 1] = arguments[_key3]; } return (_resolvers$getEntityR = resolvers_getEntityRecords).shouldInvalidate.apply(_resolvers$getEntityR, [action, kind, name].concat(args)); }; return result; }, {}); var entityActions = defaultEntities.reduce(function (result, entity) { var kind = entity.kind, name = entity.name; result[entities_getMethodName(kind, name, 'save')] = function (key) { return saveEntityRecord(kind, name, key); }; return result; }, {}); Object(external_this_wp_data_["registerStore"])(REDUCER_KEY, { reducer: build_module_reducer, controls: build_module_controls, actions: Object(objectSpread["a" /* default */])({}, build_module_actions_namespaceObject, entityActions), selectors: Object(objectSpread["a" /* default */])({}, build_module_selectors_namespaceObject, entitySelectors), resolvers: Object(objectSpread["a" /* default */])({}, resolvers_namespaceObject, entityResolvers) }); /***/ }), /***/ 31: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; var LEAF_KEY, hasWeakMap; /** * Arbitrary value used as key for referencing cache object in WeakMap tree. * * @type {Object} */ LEAF_KEY = {}; /** * Whether environment supports WeakMap. * * @type {boolean} */ hasWeakMap = typeof WeakMap !== 'undefined'; /** * Returns the first argument as the sole entry in an array. * * @param {*} value Value to return. * * @return {Array} Value returned as entry in array. */ function arrayOf( value ) { return [ value ]; } /** * Returns true if the value passed is object-like, or false otherwise. A value * is object-like if it can support property assignment, e.g. object or array. * * @param {*} value Value to test. * * @return {boolean} Whether value is object-like. */ function isObjectLike( value ) { return !! value && 'object' === typeof value; } /** * Creates and returns a new cache object. * * @return {Object} Cache object. */ function createCache() { var cache = { clear: function() { cache.head = null; }, }; return cache; } /** * Returns true if entries within the two arrays are strictly equal by * reference from a starting index. * * @param {Array} a First array. * @param {Array} b Second array. * @param {number} fromIndex Index from which to start comparison. * * @return {boolean} Whether arrays are shallowly equal. */ function isShallowEqual( a, b, fromIndex ) { var i; if ( a.length !== b.length ) { return false; } for ( i = fromIndex; i < a.length; i++ ) { if ( a[ i ] !== b[ i ] ) { return false; } } return true; } /** * Returns a memoized selector function. The getDependants function argument is * called before the memoized selector and is expected to return an immutable * reference or array of references on which the selector depends for computing * its own return value. The memoize cache is preserved only as long as those * dependant references remain the same. If getDependants returns a different * reference(s), the cache is cleared and the selector value regenerated. * * @param {Function} selector Selector function. * @param {Function} getDependants Dependant getter returning an immutable * reference or array of reference used in * cache bust consideration. * * @return {Function} Memoized selector. */ /* harmony default export */ __webpack_exports__["a"] = (function( selector, getDependants ) { var rootCache, getCache; // Use object source as dependant if getter not provided if ( ! getDependants ) { getDependants = arrayOf; } /** * Returns the root cache. If WeakMap is supported, this is assigned to the * root WeakMap cache set, otherwise it is a shared instance of the default * cache object. * * @return {(WeakMap|Object)} Root cache object. */ function getRootCache() { return rootCache; } /** * Returns the cache for a given dependants array. When possible, a WeakMap * will be used to create a unique cache for each set of dependants. This * is feasible due to the nature of WeakMap in allowing garbage collection * to occur on entries where the key object is no longer referenced. Since * WeakMap requires the key to be an object, this is only possible when the * dependant is object-like. The root cache is created as a hierarchy where * each top-level key is the first entry in a dependants set, the value a * WeakMap where each key is the next dependant, and so on. This continues * so long as the dependants are object-like. If no dependants are object- * like, then the cache is shared across all invocations. * * @see isObjectLike * * @param {Array} dependants Selector dependants. * * @return {Object} Cache object. */ function getWeakMapCache( dependants ) { var caches = rootCache, isUniqueByDependants = true, i, dependant, map, cache; for ( i = 0; i < dependants.length; i++ ) { dependant = dependants[ i ]; // Can only compose WeakMap from object-like key. if ( ! isObjectLike( dependant ) ) { isUniqueByDependants = false; break; } // Does current segment of cache already have a WeakMap? if ( caches.has( dependant ) ) { // Traverse into nested WeakMap. caches = caches.get( dependant ); } else { // Create, set, and traverse into a new one. map = new WeakMap(); caches.set( dependant, map ); caches = map; } } // We use an arbitrary (but consistent) object as key for the last item // in the WeakMap to serve as our running cache. if ( ! caches.has( LEAF_KEY ) ) { cache = createCache(); cache.isUniqueByDependants = isUniqueByDependants; caches.set( LEAF_KEY, cache ); } return caches.get( LEAF_KEY ); } // Assign cache handler by availability of WeakMap getCache = hasWeakMap ? getWeakMapCache : getRootCache; /** * Resets root memoization cache. */ function clear() { rootCache = hasWeakMap ? new WeakMap() : createCache(); } // eslint-disable-next-line jsdoc/check-param-names /** * The augmented selector call, considering first whether dependants have * changed before passing it to underlying memoize function. * * @param {Object} source Source object for derivation. * @param {...*} extraArgs Additional arguments to pass to selector. * * @return {*} Selector result. */ function callSelector( /* source, ...extraArgs */ ) { var len = arguments.length, cache, node, i, args, dependants; // Create copy of arguments (avoid leaking deoptimization). args = new Array( len ); for ( i = 0; i < len; i++ ) { args[ i ] = arguments[ i ]; } dependants = getDependants.apply( null, args ); cache = getCache( dependants ); // If not guaranteed uniqueness by dependants (primitive type or lack // of WeakMap support), shallow compare against last dependants and, if // references have changed, destroy cache to recalculate result. if ( ! cache.isUniqueByDependants ) { if ( cache.lastDependants && ! isShallowEqual( dependants, cache.lastDependants, 0 ) ) { cache.clear(); } cache.lastDependants = dependants; } node = cache.head; while ( node ) { // Check whether node arguments match arguments if ( ! isShallowEqual( node.args, args, 1 ) ) { node = node.next; continue; } // At this point we can assume we've found a match // Surface matched node to head if not already if ( node !== cache.head ) { // Adjust siblings to point to each other. node.prev.next = node.next; if ( node.next ) { node.next.prev = node.prev; } node.next = cache.head; node.prev = null; cache.head.prev = node; cache.head = node; } // Return immediately return node.val; } // No cached value found. Continue to insertion phase: node = { // Generate the result from original function val: selector.apply( null, args ), }; // Avoid including the source object in the cache. args[ 0 ] = null; node.args = args; // Don't need to check whether node is already head, since it would // have been returned above already if it was // Shift existing head down list if ( cache.head ) { cache.head.prev = node; node.next = cache.head; } cache.head = node; return node.val; } callSelector.getDependants = getDependants; callSelector.clear = clear; clear(); return callSelector; }); /***/ }), /***/ 33: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return _iterableToArray; }); function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } /***/ }), /***/ 35: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return _arrayWithHoles; }); function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } /***/ }), /***/ 36: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return _nonIterableRest; }); function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } /***/ }), /***/ 5: /***/ (function(module, exports) { (function() { module.exports = this["wp"]["data"]; }()); /***/ }), /***/ 51: /***/ (function(module, exports) { var g; // This works in non-strict mode g = (function() { return this; })(); try { // This works if eval is allowed (see CSP) g = g || Function("return this")() || (1, eval)("this"); } catch (e) { // This works if the window reference is available if (typeof window === "object") g = window; } // g can still be undefined, but nothing to do about it... // We return undefined, instead of nothing here, so it's // easier to handle this case. if(!global) { ...} module.exports = g; /***/ }), /***/ 62: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return createStore; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return combineReducers; }); /* unused harmony export bindActionCreators */ /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return applyMiddleware; }); /* unused harmony export compose */ /* unused harmony export __DO_NOT_USE__ActionTypes */ /* harmony import */ var symbol_observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(67); /** * These are private action types reserved by Redux. * For any unknown actions, you must return the current state. * If the current state is undefined, you must return the initial state. * Do not reference these action types directly in your code. */ var randomString = function randomString() { return Math.random().toString(36).substring(7).split('').join('.'); }; var ActionTypes = { INIT: "@@redux/INIT" + randomString(), REPLACE: "@@redux/REPLACE" + randomString(), PROBE_UNKNOWN_ACTION: function PROBE_UNKNOWN_ACTION() { return "@@redux/PROBE_UNKNOWN_ACTION" + randomString(); } }; /** * @param {any} obj The object to inspect. * @returns {boolean} True if the argument appears to be a plain object. */ function isPlainObject(obj) { if (typeof obj !== 'object' || obj === null) return false; var proto = obj; while (Object.getPrototypeOf(proto) !== null) { proto = Object.getPrototypeOf(proto); } return Object.getPrototypeOf(obj) === proto; } /** * Creates a Redux store that holds the state tree. * The only way to change the data in the store is to call `dispatch()` on it. * * There should only be a single store in your app. To specify how different * parts of the state tree respond to actions, you may combine several reducers * into a single reducer function by using `combineReducers`. * * @param {Function} reducer A function that returns the next state tree, given * the current state tree and the action to handle. * * @param {any} [preloadedState] The initial state. You may optionally specify it * to hydrate the state from the server in universal apps, or to restore a * previously serialized user session. * If you use `combineReducers` to produce the root reducer function, this must be * an object with the same shape as `combineReducers` keys. * * @param {Function} [enhancer] The store enhancer. You may optionally specify it * to enhance the store with third-party capabilities such as middleware, * time travel, persistence, etc. The only store enhancer that ships with Redux * is `applyMiddleware()`. * * @returns {Store} A Redux store that lets you read the state, dispatch actions * and subscribe to changes. */ function createStore(reducer, preloadedState, enhancer) { var _ref2; if (typeof preloadedState === 'function' && typeof enhancer === 'function' || typeof enhancer === 'function' && typeof arguments[3] === 'function') { throw new Error('It looks like you are passing several store enhancers to ' + 'createStore(). This is not supported. Instead, compose them ' + 'together to a single function'); } if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') { enhancer = preloadedState; preloadedState = undefined; } if (typeof enhancer !== 'undefined') { if (typeof enhancer !== 'function') { throw new Error('Expected the enhancer to be a function.'); } return enhancer(createStore)(reducer, preloadedState); } if (typeof reducer !== 'function') { throw new Error('Expected the reducer to be a function.'); } var currentReducer = reducer; var currentState = preloadedState; var currentListeners = []; var nextListeners = currentListeners; var isDispatching = false; function ensureCanMutateNextListeners() { if (nextListeners === currentListeners) { nextListeners = currentListeners.slice(); } } /** * Reads the state tree managed by the store. * * @returns {any} The current state tree of your application. */ function getState() { if (isDispatching) { throw new Error('You may not call store.getState() while the reducer is executing. ' + 'The reducer has already received the state as an argument. ' + 'Pass it down from the top reducer instead of reading it from the store.'); } return currentState; } /** * Adds a change listener. It will be called any time an action is dispatched, * and some part of the state tree may potentially have changed. You may then * call `getState()` to read the current state tree inside the callback. * * You may call `dispatch()` from a change listener, with the following * caveats: * * 1. The subscriptions are snapshotted just before every `dispatch()` call. * If you subscribe or unsubscribe while the listeners are being invoked, this * will not have any effect on the `dispatch()` that is currently in progress. * However, the next `dispatch()` call, whether nested or not, will use a more * recent snapshot of the subscription list. * * 2. The listener should not expect to see all state changes, as the state * might have been updated multiple times during a nested `dispatch()` before * the listener is called. It is, however, guaranteed that all subscribers * registered before the `dispatch()` started will be called with the latest * state by the time it exits. * * @param {Function} listener A callback to be invoked on every dispatch. * @returns {Function} A function to remove this change listener. */ function subscribe(listener) { if (typeof listener !== 'function') { throw new Error('Expected the listener to be a function.'); } if (isDispatching) { throw new Error('You may not call store.subscribe() while the reducer is executing. ' + 'If you would like to be notified after the store has been updated, subscribe from a ' + 'component and invoke store.getState() in the callback to access the latest state. ' + 'See https://redux.js.org/api-reference/store#subscribe(listener) for more details.'); } var isSubscribed = true; ensureCanMutateNextListeners(); nextListeners.push(listener); return function unsubscribe() { if (!isSubscribed) { return; } if (isDispatching) { throw new Error('You may not unsubscribe from a store listener while the reducer is executing. ' + 'See https://redux.js.org/api-reference/store#subscribe(listener) for more details.'); } isSubscribed = false; ensureCanMutateNextListeners(); var index = nextListeners.indexOf(listener); nextListeners.splice(index, 1); }; } /** * Dispatches an action. It is the only way to trigger a state change. * * The `reducer` function, used to create the store, will be called with the * current state tree and the given `action`. Its return value will * be considered the **next** state of the tree, and the change listeners * will be notified. * * The base implementation only supports plain object actions. If you want to * dispatch a Promise, an Observable, a thunk, or something else, you need to * wrap your store creating function into the corresponding middleware. For * example, see the documentation for the `redux-thunk` package. Even the * middleware will eventually dispatch plain object actions using this method. * * @param {Object} action A plain object representing “what changed”. It is * a good idea to keep actions serializable so you can record and replay user * sessions, or use the time travelling `redux-devtools`. An action must have * a `type` property which may not be `undefined`. It is a good idea to use * string constants for action types. * * @returns {Object} For convenience, the same action object you dispatched. * * Note that, if you use a custom middleware, it may wrap `dispatch()` to * return something else (for example, a Promise you can await). */ function dispatch(action) { if (!isPlainObject(action)) { throw new Error('Actions must be plain objects. ' + 'Use custom middleware for async actions.'); } if (typeof action.type === 'undefined') { throw new Error('Actions may not have an undefined "type" property. ' + 'Have you misspelled a constant?'); } if (isDispatching) { throw new Error('Reducers may not dispatch actions.'); } try { isDispatching = true; currentState = currentReducer(currentState, action); } finally { isDispatching = false; } var listeners = currentListeners = nextListeners; for (var i = 0; i < listeners.length; i++) { var listener = listeners[i]; listener(); } return action; } /** * Replaces the reducer currently used by the store to calculate the state. * * You might need this if your app implements code splitting and you want to * load some of the reducers dynamically. You might also need this if you * implement a hot reloading mechanism for Redux. * * @param {Function} nextReducer The reducer for the store to use instead. * @returns {void} */ function replaceReducer(nextReducer) { if (typeof nextReducer !== 'function') { throw new Error('Expected the nextReducer to be a function.'); } currentReducer = nextReducer; dispatch({ type: ActionTypes.REPLACE }); } /** * Interoperability point for observable/reactive libraries. * @returns {observable} A minimal observable of state changes. * For more information, see the observable proposal: * https://github.com/tc39/proposal-observable */ function observable() { var _ref; var outerSubscribe = subscribe; return _ref = { /** * The minimal observable subscription method. * @param {Object} observer Any object that can be used as an observer. * The observer object should have a `next` method. * @returns {subscription} An object with an `unsubscribe` method that can * be used to unsubscribe the observable from the store, and prevent further * emission of values from the observable. */ subscribe: function subscribe(observer) { if (typeof observer !== 'object' || observer === null) { throw new TypeError('Expected the observer to be an object.'); } function observeState() { if (observer.next) { observer.next(getState()); } } observeState(); var unsubscribe = outerSubscribe(observeState); return { unsubscribe: unsubscribe }; } }, _ref[symbol_observable__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"]] = function () { return this; }, _ref; } // When a store is created, an "INIT" action is dispatched so that every // reducer returns their initial state. This effectively populates // the initial state tree. dispatch({ type: ActionTypes.INIT }); return _ref2 = { dispatch: dispatch, subscribe: subscribe, getState: getState, replaceReducer: replaceReducer }, _ref2[symbol_observable__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"]] = observable, _ref2; } /** * Prints a warning in the console if it exists. * * @param {String} message The warning message. * @returns {void} */ function warning(message) { /* eslint-disable no-console */ if (typeof console !== 'undefined' && typeof console.error === 'function') { console.error(message); } /* eslint-enable no-console */ try { // This error was thrown as a convenience so that if you enable // "break on all exceptions" in your console, // it would pause the execution at this line. throw new Error(message); } catch (e) {} // eslint-disable-line no-empty } function getUndefinedStateErrorMessage(key, action) { var actionType = action && action.type; var actionDescription = actionType && "action \"" + String(actionType) + "\"" || 'an action'; return "Given " + actionDescription + ", reducer \"" + key + "\" returned undefined. " + "To ignore an action, you must explicitly return the previous state. " + "If you want this reducer to hold no value, you can return null instead of undefined."; } function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) { var reducerKeys = Object.keys(reducers); var argumentName = action && action.type === ActionTypes.INIT ? 'preloadedState argument passed to createStore' : 'previous state received by the reducer'; if (reducerKeys.length === 0) { return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.'; } if (!isPlainObject(inputState)) { return "The " + argumentName + " has unexpected type of \"" + {}.toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] + "\". Expected argument to be an object with the following " + ("keys: \"" + reducerKeys.join('", "') + "\""); } var unexpectedKeys = Object.keys(inputState).filter(function (key) { return !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key]; }); unexpectedKeys.forEach(function (key) { unexpectedKeyCache[key] = true; }); if (action && action.type === ActionTypes.REPLACE) return; if (unexpectedKeys.length > 0) { return "Unexpected " + (unexpectedKeys.length > 1 ? 'keys' : 'key') + " " + ("\"" + unexpectedKeys.join('", "') + "\" found in " + argumentName + ". ") + "Expected to find one of the known reducer keys instead: " + ("\"" + reducerKeys.join('", "') + "\". Unexpected keys will be ignored."); } } function assertReducerShape(reducers) { Object.keys(reducers).forEach(function (key) { var reducer = reducers[key]; var initialState = reducer(undefined, { type: ActionTypes.INIT }); if (typeof initialState === 'undefined') { throw new Error("Reducer \"" + key + "\" returned undefined during initialization. " + "If the state passed to the reducer is undefined, you must " + "explicitly return the initial state. The initial state may " + "not be undefined. If you don't want to set a value for this reducer, " + "you can use null instead of undefined."); } if (typeof reducer(undefined, { type: ActionTypes.PROBE_UNKNOWN_ACTION() }) === 'undefined') { throw new Error("Reducer \"" + key + "\" returned undefined when probed with a random type. " + ("Don't try to handle " + ActionTypes.INIT + " or other actions in \"redux/*\" ") + "namespace. They are considered private. Instead, you must return the " + "current state for any unknown actions, unless it is undefined, " + "in which case you must return the initial state, regardless of the " + "action type. The initial state may not be undefined, but can be null."); } }); } /** * Turns an object whose values are different reducer functions, into a single * reducer function. It will call every child reducer, and gather their results * into a single state object, whose keys correspond to the keys of the passed * reducer functions. * * @param {Object} reducers An object whose values correspond to different * reducer functions that need to be combined into one. One handy way to obtain * it is to use ES6 `import * as reducers` syntax. The reducers may never return * undefined for any action. Instead, they should return their initial state * if the state passed to them was undefined, and the current state for any * unrecognized action. * * @returns {Function} A reducer function that invokes every reducer inside the * passed object, and builds a state object with the same shape. */ function combineReducers(reducers) { var reducerKeys = Object.keys(reducers); var finalReducers = {}; for (var i = 0; i < reducerKeys.length; i++) { var key = reducerKeys[i]; if (false) {} if (typeof reducers[key] === 'function') { finalReducers[key] = reducers[key]; } } var finalReducerKeys = Object.keys(finalReducers); var unexpectedKeyCache; if (false) {} var shapeAssertionError; try { assertReducerShape(finalReducers); } catch (e) { shapeAssertionError = e; } return function combination(state, action) { if (state === void 0) { state = {}; } if (shapeAssertionError) { throw shapeAssertionError; } if (false) { var warningMessage; } var hasChanged = false; var nextState = {}; for (var _i = 0; _i < finalReducerKeys.length; _i++) { var _key = finalReducerKeys[_i]; var reducer = finalReducers[_key]; var previousStateForKey = state[_key]; var nextStateForKey = reducer(previousStateForKey, action); if (typeof nextStateForKey === 'undefined') { var errorMessage = getUndefinedStateErrorMessage(_key, action); throw new Error(errorMessage); } nextState[_key] = nextStateForKey; hasChanged = hasChanged || nextStateForKey !== previousStateForKey; } return hasChanged ? nextState : state; }; } function bindActionCreator(actionCreator, dispatch) { return function () { return dispatch(actionCreator.apply(this, arguments)); }; } /** * Turns an object whose values are action creators, into an object with the * same keys, but with every function wrapped into a `dispatch` call so they * may be invoked directly. This is just a convenience method, as you can call * `store.dispatch(MyActionCreators.doSomething())` yourself just fine. * * For convenience, you can also pass a single function as the first argument, * and get a function in return. * * @param {Function|Object} actionCreators An object whose values are action * creator functions. One handy way to obtain it is to use ES6 `import * as` * syntax. You may also pass a single function. * * @param {Function} dispatch The `dispatch` function available on your Redux * store. * * @returns {Function|Object} The object mimicking the original object, but with * every action creator wrapped into the `dispatch` call. If you passed a * function as `actionCreators`, the return value will also be a single * function. */ function bindActionCreators(actionCreators, dispatch) { if (typeof actionCreators === 'function') { return bindActionCreator(actionCreators, dispatch); } if (typeof actionCreators !== 'object' || actionCreators === null) { throw new Error("bindActionCreators expected an object or a function, instead received " + (actionCreators === null ? 'null' : typeof actionCreators) + ". " + "Did you write \"import ActionCreators from\" instead of \"import * as ActionCreators from\"?"); } var keys = Object.keys(actionCreators); var boundActionCreators = {}; for (var i = 0; i < keys.length; i++) { var key = keys[i]; var actionCreator = actionCreators[key]; if (typeof actionCreator === 'function') { boundActionCreators[key] = bindActionCreator(actionCreator, dispatch); } } return boundActionCreators; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } /** * Composes single-argument functions from right to left. The rightmost * function can take multiple arguments as it provides the signature for * the resulting composite function. * * @param {...Function} funcs The functions to compose. * @returns {Function} A function obtained by composing the argument functions * from right to left. For example, compose(f, g, h) is identical to doing * (...args) => f(g(h(...args))). */ function compose() { for (var _len = arguments.length, funcs = new Array(_len), _key = 0; _key < _len; _key++) { funcs[_key] = arguments[_key]; } if (funcs.length === 0) { return function (arg) { return arg; }; } if (funcs.length === 1) { return funcs[0]; } return funcs.reduce(function (a, b) { return function () { return a(b.apply(void 0, arguments)); }; }); } /** * Creates a store enhancer that applies middleware to the dispatch method * of the Redux store. This is handy for a variety of tasks, such as expressing * asynchronous actions in a concise manner, or logging every action payload. * * See `redux-thunk` package as an example of the Redux middleware. * * Because middleware is potentially asynchronous, this should be the first * store enhancer in the composition chain. * * Note that each middleware will be given the `dispatch` and `getState` functions * as named arguments. * * @param {...Function} middlewares The middleware chain to be applied. * @returns {Function} A store enhancer applying the middleware. */ function applyMiddleware() { for (var _len = arguments.length, middlewares = new Array(_len), _key = 0; _key < _len; _key++) { middlewares[_key] = arguments[_key]; } return function (createStore) { return function () { var store = createStore.apply(void 0, arguments); var _dispatch = function dispatch() { throw new Error("Dispatching while constructing your middleware is not allowed. " + "Other middleware would not be applied to this dispatch."); }; var middlewareAPI = { getState: store.getState, dispatch: function dispatch() { return _dispatch.apply(void 0, arguments); } }; var chain = middlewares.map(function (middleware) { return middleware(middlewareAPI); }); _dispatch = compose.apply(void 0, chain)(store.dispatch); return _objectSpread({}, store, { dispatch: _dispatch }); }; }; } /* * This is a dummy function to check if the function name has been altered by minification. * If the function has been minified and NODE_ENV !== 'production', warn the user. */ function isCrushed() {} if (false) {} /***/ }), /***/ 66: /***/ (function(module, exports, __webpack_require__) { "use strict"; function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function (obj) { return typeof obj; }; } else { _typeof = function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } /** * Given an instance of EquivalentKeyMap, returns its internal value pair tuple * for a key, if one exists. The tuple members consist of the last reference * value for the key (used in efficient subsequent lookups) and the value * assigned for the key at the leaf node. * * @param {EquivalentKeyMap} instance EquivalentKeyMap instance. * @param {*} key The key for which to return value pair. * * @return {?Array} Value pair, if exists. */ function getValuePair(instance, key) { var _map = instance._map, _arrayTreeMap = instance._arrayTreeMap, _objectTreeMap = instance._objectTreeMap; // Map keeps a reference to the last object-like key used to set the // value, which can be used to shortcut immediately to the value. if (_map.has(key)) { return _map.get(key); } // Sort keys to ensure stable retrieval from tree. var properties = Object.keys(key).sort(); // Tree by type to avoid conflicts on numeric object keys, empty value. var map = Array.isArray(key) ? _arrayTreeMap : _objectTreeMap; for (var i = 0; i < properties.length; i++) { var property = properties[i]; map = map.get(property); if (map === undefined) { return; } var propertyValue = key[property]; map = map.get(propertyValue); if (map === undefined) { return; } } var valuePair = map.get('_ekm_value'); if (!valuePair) { return; } // If reached, it implies that an object-like key was set with another // reference, so delete the reference and replace with the current. _map.delete(valuePair[0]); valuePair[0] = key; map.set('_ekm_value', valuePair); _map.set(key, valuePair); return valuePair; } /** * Variant of a Map object which enables lookup by equivalent (deeply equal) * object and array keys. */ var EquivalentKeyMap = /*#__PURE__*/ function () { /** * Constructs a new instance of EquivalentKeyMap. * * @param {Iterable.<*>} iterable Initial pair of key, value for map. */ function EquivalentKeyMap(iterable) { _classCallCheck(this, EquivalentKeyMap); this.clear(); if (iterable instanceof EquivalentKeyMap) { // Map#forEach is only means of iterating with support for IE11. var iterablePairs = []; iterable.forEach(function (value, key) { iterablePairs.push([key, value]); }); iterable = iterablePairs; } if (iterable != null) { for (var i = 0; i < iterable.length; i++) { this.set(iterable[i][0], iterable[i][1]); } } } /** * Accessor property returning the number of elements. * * @return {number} Number of elements. */ _createClass(EquivalentKeyMap, [{ key: "set", /** * Add or update an element with a specified key and value. * * @param {*} key The key of the element to add. * @param {*} value The value of the element to add. * * @return {EquivalentKeyMap} Map instance. */ value: function set(key, value) { // Shortcut non-object-like to set on internal Map. if (key === null || _typeof(key) !== 'object') { this._map.set(key, value); return this; } // Sort keys to ensure stable assignment into tree. var properties = Object.keys(key).sort(); var valuePair = [key, value]; // Tree by type to avoid conflicts on numeric object keys, empty value. var map = Array.isArray(key) ? this._arrayTreeMap : this._objectTreeMap; for (var i = 0; i < properties.length; i++) { var property = properties[i]; if (!map.has(property)) { map.set(property, new EquivalentKeyMap()); } map = map.get(property); var propertyValue = key[property]; if (!map.has(propertyValue)) { map.set(propertyValue, new EquivalentKeyMap()); } map = map.get(propertyValue); } // If an _ekm_value exists, there was already an equivalent key. Before // overriding, ensure that the old key reference is removed from map to // avoid memory leak of accumulating equivalent keys. This is, in a // sense, a poor man's WeakMap, while still enabling iterability. var previousValuePair = map.get('_ekm_value'); if (previousValuePair) { this._map.delete(previousValuePair[0]); } map.set('_ekm_value', valuePair); this._map.set(key, valuePair); return this; } /** * Returns a specified element. * * @param {*} key The key of the element to return. * * @return {?*} The element associated with the specified key or undefined * if the key can't be found. */ }, { key: "get", value: function get(key) { // Shortcut non-object-like to get from internal Map. if (key === null || _typeof(key) !== 'object') { return this._map.get(key); } var valuePair = getValuePair(this, key); if (valuePair) { return valuePair[1]; } } /** * Returns a boolean indicating whether an element with the specified key * exists or not. * * @param {*} key The key of the element to test for presence. * * @return {boolean} Whether an element with the specified key exists. */ }, { key: "has", value: function has(key) { if (key === null || _typeof(key) !== 'object') { return this._map.has(key); } // Test on the _presence_ of the pair, not its value, as even undefined // can be a valid member value for a key. return getValuePair(this, key) !== undefined; } /** * Removes the specified element. * * @param {*} key The key of the element to remove. * * @return {boolean} Returns true if an element existed and has been * removed, or false if the element does not exist. */ }, { key: "delete", value: function _delete(key) { if (!this.has(key)) { return false; } // This naive implementation will leave orphaned child trees. A better // implementation should traverse and remove orphans. this.set(key, undefined); return true; } /** * Executes a provided function once per each key/value pair, in insertion * order. * * @param {Function} callback Function to execute for each element. * @param {*} thisArg Value to use as `this` when executing * `callback`. */ }, { key: "forEach", value: function forEach(callback) { var _this = this; var thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this; this._map.forEach(function (value, key) { // Unwrap value from object-like value pair. if (key !== null && _typeof(key) === 'object') { value = value[1]; } callback.call(thisArg, value, key, _this); }); } /** * Removes all elements. */ }, { key: "clear", value: function clear() { this._map = new Map(); this._arrayTreeMap = new Map(); this._objectTreeMap = new Map(); } }, { key: "size", get: function get() { return this._map.size; } }]); return EquivalentKeyMap; }(); module.exports = EquivalentKeyMap; /***/ }), /***/ 67: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(global, module) {/* harmony import */ var _ponyfill_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(85); /* global window */ var root; if (typeof self !== 'undefined') { root = self; } else if (typeof window !== 'undefined') { root = window; } else if (typeof global !== 'undefined') { root = global; } else if (true) { root = module; } else {} var result = Object(_ponyfill_js__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"])(root); /* harmony default export */ __webpack_exports__["a"] = (result); /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(51), __webpack_require__(120)(module))) /***/ }), /***/ 8: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return _objectSpread; }); /* harmony import */ var _defineProperty__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(15); function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { Object(_defineProperty__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"])(target, key, source[key]); }); } return target; } /***/ }), /***/ 85: /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return symbolObservablePonyfill; }); function symbolObservablePonyfill(root) { var result; var Symbol = root.Symbol; if (typeof Symbol === 'function') { if (Symbol.observable) { result = Symbol.observable; } else { result = Symbol('observable'); Symbol.observable = result; } } else { result = '@@observable'; } return result; }; /***/ }) /******/ });
{ "content_hash": "0ba8486f9af269c4f15ccb446fa2e5cf", "timestamp": "", "source": "github", "line_count": 3412, "max_line_length": 473, "avg_line_length": 29.887456037514653, "alnum_prop": 0.6448870322428807, "repo_name": "sifonsecac/capitalino-errante", "id": "5b8cef84c767fa2ce5ee94214412bdd36a3218bb", "size": "101980", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "wp-includes/js/dist/core-data.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "3458117" }, { "name": "HTML", "bytes": "42443" }, { "name": "Hack", "bytes": "915" }, { "name": "JavaScript", "bytes": "5543630" }, { "name": "PHP", "bytes": "22604660" }, { "name": "Ruby", "bytes": "3054" }, { "name": "Shell", "bytes": "8030" }, { "name": "Smarty", "bytes": "33" }, { "name": "XSLT", "bytes": "4267" } ], "symlink_target": "" }
/** * \file RaspiMJPEG.c * Command line program to capture a camera video stream and encode it to file. * Also optionally stream a preview of current camera input with MJPEG. * * \date 9th Aprl 2015 * \Author: Silvan Melchior / Robert Tidey * * Description * * RaspiMJPEG is an OpenMAX-Application based on the mmal-library, which is * comparable to and inspired by RaspiVid and RaspiStill. RaspiMJPEG can record * 1080p 30fps videos and 5 Mpx images into a file. But instead of showing the * preview on a screen, RaspiMJPEG streams the preview as MJPEG into a file. * The update-rate and the size of the preview are customizable with parameters * and independent of the image/video. Once started, the application receives * commands with a unix-pipe and showes its status on stdout and writes it into * a status-file. The program terminates itself after receiving a SIGINT or * SIGTERM. */ #include "RaspiMJPEG.h" MMAL_STATUS_T status; MMAL_COMPONENT_T *camera = 0, *jpegencoder = 0, *jpegencoder2 = 0, *h264encoder = 0, *resizer = 0, *null_sink = 0, *splitter = 0; MMAL_CONNECTION_T *con_cam_pre = 0, *con_spli_res = 0, *con_spli_h264 = 0, *con_res_jpeg = 0, *con_cam_h264 = 0, *con_cam_jpeg = 0; FILE *jpegoutput_file = NULL, *jpegoutput2_file = NULL, *h264output_file = NULL, *status_file = NULL, *vector_file = NULL; MMAL_POOL_T *pool_jpegencoder = 0, *pool_jpegencoder_in = 0, *pool_jpegencoder2 = 0, *pool_h264encoder = 0; char *cb_buff = NULL; MMAL_COMPONENT_T *preview = 0, *splitter2 = 0 ; MMAL_CONNECTION_T *con_cam_preview = 0, *con_spli_preview = 0 ; char readbuf[FIFO_MAX][2 * MAX_COMMAND_LEN]; int fd[FIFO_MAX], readi[FIFO_MAX]; //pthread_mutex_t v_mutex; char header_bytes[29]; int cb_len, cb_wptr, cb_wrap; int iframe_buff[IFRAME_BUFSIZE], iframe_buff_wpos, iframe_buff_rpos, header_wptr; unsigned int tl_cnt=0, mjpeg_cnt=0, image_cnt=0, image2_cnt=0, lapse_cnt=0, video_cnt=0, video_stoptime=0, video_frame, video_stoptimeEnd; char *filename_recording = 0, *filename_image = 0; unsigned char timelapse=0, running=1, autostart=1, idle=0, a_error=0, v_capturing=0, i_capturing=0, v_boxing=0; unsigned char buffering=0, buffering_toggle=0; char *box_files[MAX_BOX_FILES]; int box_head=0; int box_tail=0; char *cfg_strd[KEY_COUNT + 1]; char *cfg_stru[KEY_COUNT + 1]; long int cfg_val[KEY_COUNT + 1]; struct timespec currTime; struct tm *localTime; char *cfg_key[] ={ "annotation","anno_background", "anno3_custom_background_colour","anno3_custom_background_Y","anno3_custom_background_U","anno3_custom_background_V", "anno3_custom_text_colour","anno3_custom_text_Y","anno3_custom_text_U","anno3_custom_text_V","anno_text_size", "sharpness","contrast","brightness","saturation","iso", "metering_mode","video_stabilisation","exposure_compensation","exposure_mode","white_balance","image_effect", "autowbgain_r","autowbgain_b", "colour_effect_en","colour_effect_u","colour_effect_v", "rotation","hflip","vflip", "sensor_region_x","sensor_region_y","sensor_region_w","sensor_region_h", "shutter_speed","raw_layer", "width","quality","divider", "video_width","video_height","video_fps","fps_divider","video_bitrate","video_buffer","video_split", "MP4Box","MP4Box_fps","boxing_path","MP4Box_cmd", "image_width","image_height","image_quality","tl_interval", "base_path","preview_path","image_path","lapse_path","video_path","status_file","control_file","media_path","macros_path","subdir_char","enforce_lf","fifo_interval", "thumb_gen","autostart","motion_detection","motion_file","vector_preview","vector_mode", "motion_external", "motion_noise","motion_threshold","motion_image","motion_initframes","motion_startframes","motion_stopframes","motion_pipe","motion_clip","motion_logfile", "user_config","log_file","log_size","watchdog_interval","watchdog_errors","h264_buffer_size","h264_buffers","callback_timeout", "error_soft", "error_hard", "start_img", "end_img", "start_vid", "end_vid", "end_box", "do_cmd","motion_event","startstop", "camera_num","stat_pass","user_annotate","count_format","minimise_frag","initial_quant","encode_qp","mmal_logfile","stop_pause", "hdmi_preview" }; void term (int signum) { running = 0; } void set_counts() { image2_cnt = findNextCount(cfg_stru[c_image_path], "it"); video_cnt = findNextCount(cfg_stru[c_video_path], "v"); } int getKey(char *key) { int i; for(i=0; i < KEY_COUNT; i++) { if(strcmp(key, cfg_key[i]) == 0) { return i; } } return KEY_COUNT; } void addValue(int keyI, char *value, int both){ free(cfg_stru[keyI]); cfg_stru[keyI] = 0; if (both) {free(cfg_strd[keyI]);cfg_strd[keyI] = 0;} if (value == NULL || strlen(value) == 0) { cfg_val[keyI] = 0; } else { int val=strtol(value, NULL, 10); asprintf(&cfg_stru[keyI],"%s", value); if (both) { asprintf(&cfg_strd[keyI],"%s", value); } if (strcmp(value, "true") == 0) val = 1; else if (strcmp(value, "false") == 0) val = 0; switch(keyI) { case c_autostart: if(strcmp(value, "idle") == 0) { val = 0; idle = 1; }else if(strcmp(value, "standard") == 0) { val = 1; idle = 0; }; updateStatus(); break; case c_MP4Box: if(strcmp(value, "background") == 0) val = 2; break; } cfg_val[keyI] = val; } } void addUserValue(int key, char *value){ printLog("Change: %s = %s\n", cfg_key[key], value); addValue(key, value, 0); } void saveUserConfig(char *cfilename) { FILE *fp; int i; fp = fopen(cfilename, "w"); if(fp != NULL) { for(i = 0; i < KEY_COUNT; i++) { if(strlen(cfg_key[i]) > 0) { if(cfg_stru[i] != 0 && cfg_strd[i] != 0 && strcmp(cfg_strd[i], cfg_stru[i]) != 0) { fprintf(fp, "%s %s\n", cfg_key[i], cfg_stru[i]); } else if (cfg_stru[i] != 0 && cfg_strd[i] == 0) { fprintf(fp, "%s %s\n", cfg_key[i], cfg_stru[i]); } else if (cfg_stru[i] == 0 && cfg_strd[i] != 0) { fprintf(fp, "%s\n", cfg_key[i]); } } } fclose(fp); } } void read_config(char *cfilename, int type) { FILE *fp; int length; unsigned int len = 0; char *line = NULL; char *value = NULL; int key; fp = fopen(cfilename, "r"); if(fp != NULL) { while((length = getline(&line, &len, fp)) != -1) { if (length > 3 && *line != '#') { line[length-1] = 0; value = strchr(line, ' '); if (value != NULL) { // split line into key, value *value = 0; value++; } key = getKey(line); if (key < KEY_COUNT) { if (key != c_annotation) { value = trim(value); } addValue(key, value, type); } } } if(line) free(line); } } void checkPipe(int pipe) { char *lf; int length, hPipe; hPipe = fd[pipe]; if(hPipe >= 0) { length = read(hPipe, readbuf[pipe] + readi[pipe], MAX_COMMAND_LEN - 2); if (length > 0) readi[pipe] +=length; if(readi[pipe] != 0) { lf = strchr(readbuf[pipe], 10); if (lf != NULL) { *lf = 0; length = lf - readbuf[pipe]; readi[pipe] -= length + 1; process_cmd(readbuf[pipe], length); length = readbuf[pipe] + 2 * MAX_COMMAND_LEN - 1 - lf; strncpy(readbuf[pipe], lf + 1, length); } else { if ((length == 0) && (cfg_val[c_enforce_lf] == 0)) { process_cmd(readbuf[pipe], readi[pipe]); readi[pipe] = 0; } } } } } void monitor() { while(1) { int pid = fork(); switch(pid) { case -1: //error error("fork failed", 1); case 0: //child return; //continue to execute the code from main default: //parent printLog("start monitoring for pid: %d\n", pid); int child_status; //wait for child process to terminate wait(&child_status); //child pid has terminated sleep(5); } } } int main (int argc, char* argv[]) { monitor(); int i, length; int watchdog = 0, watchdog_errors = 0; int onesec_check = 0; time_t last_pv_time = 0, pv_time; char fdName[FIFO_MAX][128]; bcm_host_init(); // // read arguments // for(i=1; i<argc; i++) { if(strcmp(argv[i], "--version") == 0) { printf("RaspiMJPEG Version %s\n", VERSION); exit(0); } else if(strcmp(argv[i], "-md") == 0) { cfg_val[c_motion_detection] = 1; } } //default base media path asprintf(&cfg_stru[c_media_path], "%s", "/var/www/media"); // // read configs and init // read_config("/etc/raspimjpeg", 1); if (cfg_stru[c_user_config] != 0) read_config(cfg_stru[c_user_config], 0); createPath(cfg_stru[c_log_file], cfg_stru[c_base_path]); if (cfg_stru[c_boxing_path] != NULL) { char *bpath; asprintf(&bpath, "%s/temp", cfg_stru[c_boxing_path]); createPath(bpath, cfg_stru[c_base_path]); free(bpath); } printLog("RaspiMJPEG Version %s\n", VERSION); exec_macro(cfg_stru[c_startstop],"start"); if(cfg_val[c_autostart]) start_all(0); // // run // updateStatus(); struct sigaction action; memset(&action, 0, sizeof(struct sigaction)); action.sa_handler = term; sigaction(SIGTERM, &action, NULL); sigaction(SIGINT, &action, NULL); //Set up FIFO names if(cfg_stru[c_control_file] == 0) { error("No PIPE defined", 1); } for(i=0;i < FIFO_MAX; i++) { if (i==0) { sprintf(fdName[i],"%s",cfg_stru[c_control_file]); } else { sprintf(fdName[i],"%s%d",cfg_stru[c_control_file],i+10); } } //Clear out anything in FIFO(s) first for(i=0;i < FIFO_MAX; i++) { do { fd[i] = open(fdName[i], O_RDONLY | O_NONBLOCK); if(fd[i] >= 0) { fcntl(fd[i], F_SETFL, 0); length = read(fd[i], readbuf[0], 60); close(fd[i]); } else { if(i==0) error("Could not open main PIPE", 1); } } while (fd[i] >=0 && length != 0); } // Main forever loop for(i=0;i < FIFO_MAX; i++) { fd[i] = open(fdName[i], O_RDONLY | O_NONBLOCK); if(fd[i] >= 0) { printLog("Opening FIFO %i %s %i\n", i, fdName[i], fd[i]); fcntl(fd[i], F_SETFL, 0); } } if(cfg_val[c_autostart]) { printLog("MJPEG streaming, ready to receive commands\n"); //kick off motion detection at start if required. if(cfg_val[c_motion_detection] && cfg_val[c_motion_external] == 1) { printLog("Autostart external motion kill any runnng motion\n"); if(system("killall motion 2> /dev/null") == -1) error("Could not stop external motion", 1); sleep(1); printLog("Autostart external motion start external motion\n"); if(system("motion") == -1) error("Could not start external motion", 1); } } else { if(cfg_stru[c_control_file] != 0) printLog("MJPEG idle, ready to receive commands\n"); else printLog("MJPEG idle\n"); } updateStatus(); //Send restart signal to scheduler send_schedulecmd("9"); printLog("Starting command loop\n"); if(cfg_val[c_fifo_interval] < 100000) cfg_val[c_fifo_interval] = 100000; while(running == 1) { for(i=0;i < FIFO_MAX; i++) { checkPipe(i); } if(timelapse) { tl_cnt++; if(tl_cnt >= cfg_val[c_tl_interval]) { if(i_capturing == 0) { capt_img(); tl_cnt = 0; } } } // check to see if image preview changing if (!idle && cfg_val[c_watchdog_interval] > 0) { if(watchdog++ > cfg_val[c_watchdog_interval]) { watchdog = 0; pv_time = get_mtime(cfg_stru[c_preview_path]); if (pv_time == 0) { watchdog_errors++; } else { if (pv_time > last_pv_time) { watchdog_errors = 0; } else { watchdog_errors++; } last_pv_time = pv_time; } if (watchdog_errors >= cfg_val[c_watchdog_errors]) { printLog("Watchdog detected problem. Stopping"); running = 2; } } } else { watchdog_errors = 0; } if (++onesec_check >= 10) { //run check on background boxing every 10 ticks and check for video timer if capturing onesec_check = 0; // 4.9 compiler seems to want a print after the box finish to get input FIFO working again if (check_box_files()) printLog("Removed item from Box Queue\n"); // Check to make sure image operation not stuck (no callback) if enabled if ((cfg_val[c_callback_timeout] > 0) && i_capturing) { i_capturing--; if (i_capturing == 0) { printLog("Image capture timed out %s\n", filename_image); close_img(0); } } if (v_capturing && video_stoptime > 0) { if (time(NULL) >= video_stoptime) { printLog("Stopping video from timer\n"); stop_video(0); if (cfg_val[c_video_split] > 0 && (video_stoptimeEnd == 0 || video_stoptimeEnd > time(NULL))) { video_stoptime = time(NULL) + cfg_val[c_video_split]; if(video_stoptimeEnd != 0 && video_stoptime >= video_stoptimeEnd) { video_stoptime = video_stoptimeEnd; } printLog("Restarting next split of %d seconds\n", cfg_val[c_video_split]); start_video(0); } } } } usleep(cfg_val[c_fifo_interval]); } close(fd); if(system("killall motion 2> /dev/null") == -1) error("Could not stop external motion", 1); printLog("SIGINT/SIGTERM received, stopping\n"); // // tidy up // if(!idle) stop_all(); if(running == 0) exec_macro(cfg_stru[c_startstop],"stop"); else exec_macro(cfg_stru[c_startstop],"watchdog"); return 0; }
{ "content_hash": "93dfed8712f83b9136e9bb554582a1d3", "timestamp": "", "source": "github", "line_count": 438, "max_line_length": 168, "avg_line_length": 32.57077625570776, "alnum_prop": 0.5652600588812562, "repo_name": "roberttidey/userland", "id": "68026e4c22d44fd511c55fa66f75bdc0a4e3fee4", "size": "15866", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "host_applications/linux/apps/raspicam/RaspiMJPEG.c", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "6810" }, { "name": "C", "bytes": "8468342" }, { "name": "C++", "bytes": "269818" }, { "name": "CMake", "bytes": "63970" }, { "name": "Makefile", "bytes": "3068" }, { "name": "Objective-C", "bytes": "20525" }, { "name": "Shell", "bytes": "6503" } ], "symlink_target": "" }
import { EventEmitter } from 'events'; import uuid from 'uuid'; import assign from 'lodash/object/assign'; import TandemDispatcher from '../dispatcher/TandemDispatcher.js'; import { ActionTypes } from '../constants/TandemConstants.js'; var CHANGE_EVENT = 'change'; var _messages = []; var _addMessage = function( message ){ // Mixin a UUID to maintain uniqueness in React message.time = new Date(); message.uuid = uuid.v1(); // Turn chat message content into arrays if( message.type === 'chat' ){ message.content = [{ text: message.content, uuid: message.uuid }]; } // Group many chat messages from one user into one message var top_message = _messages[0]; if( top_message && top_message.type === 'chat' && message.type === 'chat' && top_message.user.id === message.user.id ){ top_message.content = top_message.content.concat( message.content ); top_message.time = new Date(); return; } _messages.unshift( message ); }; var ChatStore = assign( {}, EventEmitter.prototype, { getMessages: function( limit ){ var messages = ( limit && limit < _messages.length ) ? _messages.slice( 0, limit ) : _messages; return messages; } }); ChatStore.dispatchToken = TandemDispatcher.register( payload => { var action = payload.action; switch( action.type ){ case ActionTypes.CHAT_RECEIVE_ADD_MESSAGE: _addMessage( action.message ); ChatStore.emit( CHANGE_EVENT ); break; case ActionTypes.CHAT_RECEIVE_ADD_EMOTE: _addMessage( action.message ); ChatStore.emit( CHANGE_EVENT ); break; case ActionTypes.ROOM_RECEIVE_SET_TITLE: _addMessage({ type: 'title', user: action.user, title: action.title }); ChatStore.emit( CHANGE_EVENT ); break; case ActionTypes.PLAYER_RECEIVE_LIKE_ITEM: _addMessage({ type: 'like', user: action.user, content: action.like_message }); ChatStore.emit( CHANGE_EVENT ); break; case ActionTypes.PLAYER_RECEIVE_ITEM: _addMessage({ type: 'play', item: action.item }); ChatStore.emit( CHANGE_EVENT ); break; case ActionTypes.PLAYER_RECEIVE_SKIP_ITEM: _addMessage({ type: 'skip', user: action.user, item: action.item }); ChatStore.emit( CHANGE_EVENT ); break; case ActionTypes.PLAYLIST_RECEIVE_REMOVE_ITEM: if( action.user ){ _addMessage({ type: 'remove', user: action.user, item: action.item }); ChatStore.emit( CHANGE_EVENT ); } break; case ActionTypes.PLAYLIST_RECEIVE_SORT_END: _addMessage({ type: 'sort', origin: action.origin, destination: action.destination, user: action.user, item: action.item }); ChatStore.emit( CHANGE_EVENT ); break; case ActionTypes.USERS_RECEIVE_JOIN: _addMessage({ type: 'join', user: action.user }); ChatStore.emit( CHANGE_EVENT ); break; case ActionTypes.USERS_RECEIVE_LEAVE: _addMessage({ type: 'leave', user: action.user }); ChatStore.emit( CHANGE_EVENT ); break; } }); export default ChatStore;
{ "content_hash": "74b08c65321e73ebcde8ee24d54b0c9c", "timestamp": "", "source": "github", "line_count": 121, "max_line_length": 120, "avg_line_length": 24.33884297520661, "alnum_prop": 0.6753820033955857, "repo_name": "Fauntleroy/tandem.io", "id": "0acfed8e533f3dc1bce2ef075c2645b1d1227183", "size": "2945", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "assets/scripts/stores/ChatStore.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "15582" }, { "name": "HTML", "bytes": "1723" }, { "name": "JavaScript", "bytes": "116287" } ], "symlink_target": "" }
package uk.gov.hmrc.ct.computations.calculations import uk.gov.hmrc.ct.computations.{CP118, CP235} import uk.gov.hmrc.ct.ct600.v2.B122 trait SummaryLossesArisingThisPeriodCalculator { def summaryLossesArisingThisPeriodCalculation(cp118: CP118): CP235 = { CP235( cp118.value match { case t if t > 0 => Some(t) case _ => None }) } def summaryTradingLossesArisingCalculation(cp118: CP118): B122 = { B122( cp118.value match { case t if t > 0 => Some(t) case _ => Some(0) }) } }
{ "content_hash": "a413774f2c4c437bbccddb7e14aa3806", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 72, "avg_line_length": 21.84, "alnum_prop": 0.6446886446886447, "repo_name": "keithhall/ct-calculations", "id": "c434704cf5bf3a535ffe365e680a25df729329e7", "size": "1149", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/scala/uk/gov/hmrc/ct/computations/calculations/SummaryLossesArisingThisPeriodCalculator.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Scala", "bytes": "1120693" } ], "symlink_target": "" }
================================================================================================== VirtualMachineScsiPassthroughType ================================================================================================== .. describe:: VirtualMachineScsiPassthroughType Possible SCSI classes. .. py:data:: VirtualMachineScsiPassthroughType.cdrom .. py:data:: VirtualMachineScsiPassthroughType.com .. py:data:: VirtualMachineScsiPassthroughType.disk .. py:data:: VirtualMachineScsiPassthroughType.media .. py:data:: VirtualMachineScsiPassthroughType.optical .. py:data:: VirtualMachineScsiPassthroughType.printer .. py:data:: VirtualMachineScsiPassthroughType.processor .. py:data:: VirtualMachineScsiPassthroughType.raid .. py:data:: VirtualMachineScsiPassthroughType.scanner .. py:data:: VirtualMachineScsiPassthroughType.tape .. py:data:: VirtualMachineScsiPassthroughType.unknown .. py:data:: VirtualMachineScsiPassthroughType.worm
{ "content_hash": "af6729a2e243120c9a5b6db9df89b8cb", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 98, "avg_line_length": 19.47826086956522, "alnum_prop": 0.46651785714285715, "repo_name": "xuru/pyvisdk", "id": "7fa8f27dd3ca4514eb7387d4f800ec1e6240b0e6", "size": "1345", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/source/enum/virtual_machine_scsi_passthrough_type.rst", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "369" }, { "name": "Python", "bytes": "3037849" }, { "name": "Shell", "bytes": "4517" } ], "symlink_target": "" }
namespace vlp { struct TextureResource : public Resource { size_t getType() const noexcept { return typeid(TextureResource).hash_code(); } uint32_t width = 0; uint32_t height = 0; uint32_t mipMapCount = 0; uint32_t* pixels = nullptr; uint32_t format = 0; }; }
{ "content_hash": "9070c28273ad168d2cf3a9360cca2bb6", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 46, "avg_line_length": 23.166666666666668, "alnum_prop": 0.6726618705035972, "repo_name": "jenningsm42/vulpan", "id": "f718e131e553ecff02fc9c3c728d8f530f3a76e0", "size": "314", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vulpan/include/TextureResource.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "64" }, { "name": "C++", "bytes": "13397" } ], "symlink_target": "" }
// @file rwlock.h generic reader-writer lock (cross platform support) #pragma once #include "mutex.h" #include "../time_support.h" // this requires newer windows versions // it works better than sharable_mutex under high contention #if defined(_WIN64) //#define MONGO_USE_SRW_ON_WINDOWS 1 #endif #if !defined(MONGO_USE_SRW_ON_WINDOWS) #if BOOST_VERSION >= 103500 # define BOOST_RWLOCK #else # if defined(_WIN32) # error need boost >= 1.35 for windows # endif # include <pthread.h> #endif #if defined(_WIN32) # include "shared_mutex_win.hpp" namespace mongo { typedef boost::modified_shared_mutex shared_mutex; } # undef assert # define assert MONGO_assert #elif defined(BOOST_RWLOCK) # include <boost/thread/shared_mutex.hpp> # undef assert # define assert MONGO_assert #endif #endif namespace mongo { #if defined(MONGO_USE_SRW_ON_WINDOWS) && defined(_WIN32) // Windows RWLock implementation (requires newer versions of windows thus the above macro) class RWLock : boost::noncopyable { public: RWLock(const char *, int lowPriorityWaitMS=0 ) : _lowPriorityWaitMS(lowPriorityWaitMS) { InitializeSRWLock(&_lock); } ~RWLock() { } const char * implType() const { return "WINSRW"; } int lowPriorityWaitMS() const { return _lowPriorityWaitMS; } void lock() { AcquireSRWLockExclusive(&_lock); } void unlock() { ReleaseSRWLockExclusive(&_lock); } void lock_shared() { AcquireSRWLockShared(&_lock); } void unlock_shared() { ReleaseSRWLockShared(&_lock); } bool lock_shared_try( int millis ) { if( TryAcquireSRWLockShared(&_lock) ) return true; if( millis == 0 ) return false; unsigned long long end = curTimeMicros64() + millis*1000; while( 1 ) { Sleep(1); if( TryAcquireSRWLockShared(&_lock) ) return true; if( curTimeMicros64() >= end ) break; } return false; } bool lock_try( int millis = 0 ) { if( TryAcquireSRWLockExclusive(&_lock) ) // quick check to optimistically avoid calling curTimeMicros64 return true; if( millis == 0 ) return false; unsigned long long end = curTimeMicros64() + millis*1000; do { Sleep(1); if( TryAcquireSRWLockExclusive(&_lock) ) return true; } while( curTimeMicros64() < end ); return false; } private: SRWLOCK _lock; const int _lowPriorityWaitMS; }; #elif defined(BOOST_RWLOCK) // Boost based RWLock implementation class RWLock : boost::noncopyable { shared_mutex _m; const int _lowPriorityWaitMS; public: const char * const _name; RWLock(const char *name, int lowPriorityWait=0) : _lowPriorityWaitMS(lowPriorityWait) , _name(name) { } const char * implType() const { return "boost"; } int lowPriorityWaitMS() const { return _lowPriorityWaitMS; } void lock() { _m.lock(); DEV mutexDebugger.entering(_name); } /*void lock() { // This sequence gives us the lock semantics we want: specifically that write lock acquisition is // greedy EXCEPT when someone already is in upgradable state. lockAsUpgradable(); upgrade(); DEV mutexDebugger.entering(_name); }*/ void unlock() { DEV mutexDebugger.leaving(_name); _m.unlock(); } void lockAsUpgradable() { _m.lock_upgrade(); } void unlockFromUpgradable() { // upgradable -> unlocked _m.unlock_upgrade(); } void upgrade() { // upgradable -> exclusive lock _m.unlock_upgrade_and_lock(); } void lock_shared() { _m.lock_shared(); } void unlock_shared() { _m.unlock_shared(); } bool lock_shared_try( int millis ) { if( _m.timed_lock_shared( boost::posix_time::milliseconds(millis) ) ) { return true; } return false; } bool lock_try( int millis = 0 ) { if( _m.timed_lock( boost::posix_time::milliseconds(millis) ) ) { DEV mutexDebugger.entering(_name); return true; } return false; } }; #else // Posix RWLock implementation class RWLock : boost::noncopyable { pthread_rwlock_t _lock; const int _lowPriorityWaitMS; static void check( int x ) { if( MONGO_likely(x == 0) ) return; log() << "pthread rwlock failed: " << x << endl; assert( x == 0 ); } public: const char *_name; RWLock(const char *name, int lowPriorityWaitMS=0) : _lowPriorityWaitMS(lowPriorityWaitMS), _name(name) { check( pthread_rwlock_init( &_lock , 0 ) ); } ~RWLock() { if ( ! StaticObserver::_destroyingStatics ) { wassert( pthread_rwlock_destroy( &_lock ) == 0 ); // wassert as don't want to throw from a destructor } } const char * implType() const { return "posix"; } int lowPriorityWaitMS() const { return _lowPriorityWaitMS; } void lock() { check( pthread_rwlock_wrlock( &_lock ) ); DEV mutexDebugger.entering(_name); } void unlock() { DEV mutexDebugger.leaving(_name); check( pthread_rwlock_unlock( &_lock ) ); } void lock_shared() { check( pthread_rwlock_rdlock( &_lock ) ); } void unlock_shared() { check( pthread_rwlock_unlock( &_lock ) ); } bool lock_shared_try( int millis ) { return _try( millis , false ); } bool lock_try( int millis = 0 ) { if( _try( millis , true ) ) { DEV mutexDebugger.entering(_name); return true; } return false; } bool _try( int millis , bool write ) { while ( true ) { int x = write ? pthread_rwlock_trywrlock( &_lock ) : pthread_rwlock_tryrdlock( &_lock ); if ( x <= 0 ) { return true; } if ( millis-- <= 0 ) return false; if ( x == EBUSY ) { sleepmillis(1); continue; } check(x); } return false; } }; #endif /** throws on failure to acquire in the specified time period. */ class rwlock_try_write : boost::noncopyable { public: struct exception { }; rwlock_try_write(RWLock& l, int millis = 0) : _l(l) { if( !l.lock_try(millis) ) throw exception(); } ~rwlock_try_write() { _l.unlock(); } private: RWLock& _l; }; class rwlock_shared : boost::noncopyable { public: rwlock_shared(RWLock& rwlock) : _r(rwlock) {_r.lock_shared(); } ~rwlock_shared() { _r.unlock_shared(); } private: RWLock& _r; }; /* scoped lock for RWLock */ class rwlock : boost::noncopyable { public: /** * @param write acquire write lock if true sharable if false * @param lowPriority if > 0, will try to get the lock non-greedily for that many ms */ rwlock( const RWLock& lock , bool write, /* bool alreadyHaveLock = false , */int lowPriorityWaitMS = 0 ) : _lock( (RWLock&)lock ) , _write( write ) { { if ( _write ) { if ( ! lowPriorityWaitMS && lock.lowPriorityWaitMS() ) lowPriorityWaitMS = lock.lowPriorityWaitMS(); if ( lowPriorityWaitMS ) { bool got = false; for ( int i=0; i<lowPriorityWaitMS; i++ ) { if ( _lock.lock_try(0) ) { got = true; break; } int sleep = 1; if ( i > ( lowPriorityWaitMS / 20 ) ) sleep = 10; sleepmillis(sleep); i += ( sleep - 1 ); } if ( ! got ) { log() << "couldn't get lazy rwlock" << endl; _lock.lock(); } } else { _lock.lock(); } } else { _lock.lock_shared(); } } } ~rwlock() { if ( _write ) _lock.unlock(); else _lock.unlock_shared(); } private: RWLock& _lock; const bool _write; }; /** recursive on shared locks is ok for this implementation */ class RWLockRecursive : boost::noncopyable { ThreadLocalValue<int> _state; RWLock _lk; friend class Exclusive; public: /** @param lpwaitms lazy wait */ RWLockRecursive(const char *name, int lpwaitms) : _lk(name, lpwaitms) { } void assertExclusivelyLocked() { dassert( _state.get() < 0 ); } // RWLockRecursive::Exclusive scoped lock class Exclusive : boost::noncopyable { RWLockRecursive& _r; rwlock *_scopedLock; public: Exclusive(RWLockRecursive& r) : _r(r), _scopedLock(0) { int s = _r._state.get(); dassert( s <= 0 ); if( s == 0 ) _scopedLock = new rwlock(_r._lk, true); _r._state.set(s-1); } ~Exclusive() { int s = _r._state.get(); DEV wassert( s < 0 ); // wassert: don't throw from destructors _r._state.set(s+1); delete _scopedLock; } }; // RWLockRecursive::Shared scoped lock class Shared : boost::noncopyable { RWLockRecursive& _r; bool _alreadyExclusive; public: Shared(RWLockRecursive& r) : _r(r) { int s = _r._state.get(); _alreadyExclusive = s < 0; if( !_alreadyExclusive ) { dassert( s >= 0 ); // -1 would mean exclusive if( s == 0 ) _r._lk.lock_shared(); _r._state.set(s+1); } } ~Shared() { if( _alreadyExclusive ) { DEV wassert( _r._state.get() < 0 ); } else { int s = _r._state.get() - 1; if( s == 0 ) _r._lk.unlock_shared(); _r._state.set(s); DEV wassert( s >= 0 ); } } }; }; }
{ "content_hash": "e2b6ebc38c5257968899788f20b37ed6", "timestamp": "", "source": "github", "line_count": 382, "max_line_length": 117, "avg_line_length": 30.426701570680628, "alnum_prop": 0.46777940290802716, "repo_name": "RyokoAkizuki/freshcity", "id": "ed5bda07519af95faa79ac53734def97b9230f07", "size": "12300", "binary": false, "copies": "3", "ref": "refs/heads/solo", "path": "freshcity.dependency.mongoclient/util/concurrency/rwlock.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "539964" }, { "name": "C++", "bytes": "4058877" }, { "name": "Objective-C", "bytes": "94320" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Class scoped_connection</title> <link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.79.1"> <link rel="home" href="../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset"> <link rel="up" href="../../signals/reference.html#header.boost.signals.connection_hpp" title="Header &lt;boost/signals/connection.hpp&gt;"> <link rel="prev" href="connection.html" title="Class connection"> <link rel="next" href="../visit_each.html" title="Function template visit_each"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../boost.png"></td> <td align="center"><a href="../../../../index.html">Home</a></td> <td align="center"><a href="../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="connection.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../signals/reference.html#header.boost.signals.connection_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../visit_each.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="refentry"> <a name="boost.signals.scoped_connection"></a><div class="titlepage"></div> <div class="refnamediv"> <h2><span class="refentrytitle">Class scoped_connection</span></h2> <p>boost::signals::scoped_connection &#8212; Limits a signal-slot connection lifetime to a particular scope.</p> </div> <h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2> <div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: &lt;<a class="link" href="../../signals/reference.html#header.boost.signals.connection_hpp" title="Header &lt;boost/signals/connection.hpp&gt;">boost/signals/connection.hpp</a>&gt; </span> <span class="keyword">class</span> <a class="link" href="scoped_connection.html" title="Class scoped_connection">scoped_connection</a> <span class="special">:</span> <span class="keyword">private</span> noncopyable <span class="comment">// Exposition only</span> <span class="special">{</span> <span class="keyword">public</span><span class="special">:</span> <span class="comment">// <a class="link" href="scoped_connection.html#boost.signals.scoped_connectionconstruct-copy-destruct">construct/copy/destruct</a></span> <a class="link" href="scoped_connection.html#idp945092656-bb"><span class="identifier">scoped_connection</span></a><span class="special">(</span><span class="keyword">const</span> <a class="link" href="connection.html" title="Class connection">connection</a><span class="special">&amp;</span><span class="special">)</span><span class="special">;</span> <a class="link" href="scoped_connection.html#idp945097200-bb"><span class="special">~</span><span class="identifier">scoped_connection</span></a><span class="special">(</span><span class="special">)</span><span class="special">;</span> <span class="comment">// <a class="link" href="scoped_connection.html#idp945099424-bb">connection management</a></span> <span class="keyword">void</span> <a class="link" href="scoped_connection.html#idp945099984-bb"><span class="identifier">disconnect</span></a><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span> <span class="keyword">bool</span> <a class="link" href="scoped_connection.html#idp945104848-bb"><span class="identifier">connected</span></a><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span> <span class="special">}</span><span class="special">;</span></pre></div> <div class="refsect1"> <a name="idp608868112"></a><h2>Description</h2> <div class="refsect2"> <a name="idp608868528"></a><h3> <a name="boost.signals.scoped_connectionconstruct-copy-destruct"></a><code class="computeroutput">scoped_connection</code> public construct/copy/destruct</h3> <div class="orderedlist"><ol class="orderedlist" type="1"> <li class="listitem"> <pre class="literallayout"><a name="idp945092656-bb"></a><span class="identifier">scoped_connection</span><span class="special">(</span><span class="keyword">const</span> <a class="link" href="connection.html" title="Class connection">connection</a><span class="special">&amp;</span> other<span class="special">)</span><span class="special">;</span></pre> <div class="variablelist"><table border="0" class="variablelist compact"> <colgroup> <col align="left" valign="top"> <col> </colgroup> <tbody> <tr> <td><p><span class="term">Effects:</span></p></td> <td><p><code class="computeroutput">this</code> references the connection referenced by <code class="computeroutput">other</code>.</p></td> </tr> <tr> <td><p><span class="term">Throws:</span></p></td> <td><p>Will not throw.</p></td> </tr> </tbody> </table></div> </li> <li class="listitem"> <pre class="literallayout"><a name="idp945097200-bb"></a><span class="special">~</span><span class="identifier">scoped_connection</span><span class="special">(</span><span class="special">)</span><span class="special">;</span></pre> <div class="variablelist"><table border="0" class="variablelist compact"> <colgroup> <col align="left" valign="top"> <col> </colgroup> <tbody><tr> <td><p><span class="term">Effects:</span></p></td> <td><p>If <code class="computeroutput">this-&gt;<a class="link" href="scoped_connection.html#idp945104848-bb">connected</a>()</code>, disconnects the signal-slot connection.</p></td> </tr></tbody> </table></div> </li> </ol></div> </div> <div class="refsect2"> <a name="idp608887232"></a><h3> <a name="idp945099424-bb"></a><code class="computeroutput">scoped_connection</code> connection management</h3> <div class="orderedlist"><ol class="orderedlist" type="1"> <li class="listitem"> <pre class="literallayout"><span class="keyword">void</span> <a name="idp945099984-bb"></a><span class="identifier">disconnect</span><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre> <div class="variablelist"><table border="0" class="variablelist compact"> <colgroup> <col align="left" valign="top"> <col> </colgroup> <tbody> <tr> <td><p><span class="term">Effects:</span></p></td> <td><p>If <code class="computeroutput">this-&gt;<a class="link" href="scoped_connection.html#idp945104848-bb">connected</a>()</code>, disconnects the signal and slot referenced by this; otherwise, this operation is a no-op.</p></td> </tr> <tr> <td><p><span class="term">Postconditions:</span></p></td> <td><p><code class="computeroutput">!this-&gt;<a class="link" href="scoped_connection.html#idp945104848-bb">connected</a>()</code>.</p></td> </tr> </tbody> </table></div> </li> <li class="listitem"> <pre class="literallayout"><span class="keyword">bool</span> <a name="idp945104848-bb"></a><span class="identifier">connected</span><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre> <div class="variablelist"><table border="0" class="variablelist compact"> <colgroup> <col align="left" valign="top"> <col> </colgroup> <tbody> <tr> <td><p><span class="term">Returns:</span></p></td> <td><p><code class="computeroutput">true</code> if this references a non-NULL connection that is still active (connected), and <code class="computeroutput">false</code> otherwise.</p></td> </tr> <tr> <td><p><span class="term">Throws:</span></p></td> <td><p>Will not throw.</p></td> </tr> </tbody> </table></div> </li> </ol></div> </div> </div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2001-2004 Douglas Gregor<p>Use, modification and distribution is subject to the Boost Software License, Version 1.0. (See accompanying file <code class="filename">LICENSE_1_0.txt</code> or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)</p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="connection.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../signals/reference.html#header.boost.signals.connection_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../visit_each.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
{ "content_hash": "cb104e3f80c9f9f2ef0cc954cd631949", "timestamp": "", "source": "github", "line_count": 157, "max_line_length": 457, "avg_line_length": 61.00636942675159, "alnum_prop": 0.6745667153894341, "repo_name": "keichan100yen/ode-ext", "id": "8c1606abcc36462c8250e2ea2d68e45e78febe55", "size": "9578", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "boost/doc/html/boost/signals/scoped_connection.html", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "309067" }, { "name": "Batchfile", "bytes": "37875" }, { "name": "C", "bytes": "2967570" }, { "name": "C#", "bytes": "40804" }, { "name": "C++", "bytes": "189322982" }, { "name": "CMake", "bytes": "119251" }, { "name": "CSS", "bytes": "456744" }, { "name": "Cuda", "bytes": "52444" }, { "name": "DIGITAL Command Language", "bytes": "6246" }, { "name": "Fortran", "bytes": "1856" }, { "name": "Groff", "bytes": "5189" }, { "name": "HTML", "bytes": "181460055" }, { "name": "IDL", "bytes": "28" }, { "name": "JavaScript", "bytes": "419776" }, { "name": "Lex", "bytes": "1231" }, { "name": "M4", "bytes": "29689" }, { "name": "Makefile", "bytes": "1088024" }, { "name": "Max", "bytes": "36857" }, { "name": "Objective-C", "bytes": "11406" }, { "name": "Objective-C++", "bytes": "630" }, { "name": "PHP", "bytes": "68641" }, { "name": "Perl", "bytes": "36491" }, { "name": "Perl6", "bytes": "2053" }, { "name": "Python", "bytes": "1612978" }, { "name": "QML", "bytes": "593" }, { "name": "QMake", "bytes": "16692" }, { "name": "Rebol", "bytes": "354" }, { "name": "Ruby", "bytes": "5532" }, { "name": "Shell", "bytes": "354720" }, { "name": "Tcl", "bytes": "1172" }, { "name": "TeX", "bytes": "32117" }, { "name": "XSLT", "bytes": "553585" }, { "name": "Yacc", "bytes": "19623" } ], "symlink_target": "" }
/* $NetBSD: unicode.h,v 1.4 2010/02/25 11:20:09 drochner Exp $ */ /* * some private character definitions for stuff not found * in the Unicode database, for communication between * terminal emulation and graphics driver */ #define _e000U 0xe000 /* mirrored question mark? */ #define _e006U 0xe006 /* N/L control */ #define _e007U 0xe007 /* bracelefttp */ #define _e008U 0xe008 /* braceleftbt */ #define _e009U 0xe009 /* bracerighttp */ #define _e00aU 0xe00a /* bracerighrbt */ #define _e00bU 0xe00b /* braceleftmid */ #define _e00cU 0xe00c /* bracerightmid */ #define _e00dU 0xe00d /* inverted angle? */ #define _e00eU 0xe00e /* angle? */ #define _e00fU 0xe00f /* mirrored not sign? */
{ "content_hash": "2729028b3d89bcd92905c5f955f36134", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 65, "avg_line_length": 36.421052631578945, "alnum_prop": 0.7023121387283237, "repo_name": "execunix/vinos", "id": "333f2523586be31c87e8d9c6ace7f149fd249ea7", "size": "692", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "sys/dev/wscons/unicode.h", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package com.team.mybatis.common; import com.team.mybatis.common.base.BaseDeleteMapper; import com.team.mybatis.common.base.BaseInsertMapper; import com.team.mybatis.common.base.BaseSelectMapper; import com.team.mybatis.common.base.BaseUpdateMapper; /** * 通用Mapper接口,其他接口继承该接口即可 * <p/> * <p>这是一个例子,自己扩展时可以参考</p> * <p/> * <p>项目地址 : <a href="https://github.com/abel533/Mapper" target="_blank">https://github.com/abel533/Mapper</a></p> * * @param <T> 不能为空 * @author liuzh */ public interface BaseMapper<T> extends BaseSelectMapper<T>, BaseInsertMapper<T>, BaseUpdateMapper<T>, BaseDeleteMapper<T> { }
{ "content_hash": "324ba82fda21713f4fd3e53552587a83", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 114, "avg_line_length": 24.692307692307693, "alnum_prop": 0.7009345794392523, "repo_name": "20gg/weChat", "id": "21652a71b94b758df5b5b617c925ab6598ca3aa3", "size": "1874", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/team/mybatis/common/BaseMapper.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1098" }, { "name": "HTML", "bytes": "8655" }, { "name": "Java", "bytes": "361945" } ], "symlink_target": "" }
Personal web site with info related to me career. Created with **hugo**
{ "content_hash": "d067f5eabe4739f552f69b6d7d4bf6c7", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 49, "avg_line_length": 24.333333333333332, "alnum_prop": 0.7534246575342466, "repo_name": "juanitodread/juanitodread.github.io", "id": "7df301b24dfa8d4875bcf51c0968cd6c09e530c7", "size": "99", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "302253" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in Khumbu Himal 6(3): 312 (1977) #### Original name Lecidea malesiana Hertel ### Remarks null
{ "content_hash": "a083fd923808dc1c603612efcc7f39da", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 29, "avg_line_length": 11.846153846153847, "alnum_prop": 0.7012987012987013, "repo_name": "mdoering/backbone", "id": "f140c5339a6a436f69e41d2ea572fc79be3b3fb1", "size": "202", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Lecanoromycetes/Lecanorales/Lecideaceae/Lecidea/Lecidea malesiana/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
[![GoDoc](https://godoc.org/github.com/e-XpertSolutions/go-diff/diff?status.png)](http://godoc.org/github.com/e-XpertSolutions/go-diff/diff) [![License](https://img.shields.io/badge/license-BSD%203--Clause-yellow.svg?style=flat)](https://github.com/e-XpertSolutions/go-diff/blob/master/LICENSE) [![Travis](https://travis-ci.org/e-XpertSolutions/go-diff.svg?branch=master)](https://travis-ci.org/e-XpertSolutions/go-diff) go-diff is a Go package that aims to provide functions to calculate differences between two Go structures. The result is presented as a generic map containing old and new values. See the [documentation](http://godoc.org/github.com/e-XpertSolutions/go-diff/diff) for more details and examples. ## Installation ``` go get -u github.com/e-XpertSolutions/go-diff/diff ``` ## Usage ```go package main import ( "fmt" "log" "github.com/e-XpertSolutions/go-diff/diff" ) type StructA struct { SomeInt int B *StructB } type StructB struct { SomeVal string SomeFloat float32 } func main() { a1 := StructA{ SomeInt: 42, B: &StructB{ SomeVal: "Foo", SomeFloat: 123.456 }, } a2 := StructA{ SomeInt: 24, B: &StructB{ SomeVal: "Bar", SomeFloat: 123.4567 }, } d, err := diff.Compute(a1, a2) if err != nil { log.Fatal(err) } fmt.Println(string(d.PrettyJSON())) // Output: // { // "B": { // "SomeVal": { // "old_value": "Foo", // "new_value": "Bar", // "type": "MOD" // } // }, // "SomeInt": { // "old_value": 42, // "new_value": 24, // "type": "MOD" // } // } } ``` ## Diff calculation * **Basic types (int, float, bool and string):** Basic types are directly compared using language defined operators (== and !=). * **Pointers:** The values pointed are compared, not the addresses. * **Structures:** Structures are compared recursively. If they do not contain any exported fields, the structures are compared as strings. * **Slices and arrays:** Slices and arrays are compared row by row. * **Maps:** Maps are not yet supported. ## TODO - [ ] Add support for map types - [ ] Add support for complex numbers - [ ] Allow the user to override comparisons through an interface - [ ] Add an option to limit the depth of the comparisons - [ ] Better support for slices/arrays comparison - [ ] More tests and benchmarks - [ ] Add XML serialization ## Contributing We appreciate any form of contribution (feature request, bug report, pull request, ...). We have no special requirements for Pull Request, just follow the standard [GitHub way](https://help.github.com/articles/using-pull-requests/). ## License The sources are release under a BSD 3-Clause License. The full terms of that license can be found in `LICENSE` file of this repository.
{ "content_hash": "972bdeba5e3c3f79f8908b34b6c912db", "timestamp": "", "source": "github", "line_count": 109, "max_line_length": 153, "avg_line_length": 25.65137614678899, "alnum_prop": 0.6720314735336195, "repo_name": "e-XpertSolutions/go-diff", "id": "8dba722e29549aab9efdc88e883212add384d193", "size": "2807", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Go", "bytes": "13364" }, { "name": "Makefile", "bytes": "319" } ], "symlink_target": "" }
<!DOCTYPE html> <HTML lang="en"> <HEAD> <meta content="text/html;charset=utf-8" http-equiv="Content-Type"> <meta content="utf-8" http-equiv="encoding"> <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css"> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> <link href="http://netdna.bootstrapcdn.com/bootswatch/2.3.0/spacelab/bootstrap.min.css" rel="stylesheet"> </HEAD> <BODY> <div class="container-fluid"> <div class="row well"> <h3>Header Content and Stuff</h3> </div> <div class="row"> <div class="col-md-10 col-md-offset-1"> <h1>Farm To School: Measuring Our Impact</h1> <h2>Wireframes</h2> </div> </div> </div> </BODY> </HTML>
{ "content_hash": "b837888c7b8f29ca1f6020ed90d70c29", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 114, "avg_line_length": 37.205882352941174, "alnum_prop": 0.566798418972332, "repo_name": "Ecotrust/F2S-MOI", "id": "1a09d84ac976d9d06d83b2d8b0a7278bb4326a53", "size": "1265", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "wireframes/index.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "68031" }, { "name": "HTML", "bytes": "35254" }, { "name": "JavaScript", "bytes": "127637" }, { "name": "Python", "bytes": "296456" }, { "name": "Shell", "bytes": "514" } ], "symlink_target": "" }
package com.example.android.background.sync; import android.content.Context; import com.example.android.background.utilities.NotificationUtils; import com.example.android.background.utilities.PreferenceUtilities; public class ReminderTasks { public static final String ACTION_INCREMENT_WATER_COUNT = "increment-water-count"; public static final String ACTION_DISMISS_NOTIFICATION = "dismiss-notification"; public static final String ACTION_CHARGING_REMINDER = "charging-reminder"; public static void executeTask(Context context, String action) { if (ACTION_INCREMENT_WATER_COUNT.equals(action)) { incrementWaterCount(context); } else if (ACTION_DISMISS_NOTIFICATION.equals(action)) { NotificationUtils.clearAllNotifications(context); } else if (ACTION_CHARGING_REMINDER.equals(action)) { issueChargingReminder(context); } } private static void incrementWaterCount(Context context) { PreferenceUtilities.incrementWaterCount(context); NotificationUtils.clearAllNotifications(context); } // TODO (2) Create an additional task for issuing a charging reminder notification. (DONE) // This should be done in a similar way to how you have an action for incrementingWaterCount // and dismissing notifications. This task should both create a notification AND // increment the charging reminder count (hint: there is a method for this in PreferenceUtilities) // When finished, you should be able to call executeTask with the correct parameters to execute // this task. Don't forget to add the code to executeTask which actually calls your new task! private static void issueChargingReminder(Context context) { PreferenceUtilities.incrementChargingReminderCount(context); NotificationUtils.remindUserBecauseCharging(context); } }
{ "content_hash": "5f35bb9d9877985c42dbc448ceaab8a7", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 102, "avg_line_length": 47.15, "alnum_prop": 0.749204665959703, "repo_name": "darurats/ud851-Exercises", "id": "b2912aaaf2259f9a40f052d428efce4157e29d57", "size": "2505", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Lesson10-Hydration-Reminder/T10.04-Solution-PeriodicSyncWithJobDispatcher/app/src/main/java/com/example/android/background/sync/ReminderTasks.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2307154" } ], "symlink_target": "" }
// // MBMenuView.m // MorningBee // // Created by Pay on 13/3/8. // Copyright (c) 2013年 Octalord. All rights reserved. // #import "OLImperialMenuView.h" #import <OLCategoryHelper/UIView+ViewFrameGeometry.h> #import "UIButton+Passtouch.h" #pragma mark - Define Area #define kSCREEN_WIDTH self.superview.bounds.size.width #define kSCREEN_HEIGHT self.superview.bounds.size.height #define kEXPAND_THRESHOLD_CENTER_HORIZONTAL ((kSCREEN_WIDTH - _openSize + _closeSize) * 0.5f) #define kEXPAND_THRESHOLD_CENTER_VERTICAL ((kSCREEN_HEIGHT - _openSize + _closeSize) * 0.5f) #define kEXPAND_THRESHOLD_FACTOR 0.4f #define kANIMATION_INTERVAL 0.2f #define kBACKGROUND_ALPHA 0.85f #define kMAX_MOVEMENT abs(self.openPosition - self.closePosition) #pragma mark - Class Extension @interface OLImperialMenuView () typedef NS_ENUM (NSUInteger, MoveAgreement) { MoveAgreementUnknow, MoveAgreementCanMove, MoveAgreementDeny, MoveAgreementNoResponsed }; @property (nonatomic, assign) CGFloat closePosition; // X or Y @property (nonatomic, assign) CGFloat openPosition; // X or Y @property (nonatomic, assign) MoveAgreement moveAgreement; @end @implementation OLImperialMenuView #pragma mark - Memory management - (void) dealloc { [_backgroundView removeFromSuperview]; } #pragma mark - setter/getter - (UIView *) backgroundView { if (_backgroundView == nil) { UIColor *backColor = [[UIColor alloc] initWithWhite:(58.0f / 255.0f) alpha:kBACKGROUND_ALPHA]; _backgroundView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; _backgroundView.backgroundColor = backColor; _backgroundView.alpha = 0.0f; } if (_backgroundView.superview == nil) { if (self.disableBackgroundView == NO) { [self.superview insertSubview:_backgroundView belowSubview:self]; } } return _backgroundView; } - (void) setManuBackgroudView:(UIImageView *)manuBackgroudView { if (_manuBackgroudView == manuBackgroudView) { return; } if (_manuBackgroudView != nil) { [_manuBackgroudView removeFromSuperview]; } _manuBackgroudView = manuBackgroudView; [self insertSubview:_manuBackgroudView atIndex:0]; } - (void) setClosePositionValue { if (self.direction == ImperialDirecitonLeft) { _closePosition = self.left; } else if (self.direction == ImperialDirecitonRight) { _closePosition = self.left; } else if (self.direction == ImperialDirecitonTop) { _closePosition = self.top; } else if (self.direction == ImperialDirecitonBottom) { _closePosition = self.top; } } - (CGFloat) openPosition { if (_openPosition != CGFLOAT_MAX) { return _openPosition; } if (self.direction == ImperialDirecitonLeft) { _openPosition = kSCREEN_WIDTH - _openSize - self.size.width; } else if (self.direction == ImperialDirecitonRight) { _openPosition = _openSize; } else if (self.direction == ImperialDirecitonTop) { _openPosition = kSCREEN_HEIGHT - _openSize - self.size.height; } else if (self.direction == ImperialDirecitonBottom) { _openPosition = _openSize; } return _openPosition; } #pragma mark - View lifecycle - (id) initWithFrame:(CGRect)frame closeSize:(CGFloat)closeSize openSize:(CGFloat)openSize direction:(ImperialDireciton)direction { self = [super initWithFrame:frame]; if (self != nil) { _closePosition = CGFLOAT_MAX; _openPosition = CGFLOAT_MAX; _direction = direction; _open = NO; _closeSize = closeSize; _openSize = openSize; [self setClosePositionValue]; [self setupGesture]; _disableBackgroundView = NO; // self.backgroundColor = [UIColor redColor]; // for debug } return self; } #pragma mark - gesture - (void) setupGesture { UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapGestureRecognizer:)]; tapGestureRecognizer.delegate = self; tapGestureRecognizer.numberOfTapsRequired = 1; [self addGestureRecognizer:tapGestureRecognizer]; } /* UIGestureRecognizerDelegate */ - (BOOL) gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch { if ([touch.view isKindOfClass:[UIControl class]]) { return NO; } return YES; } /* action: tapGestureRecognizer */ - (void) singleTapGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer { NSLog(@"%@", NSStringFromSelector(_cmd)); [self setImperialMenuOpen:(_open == NO) animated:YES]; } #pragma mark - touchs - (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesBegan:touches withEvent:event]; UITouch *t = [touches anyObject]; CGPoint touchPosition = [t locationInView:self.superview]; NSLog(@"%@, %@", NSStringFromSelector(_cmd), NSStringFromCGPoint(touchPosition)); [self decorateView]; [self backgroundView]; // fire to alloc backgroundView if don't exist. 否則在第一次,往左邊拉動時候,會閃黑 (在動畫 驅動第一次) } - (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesMoved:touches withEvent:event]; if ([self invokeImperialMenuViewWillMove] == NO) { // user wouldn't like to move it. } else { UITouch *t = [touches anyObject]; CGPoint touchLocation = [t locationInView:self.superview]; CGPoint previousTouchLocation = [t previousLocationInView:self.superview]; NSLog(@"%@, %@ -> %@", NSStringFromSelector(_cmd), NSStringFromCGPoint(previousTouchLocation), NSStringFromCGPoint(touchLocation)); if (self.direction == ImperialDirecitonLeft || self.direction == ImperialDirecitonRight) { CGFloat delta = touchLocation.x - previousTouchLocation.x; CGFloat left = self.left + delta; left = [self boundLayoutHorizontal:left]; if (left != self.left) { self.left = left; self.backgroundView.alpha = kBACKGROUND_ALPHA * abs(left - self.closePosition) / kMAX_MOVEMENT; _moving = YES; } else { _moving = NO; } } else { // ImperialDirecitonTop or ImperialDirecitonBottom CGFloat delta = touchLocation.y - previousTouchLocation.y; CGFloat top = self.top + delta; top = [self boundLayoutVertical:top]; if (top != self.top) { self.top = top; self.backgroundView.alpha = kBACKGROUND_ALPHA * abs(top - self.closePosition) / kMAX_MOVEMENT; _moving = YES; } else { _moving = NO; } } } } - (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesEnded:touches withEvent:event]; UITouch *t = [touches anyObject]; CGPoint touchPosition = [t locationInView:self.superview]; NSLog(@"%@, %@", NSStringFromSelector(_cmd), NSStringFromCGPoint(touchPosition)); [self gotoRightPosition]; _moving = NO; if (_moveAgreement != MoveAgreementNoResponsed) { _moveAgreement = MoveAgreementUnknow; } } - (CGFloat) thresholdLeft { static CGFloat threshold = MAXFLOAT; if (threshold == MAXFLOAT) { threshold = kEXPAND_THRESHOLD_CENTER_HORIZONTAL * (1.0f - kEXPAND_THRESHOLD_FACTOR); } return threshold; } - (CGFloat) thresholdRight { static CGFloat threshold = MAXFLOAT; if (threshold == MAXFLOAT) { threshold = kEXPAND_THRESHOLD_CENTER_HORIZONTAL * (1.0f + kEXPAND_THRESHOLD_FACTOR); } return threshold; } - (CGFloat) thresholdTop { static CGFloat threshold = MAXFLOAT; if (threshold == MAXFLOAT) { threshold = kEXPAND_THRESHOLD_CENTER_VERTICAL * (1.0f - kEXPAND_THRESHOLD_FACTOR); } return threshold; } - (CGFloat) thresholdBottom { static CGFloat threshold = MAXFLOAT; if (threshold == MAXFLOAT) { threshold = kEXPAND_THRESHOLD_CENTER_VERTICAL * (1.0f + kEXPAND_THRESHOLD_FACTOR); } return threshold; } - (void) gotoRightPosition { if (self.isOpen == YES) { NSLog(@"%@, %f, %f", NSStringFromSelector(_cmd), self.right, self.thresholdRight); if ((self.direction == ImperialDirecitonLeft && self.right > self.thresholdRight) || (self.direction == ImperialDirecitonRight && self.left < self.thresholdLeft) || (self.direction == ImperialDirecitonTop && self.bottom > self.thresholdBottom) || (self.direction == ImperialDirecitonBottom && self.top < self.thresholdTop)) { // restore to open [self runOpenAnimationAndDidOpen:NO]; } else { // close process [self runCloseProcessWithAnimated:YES]; } } else { NSLog(@"%@, %f, %f", NSStringFromSelector(_cmd), self.right, self.thresholdLeft); if ((self.direction == ImperialDirecitonLeft && self.right < self.thresholdLeft) || (self.direction == ImperialDirecitonRight && self.left > self.thresholdRight) || (self.direction == ImperialDirecitonTop && self.bottom < self.thresholdTop) || (self.direction == ImperialDirecitonBottom && self.top > self.thresholdBottom)) { // restore to close [self runCloseAnimationAndDidClose:NO]; } else { // open process [self runOpenProcessWithAnimated:YES]; } } } - (void) runCloseProcessWithAnimated:(BOOL)animated { BOOL continued = [self invokeImperialMenuViewWillClose]; if (continued == NO) { // user cancel it if (animated == YES) { // restore to close [self runOpenAnimationAndDidOpen:NO]; } } else { _open = NO; if (animated == YES) { [self runCloseAnimationAndDidClose:YES]; } else { [self setClosedViewAttribute]; [self invokeImperialMenuViewDidClose]; } } } - (void) runOpenProcessWithAnimated:(BOOL)animated { BOOL continued = [self invokeImperialMenuViewWillOpen]; if (continued == NO) { // user cancel it if (animated == YES) { // restore to close [self runCloseAnimationAndDidClose:NO]; } } else { _open = YES; if (animated == YES) { [self runOpenAnimationAndDidOpen:YES]; } else { [self setOpenViewAttribute]; [self invokeImperialMenuViewDidOpen]; } } } - (void) runOpenAnimationAndDidOpen:(BOOL)didOpen { [UIView animateWithDuration:kANIMATION_INTERVAL delay:0.0f options:UIViewAnimationOptionCurveEaseIn animations:^{ [self setOpenViewAttribute]; } completion:^(BOOL finished) { if (didOpen == YES) { [self invokeImperialMenuViewDidOpen]; } else { [self invokeImperialMenuViewDidMove]; } }]; } - (void) runCloseAnimationAndDidClose:(BOOL)didClose { [UIView animateWithDuration:kANIMATION_INTERVAL delay:0.0f options:UIViewAnimationOptionCurveEaseIn animations:^{ [self setClosedViewAttribute]; } completion:^(BOOL finished) { if (didClose == YES) { [self invokeImperialMenuViewDidClose]; } else { [self invokeImperialMenuViewDidMove]; } }]; } - (void) setOpenViewAttribute { if (self.direction == ImperialDirecitonLeft || self.direction == ImperialDirecitonRight) { self.left = self.openPosition; } else { self.top = self.openPosition; } self.backgroundView.alpha = kBACKGROUND_ALPHA; } - (void) setClosedViewAttribute { if (self.direction == ImperialDirecitonLeft || self.direction == ImperialDirecitonRight) { self.left = self.closePosition; } else { self.top = self.closePosition; } self.backgroundView.alpha = 0.0f; } /* 讓view.right 不會超過 closeSize and openSize */ - (CGFloat) boundLayoutHorizontal:(CGFloat)left { if (self.direction == ImperialDirecitonLeft) { if (left >= self.openPosition) { left = self.openPosition; } else if (left <= self.closePosition) { // right <= _closeSize left = self.closePosition; } } else if (self.direction == ImperialDirecitonRight) { if (left <= self.openPosition) { left = self.openPosition; } else if (left >= self.closePosition) { left = self.closePosition; } } return left; } - (CGFloat) boundLayoutVertical:(CGFloat)top { if (self.direction == ImperialDirecitonTop) { if (top >= self.openPosition) { top = self.openPosition; } else if (top <= self.closePosition) { top = self.closePosition; } } else if (self.direction == ImperialDirecitonBottom) { if (top <= self.openPosition) { top = self.openPosition; } else if (top >= self.closePosition) { top = self.closePosition; } } return top; } #pragma mark - public method - (void) setImperialMenuOpen:(BOOL)open animated:(BOOL)animated { NSLog(@"%@", NSStringFromSelector(_cmd)); if (self.open == open) { // no change, do nothing. } else { if (open == YES) { [self decorateView]; // maybe, still not decorate view at present [self runOpenProcessWithAnimated:animated]; } else { [self runCloseProcessWithAnimated:animated]; } } } #pragma mark - MBImperialMenuViewDelegate - (void) decorateView { if (_decoView != nil) { return; // aleray decorate } SEL decorateViewSel = @selector(imperialMenuView:decorateView:); BOOL isResponsed = [_delegate respondsToSelector:decorateViewSel]; if (isResponsed == NO) { // there is no deco view. } else { // preare decoView for delegate _decoView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.frame.size.width, self.frame.size.height)]; self.decoView = [self.delegate imperialMenuView:self decorateView:_decoView]; [self addSubview:_decoView]; } } - (BOOL) invokeImperialMenuViewWillMove { BOOL continued = YES; if (_moveAgreement == MoveAgreementNoResponsed) { continued = YES; } else if (_moveAgreement == MoveAgreementDeny) { continued = NO; } else if (_moveAgreement == MoveAgreementCanMove) { continued = YES; } else if (_moveAgreement == MoveAgreementUnknow) { NSLog(@"%@", NSStringFromSelector(_cmd)); SEL sel = @selector(imperialMenuViewWillMove:open:); if ([_delegate respondsToSelector:sel] == NO) { continued = YES; _moveAgreement = MoveAgreementNoResponsed; } else { continued = [self.delegate imperialMenuViewWillMove:self open:_open]; if (continued == NO) { // user cancel it NSLog(@"%@ [delegate(%@) %@] return NO", NSStringFromSelector(_cmd) , NSStringFromClass([self.delegate class]) , NSStringFromSelector(sel)); _moveAgreement = MoveAgreementDeny; } else { _moveAgreement = MoveAgreementCanMove; } } } else { NSLog(@"%@, _moveAgreement(%d) is undefined.", NSStringFromSelector(_cmd), _moveAgreement); continued = NO; } return continued; } - (void) invokeImperialMenuViewDidMove { static NSObject *checked = nil; static BOOL isResponsed = NO; if (checked == nil) { checked = [[NSObject alloc] init]; // do once SEL sel = @selector(imperialMenuViewDidMove:open:); isResponsed = [_delegate respondsToSelector:sel]; } if (isResponsed == NO) { // do not implement imperialMenuViewDidOpen } else { [self.delegate imperialMenuViewDidMove:self open:_open]; } } - (BOOL) invokeImperialMenuViewWillOpen { SEL sel = @selector(imperialMenuViewWillOpen:); static NSObject *checked = nil; static BOOL isResponsed = NO; if (checked == nil) { checked = [[NSObject alloc] init]; // do once isResponsed = [_delegate respondsToSelector:sel]; } BOOL continued = YES; if (isResponsed == NO) { // do not implement imperialMenuViewWillOpen continued = YES; } else { continued = [self.delegate imperialMenuViewWillOpen:self]; if (continued == NO) { // user cancel it NSLog(@"%@ [delegate(%@) %@] return NO", NSStringFromSelector(_cmd) , NSStringFromClass([self.delegate class]) , NSStringFromSelector(sel)); } } return continued; } - (void) invokeImperialMenuViewDidOpen { static NSObject *checked = nil; static BOOL isResponsed = NO; if (checked == nil) { checked = [[NSObject alloc] init]; // do once SEL sel = @selector(imperialMenuViewDidOpen:); isResponsed = [_delegate respondsToSelector:sel]; } if (isResponsed == NO) { // do not implement imperialMenuViewDidOpen } else { [self.delegate imperialMenuViewDidOpen:self]; } } - (BOOL) invokeImperialMenuViewWillClose { SEL sel = @selector(imperialMenuViewWillClose:); static NSObject *checked = nil; static BOOL isResponsed = NO; if (checked == nil) { checked = [[NSObject alloc] init]; // do once isResponsed = [_delegate respondsToSelector:sel]; } BOOL continued = YES; if (isResponsed == NO) { // do not implement imperialMenuViewWillClose, but still continued process continued = YES; } else { continued = [self.delegate imperialMenuViewWillClose:self]; if (continued == NO) { // user cancel it NSLog(@"%@ [delegate(%@) %@] return NO", NSStringFromSelector(_cmd) , NSStringFromClass([self.delegate class]) , NSStringFromSelector(sel)); } } return continued; } - (void) invokeImperialMenuViewDidClose { static NSObject *checked = nil; static BOOL isResponsed = NO; if (checked == nil) { checked = [[NSObject alloc] init]; // do once SEL sel = @selector(imperialMenuViewDidClose:); isResponsed = [_delegate respondsToSelector:sel]; } if (isResponsed == NO) { // do not implement imperialMenuViewDidClose } else { [self.delegate imperialMenuViewDidClose:self]; } } #pragma mark - draw /* -(void)drawRect:(CGRect)rect { [super drawRect:rect]; CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor); CGContextSetLineWidth(context, 3.0f); CGContextMoveToPoint(context, kEXPAND_THRESHOLD_CENTER, 0); CGContextAddLineToPoint(context, kEXPAND_THRESHOLD_CENTER, [UIScreen mainScreen].bounds.size.height); CGContextStrokePath(context); CGContextMoveToPoint(context, kEXPAND_THRESHOLD_CENTER * (1.0f + kEXPAND_THRESHOLD_FACTOR), 0); CGContextAddLineToPoint(context, kEXPAND_THRESHOLD_CENTER * (1.0f + kEXPAND_THRESHOLD_FACTOR), [UIScreen mainScreen].bounds.size.height); CGContextStrokePath(context); CGContextMoveToPoint(context, kEXPAND_THRESHOLD_CENTER * (1.0f - kEXPAND_THRESHOLD_FACTOR), 0); CGContextAddLineToPoint(context, kEXPAND_THRESHOLD_CENTER * (1.0f + kEXPAND_THRESHOLD_FACTOR), [UIScreen mainScreen].bounds.size.height); CGContextStrokePath(context); } */ @end
{ "content_hash": "cc22927695fcebc27527805e3b7031dc", "timestamp": "", "source": "github", "line_count": 868, "max_line_length": 150, "avg_line_length": 23.369815668202765, "alnum_prop": 0.6159230958836579, "repo_name": "payliu/OLImperialMenu", "id": "ea1bb392e411ac328f9ae1c454362944c24827b1", "size": "20351", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/OLImperialMenuView.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "34095" }, { "name": "Ruby", "bytes": "236" } ], "symlink_target": "" }
package org.wrml.core.runtime.system; import org.wrml.core.model.schema.Constrainable; import org.wrml.core.model.schema.Constraint; import org.wrml.core.runtime.Context; import org.wrml.core.runtime.RuntimeObject; /** * The ability to add Constraints to Schemas can have serve a few different * functions. * * 1. SchemaConstraints can be added to generate parameterized types. For * example a SchemaConstraint named "T" could be used in a WRML schema like * "Container" to generate "Container<T extends Model>" in Java. The use of * one or more named SchemaConstraints at the Schema level has the effect of * creating named schema "slots" whenever these types are referenced in WRML * "builder" GUI tools. * * @return */ public final class ConstraintPrototype<T extends Constrainable<T>> extends RuntimeObject { private final Constraint<T> _Constraint; public ConstraintPrototype(Context context, Constraint<T> constraint) { super(context); _Constraint = constraint; } public Constraint<T> getConstraint() { return _Constraint; } }
{ "content_hash": "705f109381944ae1f8666161985ed6d3", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 90, "avg_line_length": 29.72972972972973, "alnum_prop": 0.7363636363636363, "repo_name": "scandeezy/wrml-prototype", "id": "7c8d436cc6970ccf9a5b38631842aee9fb986dc0", "size": "1716", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/org/wrml/core/runtime/system/ConstraintPrototype.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "507652" }, { "name": "PHP", "bytes": "35833" } ], "symlink_target": "" }
//! \file fbxnurbssurface.h #ifndef _FBXSDK_SCENE_GEOMETRY_NURBS_SURFACE_H_ #define _FBXSDK_SCENE_GEOMETRY_NURBS_SURFACE_H_ #include <fbxsdk/fbxsdk_def.h> #include <fbxsdk/scene/geometry/fbxgeometry.h> #include <fbxsdk/fbxsdk_nsbegin.h> class FbxNode; /** A NURBS surface is a type of parametric geometry. A NURBS surface is defined by the order, form, knot vector and control points in the U and V directions. For more information on the meaning of the form, knot vector and control points, see the documentation for the FbxNurbsCurve. The same concepts for NURBS curves apply to NURBS surfaces. NURBS surfaces simply have two dimensions (U and V). * \nosubgrouping */ class FBXSDK_DLL FbxNurbsSurface : public FbxGeometry { FBXSDK_OBJECT_DECLARE(FbxNurbsSurface, FbxGeometry); public: //! Returns the FbxNodeAttribute::EType::eNurbsSurface node attribute type. virtual FbxNodeAttribute::EType GetAttributeType() const; //! Resets the NURBS surface its default values. void Reset(); /** * \name NURBS surface Properties */ //@{ /** Sets the surface mode. * \param pMode Surface mode identifier (see class FbxGeometry). */ void SetSurfaceMode(FbxGeometry::ESurfaceMode pMode); /** Returns the surface mode. * \return The surface mode identifier that is currently set. */ inline ESurfaceMode GetSurfaceMode() const { return mSurfaceMode; } /** \enum EType NURBS types. * - \e ePeriodic * - \e eClosed * - \e eOpen */ enum EType { ePeriodic, eClosed, eOpen }; /** Allocates memory space for an array of control points as well as knot * and multiplicity vectors. * \param pUCount Number of U-dimension control points. * \param pUType U-dimension NURBS type. * \param pVCount Number of V-dimension control points. * \param pVType V-dimension NURBS type. * \remarks Always call this function after FbxNurbsSurface::SetOrder(). */ void InitControlPoints(int pUCount, EType pUType, int pVCount, EType pVType); /** Returns the number of U-dimension control points. * \return Number of U-dimension control points. */ inline int GetUCount() const { return mUCount; } /** Returns the number of V-dimension control points. * \return Number of V-dimension control points. */ inline int GetVCount() const { return mVCount; } /** Returns the U-dimension NURBS type. * \return NURBS type identifier. */ inline EType GetNurbsUType() const { return mUType; } /** Returns the V-dimension NURBS type. * \return NURBS type identifier. */ inline EType GetNurbsVType() const { return mVType; } /** Returns the number of elements in the U-dimension knot vector. See FbxNurbsCurve for more information. * \return The number of elements in the U-dimension knot vector. */ int GetUKnotCount() const; /** Returns the U-dimension knot vector. * \return Pointer to the U-dimension knot vector. */ double* GetUKnotVector() const; /** Returns the number of elements in the V-dimension knot vector. See FbxNurbsCurve for more information. * \return The number of elements in the V-dimension knot vector. */ int GetVKnotCount() const; /** Returns the V-dimension knot vector. * \return Pointer to the V-dimension knot vector. */ double* GetVKnotVector() const; /** Sets the order of the NURBS surface. * \param pUOrder NURBS order in U dimension. * \param pVOrder NURBS order in V dimension. */ void SetOrder(FbxUInt pUOrder, FbxUInt pVOrder); /** Returns the NURBS order in U dimension. * \return NURBS order in U dimension. */ inline int GetUOrder() const { return mUOrder; } /** Returns the NURBS order in V dimension. * \return NURBS order in V dimension. */ inline int GetVOrder() const { return mVOrder; } /** Sets the NURBS step. * The step value is the number of divisions between adjacent control points. * \param pUStep Steps in U dimension. * \param pVStep Steps in V dimension. */ void SetStep(int pUStep, int pVStep); /** Returns the number of divisions between adjacent control points in U dimension. * \return Steps in U dimension. */ inline int GetUStep() const { return mUStep; } /** Returns the number of divisions between adjacent control points in V dimension. * \return Steps in V dimension. */ inline int GetVStep() const { return mVStep; } /** Calculates the number of surface spans in the U dimension. * See FbxNurbsCurve::GetSpanCount() for more information. * \return The number of spans in the U dimension if the surface has been initialized. * If the spans have not been initialized, returns -1. */ int GetUSpanCount() const; /** Calculates the number of surface spans in the V dimension. * See FbxNurbsCurve::GetSpanCount() for more information. * \return The number of spans in the V dimension if the surface has been initialized. * If the spans have not been initialized, returns -1. */ int GetVSpanCount() const; //@} /** * \name NURBS surface Export Flags */ //@{ /** Sets the flag that induces UV flipping at export. * \param pFlag If \c true, UV flipping occurs. */ void SetApplyFlipUV(bool pFlag); /** Returns the flag that induces UV flipping at export. * \return The current state of the UV flip flag. */ bool GetApplyFlipUV() const; /** Sets the flag that induces link flipping at export. * \param pFlag If \c true, the links control points indices are flipped. */ void SetApplyFlipLinks(bool pFlag); /** Returns the flag that induces link flipping at export. * \return The current state of the link flip flag. */ bool GetApplyFlipLinks() const; /** Returns flip flags state. * \return \c True if we need to flip either the UV or the links. */ bool GetApplyFlip() const { return GetApplyFlipUV() || GetApplyFlipLinks(); } /** Adds a curve to the NURBS surface. * Adds a 2D, parametric space curve to this surface * \param pCurve The curve to be added to the surface. */ void AddCurveOnSurface(FbxNode* pCurve); /** Retrieves a curve from this surface * \param pIndex Index of the curve to retrieve (Valid range is 0 to GetCurveOnSurfaceCount() - 1). * \return The curve at the specified index, or returns NULL if pIndex is out of range. */ FbxNode* GetCurveOnSurface(int pIndex); /** Retrieves a curve from this surface * \param pIndex Index of the curve to retrieve (Valid range is 0 to GetCurveOnSurfaceCount() - 1). * \return The curve at the specified index, or returns NULL if pIndex is out of range. */ const FbxNode* GetCurveOnSurface(int pIndex) const; /** Returns the number of curves on this surface. * \return The number of curves on this surface. */ int GetCurveOnSurfaceCount() const; /** Removes a curve from this surface. * \param pCurve The curve to be removed. * \return \c True if the curve is removed successfully, if unsuccessful, returns \c false. */ bool RemoveCurveOnSurface(FbxNode* pCurve); //@} /** Checks if the surface has all rational control points. * \return \c True if rational, \c false otherwise */ bool IsRational() const; /***************************************************************************************************************************** ** WARNING! Anything beyond these lines is for internal use, may not be documented and is subject to change without notice! ** *****************************************************************************************************************************/ #ifndef DOXYGEN_SHOULD_SKIP_THIS // Error identifiers, these are only used internally. enum EErrorCode { eNurbsTypeUnknown, eWrongNumberOfControlPoint, eWeightTooSmall, eUKnotVectorError, eVKnotVectorError, eErrorCount }; virtual FbxObject& Copy(const FbxObject& pObject); virtual void InitControlPoints(int pCount) { ParentClass::InitControlPoints(pCount); } void SetFlipNormals(bool pFlipNormals); bool GetFlipNormals() const; bool IsValidKnots() const; protected: virtual void Construct(const FbxObject* pFrom); virtual void Destruct(bool pRecursive); FbxUInt mUOrder, mVOrder; int mUCount, mVCount; int mUStep, mVStep; EType mUType, mVType; double* mUKnotVector; double* mVKnotVector; ESurfaceMode mSurfaceMode; bool mApplyFlipUV; bool mApplyFlipLinks; bool mFlipNormals; friend class FbxGeometryConverter; #endif /* !DOXYGEN_SHOULD_SKIP_THIS *****************************************************************************************/ }; #include <fbxsdk/fbxsdk_nsend.h> #endif /* _FBXSDK_SCENE_GEOMETRY_NURBS_SURFACE_H_ */
{ "content_hash": "adc9193d45d8c30bc6af4245d0d43ed5", "timestamp": "", "source": "github", "line_count": 306, "max_line_length": 126, "avg_line_length": 32.052287581699346, "alnum_prop": 0.6044045676998369, "repo_name": "dava/dava.engine", "id": "da46b17dcd4a97d97dd6f67f2e21904f76231cd7", "size": "10277", "binary": false, "copies": "1", "ref": "refs/heads/development", "path": "Modules/FBX/Thirdparty/include/fbxsdk/scene/geometry/fbxnurbssurface.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Ada", "bytes": "89080" }, { "name": "Assembly", "bytes": "166572" }, { "name": "Batchfile", "bytes": "18562" }, { "name": "C", "bytes": "61621347" }, { "name": "C#", "bytes": "574524" }, { "name": "C++", "bytes": "50229645" }, { "name": "CLIPS", "bytes": "5291" }, { "name": "CMake", "bytes": "11439187" }, { "name": "CSS", "bytes": "32773" }, { "name": "Cuda", "bytes": "37073" }, { "name": "DIGITAL Command Language", "bytes": "27303" }, { "name": "Emacs Lisp", "bytes": "44259" }, { "name": "Fortran", "bytes": "8835" }, { "name": "GLSL", "bytes": "3726" }, { "name": "Go", "bytes": "1235" }, { "name": "HTML", "bytes": "8621333" }, { "name": "Java", "bytes": "232072" }, { "name": "JavaScript", "bytes": "2560" }, { "name": "Lua", "bytes": "43080" }, { "name": "M4", "bytes": "165145" }, { "name": "Makefile", "bytes": "1349214" }, { "name": "Mathematica", "bytes": "4633" }, { "name": "Module Management System", "bytes": "15224" }, { "name": "Objective-C", "bytes": "1909821" }, { "name": "Objective-C++", "bytes": "498191" }, { "name": "Pascal", "bytes": "99390" }, { "name": "Perl", "bytes": "396608" }, { "name": "Python", "bytes": "782784" }, { "name": "QML", "bytes": "43105" }, { "name": "QMake", "bytes": "156" }, { "name": "Roff", "bytes": "71083" }, { "name": "Ruby", "bytes": "22742" }, { "name": "SAS", "bytes": "16030" }, { "name": "Shell", "bytes": "2482394" }, { "name": "Slash", "bytes": "117430" }, { "name": "Smalltalk", "bytes": "5908" }, { "name": "TeX", "bytes": "428489" }, { "name": "Vim script", "bytes": "133255" }, { "name": "Visual Basic", "bytes": "54056" }, { "name": "WebAssembly", "bytes": "13987" } ], "symlink_target": "" }
<?php //Created By dipanjan @5/1/2015 namespace Bundle\ParentBundle\Controller; use Symfony\Component\HttpFoundation\Session; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Bundle\AdminBundle\Entity\KidsKulaUsers; use Bundle\KidskulaBundle\Form\forgotpassType; use Symfony\Component\HttpFoundation\Request; use FOS\UserBundle\Event\GetResponseUserEvent; use FOS\UserBundle\FOSUserEvents; use FOS\UserBundle\Event\FilterUserResponseEvent; use FOS\UserBundle\Event\FormEvent; use Symfony\Component\Security\Core\SecurityContext; use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken; use Symfony\Component\Security\Http\Event\InteractiveLoginEvent; use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\RedirectResponse; class ParentLoginController extends Controller { public function indexAction(Request $request) { $securityContext = $this->container->get('security.context'); if ($securityContext->isGranted('IS_AUTHENTICATED_FULLY')) { return new RedirectResponse($this->generateUrl('parent-home')); } $request = $this->getRequest(); $session = $request->getSession(); $error = ""; if ($request->getMethod() == 'POST'): $username = $request->get('_username'); $password = $request->get('_password'); $rememberme = $request->get('_rememberme'); //echo $username.'--'.$password; exit; if (empty($username) || empty($password)) { $this->get('session')->getFlashBag()->set('error', 'Email or password field is empty.'); return $this->redirect($this->generateUrl('fornt_login')); } $userManager = $this->container->get('fos_user.user_manager'); $user = $userManager->findUserByUsername($username); $em = $this->getDoctrine()->getManager(); $enabled = ($user) ? $user->isEnabled() : 0; $referer = $this->getRequest()->headers->get('referer'); if (!$user || !$enabled) { //Check If ajax Request if ($request->isXmlHttpRequest()) { $response = new JsonResponse(array('success' => 0, 'error' => 'Wrong credentials. Please try again.')); } else { $this->get('session')->getFlashBag()->set('error', 'Wrong credentials. Please try again.'); //$url = $this->generateUrl('public_user_login'); $response = new RedirectResponse($referer); //return $this->redirect($this->generateUrl('public_user_login')); } return $response; }else { //Encode Password $encoder = $this->container->get('security.encoder_factory')->getEncoder($user); //get encoder for hashing pwd later $Passwordresult = $encoder->encodePassword($password, $user->getSalt()); $canlogin=''; //CHECK IF Admin or student $roles = $user->getRoles(); $role = array("ROLE_ADMIN","ROLE_STUDENT"); // $canlogin = in_array($role, $roles); if(count(array_intersect($role, $roles)) > 0){ $canlogin =1; } if ($Passwordresult == $user->getPassword() && !$canlogin) { $token = new UsernamePasswordToken($user, $Passwordresult, 'admin_area', $user->getRoles()); //echo $user->getId();exit; $this->get('security.context')->setToken($token); $this->get('session')->set('_security_main', serialize($token)); $event = new InteractiveLoginEvent($request, $token); $this->get("event_dispatcher")->dispatch("security.authentication", $event); // echo 'parent-home';exit; return new RedirectResponse($this->generateUrl('parent-home')); } } // get the login error if there is one endif; return $this->render('BundleParentBundle:Registration:login.html.twig'); } public function forgotpasswordAction(Request $request) { if ($request->getMethod() == "POST") { $em = $this->getDoctrine()->getManager(); $username = $request->get('_username'); $q = $em ->createQueryBuilder() ->select('u') ->from('BundleAdminBundle:KidsKulaUsers', 'u') ->where('u.username = :username OR u.email = :email and u.roles LIKE :roles') ->setParameter('username', $username) ->setParameter('email', $username) ->setParameter('roles', '%ROLE_STUDENT%') ->getQuery(); if (!$q->getResult()) { //Check If ajax Request if ($request->isXmlHttpRequest()) { $response = new JsonResponse(array('success' => 0, 'error' => 'User does not exist. Please try again.')); } else { $this->get('session')->getFlashBag()->set('error', 'User does not exist. Please try again.'); $url = $this->generateUrl('fornt_forgotpassword'); $response = new RedirectResponse($url); //return $this->redirect($this->generateUrl('public_user_login')); } return $response; } elseif (count ($q->getResult())>1) { $this->get('session')->getFlashBag()->set('error', 'There are multiple instance on this Email. Please try again with your username.'); $url = $this->generateUrl('fornt_forgotpassword'); $response = new RedirectResponse($url); } else { $user = $q->getSingleResult(); $tokenGenerator = $this->container->get('fos_user.util.token_generator'); $user->setConfirmationToken($tokenGenerator->generateToken()); $currentTime = new \DateTime(); $user->setPasswordRequestedAt($currentTime); $em->flush(); /********** mail part start *********/ $emailcode = 'forgot_password'; $em = $this->getDoctrine()->getManager(); $emailEntity = $em->getRepository('BundleAdminBundle:KidsKulaEmailNotification')->findOneBy(array('emailCode' => $emailcode)); $mailsendEmail=$user->getEmail(); $userName=$user->getUsername(); if ($emailEntity) { $id = $user->getConfirmationToken(); $username = $username; $to_mail = $mailsendEmail; $from_mail = ''; /*$info = 'please click <a href="'.$this->generateUrl('fornt_forgot_passowrd_link', array('token' => $id)).'">here</a>.';*/ $info = 'please click <a href="http://'.$_SERVER['HTTP_HOST'].$this->generateUrl('fornt_forgot_passowrd_link', array('token' => $id)).'">here</a>.'; $subject = $emailEntity->getSubject(); $email_content = $emailEntity->getContent(); $email_content = str_replace("###username###", $userName, $email_content); $email_content = str_replace("###Info###", $info, $email_content); //echo $email_content;exit; $cc =''; $template = ''; $this->container->get('Bundle_mailservice')->sendMail(array( 'text' => $email_content, 'subject' => $subject), $from_mail, $to_mail,'confirmation'); } /********** mail part end *********/ if ($request->isXmlHttpRequest()) { $response = new JsonResponse(array('success' => 1, 'error' => 'Password reset url has been sent to your email.')); } else { $this->get('session')->getFlashBag()->set('success', 'Password reset url has been sent to your email.'); $url = $this->generateUrl('fornt_forgotpassword'); $response = new RedirectResponse($url); //return $this->redirect($this->generateUrl('public_user_login')); } return $response; } } return $this->render( 'BundleKidskulaBundle:Registration:forgotpassword.html.twig' ); } public function resetAction(Request $request, $token) { $em = $this->getDoctrine()->getManager(); /** @var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */ $formFactory = $this->container->get('fos_user.resetting.form.factory'); /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */ $userManager = $this->container->get('fos_user.user_manager'); /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */ $dispatcher = $this->container->get('event_dispatcher'); $user = $userManager->findUserByConfirmationToken($token); $form = $this->createForm(new forgotpassType($em), $user, array( 'action' => $this->generateUrl('fornt_forgot_passowrd_link',array('token' => $token)), 'method' => 'POST', )); if ($request->getMethod() == "POST") { $form->handleRequest($request); //\Doctrine\Common\Util\Debug::dump($form);exit; if ($form->isValid()) { $password=$form->get('password')->getData(); //Encode Password $encoder = $this->container->get('security.encoder_factory')->getEncoder($user); //get encoder for hashing pwd later $Passwordresult = $encoder->encodePassword($password, $user->getSalt()); $user->setPassword($Passwordresult); $userManager->updateUser($user); $this->get('session')->getFlashBag()->set('success', 'Password changed Successfully'); $url = $this->container->get('router')->generate('home'); return new RedirectResponse($url); } } return $this->render( 'BundleKidskulaBundle:Registration:reset-password.html.twig',array( 'token' => $token, 'form'=>$form->createView())); } public function logoutAction() { $this->get('security.context')->setToken(null); $this->get('request')->getSession()->invalidate(); $this->get('session')->getFlashBag()->set('success', 'You are successfully logged out !!!'); return $this->redirect($this->generateUrl('kidskula_bundle_parents')); } }
{ "content_hash": "0037340c02833e38d1115dbe166bc24e", "timestamp": "", "source": "github", "line_count": 278, "max_line_length": 156, "avg_line_length": 39.910071942446045, "alnum_prop": 0.5434880576836413, "repo_name": "dip712204123/kidskula", "id": "579583a33f997a34e1506e57ec82aea169cc7362", "size": "11095", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Bundle/ParentBundle/Controller/ParentLoginController.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2471794" }, { "name": "CoffeeScript", "bytes": "114344" }, { "name": "Go", "bytes": "13426" }, { "name": "JavaScript", "bytes": "8279059" }, { "name": "Makefile", "bytes": "896" }, { "name": "PHP", "bytes": "3086141" }, { "name": "Python", "bytes": "10346" }, { "name": "Ruby", "bytes": "1722" }, { "name": "Shell", "bytes": "4074" } ], "symlink_target": "" }
Experimenting with WebGL for fun. Based on [talk](https://www.youtube.com/embed/H4c8t6myAWU/) by Nick Desaulniers.
{ "content_hash": "35061c833cfb3fdace1084e9dee68884", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 80, "avg_line_length": 38.666666666666664, "alnum_prop": 0.7758620689655172, "repo_name": "tparonen/webgl-experiment", "id": "94c56d9aee6a08e848e0031ce00954644470840b", "size": "136", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "GLSL", "bytes": "1940" }, { "name": "HTML", "bytes": "849" }, { "name": "JavaScript", "bytes": "11285" } ], "symlink_target": "" }
import types from './types' import traverseSchema from './traverse-schema' function assignValue (result, segments, value) { const firstSegment = segments[0] if (segments.length === 1) { result[firstSegment] = value return } let nextResult = result[firstSegment] if (!nextResult) { nextResult = result[firstSegment] = {} } assignValue(nextResult, segments.slice(1), value) } function throwIfStrict (options) { if (options.strict) { throw new Error('Incorrect type') } } function processPrimitiveType (raw, type, options) { let value = raw switch (type) { case types.string: { if (typeof raw !== 'string') { throwIfStrict(options) value = `${raw}` } break } case types.boolean: { if (typeof raw !== 'boolean') { throwIfStrict(options) value = raw === 'true' } break } case types.integer: { if (typeof raw !== 'number') { throwIfStrict(options) value = parseInt(raw, 10) if (isNaN(value)) { throw new Error('Couldn\'t parse integer') } } break } case types.float: { if (typeof setting !== 'number') { throwIfStrict(options) value = parseFloat(raw) } if (isNaN(value)) { throw new Error('Couldn\'t parse float') } break } case types.date: { if (!(raw instanceof Date)) { throwIfStrict(options) value = new Date(raw) } if (value.toString() === 'Invalid Date') { throw new Error('Couldn\'t parse date') } break } case types.array: { if (!(raw instanceof Array)) { throwIfStrict(options) value = raw } break } default: { value = raw } } return value } function buildConfig (schema, getValue, options) { let result = {} traverseSchema(schema, (descriptor, segments) => { let raw = getValue(segments, descriptor) let value = raw if (descriptor.type instanceof Array) { if (!(raw instanceof Array)) { throwIfStrict(options) value = [raw] } let underlyingType = descriptor.type[0] value = value.map(x => processPrimitiveType(x, underlyingType, options)) } else { value = processPrimitiveType(value, descriptor.type, options) } assignValue(result, segments, value) }) return result } export default buildConfig
{ "content_hash": "121ec31631a30e44ded85de47018f0bb", "timestamp": "", "source": "github", "line_count": 127, "max_line_length": 78, "avg_line_length": 19.519685039370078, "alnum_prop": 0.5748285599031868, "repo_name": "Deadarius/confeta", "id": "bada9c7ab14e09fd1608aecbebbab9d0c93db957", "size": "2479", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/confeta/src/build-config.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "16167" } ], "symlink_target": "" }
""" WSGI config for micro_finance project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "micro_finance.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application()
{ "content_hash": "adfb869f03a140cdc93d10e5c8a86845", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 78, "avg_line_length": 28.642857142857142, "alnum_prop": 0.7755610972568578, "repo_name": "swethanaretla/micro_finance", "id": "b8eecdbda0bb4e0b8aab1069764c615e6600f94a", "size": "401", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "micro_finance/wsgi.py", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
import unittest import azure.mgmt.imagebuilder from devtools_testutils import AzureMgmtTestCase, ResourceGroupPreparer AZURE_LOCATION = 'eastus' IMAGE_TEMPLATE_NAME = "MyImageTemplate" IMAGE_NAME = 'MyImage' RUN_OUTPUT_NAME = 'image_it_pir_1' # make sure to create user identity with this doc before running live test: https://github.com/danielsollondon/azvmimagebuilder/tree/master/quickquickstarts/0_Creating_a_Custom_Windows_Managed_Image#step-2--permissions-create-user-idenity-and-role-for-aib IDENTITY_NAME = 'aibIdentity1588309486' class MgmtImageBuilderClientTest(AzureMgmtTestCase): def setUp(self): super(MgmtImageBuilderClientTest, self).setUp() self.mgmt_client = self.create_mgmt_client( azure.mgmt.imagebuilder.ImageBuilderClient ) @unittest.skip('hard to test') @ResourceGroupPreparer(location=AZURE_LOCATION) def test_imagebuilder(self, resource_group): # Create an Image Template with a user assigned identity configured[put] BODY = { "location": "eastus", "tags": { "imagetemplate_tag1": "IT_T1", "imagetemplate_tag2": "IT_T2" }, "identity": { "type": "UserAssigned", "user_assigned_identities": { "/subscriptions/{}/resourceGroups/{}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{}".format(self.settings.SUBSCRIPTION_ID, resource_group.name, IDENTITY_NAME): {}} }, "properties": { "source": { "type": "ManagedImage", "image_id": "/subscriptions/" + self.settings.SUBSCRIPTION_ID + "/resourceGroups/" + resource_group.name + "/providers/Microsoft.Compute/images/" + IMAGE_NAME + "" }, "customize": [ { "type": "Shell", "name": "Shell Customizer Example", "script_uri": "https://raw.githubusercontent.com/Azure/azure-sdk-for-python/619a017566f2bdb2d9a85afd1fe2018bed822cc8/sdk/compute/azure-mgmt-imagebuilder/tests/script.sh" } ], "distribute": [ { "type": "ManagedImage", "location": "eastus", "run_output_name": "image_it_pir_1", "image_id": "/subscriptions/" + self.settings.SUBSCRIPTION_ID + "/resourceGroups/" + resource_group.name + "/providers/Microsoft.Compute/images/" + IMAGE_NAME + "", "artifact_tags": { "tag_name": "value" } } ], "vm_profile": { "vm_size": "Standard_D2s_v3" } } } result = self.mgmt_client.virtual_machine_image_templates.create_or_update(BODY, resource_group.name, IMAGE_TEMPLATE_NAME) result = result.result() # Retrieve an Image Template.[get] result = self.mgmt_client.virtual_machine_image_templates.get(resource_group.name, IMAGE_TEMPLATE_NAME) # List images by resource group[get] result = self.mgmt_client.virtual_machine_image_templates.list_by_resource_group(resource_group.name) # List images by subscription.[get] result = self.mgmt_client.virtual_machine_image_templates.list() # Create image(s) from existing imageTemplate.[post] result = self.mgmt_client.virtual_machine_image_templates.run(resource_group.name, IMAGE_TEMPLATE_NAME) result = result.result() # Retrieve single runOutput[get] result = self.mgmt_client.virtual_machine_image_templates.get_run_output(resource_group.name, IMAGE_TEMPLATE_NAME, RUN_OUTPUT_NAME) # Retrieve a list of all outputs created by the last run of an Image Template[get] result = self.mgmt_client.virtual_machine_image_templates.list_run_outputs(resource_group.name, IMAGE_TEMPLATE_NAME) # Remove identities for an Image Template.[patch] BODY = { "identity": { "type": "None" } } #result = self.mgmt_client.virtual_machine_image_templates.update(resource_group.name, IMAGE_TEMPLATE_NAME, BODY) #result = result.result() # Update the tags for an Image Template.[patch] BODY = { "tags": { "new-tag": "new-value" } } #result = self.mgmt_client.virtual_machine_image_templates.update(resource_group.name, IMAGE_TEMPLATE_NAME, BODY) #result = result.result() # Delete an Image Template.[delete] result = self.mgmt_client.virtual_machine_image_templates.delete(resource_group.name, IMAGE_TEMPLATE_NAME) result = result.result() #------------------------------------------------------------------------------ if __name__ == '__main__': unittest.main()
{ "content_hash": "ab0901648fa591e3be3c5408e483bebe", "timestamp": "", "source": "github", "line_count": 112, "max_line_length": 255, "avg_line_length": 43.026785714285715, "alnum_prop": 0.6111226395517743, "repo_name": "Azure/azure-sdk-for-python", "id": "31956a53dc197a3b089c15a84163bc8e2308df89", "size": "5336", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "sdk/compute/azure-mgmt-imagebuilder/tests/disable_test_cli_mgmt_imagebuilder.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1224" }, { "name": "Bicep", "bytes": "24196" }, { "name": "CSS", "bytes": "6089" }, { "name": "Dockerfile", "bytes": "4892" }, { "name": "HTML", "bytes": "12058" }, { "name": "JavaScript", "bytes": "8137" }, { "name": "Jinja", "bytes": "10377" }, { "name": "Jupyter Notebook", "bytes": "272022" }, { "name": "PowerShell", "bytes": "518535" }, { "name": "Python", "bytes": "715484989" }, { "name": "Shell", "bytes": "3631" } ], "symlink_target": "" }