text
stringlengths
2
1.04M
meta
dict
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "ed8b09d97d5cdf2654a2c3513b633d8f", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "20858bf78ab88d7502e6b8bbd84c2ff82390a9a2", "size": "174", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Ericales/Primulaceae/Ardisia/Ardisia rhomboidea/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title> Oracle &mdash; SQLAlchemy 1.0 Documentation </title> <!-- begin iterate through SQLA + sphinx environment css_files --> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <link rel="stylesheet" href="../_static/changelog.css" type="text/css" /> <link rel="stylesheet" href="../_static/sphinx_paramlinks.css" type="text/css" /> <link rel="stylesheet" href="../_static/docs.css" type="text/css" /> <!-- end iterate through SQLA + sphinx environment css_files --> <!-- begin layout.mako headers --> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="copyright" title="Copyright" href="../copyright.html" /> <link rel="top" title="SQLAlchemy 1.0 Documentation" href="../index.html" /> <link rel="up" title="Dialects" href="index.html" /> <link rel="next" title="PostgreSQL" href="postgresql.html" /> <link rel="prev" title="MySQL" href="mysql.html" /> <!-- end layout.mako headers --> </head> <body> <div id="docs-container"> <div id="docs-top-navigation-container" class="body-background"> <div id="docs-header"> <div id="docs-version-header"> Release: <span class="version-num">1.0.6</span> | Release Date: June 25, 2015 </div> <h1>SQLAlchemy 1.0 Documentation</h1> </div> </div> <div id="docs-body-container"> <div id="fixed-sidebar" class="withsidebar"> <div id="docs-sidebar-popout"> <h3><a href="../index.html">SQLAlchemy 1.0 Documentation</a></h3> <p id="sidebar-topnav"> <a href="../contents.html">Contents</a> | <a href="../genindex.html">Index</a> </p> <div id="sidebar-search"> <form class="search" action="../search.html" method="get"> <input type="text" name="q" size="12" /> <input type="submit" value="Search" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div> <div id="docs-sidebar"> <h3> <a href="index.html" title="Dialects">Dialects</a> </h3> <ul> <li><span class="link-container first"><a class="reference external" href="firebird.html">Firebird</a></span></li> <li><span class="link-container first"><a class="reference external" href="mssql.html">Microsoft SQL Server</a></span></li> <li><span class="link-container first"><a class="reference external" href="mysql.html">MySQL</a></span></li> <li class="selected"><span class="link-container first"><strong>Oracle</strong><a class="paramlink headerlink reference internal" href="#">¶</a></span><ul> <li><span class="link-container first"><a class="reference external" href="#dialect-oracle">Support for the Oracle database.</a></span></li> <li><span class="link-container first"><a class="reference external" href="#connect-arguments">Connect Arguments</a></span></li> <li><span class="link-container first"><a class="reference external" href="#auto-increment-behavior">Auto Increment Behavior</a></span></li> <li><span class="link-container first"><a class="reference external" href="#identifier-casing">Identifier Casing</a></span></li> <li><span class="link-container first"><a class="reference external" href="#limit-offset-support">LIMIT/OFFSET Support</a></span></li> <li><span class="link-container first"><a class="reference external" href="#returning-support">RETURNING Support</a></span></li> <li><span class="link-container first"><a class="reference external" href="#on-update-cascade">ON UPDATE CASCADE</a></span></li> <li><span class="link-container first"><a class="reference external" href="#oracle-8-compatibility">Oracle 8 Compatibility</a></span></li> <li><span class="link-container first"><a class="reference external" href="#synonym-dblink-reflection">Synonym/DBLINK Reflection</a></span></li> <li><span class="link-container first"><a class="reference external" href="#datetime-compatibility">DateTime Compatibility</a></span></li> <li><span class="link-container first"><a class="reference external" href="#oracle-table-options">Oracle Table Options</a></span></li> <li><span class="link-container first"><a class="reference external" href="#oracle-specific-index-options">Oracle Specific Index Options</a></span><ul> <li><span class="link-container first"><a class="reference external" href="#bitmap-indexes">Bitmap Indexes</a></span></li> <li><span class="link-container first"><a class="reference external" href="#index-compression">Index compression</a></span></li> </ul> </li> <li><span class="link-container first"><a class="reference external" href="#oracle-data-types">Oracle Data Types</a></span></li> <li><span class="link-container first"><a class="reference external" href="#module-sqlalchemy.dialects.oracle.cx_oracle">cx_Oracle</a></span><ul> <li><span class="link-container first"><a class="reference external" href="#dialect-oracle-cx_oracle-url">DBAPI</a></span></li> <li><span class="link-container first"><a class="reference external" href="#dialect-oracle-cx_oracle-connect">Connecting</a></span></li> <li><span class="link-container first"><a class="reference external" href="#additional-connect-arguments">Additional Connect Arguments</a></span></li> <li><span class="link-container first"><a class="reference external" href="#unicode">Unicode</a></span></li> <li><span class="link-container first"><a class="reference external" href="#cx-oracle-returning">RETURNING Support</a></span></li> <li><span class="link-container first"><a class="reference external" href="#lob-objects">LOB Objects</a></span></li> <li><span class="link-container first"><a class="reference external" href="#two-phase-transaction-support">Two Phase Transaction Support</a></span></li> <li><span class="link-container first"><a class="reference external" href="#precision-numerics">Precision Numerics</a></span></li> </ul> </li> <li><span class="link-container first"><a class="reference external" href="#module-sqlalchemy.dialects.oracle.zxjdbc">zxjdbc</a></span><ul> <li><span class="link-container first"><a class="reference external" href="#dialect-oracle-zxjdbc-url">DBAPI</a></span></li> <li><span class="link-container first"><a class="reference external" href="#dialect-oracle-zxjdbc-connect">Connecting</a></span></li> </ul> </li> </ul> </li> <li><span class="link-container first"><a class="reference external" href="postgresql.html">PostgreSQL</a></span></li> <li><span class="link-container first"><a class="reference external" href="sqlite.html">SQLite</a></span></li> <li><span class="link-container first"><a class="reference external" href="sybase.html">Sybase</a></span></li> </ul> </div> </div> <div id="docs-body" class="withsidebar" > <div class="section" id="module-sqlalchemy.dialects.oracle.base"> <span id="oracle"></span><span id="oracle-toplevel"></span><h1>Oracle<a class="headerlink" href="#module-sqlalchemy.dialects.oracle.base" title="Permalink to this headline">¶</a></h1> <div class="section" id="dialect-oracle"> <p>Support for the Oracle database.</p> <h2>DBAPI Support<a class="headerlink" href="#dialect-oracle" title="Permalink to this headline">¶</a></h2> <p>The following dialect/DBAPI options are available. Please refer to individual DBAPI sections for connect information.<ul class="simple"> <li><a class="reference external" href="#module-sqlalchemy.dialects.oracle.cx_oracle">cx-Oracle</a></li> <li><a class="reference external" href="#module-sqlalchemy.dialects.oracle.zxjdbc">zxJDBC for Jython</a></li> </ul> </p> </div> <div class="section" id="connect-arguments"> <h2>Connect Arguments<a class="headerlink" href="#connect-arguments" title="Permalink to this headline">¶</a></h2> <p>The dialect supports several <a class="reference internal" href="../core/engines.html#sqlalchemy.create_engine" title="sqlalchemy.create_engine"><code class="xref py py-func docutils literal"><span class="pre">create_engine()</span></code></a> arguments which affect the behavior of the dialect regardless of driver in use.</p> <ul class="simple"> <li><code class="docutils literal"><span class="pre">use_ansi</span></code> - Use ANSI JOIN constructs (see the section on Oracle 8). Defaults to <code class="docutils literal"><span class="pre">True</span></code>. If <code class="docutils literal"><span class="pre">False</span></code>, Oracle-8 compatible constructs are used for joins.</li> <li><code class="docutils literal"><span class="pre">optimize_limits</span></code> - defaults to <code class="docutils literal"><span class="pre">False</span></code>. see the section on LIMIT/OFFSET.</li> <li><code class="docutils literal"><span class="pre">use_binds_for_limits</span></code> - defaults to <code class="docutils literal"><span class="pre">True</span></code>. see the section on LIMIT/OFFSET.</li> </ul> </div> <div class="section" id="auto-increment-behavior"> <h2>Auto Increment Behavior<a class="headerlink" href="#auto-increment-behavior" title="Permalink to this headline">¶</a></h2> <p>SQLAlchemy Table objects which include integer primary keys are usually assumed to have &#8220;autoincrementing&#8221; behavior, meaning they can generate their own primary key values upon INSERT. Since Oracle has no &#8220;autoincrement&#8221; feature, SQLAlchemy relies upon sequences to produce these values. With the Oracle dialect, <em>a sequence must always be explicitly specified to enable autoincrement</em>. This is divergent with the majority of documentation examples which assume the usage of an autoincrement-capable database. To specify sequences, use the sqlalchemy.schema.Sequence object which is passed to a Column construct:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">t</span> <span class="o">=</span> <span class="n">Table</span><span class="p">(</span><span class="s">&#39;mytable&#39;</span><span class="p">,</span> <span class="n">metadata</span><span class="p">,</span> <span class="n">Column</span><span class="p">(</span><span class="s">&#39;id&#39;</span><span class="p">,</span> <span class="n">Integer</span><span class="p">,</span> <span class="n">Sequence</span><span class="p">(</span><span class="s">&#39;id_seq&#39;</span><span class="p">),</span> <span class="n">primary_key</span><span class="o">=</span><span class="bp">True</span><span class="p">),</span> <span class="n">Column</span><span class="p">(</span><span class="o">...</span><span class="p">),</span> <span class="o">...</span> <span class="p">)</span></pre></div> </div> <p>This step is also required when using table reflection, i.e. autoload=True:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">t</span> <span class="o">=</span> <span class="n">Table</span><span class="p">(</span><span class="s">&#39;mytable&#39;</span><span class="p">,</span> <span class="n">metadata</span><span class="p">,</span> <span class="n">Column</span><span class="p">(</span><span class="s">&#39;id&#39;</span><span class="p">,</span> <span class="n">Integer</span><span class="p">,</span> <span class="n">Sequence</span><span class="p">(</span><span class="s">&#39;id_seq&#39;</span><span class="p">),</span> <span class="n">primary_key</span><span class="o">=</span><span class="bp">True</span><span class="p">),</span> <span class="n">autoload</span><span class="o">=</span><span class="bp">True</span> <span class="p">)</span></pre></div> </div> </div> <div class="section" id="identifier-casing"> <h2>Identifier Casing<a class="headerlink" href="#identifier-casing" title="Permalink to this headline">¶</a></h2> <p>In Oracle, the data dictionary represents all case insensitive identifier names using UPPERCASE text. SQLAlchemy on the other hand considers an all-lower case identifier name to be case insensitive. The Oracle dialect converts all case insensitive identifiers to and from those two formats during schema level communication, such as reflection of tables and indexes. Using an UPPERCASE name on the SQLAlchemy side indicates a case sensitive identifier, and SQLAlchemy will quote the name - this will cause mismatches against data dictionary data received from Oracle, so unless identifier names have been truly created as case sensitive (i.e. using quoted names), all lowercase names should be used on the SQLAlchemy side.</p> </div> <div class="section" id="limit-offset-support"> <h2>LIMIT/OFFSET Support<a class="headerlink" href="#limit-offset-support" title="Permalink to this headline">¶</a></h2> <p>Oracle has no support for the LIMIT or OFFSET keywords. SQLAlchemy uses a wrapped subquery approach in conjunction with ROWNUM. The exact methodology is taken from <a class="reference external" href="http://www.oracle.com/technology/oramag/oracle/06-sep/o56asktom.html">http://www.oracle.com/technology/oramag/oracle/06-sep/o56asktom.html</a> .</p> <p>There are two options which affect its behavior:</p> <ul class="simple"> <li>the &#8220;FIRST ROWS()&#8221; optimization keyword is not used by default. To enable the usage of this optimization directive, specify <code class="docutils literal"><span class="pre">optimize_limits=True</span></code> to <a class="reference internal" href="../core/engines.html#sqlalchemy.create_engine" title="sqlalchemy.create_engine"><code class="xref py py-func docutils literal"><span class="pre">create_engine()</span></code></a>.</li> <li>the values passed for the limit/offset are sent as bound parameters. Some users have observed that Oracle produces a poor query plan when the values are sent as binds and not rendered literally. To render the limit/offset values literally within the SQL statement, specify <code class="docutils literal"><span class="pre">use_binds_for_limits=False</span></code> to <a class="reference internal" href="../core/engines.html#sqlalchemy.create_engine" title="sqlalchemy.create_engine"><code class="xref py py-func docutils literal"><span class="pre">create_engine()</span></code></a>.</li> </ul> <p>Some users have reported better performance when the entirely different approach of a window query is used, i.e. ROW_NUMBER() OVER (ORDER BY), to provide LIMIT/OFFSET (note that the majority of users don&#8217;t observe this). To suit this case the method used for LIMIT/OFFSET can be replaced entirely. See the recipe at <a class="reference external" href="http://www.sqlalchemy.org/trac/wiki/UsageRecipes/WindowFunctionsByDefault">http://www.sqlalchemy.org/trac/wiki/UsageRecipes/WindowFunctionsByDefault</a> which installs a select compiler that overrides the generation of limit/offset with a window function.</p> </div> <div class="section" id="returning-support"> <span id="oracle-returning"></span><h2>RETURNING Support<a class="headerlink" href="#returning-support" title="Permalink to this headline">¶</a></h2> <p>The Oracle database supports a limited form of RETURNING, in order to retrieve result sets of matched rows from INSERT, UPDATE and DELETE statements. Oracle&#8217;s RETURNING..INTO syntax only supports one row being returned, as it relies upon OUT parameters in order to function. In addition, supported DBAPIs have further limitations (see <a class="reference internal" href="#cx-oracle-returning"><span>RETURNING Support</span></a>).</p> <p>SQLAlchemy&#8217;s &#8220;implicit returning&#8221; feature, which employs RETURNING within an INSERT and sometimes an UPDATE statement in order to fetch newly generated primary key values and other SQL defaults and expressions, is normally enabled on the Oracle backend. By default, &#8220;implicit returning&#8221; typically only fetches the value of a single <code class="docutils literal"><span class="pre">nextval(some_seq)</span></code> expression embedded into an INSERT in order to increment a sequence within an INSERT statement and get the value back at the same time. To disable this feature across the board, specify <code class="docutils literal"><span class="pre">implicit_returning=False</span></code> to <a class="reference internal" href="../core/engines.html#sqlalchemy.create_engine" title="sqlalchemy.create_engine"><code class="xref py py-func docutils literal"><span class="pre">create_engine()</span></code></a>:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">engine</span> <span class="o">=</span> <span class="n">create_engine</span><span class="p">(</span><span class="s">&quot;oracle://scott:tiger@dsn&quot;</span><span class="p">,</span> <span class="n">implicit_returning</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span></pre></div> </div> <p>Implicit returning can also be disabled on a table-by-table basis as a table option:</p> <div class="highlight-python"><div class="highlight"><pre><span class="c"># Core Table</span> <span class="n">my_table</span> <span class="o">=</span> <span class="n">Table</span><span class="p">(</span><span class="s">&quot;my_table&quot;</span><span class="p">,</span> <span class="n">metadata</span><span class="p">,</span> <span class="o">...</span><span class="p">,</span> <span class="n">implicit_returning</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span> <span class="c"># declarative</span> <span class="k">class</span> <span class="nc">MyClass</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span> <span class="n">__tablename__</span> <span class="o">=</span> <span class="s">&#39;my_table&#39;</span> <span class="n">__table_args__</span> <span class="o">=</span> <span class="p">{</span><span class="s">&quot;implicit_returning&quot;</span><span class="p">:</span> <span class="bp">False</span><span class="p">}</span></pre></div> </div> <div class="admonition seealso"> <p class="first admonition-title">See also</p> <p class="last"><a class="reference internal" href="#cx-oracle-returning"><span>RETURNING Support</span></a> - additional cx_oracle-specific restrictions on implicit returning.</p> </div> </div> <div class="section" id="on-update-cascade"> <h2>ON UPDATE CASCADE<a class="headerlink" href="#on-update-cascade" title="Permalink to this headline">¶</a></h2> <p>Oracle doesn&#8217;t have native ON UPDATE CASCADE functionality. A trigger based solution is available at <a class="reference external" href="http://asktom.oracle.com/tkyte/update_cascade/index.html">http://asktom.oracle.com/tkyte/update_cascade/index.html</a> .</p> <p>When using the SQLAlchemy ORM, the ORM has limited ability to manually issue cascading updates - specify ForeignKey objects using the &#8220;deferrable=True, initially=&#8217;deferred&#8217;&#8221; keyword arguments, and specify &#8220;passive_updates=False&#8221; on each relationship().</p> </div> <div class="section" id="oracle-8-compatibility"> <h2>Oracle 8 Compatibility<a class="headerlink" href="#oracle-8-compatibility" title="Permalink to this headline">¶</a></h2> <p>When Oracle 8 is detected, the dialect internally configures itself to the following behaviors:</p> <ul class="simple"> <li>the use_ansi flag is set to False. This has the effect of converting all JOIN phrases into the WHERE clause, and in the case of LEFT OUTER JOIN makes use of Oracle&#8217;s (+) operator.</li> <li>the NVARCHAR2 and NCLOB datatypes are no longer generated as DDL when the <a class="reference internal" href="../core/type_basics.html#sqlalchemy.types.Unicode" title="sqlalchemy.types.Unicode"><code class="xref py py-class docutils literal"><span class="pre">Unicode</span></code></a> is used - VARCHAR2 and CLOB are issued instead. This because these types don&#8217;t seem to work correctly on Oracle 8 even though they are available. The <a class="reference internal" href="../core/type_basics.html#sqlalchemy.types.NVARCHAR" title="sqlalchemy.types.NVARCHAR"><code class="xref py py-class docutils literal"><span class="pre">NVARCHAR</span></code></a> and <a class="reference internal" href="#sqlalchemy.dialects.oracle.NCLOB" title="sqlalchemy.dialects.oracle.NCLOB"><code class="xref py py-class docutils literal"><span class="pre">NCLOB</span></code></a> types will always generate NVARCHAR2 and NCLOB.</li> <li>the &#8220;native unicode&#8221; mode is disabled when using cx_oracle, i.e. SQLAlchemy encodes all Python unicode objects to &#8220;string&#8221; before passing in as bind parameters.</li> </ul> </div> <div class="section" id="synonym-dblink-reflection"> <h2>Synonym/DBLINK Reflection<a class="headerlink" href="#synonym-dblink-reflection" title="Permalink to this headline">¶</a></h2> <p>When using reflection with Table objects, the dialect can optionally search for tables indicated by synonyms, either in local or remote schemas or accessed over DBLINK, by passing the flag <code class="docutils literal"><span class="pre">oracle_resolve_synonyms=True</span></code> as a keyword argument to the <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Table" title="sqlalchemy.schema.Table"><code class="xref py py-class docutils literal"><span class="pre">Table</span></code></a> construct:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">some_table</span> <span class="o">=</span> <span class="n">Table</span><span class="p">(</span><span class="s">&#39;some_table&#39;</span><span class="p">,</span> <span class="n">autoload</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">autoload_with</span><span class="o">=</span><span class="n">some_engine</span><span class="p">,</span> <span class="n">oracle_resolve_synonyms</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span></pre></div> </div> <p>When this flag is set, the given name (such as <code class="docutils literal"><span class="pre">some_table</span></code> above) will be searched not just in the <code class="docutils literal"><span class="pre">ALL_TABLES</span></code> view, but also within the <code class="docutils literal"><span class="pre">ALL_SYNONYMS</span></code> view to see if this name is actually a synonym to another name. If the synonym is located and refers to a DBLINK, the oracle dialect knows how to locate the table&#8217;s information using DBLINK syntax(e.g. <code class="docutils literal"><span class="pre">&#64;dblink</span></code>).</p> <p><code class="docutils literal"><span class="pre">oracle_resolve_synonyms</span></code> is accepted wherever reflection arguments are accepted, including methods such as <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.MetaData.reflect" title="sqlalchemy.schema.MetaData.reflect"><code class="xref py py-meth docutils literal"><span class="pre">MetaData.reflect()</span></code></a> and <a class="reference internal" href="../core/reflection.html#sqlalchemy.engine.reflection.Inspector.get_columns" title="sqlalchemy.engine.reflection.Inspector.get_columns"><code class="xref py py-meth docutils literal"><span class="pre">Inspector.get_columns()</span></code></a>.</p> <p>If synonyms are not in use, this flag should be left disabled.</p> </div> <div class="section" id="datetime-compatibility"> <h2>DateTime Compatibility<a class="headerlink" href="#datetime-compatibility" title="Permalink to this headline">¶</a></h2> <p>Oracle has no datatype known as <code class="docutils literal"><span class="pre">DATETIME</span></code>, it instead has only <code class="docutils literal"><span class="pre">DATE</span></code>, which can actually store a date and time value. For this reason, the Oracle dialect provides a type <a class="reference internal" href="#sqlalchemy.dialects.oracle.DATE" title="sqlalchemy.dialects.oracle.DATE"><code class="xref py py-class docutils literal"><span class="pre">oracle.DATE</span></code></a> which is a subclass of <a class="reference internal" href="../core/type_basics.html#sqlalchemy.types.DateTime" title="sqlalchemy.types.DateTime"><code class="xref py py-class docutils literal"><span class="pre">DateTime</span></code></a>. This type has no special behavior, and is only present as a &#8220;marker&#8221; for this type; additionally, when a database column is reflected and the type is reported as <code class="docutils literal"><span class="pre">DATE</span></code>, the time-supporting <a class="reference internal" href="#sqlalchemy.dialects.oracle.DATE" title="sqlalchemy.dialects.oracle.DATE"><code class="xref py py-class docutils literal"><span class="pre">oracle.DATE</span></code></a> type is used.</p> <div class="versionchanged"> <p><span class="versionmodified">Changed in version 0.9.4: </span>Added <a class="reference internal" href="#sqlalchemy.dialects.oracle.DATE" title="sqlalchemy.dialects.oracle.DATE"><code class="xref py py-class docutils literal"><span class="pre">oracle.DATE</span></code></a> to subclass <a class="reference internal" href="../core/type_basics.html#sqlalchemy.types.DateTime" title="sqlalchemy.types.DateTime"><code class="xref py py-class docutils literal"><span class="pre">DateTime</span></code></a>. This is a change as previous versions would reflect a <code class="docutils literal"><span class="pre">DATE</span></code> column as <a class="reference internal" href="../core/type_basics.html#sqlalchemy.types.DATE" title="sqlalchemy.types.DATE"><code class="xref py py-class docutils literal"><span class="pre">types.DATE</span></code></a>, which subclasses <a class="reference internal" href="../core/type_basics.html#sqlalchemy.types.Date" title="sqlalchemy.types.Date"><code class="xref py py-class docutils literal"><span class="pre">Date</span></code></a>. The only significance here is for schemes that are examining the type of column for use in special Python translations or for migrating schemas to other database backends.</p> </div> </div> <div class="section" id="oracle-table-options"> <span id="id1"></span><h2>Oracle Table Options<a class="headerlink" href="#oracle-table-options" title="Permalink to this headline">¶</a></h2> <p>The CREATE TABLE phrase supports the following options with Oracle in conjunction with the <a class="reference internal" href="../core/metadata.html#sqlalchemy.schema.Table" title="sqlalchemy.schema.Table"><code class="xref py py-class docutils literal"><span class="pre">Table</span></code></a> construct:</p> <ul> <li><p class="first"><code class="docutils literal"><span class="pre">ON</span> <span class="pre">COMMIT</span></code>:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">Table</span><span class="p">(</span> <span class="s">&quot;some_table&quot;</span><span class="p">,</span> <span class="n">metadata</span><span class="p">,</span> <span class="o">...</span><span class="p">,</span> <span class="n">prefixes</span><span class="o">=</span><span class="p">[</span><span class="s">&#39;GLOBAL TEMPORARY&#39;</span><span class="p">],</span> <span class="n">oracle_on_commit</span><span class="o">=</span><span class="s">&#39;PRESERVE ROWS&#39;</span><span class="p">)</span></pre></div> </div> </li> </ul> <div class="versionadded"> <p><span class="versionmodified">New in version 1.0.0.</span></p> </div> <ul> <li><p class="first"><code class="docutils literal"><span class="pre">COMPRESS</span></code>:</p> <div class="highlight-python"><div class="highlight"><pre> Table(&#39;mytable&#39;, metadata, Column(&#39;data&#39;, String(32)), oracle_compress=True) Table(&#39;mytable&#39;, metadata, Column(&#39;data&#39;, String(32)), oracle_compress=6) The ``oracle_compress`` parameter accepts either an integer compression level, or ``True`` to use the default compression level.</pre></div> </div> </li> </ul> <div class="versionadded"> <p><span class="versionmodified">New in version 1.0.0.</span></p> </div> </div> <div class="section" id="oracle-specific-index-options"> <span id="oracle-index-options"></span><h2>Oracle Specific Index Options<a class="headerlink" href="#oracle-specific-index-options" title="Permalink to this headline">¶</a></h2> <div class="section" id="bitmap-indexes"> <h3>Bitmap Indexes<a class="headerlink" href="#bitmap-indexes" title="Permalink to this headline">¶</a></h3> <p>You can specify the <code class="docutils literal"><span class="pre">oracle_bitmap</span></code> parameter to create a bitmap index instead of a B-tree index:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">Index</span><span class="p">(</span><span class="s">&#39;my_index&#39;</span><span class="p">,</span> <span class="n">my_table</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">data</span><span class="p">,</span> <span class="n">oracle_bitmap</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span></pre></div> </div> <p>Bitmap indexes cannot be unique and cannot be compressed. SQLAlchemy will not check for such limitations, only the database will.</p> <div class="versionadded"> <p><span class="versionmodified">New in version 1.0.0.</span></p> </div> </div> <div class="section" id="index-compression"> <h3>Index compression<a class="headerlink" href="#index-compression" title="Permalink to this headline">¶</a></h3> <p>Oracle has a more efficient storage mode for indexes containing lots of repeated values. Use the <code class="docutils literal"><span class="pre">oracle_compress</span></code> parameter to turn on key c ompression:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">Index</span><span class="p">(</span><span class="s">&#39;my_index&#39;</span><span class="p">,</span> <span class="n">my_table</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">data</span><span class="p">,</span> <span class="n">oracle_compress</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span> <span class="n">Index</span><span class="p">(</span><span class="s">&#39;my_index&#39;</span><span class="p">,</span> <span class="n">my_table</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">data1</span><span class="p">,</span> <span class="n">my_table</span><span class="o">.</span><span class="n">c</span><span class="o">.</span><span class="n">data2</span><span class="p">,</span> <span class="n">unique</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">oracle_compress</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span></pre></div> </div> <p>The <code class="docutils literal"><span class="pre">oracle_compress</span></code> parameter accepts either an integer specifying the number of prefix columns to compress, or <code class="docutils literal"><span class="pre">True</span></code> to use the default (all columns for non-unique indexes, all but the last column for unique indexes).</p> <div class="versionadded"> <p><span class="versionmodified">New in version 1.0.0.</span></p> </div> </div> </div> <div class="section" id="oracle-data-types"> <h2>Oracle Data Types<a class="headerlink" href="#oracle-data-types" title="Permalink to this headline">¶</a></h2> <p>As with all SQLAlchemy dialects, all UPPERCASE types that are known to be valid with Oracle are importable from the top level dialect, whether they originate from <a class="reference internal" href="../core/type_basics.html#module-sqlalchemy.types" title="sqlalchemy.types"><code class="xref py py-mod docutils literal"><span class="pre">sqlalchemy.types</span></code></a> or from the local dialect:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">sqlalchemy.dialects.oracle</span> <span class="kn">import</span> \ <span class="n">BFILE</span><span class="p">,</span> <span class="n">BLOB</span><span class="p">,</span> <span class="n">CHAR</span><span class="p">,</span> <span class="n">CLOB</span><span class="p">,</span> <span class="n">DATE</span><span class="p">,</span> \ <span class="n">DOUBLE_PRECISION</span><span class="p">,</span> <span class="n">FLOAT</span><span class="p">,</span> <span class="n">INTERVAL</span><span class="p">,</span> <span class="n">LONG</span><span class="p">,</span> <span class="n">NCLOB</span><span class="p">,</span> \ <span class="n">NUMBER</span><span class="p">,</span> <span class="n">NVARCHAR</span><span class="p">,</span> <span class="n">NVARCHAR2</span><span class="p">,</span> <span class="n">RAW</span><span class="p">,</span> <span class="n">TIMESTAMP</span><span class="p">,</span> <span class="n">VARCHAR</span><span class="p">,</span> \ <span class="n">VARCHAR2</span></pre></div> </div> <p>Types which are specific to Oracle, or have Oracle-specific construction arguments, are as follows:</p> <dl class="class"> <dt id="sqlalchemy.dialects.oracle.BFILE"> <em class="property">class </em><code class="descclassname">sqlalchemy.dialects.oracle.</code><code class="descname">BFILE</code><span class="sig-paren">(</span><em>length=None</em><span class="sig-paren">)</span><a class="headerlink" href="#sqlalchemy.dialects.oracle.BFILE" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <a class="reference internal" href="../core/type_basics.html#sqlalchemy.types.LargeBinary" title="sqlalchemy.types.LargeBinary"><code class="xref py py-class docutils literal"><span class="pre">sqlalchemy.types.LargeBinary</span></code></a></p> <dl class="method"> <dt id="sqlalchemy.dialects.oracle.BFILE.__init__"> <code class="descname">__init__</code><span class="sig-paren">(</span><em>length=None</em><span class="sig-paren">)</span><a class="headerlink" href="#sqlalchemy.dialects.oracle.BFILE.__init__" title="Permalink to this definition">¶</a></dt> <dd><p>Construct a LargeBinary type.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><span class="target" id="sqlalchemy.dialects.oracle.BFILE.params.length"></span><strong>length</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.dialects.oracle.BFILE.params.length">¶</a> &#8211; optional, a length for the column for use in DDL statements, for those BLOB types that accept a length (i.e. MySQL). It does <em>not</em> produce a <em>lengthed</em> BINARY/VARBINARY type - use the BINARY/VARBINARY types specifically for those. May be safely omitted if no <code class="docutils literal"><span class="pre">CREATE</span> <span class="pre">TABLE</span></code> will be issued. Certain databases may require a <em>length</em> for use in DDL, and will raise an exception when the <code class="docutils literal"><span class="pre">CREATE</span> <span class="pre">TABLE</span></code> DDL is issued.</td> </tr> </tbody> </table> </dd></dl> </dd></dl> <dl class="class"> <dt id="sqlalchemy.dialects.oracle.DATE"> <em class="property">class </em><code class="descclassname">sqlalchemy.dialects.oracle.</code><code class="descname">DATE</code><span class="sig-paren">(</span><em>timezone=False</em><span class="sig-paren">)</span><a class="headerlink" href="#sqlalchemy.dialects.oracle.DATE" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <a class="reference internal" href="../core/type_basics.html#sqlalchemy.types.DateTime" title="sqlalchemy.types.DateTime"><code class="xref py py-class docutils literal"><span class="pre">sqlalchemy.types.DateTime</span></code></a></p> <p>Provide the oracle DATE type.</p> <p>This type has no special Python behavior, except that it subclasses <a class="reference internal" href="../core/type_basics.html#sqlalchemy.types.DateTime" title="sqlalchemy.types.DateTime"><code class="xref py py-class docutils literal"><span class="pre">types.DateTime</span></code></a>; this is to suit the fact that the Oracle <code class="docutils literal"><span class="pre">DATE</span></code> type supports a time value.</p> <div class="versionadded"> <p><span class="versionmodified">New in version 0.9.4.</span></p> </div> <dl class="method"> <dt id="sqlalchemy.dialects.oracle.DATE.__init__"> <code class="descname">__init__</code><span class="sig-paren">(</span><em>timezone=False</em><span class="sig-paren">)</span><a class="headerlink" href="#sqlalchemy.dialects.oracle.DATE.__init__" title="Permalink to this definition">¶</a></dt> <dd><p>Construct a new <a class="reference internal" href="../core/type_basics.html#sqlalchemy.types.DateTime" title="sqlalchemy.types.DateTime"><code class="xref py py-class docutils literal"><span class="pre">DateTime</span></code></a>.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><span class="target" id="sqlalchemy.dialects.oracle.DATE.params.timezone"></span><strong>timezone</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.dialects.oracle.DATE.params.timezone">¶</a> &#8211; boolean. If True, and supported by the backend, will produce &#8216;TIMESTAMP WITH TIMEZONE&#8217;. For backends that don&#8217;t support timezone aware timestamps, has no effect.</td> </tr> </tbody> </table> </dd></dl> </dd></dl> <dl class="class"> <dt id="sqlalchemy.dialects.oracle.DOUBLE_PRECISION"> <em class="property">class </em><code class="descclassname">sqlalchemy.dialects.oracle.</code><code class="descname">DOUBLE_PRECISION</code><span class="sig-paren">(</span><em>precision=None</em>, <em>scale=None</em>, <em>asdecimal=None</em><span class="sig-paren">)</span><a class="headerlink" href="#sqlalchemy.dialects.oracle.DOUBLE_PRECISION" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <a class="reference internal" href="../core/type_basics.html#sqlalchemy.types.Numeric" title="sqlalchemy.types.Numeric"><code class="xref py py-class docutils literal"><span class="pre">sqlalchemy.types.Numeric</span></code></a></p> </dd></dl> <dl class="class"> <dt id="sqlalchemy.dialects.oracle.INTERVAL"> <em class="property">class </em><code class="descclassname">sqlalchemy.dialects.oracle.</code><code class="descname">INTERVAL</code><span class="sig-paren">(</span><em>day_precision=None</em>, <em>second_precision=None</em><span class="sig-paren">)</span><a class="headerlink" href="#sqlalchemy.dialects.oracle.INTERVAL" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <a class="reference internal" href="../core/type_api.html#sqlalchemy.types.TypeEngine" title="sqlalchemy.types.TypeEngine"><code class="xref py py-class docutils literal"><span class="pre">sqlalchemy.types.TypeEngine</span></code></a></p> <dl class="method"> <dt id="sqlalchemy.dialects.oracle.INTERVAL.__init__"> <code class="descname">__init__</code><span class="sig-paren">(</span><em>day_precision=None</em>, <em>second_precision=None</em><span class="sig-paren">)</span><a class="headerlink" href="#sqlalchemy.dialects.oracle.INTERVAL.__init__" title="Permalink to this definition">¶</a></dt> <dd><p>Construct an INTERVAL.</p> <p>Note that only DAY TO SECOND intervals are currently supported. This is due to a lack of support for YEAR TO MONTH intervals within available DBAPIs (cx_oracle and zxjdbc).</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"> <li><span class="target" id="sqlalchemy.dialects.oracle.INTERVAL.params.day_precision"></span><strong>day_precision</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.dialects.oracle.INTERVAL.params.day_precision">¶</a> &#8211; the day precision value. this is the number of digits to store for the day field. Defaults to &#8220;2&#8221;</li> <li><span class="target" id="sqlalchemy.dialects.oracle.INTERVAL.params.second_precision"></span><strong>second_precision</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.dialects.oracle.INTERVAL.params.second_precision">¶</a> &#8211; the second precision value. this is the number of digits to store for the fractional seconds field. Defaults to &#8220;6&#8221;.</li> </ul> </td> </tr> </tbody> </table> </dd></dl> </dd></dl> <dl class="class"> <dt id="sqlalchemy.dialects.oracle.NCLOB"> <em class="property">class </em><code class="descclassname">sqlalchemy.dialects.oracle.</code><code class="descname">NCLOB</code><span class="sig-paren">(</span><em>length=None</em>, <em>collation=None</em>, <em>convert_unicode=False</em>, <em>unicode_error=None</em>, <em>_warn_on_bytestring=False</em><span class="sig-paren">)</span><a class="headerlink" href="#sqlalchemy.dialects.oracle.NCLOB" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <a class="reference internal" href="../core/type_basics.html#sqlalchemy.types.Text" title="sqlalchemy.types.Text"><code class="xref py py-class docutils literal"><span class="pre">sqlalchemy.types.Text</span></code></a></p> <dl class="method"> <dt id="sqlalchemy.dialects.oracle.NCLOB.__init__"> <code class="descname">__init__</code><span class="sig-paren">(</span><em>length=None</em>, <em>collation=None</em>, <em>convert_unicode=False</em>, <em>unicode_error=None</em>, <em>_warn_on_bytestring=False</em><span class="sig-paren">)</span><a class="headerlink" href="#sqlalchemy.dialects.oracle.NCLOB.__init__" title="Permalink to this definition">¶</a></dt> <dd><p>Create a string-holding type.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"> <li><span class="target" id="sqlalchemy.dialects.oracle.NCLOB.params.length"></span><strong>length</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.dialects.oracle.NCLOB.params.length">¶</a> &#8211; optional, a length for the column for use in DDL and CAST expressions. May be safely omitted if no <code class="docutils literal"><span class="pre">CREATE</span> <span class="pre">TABLE</span></code> will be issued. Certain databases may require a <code class="docutils literal"><span class="pre">length</span></code> for use in DDL, and will raise an exception when the <code class="docutils literal"><span class="pre">CREATE</span> <span class="pre">TABLE</span></code> DDL is issued if a <code class="docutils literal"><span class="pre">VARCHAR</span></code> with no length is included. Whether the value is interpreted as bytes or characters is database specific.</li> <li><span class="target" id="sqlalchemy.dialects.oracle.NCLOB.params.collation"></span><strong>collation</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.dialects.oracle.NCLOB.params.collation">¶</a> &#8211; <p>Optional, a column-level collation for use in DDL and CAST expressions. Renders using the COLLATE keyword supported by SQLite, MySQL, and Postgresql. E.g.:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="kn">import</span> <span class="n">cast</span><span class="p">,</span> <span class="n">select</span><span class="p">,</span> <span class="n">String</span> <span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">select</span><span class="p">([</span><span class="n">cast</span><span class="p">(</span><span class="s">&#39;some string&#39;</span><span class="p">,</span> <span class="n">String</span><span class="p">(</span><span class="n">collation</span><span class="o">=</span><span class="s">&#39;utf8&#39;</span><span class="p">))])</span> <span class="go">SELECT CAST(:param_1 AS VARCHAR COLLATE utf8) AS anon_1</span></pre></div> </div> <div class="versionadded"> <p><span class="versionmodified">New in version 0.8: </span>Added support for COLLATE to all string types.</p> </div> </li> <li><span class="target" id="sqlalchemy.dialects.oracle.NCLOB.params.convert_unicode"></span><strong>convert_unicode</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.dialects.oracle.NCLOB.params.convert_unicode">¶</a> &#8211; <p>When set to <code class="docutils literal"><span class="pre">True</span></code>, the <a class="reference internal" href="../core/type_basics.html#sqlalchemy.types.String" title="sqlalchemy.types.String"><code class="xref py py-class docutils literal"><span class="pre">String</span></code></a> type will assume that input is to be passed as Python <code class="docutils literal"><span class="pre">unicode</span></code> objects, and results returned as Python <code class="docutils literal"><span class="pre">unicode</span></code> objects. If the DBAPI in use does not support Python unicode (which is fewer and fewer these days), SQLAlchemy will encode/decode the value, using the value of the <code class="docutils literal"><span class="pre">encoding</span></code> parameter passed to <a class="reference internal" href="../core/engines.html#sqlalchemy.create_engine" title="sqlalchemy.create_engine"><code class="xref py py-func docutils literal"><span class="pre">create_engine()</span></code></a> as the encoding.</p> <p>When using a DBAPI that natively supports Python unicode objects, this flag generally does not need to be set. For columns that are explicitly intended to store non-ASCII data, the <a class="reference internal" href="../core/type_basics.html#sqlalchemy.types.Unicode" title="sqlalchemy.types.Unicode"><code class="xref py py-class docutils literal"><span class="pre">Unicode</span></code></a> or <a class="reference internal" href="../core/type_basics.html#sqlalchemy.types.UnicodeText" title="sqlalchemy.types.UnicodeText"><code class="xref py py-class docutils literal"><span class="pre">UnicodeText</span></code></a> types should be used regardless, which feature the same behavior of <code class="docutils literal"><span class="pre">convert_unicode</span></code> but also indicate an underlying column type that directly supports unicode, such as <code class="docutils literal"><span class="pre">NVARCHAR</span></code>.</p> <p>For the extremely rare case that Python <code class="docutils literal"><span class="pre">unicode</span></code> is to be encoded/decoded by SQLAlchemy on a backend that does natively support Python <code class="docutils literal"><span class="pre">unicode</span></code>, the value <code class="docutils literal"><span class="pre">force</span></code> can be passed here which will cause SQLAlchemy&#8217;s encode/decode services to be used unconditionally.</p> </li> <li><span class="target" id="sqlalchemy.dialects.oracle.NCLOB.params.unicode_error"></span><strong>unicode_error</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.dialects.oracle.NCLOB.params.unicode_error">¶</a> &#8211; Optional, a method to use to handle Unicode conversion errors. Behaves like the <code class="docutils literal"><span class="pre">errors</span></code> keyword argument to the standard library&#8217;s <code class="docutils literal"><span class="pre">string.decode()</span></code> functions. This flag requires that <code class="docutils literal"><span class="pre">convert_unicode</span></code> is set to <code class="docutils literal"><span class="pre">force</span></code> - otherwise, SQLAlchemy is not guaranteed to handle the task of unicode conversion. Note that this flag adds significant performance overhead to row-fetching operations for backends that already return unicode objects natively (which most DBAPIs do). This flag should only be used as a last resort for reading strings from a column with varied or corrupted encodings.</li> </ul> </td> </tr> </tbody> </table> </dd></dl> </dd></dl> <dl class="class"> <dt id="sqlalchemy.dialects.oracle.NUMBER"> <em class="property">class </em><code class="descclassname">sqlalchemy.dialects.oracle.</code><code class="descname">NUMBER</code><span class="sig-paren">(</span><em>precision=None</em>, <em>scale=None</em>, <em>asdecimal=None</em><span class="sig-paren">)</span><a class="headerlink" href="#sqlalchemy.dialects.oracle.NUMBER" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <a class="reference internal" href="../core/type_basics.html#sqlalchemy.types.Numeric" title="sqlalchemy.types.Numeric"><code class="xref py py-class docutils literal"><span class="pre">sqlalchemy.types.Numeric</span></code></a>, <a class="reference internal" href="../core/type_basics.html#sqlalchemy.types.Integer" title="sqlalchemy.types.Integer"><code class="xref py py-class docutils literal"><span class="pre">sqlalchemy.types.Integer</span></code></a></p> </dd></dl> <dl class="class"> <dt id="sqlalchemy.dialects.oracle.LONG"> <em class="property">class </em><code class="descclassname">sqlalchemy.dialects.oracle.</code><code class="descname">LONG</code><span class="sig-paren">(</span><em>length=None</em>, <em>collation=None</em>, <em>convert_unicode=False</em>, <em>unicode_error=None</em>, <em>_warn_on_bytestring=False</em><span class="sig-paren">)</span><a class="headerlink" href="#sqlalchemy.dialects.oracle.LONG" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <a class="reference internal" href="../core/type_basics.html#sqlalchemy.types.Text" title="sqlalchemy.types.Text"><code class="xref py py-class docutils literal"><span class="pre">sqlalchemy.types.Text</span></code></a></p> <dl class="method"> <dt id="sqlalchemy.dialects.oracle.LONG.__init__"> <code class="descname">__init__</code><span class="sig-paren">(</span><em>length=None</em>, <em>collation=None</em>, <em>convert_unicode=False</em>, <em>unicode_error=None</em>, <em>_warn_on_bytestring=False</em><span class="sig-paren">)</span><a class="headerlink" href="#sqlalchemy.dialects.oracle.LONG.__init__" title="Permalink to this definition">¶</a></dt> <dd><p>Create a string-holding type.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"> <li><span class="target" id="sqlalchemy.dialects.oracle.LONG.params.length"></span><strong>length</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.dialects.oracle.LONG.params.length">¶</a> &#8211; optional, a length for the column for use in DDL and CAST expressions. May be safely omitted if no <code class="docutils literal"><span class="pre">CREATE</span> <span class="pre">TABLE</span></code> will be issued. Certain databases may require a <code class="docutils literal"><span class="pre">length</span></code> for use in DDL, and will raise an exception when the <code class="docutils literal"><span class="pre">CREATE</span> <span class="pre">TABLE</span></code> DDL is issued if a <code class="docutils literal"><span class="pre">VARCHAR</span></code> with no length is included. Whether the value is interpreted as bytes or characters is database specific.</li> <li><span class="target" id="sqlalchemy.dialects.oracle.LONG.params.collation"></span><strong>collation</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.dialects.oracle.LONG.params.collation">¶</a> &#8211; <p>Optional, a column-level collation for use in DDL and CAST expressions. Renders using the COLLATE keyword supported by SQLite, MySQL, and Postgresql. E.g.:</p> <div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="kn">import</span> <span class="n">cast</span><span class="p">,</span> <span class="n">select</span><span class="p">,</span> <span class="n">String</span> <span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">select</span><span class="p">([</span><span class="n">cast</span><span class="p">(</span><span class="s">&#39;some string&#39;</span><span class="p">,</span> <span class="n">String</span><span class="p">(</span><span class="n">collation</span><span class="o">=</span><span class="s">&#39;utf8&#39;</span><span class="p">))])</span> <span class="go">SELECT CAST(:param_1 AS VARCHAR COLLATE utf8) AS anon_1</span></pre></div> </div> <div class="versionadded"> <p><span class="versionmodified">New in version 0.8: </span>Added support for COLLATE to all string types.</p> </div> </li> <li><span class="target" id="sqlalchemy.dialects.oracle.LONG.params.convert_unicode"></span><strong>convert_unicode</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.dialects.oracle.LONG.params.convert_unicode">¶</a> &#8211; <p>When set to <code class="docutils literal"><span class="pre">True</span></code>, the <a class="reference internal" href="../core/type_basics.html#sqlalchemy.types.String" title="sqlalchemy.types.String"><code class="xref py py-class docutils literal"><span class="pre">String</span></code></a> type will assume that input is to be passed as Python <code class="docutils literal"><span class="pre">unicode</span></code> objects, and results returned as Python <code class="docutils literal"><span class="pre">unicode</span></code> objects. If the DBAPI in use does not support Python unicode (which is fewer and fewer these days), SQLAlchemy will encode/decode the value, using the value of the <code class="docutils literal"><span class="pre">encoding</span></code> parameter passed to <a class="reference internal" href="../core/engines.html#sqlalchemy.create_engine" title="sqlalchemy.create_engine"><code class="xref py py-func docutils literal"><span class="pre">create_engine()</span></code></a> as the encoding.</p> <p>When using a DBAPI that natively supports Python unicode objects, this flag generally does not need to be set. For columns that are explicitly intended to store non-ASCII data, the <a class="reference internal" href="../core/type_basics.html#sqlalchemy.types.Unicode" title="sqlalchemy.types.Unicode"><code class="xref py py-class docutils literal"><span class="pre">Unicode</span></code></a> or <a class="reference internal" href="../core/type_basics.html#sqlalchemy.types.UnicodeText" title="sqlalchemy.types.UnicodeText"><code class="xref py py-class docutils literal"><span class="pre">UnicodeText</span></code></a> types should be used regardless, which feature the same behavior of <code class="docutils literal"><span class="pre">convert_unicode</span></code> but also indicate an underlying column type that directly supports unicode, such as <code class="docutils literal"><span class="pre">NVARCHAR</span></code>.</p> <p>For the extremely rare case that Python <code class="docutils literal"><span class="pre">unicode</span></code> is to be encoded/decoded by SQLAlchemy on a backend that does natively support Python <code class="docutils literal"><span class="pre">unicode</span></code>, the value <code class="docutils literal"><span class="pre">force</span></code> can be passed here which will cause SQLAlchemy&#8217;s encode/decode services to be used unconditionally.</p> </li> <li><span class="target" id="sqlalchemy.dialects.oracle.LONG.params.unicode_error"></span><strong>unicode_error</strong><a class="paramlink headerlink reference internal" href="#sqlalchemy.dialects.oracle.LONG.params.unicode_error">¶</a> &#8211; Optional, a method to use to handle Unicode conversion errors. Behaves like the <code class="docutils literal"><span class="pre">errors</span></code> keyword argument to the standard library&#8217;s <code class="docutils literal"><span class="pre">string.decode()</span></code> functions. This flag requires that <code class="docutils literal"><span class="pre">convert_unicode</span></code> is set to <code class="docutils literal"><span class="pre">force</span></code> - otherwise, SQLAlchemy is not guaranteed to handle the task of unicode conversion. Note that this flag adds significant performance overhead to row-fetching operations for backends that already return unicode objects natively (which most DBAPIs do). This flag should only be used as a last resort for reading strings from a column with varied or corrupted encodings.</li> </ul> </td> </tr> </tbody> </table> </dd></dl> </dd></dl> <dl class="class"> <dt id="sqlalchemy.dialects.oracle.RAW"> <em class="property">class </em><code class="descclassname">sqlalchemy.dialects.oracle.</code><code class="descname">RAW</code><span class="sig-paren">(</span><em>length=None</em><span class="sig-paren">)</span><a class="headerlink" href="#sqlalchemy.dialects.oracle.RAW" title="Permalink to this definition">¶</a></dt> <dd><p>Bases: <code class="xref py py-class docutils literal"><span class="pre">sqlalchemy.types._Binary</span></code></p> </dd></dl> </div> <div class="section" id="module-sqlalchemy.dialects.oracle.cx_oracle"> <span id="cx-oracle"></span><h2>cx_Oracle<a class="headerlink" href="#module-sqlalchemy.dialects.oracle.cx_oracle" title="Permalink to this headline">¶</a></h2> <p>Support for the Oracle database via the cx-Oracle driver.</p> <div class="section" id="dialect-oracle-cx_oracle-url"> <h3>DBAPI<a class="headerlink" href="#dialect-oracle-cx_oracle-url" title="Permalink to this headline">¶</a></h3> <p>Documentation and download information (if applicable) for cx-Oracle is available at: <a class="reference external" href="http://cx-oracle.sourceforge.net/">http://cx-oracle.sourceforge.net/</a></p> </div> <div class="section" id="dialect-oracle-cx_oracle-connect"> <h3>Connecting<a class="headerlink" href="#dialect-oracle-cx_oracle-connect" title="Permalink to this headline">¶</a></h3> <p>Connect String:<div class="highlight-python"><div class="highlight"><pre>oracle+cx_oracle://user:pass@host:port/dbname[?key=value&amp;key=value...]</pre></div> </div> </p> </div> <div class="section" id="additional-connect-arguments"> <h3>Additional Connect Arguments<a class="headerlink" href="#additional-connect-arguments" title="Permalink to this headline">¶</a></h3> <p>When connecting with <code class="docutils literal"><span class="pre">dbname</span></code> present, the host, port, and dbname tokens are converted to a TNS name using the cx_oracle <code class="docutils literal"><span class="pre">makedsn()</span></code> function. Otherwise, the host token is taken directly as a TNS name.</p> <p>Additional arguments which may be specified either as query string arguments on the URL, or as keyword arguments to <a class="reference internal" href="../core/engines.html#sqlalchemy.create_engine" title="sqlalchemy.create_engine"><code class="xref py py-func docutils literal"><span class="pre">create_engine()</span></code></a> are:</p> <ul> <li><p class="first"><code class="docutils literal"><span class="pre">allow_twophase</span></code> - enable two-phase transactions. Defaults to <code class="docutils literal"><span class="pre">True</span></code>.</p> </li> <li><p class="first"><code class="docutils literal"><span class="pre">arraysize</span></code> - set the cx_oracle.arraysize value on cursors, defaulted to 50. This setting is significant with cx_Oracle as the contents of LOB objects are only readable within a &#8220;live&#8221; row (e.g. within a batch of 50 rows).</p> </li> <li><p class="first"><code class="docutils literal"><span class="pre">auto_convert_lobs</span></code> - defaults to True; See <a class="reference internal" href="#cx-oracle-lob"><span>LOB Objects</span></a>.</p> </li> <li><p class="first"><code class="docutils literal"><span class="pre">auto_setinputsizes</span></code> - the cx_oracle.setinputsizes() call is issued for all bind parameters. This is required for LOB datatypes but can be disabled to reduce overhead. Defaults to <code class="docutils literal"><span class="pre">True</span></code>. Specific types can be excluded from this process using the <code class="docutils literal"><span class="pre">exclude_setinputsizes</span></code> parameter.</p> </li> <li><p class="first"><code class="docutils literal"><span class="pre">coerce_to_unicode</span></code> - see <a class="reference internal" href="#cx-oracle-unicode"><span>Unicode</span></a> for detail.</p> </li> <li><p class="first"><code class="docutils literal"><span class="pre">coerce_to_decimal</span></code> - see <a class="reference internal" href="#cx-oracle-numeric"><span>Precision Numerics</span></a> for detail.</p> </li> <li><p class="first"><code class="docutils literal"><span class="pre">exclude_setinputsizes</span></code> - a tuple or list of string DBAPI type names to be excluded from the &#8220;auto setinputsizes&#8221; feature. The type names here must match DBAPI types that are found in the &#8220;cx_Oracle&#8221; module namespace, such as cx_Oracle.UNICODE, cx_Oracle.NCLOB, etc. Defaults to <code class="docutils literal"><span class="pre">(STRING,</span> <span class="pre">UNICODE)</span></code>.</p> <div class="versionadded"> <p><span class="versionmodified">New in version 0.8: </span>specific DBAPI types can be excluded from the auto_setinputsizes feature via the exclude_setinputsizes attribute.</p> </div> </li> <li><p class="first"><code class="docutils literal"><span class="pre">mode</span></code> - This is given the string value of SYSDBA or SYSOPER, or alternatively an integer value. This value is only available as a URL query string argument.</p> </li> <li><p class="first"><code class="docutils literal"><span class="pre">threaded</span></code> - enable multithreaded access to cx_oracle connections. Defaults to <code class="docutils literal"><span class="pre">True</span></code>. Note that this is the opposite default of the cx_Oracle DBAPI itself.</p> </li> <li><p class="first"><code class="docutils literal"><span class="pre">service_name</span></code> - An option to use connection string (DSN) with <code class="docutils literal"><span class="pre">SERVICE_NAME</span></code> instead of <code class="docutils literal"><span class="pre">SID</span></code>. It can&#8217;t be passed when a <code class="docutils literal"><span class="pre">database</span></code> part is given. E.g. <code class="docutils literal"><span class="pre">oracle+cx_oracle://scott:tiger&#64;host:1521/?service_name=hr</span></code> is a valid url. This value is only available as a URL query string argument.</p> <div class="versionadded"> <p><span class="versionmodified">New in version 1.0.0.</span></p> </div> </li> </ul> </div> <div class="section" id="unicode"> <span id="cx-oracle-unicode"></span><h3>Unicode<a class="headerlink" href="#unicode" title="Permalink to this headline">¶</a></h3> <p>The cx_Oracle DBAPI as of version 5 fully supports unicode, and has the ability to return string results as Python unicode objects natively.</p> <p>When used in Python 3, cx_Oracle returns all strings as Python unicode objects (that is, plain <code class="docutils literal"><span class="pre">str</span></code> in Python 3). In Python 2, it will return as Python unicode those column values that are of type <code class="docutils literal"><span class="pre">NVARCHAR</span></code> or <code class="docutils literal"><span class="pre">NCLOB</span></code>. For column values that are of type <code class="docutils literal"><span class="pre">VARCHAR</span></code> or other non-unicode string types, it will return values as Python strings (e.g. bytestrings).</p> <p>The cx_Oracle SQLAlchemy dialect presents two different options for the use case of returning <code class="docutils literal"><span class="pre">VARCHAR</span></code> column values as Python unicode objects under Python 2:</p> <ul class="simple"> <li>the cx_Oracle DBAPI has the ability to coerce all string results to Python unicode objects unconditionally using output type handlers. This has the advantage that the unicode conversion is global to all statements at the cx_Oracle driver level, meaning it works with raw textual SQL statements that have no typing information associated. However, this system has been observed to incur signfiicant performance overhead, not only because it takes effect for all string values unconditionally, but also because cx_Oracle under Python 2 seems to use a pure-Python function call in order to do the decode operation, which under cPython can orders of magnitude slower than doing it using C functions alone.</li> <li>SQLAlchemy has unicode-decoding services built in, and when using SQLAlchemy&#8217;s C extensions, these functions do not use any Python function calls and are very fast. The disadvantage to this approach is that the unicode conversion only takes effect for statements where the <a class="reference internal" href="../core/type_basics.html#sqlalchemy.types.Unicode" title="sqlalchemy.types.Unicode"><code class="xref py py-class docutils literal"><span class="pre">Unicode</span></code></a> type or <a class="reference internal" href="../core/type_basics.html#sqlalchemy.types.String" title="sqlalchemy.types.String"><code class="xref py py-class docutils literal"><span class="pre">String</span></code></a> type with <code class="docutils literal"><span class="pre">convert_unicode=True</span></code> is explicitly associated with the result column. This is the case for any ORM or Core query or SQL expression as well as for a <a class="reference internal" href="../core/sqlelement.html#sqlalchemy.sql.expression.text" title="sqlalchemy.sql.expression.text"><code class="xref py py-func docutils literal"><span class="pre">text()</span></code></a> construct that specifies output column types, so in the vast majority of cases this is not an issue. However, when sending a completely raw string to <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection.execute" title="sqlalchemy.engine.Connection.execute"><code class="xref py py-meth docutils literal"><span class="pre">Connection.execute()</span></code></a>, this typing information isn&#8217;t present, unless the string is handled within a <a class="reference internal" href="../core/sqlelement.html#sqlalchemy.sql.expression.text" title="sqlalchemy.sql.expression.text"><code class="xref py py-func docutils literal"><span class="pre">text()</span></code></a> construct that adds typing information.</li> </ul> <p>As of version 0.9.2 of SQLAlchemy, the default approach is to use SQLAlchemy&#8217;s typing system. This keeps cx_Oracle&#8217;s expensive Python 2 approach disabled unless the user explicitly wants it. Under Python 3, SQLAlchemy detects that cx_Oracle is returning unicode objects natively and cx_Oracle&#8217;s system is used.</p> <p>To re-enable cx_Oracle&#8217;s output type handler under Python 2, the <code class="docutils literal"><span class="pre">coerce_to_unicode=True</span></code> flag (new in 0.9.4) can be passed to <a class="reference internal" href="../core/engines.html#sqlalchemy.create_engine" title="sqlalchemy.create_engine"><code class="xref py py-func docutils literal"><span class="pre">create_engine()</span></code></a>:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">engine</span> <span class="o">=</span> <span class="n">create_engine</span><span class="p">(</span><span class="s">&quot;oracle+cx_oracle://dsn&quot;</span><span class="p">,</span> <span class="n">coerce_to_unicode</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span></pre></div> </div> <p>Alternatively, to run a pure string SQL statement and get <code class="docutils literal"><span class="pre">VARCHAR</span></code> results as Python unicode under Python 2 without using cx_Oracle&#8217;s native handlers, the <a class="reference internal" href="../core/sqlelement.html#sqlalchemy.sql.expression.text" title="sqlalchemy.sql.expression.text"><code class="xref py py-func docutils literal"><span class="pre">text()</span></code></a> feature can be used:</p> <div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">sqlalchemy</span> <span class="kn">import</span> <span class="n">text</span><span class="p">,</span> <span class="n">Unicode</span> <span class="n">result</span> <span class="o">=</span> <span class="n">conn</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span> <span class="n">text</span><span class="p">(</span><span class="s">&quot;select username from user&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">columns</span><span class="p">(</span><span class="n">username</span><span class="o">=</span><span class="n">Unicode</span><span class="p">))</span></pre></div> </div> <div class="versionchanged"> <p><span class="versionmodified">Changed in version 0.9.2: </span>cx_Oracle&#8217;s outputtypehandlers are no longer used for unicode results of non-unicode datatypes in Python 2, after they were identified as a major performance bottleneck. SQLAlchemy&#8217;s own unicode facilities are used instead.</p> </div> <div class="versionadded"> <p><span class="versionmodified">New in version 0.9.4: </span>Added the <code class="docutils literal"><span class="pre">coerce_to_unicode</span></code> flag, to re-enable cx_Oracle&#8217;s outputtypehandler and revert to pre-0.9.2 behavior.</p> </div> </div> <div class="section" id="cx-oracle-returning"> <span id="id2"></span><h3>RETURNING Support<a class="headerlink" href="#cx-oracle-returning" title="Permalink to this headline">¶</a></h3> <p>The cx_oracle DBAPI supports a limited subset of Oracle&#8217;s already limited RETURNING support. Typically, results can only be guaranteed for at most one column being returned; this is the typical case when SQLAlchemy uses RETURNING to get just the value of a primary-key-associated sequence value. Additional column expressions will cause problems in a non-determinative way, due to cx_oracle&#8217;s lack of support for the OCI_DATA_AT_EXEC API which is required for more complex RETURNING scenarios.</p> <p>For this reason, stability may be enhanced by disabling RETURNING support completely; SQLAlchemy otherwise will use RETURNING to fetch newly sequence-generated primary keys. As illustrated in <a class="reference internal" href="#oracle-returning"><span>RETURNING Support</span></a>:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">engine</span> <span class="o">=</span> <span class="n">create_engine</span><span class="p">(</span><span class="s">&quot;oracle://scott:tiger@dsn&quot;</span><span class="p">,</span> <span class="n">implicit_returning</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span></pre></div> </div> <div class="admonition seealso"> <p class="first admonition-title">See also</p> <p><a class="reference external" href="http://docs.oracle.com/cd/B10501_01/appdev.920/a96584/oci05bnd.htm#420693">http://docs.oracle.com/cd/B10501_01/appdev.920/a96584/oci05bnd.htm#420693</a> - OCI documentation for RETURNING</p> <p class="last"><a class="reference external" href="http://sourceforge.net/mailarchive/message.php?msg_id=31338136">http://sourceforge.net/mailarchive/message.php?msg_id=31338136</a> - cx_oracle developer commentary</p> </div> </div> <div class="section" id="lob-objects"> <span id="cx-oracle-lob"></span><h3>LOB Objects<a class="headerlink" href="#lob-objects" title="Permalink to this headline">¶</a></h3> <p>cx_oracle returns oracle LOBs using the cx_oracle.LOB object. SQLAlchemy converts these to strings so that the interface of the Binary type is consistent with that of other backends, and so that the linkage to a live cursor is not needed in scenarios like result.fetchmany() and result.fetchall(). This means that by default, LOB objects are fully fetched unconditionally by SQLAlchemy, and the linkage to a live cursor is broken.</p> <p>To disable this processing, pass <code class="docutils literal"><span class="pre">auto_convert_lobs=False</span></code> to <a class="reference internal" href="../core/engines.html#sqlalchemy.create_engine" title="sqlalchemy.create_engine"><code class="xref py py-func docutils literal"><span class="pre">create_engine()</span></code></a>.</p> </div> <div class="section" id="two-phase-transaction-support"> <h3>Two Phase Transaction Support<a class="headerlink" href="#two-phase-transaction-support" title="Permalink to this headline">¶</a></h3> <p>Two Phase transactions are implemented using XA transactions, and are known to work in a rudimental fashion with recent versions of cx_Oracle as of SQLAlchemy 0.8.0b2, 0.7.10. However, the mechanism is not yet considered to be robust and should still be regarded as experimental.</p> <p>In particular, the cx_Oracle DBAPI as recently as 5.1.2 has a bug regarding two phase which prevents a particular DBAPI connection from being consistently usable in both prepared transactions as well as traditional DBAPI usage patterns; therefore once a particular connection is used via <code class="xref py py-meth docutils literal"><span class="pre">Connection.begin_prepared()</span></code>, all subsequent usages of the underlying DBAPI connection must be within the context of prepared transactions.</p> <p>The default behavior of <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Engine" title="sqlalchemy.engine.Engine"><code class="xref py py-class docutils literal"><span class="pre">Engine</span></code></a> is to maintain a pool of DBAPI connections. Therefore, due to the above glitch, a DBAPI connection that has been used in a two-phase operation, and is then returned to the pool, will not be usable in a non-two-phase context. To avoid this situation, the application can make one of several choices:</p> <ul class="simple"> <li>Disable connection pooling using <a class="reference internal" href="../core/pooling.html#sqlalchemy.pool.NullPool" title="sqlalchemy.pool.NullPool"><code class="xref py py-class docutils literal"><span class="pre">NullPool</span></code></a></li> <li>Ensure that the particular <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Engine" title="sqlalchemy.engine.Engine"><code class="xref py py-class docutils literal"><span class="pre">Engine</span></code></a> in use is only used for two-phase operations. A <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Engine" title="sqlalchemy.engine.Engine"><code class="xref py py-class docutils literal"><span class="pre">Engine</span></code></a> bound to an ORM <a class="reference internal" href="../orm/session_api.html#sqlalchemy.orm.session.Session" title="sqlalchemy.orm.session.Session"><code class="xref py py-class docutils literal"><span class="pre">Session</span></code></a> which includes <code class="docutils literal"><span class="pre">twophase=True</span></code> will consistently use the two-phase transaction style.</li> <li>For ad-hoc two-phase operations without disabling pooling, the DBAPI connection in use can be evicted from the connection pool using the <a class="reference internal" href="../core/connections.html#sqlalchemy.engine.Connection.detach" title="sqlalchemy.engine.Connection.detach"><code class="xref py py-meth docutils literal"><span class="pre">Connection.detach()</span></code></a> method.</li> </ul> <div class="versionchanged"> <p><span class="versionmodified">Changed in version 0.8.0b2,0.7.10: </span>Support for cx_oracle prepared transactions has been implemented and tested.</p> </div> </div> <div class="section" id="precision-numerics"> <span id="cx-oracle-numeric"></span><h3>Precision Numerics<a class="headerlink" href="#precision-numerics" title="Permalink to this headline">¶</a></h3> <p>The SQLAlchemy dialect goes through a lot of steps to ensure that decimal numbers are sent and received with full accuracy. An &#8220;outputtypehandler&#8221; callable is associated with each cx_oracle connection object which detects numeric types and receives them as string values, instead of receiving a Python <code class="docutils literal"><span class="pre">float</span></code> directly, which is then passed to the Python <code class="docutils literal"><span class="pre">Decimal</span></code> constructor. The <a class="reference internal" href="../core/type_basics.html#sqlalchemy.types.Numeric" title="sqlalchemy.types.Numeric"><code class="xref py py-class docutils literal"><span class="pre">Numeric</span></code></a> and <a class="reference internal" href="../core/type_basics.html#sqlalchemy.types.Float" title="sqlalchemy.types.Float"><code class="xref py py-class docutils literal"><span class="pre">Float</span></code></a> types under the cx_oracle dialect are aware of this behavior, and will coerce the <code class="docutils literal"><span class="pre">Decimal</span></code> to <code class="docutils literal"><span class="pre">float</span></code> if the <code class="docutils literal"><span class="pre">asdecimal</span></code> flag is <code class="docutils literal"><span class="pre">False</span></code> (default on <a class="reference internal" href="../core/type_basics.html#sqlalchemy.types.Float" title="sqlalchemy.types.Float"><code class="xref py py-class docutils literal"><span class="pre">Float</span></code></a>, optional on <a class="reference internal" href="../core/type_basics.html#sqlalchemy.types.Numeric" title="sqlalchemy.types.Numeric"><code class="xref py py-class docutils literal"><span class="pre">Numeric</span></code></a>).</p> <p>Because the handler coerces to <code class="docutils literal"><span class="pre">Decimal</span></code> in all cases first, the feature can detract significantly from performance. If precision numerics aren&#8217;t required, the decimal handling can be disabled by passing the flag <code class="docutils literal"><span class="pre">coerce_to_decimal=False</span></code> to <a class="reference internal" href="../core/engines.html#sqlalchemy.create_engine" title="sqlalchemy.create_engine"><code class="xref py py-func docutils literal"><span class="pre">create_engine()</span></code></a>:</p> <div class="highlight-python"><div class="highlight"><pre><span class="n">engine</span> <span class="o">=</span> <span class="n">create_engine</span><span class="p">(</span><span class="s">&quot;oracle+cx_oracle://dsn&quot;</span><span class="p">,</span> <span class="n">coerce_to_decimal</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span></pre></div> </div> <div class="versionadded"> <p><span class="versionmodified">New in version 0.7.6: </span>Add the <code class="docutils literal"><span class="pre">coerce_to_decimal</span></code> flag.</p> </div> <p>Another alternative to performance is to use the <a class="reference external" href="http://pypi.python.org/pypi/cdecimal/">cdecimal</a> library; see <a class="reference internal" href="../core/type_basics.html#sqlalchemy.types.Numeric" title="sqlalchemy.types.Numeric"><code class="xref py py-class docutils literal"><span class="pre">Numeric</span></code></a> for additional notes.</p> <p>The handler attempts to use the &#8220;precision&#8221; and &#8220;scale&#8221; attributes of the result set column to best determine if subsequent incoming values should be received as <code class="docutils literal"><span class="pre">Decimal</span></code> as opposed to int (in which case no processing is added). There are several scenarios where <a class="reference external" href="http://www.oracle.com/technetwork/database/features/oci/index.html">OCI</a> does not provide unambiguous data as to the numeric type, including some situations where individual rows may return a combination of floating point and integer values. Certain values for &#8220;precision&#8221; and &#8220;scale&#8221; have been observed to determine this scenario. When it occurs, the outputtypehandler receives as string and then passes off to a processing function which detects, for each returned value, if a decimal point is present, and if so converts to <code class="docutils literal"><span class="pre">Decimal</span></code>, otherwise to int. The intention is that simple int-based statements like &#8220;SELECT my_seq.nextval() FROM DUAL&#8221; continue to return ints and not <code class="docutils literal"><span class="pre">Decimal</span></code> objects, and that any kind of floating point value is received as a string so that there is no floating point loss of precision.</p> <p>The &#8220;decimal point is present&#8221; logic itself is also sensitive to locale. Under <a class="reference external" href="http://www.oracle.com/technetwork/database/features/oci/index.html">OCI</a>, this is controlled by the NLS_LANG environment variable. Upon first connection, the dialect runs a test to determine the current &#8220;decimal&#8221; character, which can be a comma &#8221;,&#8221; for European locales. From that point forward the outputtypehandler uses that character to represent a decimal point. Note that cx_oracle 5.0.3 or greater is required when dealing with numerics with locale settings that don&#8217;t use a period &#8221;.&#8221; as the decimal character.</p> <div class="versionchanged"> <p><span class="versionmodified">Changed in version 0.6.6: </span>The outputtypehandler supports the case where the locale uses a comma &#8221;,&#8221; character to represent a decimal point.</p> </div> </div> </div> <div class="section" id="module-sqlalchemy.dialects.oracle.zxjdbc"> <span id="zxjdbc"></span><h2>zxjdbc<a class="headerlink" href="#module-sqlalchemy.dialects.oracle.zxjdbc" title="Permalink to this headline">¶</a></h2> <p>Support for the Oracle database via the zxJDBC for Jython driver.<div class="admonition note"> <p class="first admonition-title">Note</p> <p class="last">Jython is not supported by current versions of SQLAlchemy. The zxjdbc dialect should be considered as experimental.</p> </div> </p> <div class="section" id="dialect-oracle-zxjdbc-url"> <h3>DBAPI<a class="headerlink" href="#dialect-oracle-zxjdbc-url" title="Permalink to this headline">¶</a></h3> <p>Drivers for this database are available at: <a class="reference external" href="http://www.oracle.com/technology/software/tech/java/sqlj_jdbc/index.html.">http://www.oracle.com/technology/software/tech/java/sqlj_jdbc/index.html.</a></p> </div> <div class="section" id="dialect-oracle-zxjdbc-connect"> <h3>Connecting<a class="headerlink" href="#dialect-oracle-zxjdbc-connect" title="Permalink to this headline">¶</a></h3> <p>Connect String:<div class="highlight-python"><div class="highlight"><pre>oracle+zxjdbc://user:pass@host/dbname</pre></div> </div> </p> </div> </div> </div> </div> </div> <div id="docs-bottom-navigation" class="docs-navigation-links"> Previous: <a href="mysql.html" title="previous chapter">MySQL</a> Next: <a href="postgresql.html" title="next chapter">PostgreSQL</a> <div id="docs-copyright"> &copy; <a href="../copyright.html">Copyright</a> 2007-2015, the SQLAlchemy authors and contributors. Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.3.1. </div> </div> </div> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '../', VERSION: '1.0.6', COLLAPSE_MODINDEX: false, FILE_SUFFIX: '.html' }; </script> <!-- begin iterate through sphinx environment script_files --> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <!-- end iterate through sphinx environment script_files --> <script type="text/javascript" src="../_static/detectmobile.js"></script> <script type="text/javascript" src="../_static/init.js"></script> </body> </html>
{ "content_hash": "a2a73126696a78ceecdefa51bf86dbc2", "timestamp": "", "source": "github", "line_count": 1017, "max_line_length": 535, "avg_line_length": 83.4621435594887, "alnum_prop": 0.7227059059153403, "repo_name": "nzavagli/UnrealPy", "id": "96cdf10accb2497cef4cdc7964ef07bdffacc7c1", "size": "84935", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "UnrealPyEmbed/Development/Python/2015.08.07-Python2710-x64-Source-vs2015/Python27/Source/SQLAlchemy-1.0.6/doc/dialects/oracle.html", "mode": "33188", "license": "mit", "language": [ { "name": "APL", "bytes": "587" }, { "name": "ASP", "bytes": "2753" }, { "name": "ActionScript", "bytes": "5686" }, { "name": "Ada", "bytes": "94225" }, { "name": "Agda", "bytes": "3154" }, { "name": "Alloy", "bytes": "6579" }, { "name": "ApacheConf", "bytes": "12482" }, { "name": "AppleScript", "bytes": "421" }, { "name": "Assembly", "bytes": "1093261" }, { "name": "AutoHotkey", "bytes": "3733" }, { "name": "AutoIt", "bytes": "667" }, { "name": "Awk", "bytes": "63276" }, { "name": "Batchfile", "bytes": "147828" }, { "name": "BlitzBasic", "bytes": "185102" }, { "name": "BlitzMax", "bytes": "2387" }, { "name": "Boo", "bytes": "1111" }, { "name": "Bro", "bytes": "7337" }, { "name": "C", "bytes": "108397183" }, { "name": "C#", "bytes": "156749" }, { "name": "C++", "bytes": "13535833" }, { "name": "CLIPS", "bytes": "6933" }, { "name": "CMake", "bytes": "12441" }, { "name": "COBOL", "bytes": "114812" }, { "name": "CSS", "bytes": "430375" }, { "name": "Ceylon", "bytes": "1387" }, { "name": "Chapel", "bytes": "4366" }, { "name": "Cirru", "bytes": "2574" }, { "name": "Clean", "bytes": "9679" }, { "name": "Clojure", "bytes": "23871" }, { "name": "CoffeeScript", "bytes": "20149" }, { "name": "ColdFusion", "bytes": "9006" }, { "name": "Common Lisp", "bytes": "49017" }, { "name": "Coq", "bytes": "66" }, { "name": "Cucumber", "bytes": "390" }, { "name": "Cuda", "bytes": "776" }, { "name": "D", "bytes": "7556" }, { "name": "DIGITAL Command Language", "bytes": "425938" }, { "name": "DTrace", "bytes": "6706" }, { "name": "Dart", "bytes": "591" }, { "name": "Dylan", "bytes": "6343" }, { "name": "Ecl", "bytes": "2599" }, { "name": "Eiffel", "bytes": "2145" }, { "name": "Elixir", "bytes": "4340" }, { "name": "Emacs Lisp", "bytes": "18303" }, { "name": "Erlang", "bytes": "5746" }, { "name": "F#", "bytes": "19156" }, { "name": "FORTRAN", "bytes": "38458" }, { "name": "Factor", "bytes": "10194" }, { "name": "Fancy", "bytes": "2581" }, { "name": "Fantom", "bytes": "25331" }, { "name": "GAP", "bytes": "29880" }, { "name": "GLSL", "bytes": "450" }, { "name": "Gnuplot", "bytes": "11501" }, { "name": "Go", "bytes": "5444" }, { "name": "Golo", "bytes": "1649" }, { "name": "Gosu", "bytes": "2853" }, { "name": "Groff", "bytes": "3458639" }, { "name": "Groovy", "bytes": "2586" }, { "name": "HTML", "bytes": "92126540" }, { "name": "Haskell", "bytes": "49593" }, { "name": "Haxe", "bytes": "16812" }, { "name": "Hy", "bytes": "7237" }, { "name": "IDL", "bytes": "2098" }, { "name": "Idris", "bytes": "2771" }, { "name": "Inform 7", "bytes": "1944" }, { "name": "Inno Setup", "bytes": "18796" }, { "name": "Ioke", "bytes": "469" }, { "name": "Isabelle", "bytes": "21392" }, { "name": "Jasmin", "bytes": "9428" }, { "name": "Java", "bytes": "4040623" }, { "name": "JavaScript", "bytes": "223927" }, { "name": "Julia", "bytes": "27687" }, { "name": "KiCad", "bytes": "475" }, { "name": "Kotlin", "bytes": "971" }, { "name": "LSL", "bytes": "160" }, { "name": "Lasso", "bytes": "18650" }, { "name": "Lean", "bytes": "6921" }, { "name": "Limbo", "bytes": "9891" }, { "name": "Liquid", "bytes": "862" }, { "name": "LiveScript", "bytes": "972" }, { "name": "Logos", "bytes": "19509" }, { "name": "Logtalk", "bytes": "7260" }, { "name": "Lua", "bytes": "8677" }, { "name": "Makefile", "bytes": "2053844" }, { "name": "Mask", "bytes": "815" }, { "name": "Mathematica", "bytes": "191" }, { "name": "Max", "bytes": "296" }, { "name": "Modelica", "bytes": "6213" }, { "name": "Modula-2", "bytes": "23838" }, { "name": "Module Management System", "bytes": "14798" }, { "name": "Monkey", "bytes": "2587" }, { "name": "Moocode", "bytes": "3343" }, { "name": "MoonScript", "bytes": "14862" }, { "name": "Myghty", "bytes": "3939" }, { "name": "NSIS", "bytes": "7663" }, { "name": "Nemerle", "bytes": "1517" }, { "name": "NewLisp", "bytes": "42726" }, { "name": "Nimrod", "bytes": "37191" }, { "name": "Nit", "bytes": "55581" }, { "name": "Nix", "bytes": "2448" }, { "name": "OCaml", "bytes": "42416" }, { "name": "Objective-C", "bytes": "104883" }, { "name": "Objective-J", "bytes": "15340" }, { "name": "Opa", "bytes": "172" }, { "name": "OpenEdge ABL", "bytes": "49943" }, { "name": "PAWN", "bytes": "6555" }, { "name": "PHP", "bytes": "68611" }, { "name": "PLSQL", "bytes": "45772" }, { "name": "Pan", "bytes": "1241" }, { "name": "Pascal", "bytes": "349743" }, { "name": "Perl", "bytes": "5931502" }, { "name": "Perl6", "bytes": "113623" }, { "name": "PigLatin", "bytes": "6657" }, { "name": "Pike", "bytes": "8479" }, { "name": "PostScript", "bytes": "18216" }, { "name": "PowerShell", "bytes": "14236" }, { "name": "Prolog", "bytes": "43750" }, { "name": "Protocol Buffer", "bytes": "3401" }, { "name": "Puppet", "bytes": "130" }, { "name": "Python", "bytes": "122886156" }, { "name": "QML", "bytes": "3912" }, { "name": "R", "bytes": "49247" }, { "name": "Racket", "bytes": "11341" }, { "name": "Rebol", "bytes": "17708" }, { "name": "Red", "bytes": "10536" }, { "name": "Redcode", "bytes": "830" }, { "name": "Ruby", "bytes": "91403" }, { "name": "Rust", "bytes": "6788" }, { "name": "SAS", "bytes": "15603" }, { "name": "SaltStack", "bytes": "1040" }, { "name": "Scala", "bytes": "730" }, { "name": "Scheme", "bytes": "50346" }, { "name": "Scilab", "bytes": "943" }, { "name": "Shell", "bytes": "2925097" }, { "name": "ShellSession", "bytes": "320" }, { "name": "Smali", "bytes": "832" }, { "name": "Smalltalk", "bytes": "158636" }, { "name": "Smarty", "bytes": "523" }, { "name": "SourcePawn", "bytes": "130" }, { "name": "Standard ML", "bytes": "36869" }, { "name": "Swift", "bytes": "2035" }, { "name": "SystemVerilog", "bytes": "265" }, { "name": "Tcl", "bytes": "6077233" }, { "name": "TeX", "bytes": "487999" }, { "name": "Tea", "bytes": "391" }, { "name": "TypeScript", "bytes": "535" }, { "name": "VHDL", "bytes": "4446" }, { "name": "VimL", "bytes": "32053" }, { "name": "Visual Basic", "bytes": "19441" }, { "name": "XQuery", "bytes": "4289" }, { "name": "XS", "bytes": "178055" }, { "name": "XSLT", "bytes": "1995174" }, { "name": "Xtend", "bytes": "727" }, { "name": "Yacc", "bytes": "25665" }, { "name": "Zephir", "bytes": "485" }, { "name": "eC", "bytes": "31545" }, { "name": "mupad", "bytes": "2442" }, { "name": "nesC", "bytes": "23697" }, { "name": "xBase", "bytes": "3349" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using DevRainSolutions.KyivSmartCity.New.Models; using DevRainSolutions.KyivSmartCity.New.Areas.Admin.Models; using PagedList; namespace DevRainSolutions.KyivSmartCity.New.Areas.Admin.Controllers { public class ExpertsController : BaseAdminController { private readonly IGroupRepository groupRepository; private readonly IExpertRepository expertRepository; // If you are using Dependency Injection, you can delete the following constructor public ExpertsController() : this(new GroupRepository(), new ExpertRepository()) { } public ExpertsController(IGroupRepository groupRepository, IExpertRepository expertRepository) { this.groupRepository = groupRepository; this.expertRepository = expertRepository; } // // GET: /Experts/ public ViewResult Index(int? page) { var pageNumber = page ?? 1; return View(expertRepository.AllIncluding(expert => expert.Group) .OrderBy(i=>i.Title) .ToPagedList(pageNumber, 10)); } // // GET: /Experts/Details/5 public ViewResult Details(int id) { return View(expertRepository.Find(id)); } // // GET: /Experts/Create public ActionResult Create() { ViewBag.PossibleGroups = groupRepository.All; return View(); } // // POST: /Experts/Create [HttpPost] public ActionResult Create(Expert expert) { if (ModelState.IsValid) { expertRepository.InsertOrUpdate(expert); expertRepository.Save(); return RedirectToAction("Index"); } else { ViewBag.PossibleGroups = groupRepository.All; return View(); } } // // GET: /Experts/Edit/5 public ActionResult Edit(int id) { ViewBag.PossibleGroups = groupRepository.All; return View(expertRepository.Find(id)); } // // POST: /Experts/Edit/5 [HttpPost] public ActionResult Edit(Expert expert) { if (ModelState.IsValid) { expertRepository.InsertOrUpdate(expert); expertRepository.Save(); return RedirectToAction("Index"); } else { ViewBag.PossibleGroups = groupRepository.All; return View(); } } // // GET: /Experts/Delete/5 public ActionResult Delete(int id) { return View(expertRepository.Find(id)); } // // POST: /Experts/Delete/5 [HttpPost, ActionName("Delete")] public ActionResult DeleteConfirmed(int id) { expertRepository.Delete(id); expertRepository.Save(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { groupRepository.Dispose(); expertRepository.Dispose(); } base.Dispose(disposing); } } }
{ "content_hash": "ecc3002e2c5fb55087bf35ffc3d55a0c", "timestamp": "", "source": "github", "line_count": 127, "max_line_length": 102, "avg_line_length": 25.811023622047244, "alnum_prop": 0.5765710799267846, "repo_name": "DevRainSolutions/KyivSmartCity", "id": "4bb433ce79adfedf42e9618de6840f0c5491a901", "size": "3278", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "DevRainSolutions.KyivSmartCity.New/Areas/Admin/Controllers/ExpertsController.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "125" }, { "name": "C#", "bytes": "318335" }, { "name": "CSS", "bytes": "12589" }, { "name": "HTML", "bytes": "3226" }, { "name": "JavaScript", "bytes": "136297" } ], "symlink_target": "" }
FactoryBot.define do factory :roster do sequence(:name) { |n| "Name #{n}" } end end
{ "content_hash": "d778adeccf5a93598163fe8ff6ff83a6", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 39, "avg_line_length": 18.4, "alnum_prop": 0.6195652173913043, "repo_name": "umts/screaming-dinosaur", "id": "38ba15bff3728bd67f31bbf384584b095296ca98", "size": "123", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "spec/factories/rosters.rb", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "7295" }, { "name": "Haml", "bytes": "13350" }, { "name": "JavaScript", "bytes": "2425" }, { "name": "Ruby", "bytes": "146058" }, { "name": "SCSS", "bytes": "2591" } ], "symlink_target": "" }
var assert = require('assert') describe('Messages', () => { it('should be able to see the messages in a specific room') it('should be able to send a new message in a new room') it('should be able to see your newly send message') it('should emit socket:message via websockets on message sending') })
{ "content_hash": "2a4e8b0d4273fe1cd420295c8f40e5b2", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 68, "avg_line_length": 38.5, "alnum_prop": 0.7045454545454546, "repo_name": "SivanMehta/chatroom", "id": "db4ce4aa808ae61f894fbbac03df650cd4edb32c", "size": "308", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/api/messages.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "1783" }, { "name": "JavaScript", "bytes": "28921" } ], "symlink_target": "" }
/* * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package java.security; /** * A {@code DomainCombiner} provides a means to dynamically * update the ProtectionDomains associated with the current * {@code AccessControlContext}. * * <p> A {@code DomainCombiner} is passed as a parameter to the * appropriate constructor for {@code AccessControlContext}. * The newly constructed context is then passed to the * {@code AccessController.doPrivileged(..., context)} method * to bind the provided context (and associated {@code DomainCombiner}) * with the current execution Thread. Subsequent calls to * {@code AccessController.getContext} or * {@code AccessController.checkPermission} * cause the {@code DomainCombiner.combine} to get invoked. * * <p> The combine method takes two arguments. The first argument represents * an array of ProtectionDomains from the current execution Thread, * since the most recent call to {@code AccessController.doPrivileged}. * If no call to doPrivileged was made, then the first argument will contain * all the ProtectionDomains from the current execution Thread. * The second argument represents an array of inherited ProtectionDomains, * which may be {@code null}. ProtectionDomains may be inherited * from a parent Thread, or from a privileged context. If no call to * doPrivileged was made, then the second argument will contain the * ProtectionDomains inherited from the parent Thread. If one or more calls * to doPrivileged were made, and the most recent call was to * doPrivileged(action, context), then the second argument will contain the * ProtectionDomains from the privileged context. If the most recent call * was to doPrivileged(action), then there is no privileged context, * and the second argument will be {@code null}. * * <p> The {@code combine} method investigates the two input arrays * of ProtectionDomains and returns a single array containing the updated * ProtectionDomains. In the simplest case, the {@code combine} * method merges the two stacks into one. In more complex cases, * the {@code combine} method returns a modified * stack of ProtectionDomains. The modification may have added new * ProtectionDomains, removed certain ProtectionDomains, or simply * updated existing ProtectionDomains. Re-ordering and other optimizations * to the ProtectionDomains are also permitted. Typically the * {@code combine} method bases its updates on the information * encapsulated in the {@code DomainCombiner}. * * <p> After the {@code AccessController.getContext} method * receives the combined stack of ProtectionDomains back from * the {@code DomainCombiner}, it returns a new * AccessControlContext that has both the combined ProtectionDomains * as well as the {@code DomainCombiner}. * * @see AccessController * @see AccessControlContext * @since 1.3 */ public interface DomainCombiner { /** * Modify or update the provided ProtectionDomains. * ProtectionDomains may be added to or removed from the given * ProtectionDomains. The ProtectionDomains may be re-ordered. * Individual ProtectionDomains may be modified (with a new * set of Permissions, for example). * * <p> * * @param currentDomains the ProtectionDomains associated with the * current execution Thread, up to the most recent * privileged {@code ProtectionDomain}. * The ProtectionDomains are are listed in order of execution, * with the most recently executing {@code ProtectionDomain} * residing at the beginning of the array. This parameter may * be {@code null} if the current execution Thread * has no associated ProtectionDomains.<p> * * @param assignedDomains an array of inherited ProtectionDomains. * ProtectionDomains may be inherited from a parent Thread, * or from a privileged {@code AccessControlContext}. * This parameter may be {@code null} * if there are no inherited ProtectionDomains. * * @return a new array consisting of the updated ProtectionDomains, * or {@code null}. */ ProtectionDomain[] combine(ProtectionDomain[] currentDomains, ProtectionDomain[] assignedDomains); }
{ "content_hash": "31f13267308b408bdf0728f3618fd8ae", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 79, "avg_line_length": 40.017699115044245, "alnum_prop": 0.7127377266696152, "repo_name": "flyzsd/java-code-snippets", "id": "af41f3968024208637b8bdbe28f4247305852bda", "size": "4996", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ibm.jdk8/src/java/security/DomainCombiner.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "51741503" } ], "symlink_target": "" }
/*jshint loopfunc: true */ var debug = require('debug')('gatt'); var events = require('events'); var os = require('os'); var util = require('util'); var ATT_OP_ERROR = 0x01; var ATT_OP_MTU_REQ = 0x02; var ATT_OP_MTU_RESP = 0x03; var ATT_OP_FIND_INFO_REQ = 0x04; var ATT_OP_FIND_INFO_RESP = 0x05; var ATT_OP_FIND_BY_TYPE_REQ = 0x06; var ATT_OP_FIND_BY_TYPE_RESP = 0x07; var ATT_OP_READ_BY_TYPE_REQ = 0x08; var ATT_OP_READ_BY_TYPE_RESP = 0x09; var ATT_OP_READ_REQ = 0x0a; var ATT_OP_READ_RESP = 0x0b; var ATT_OP_READ_BLOB_REQ = 0x0c; var ATT_OP_READ_BLOB_RESP = 0x0d; var ATT_OP_READ_MULTI_REQ = 0x0e; var ATT_OP_READ_MULTI_RESP = 0x0f; var ATT_OP_READ_BY_GROUP_REQ = 0x10; var ATT_OP_READ_BY_GROUP_RESP = 0x11; var ATT_OP_WRITE_REQ = 0x12; var ATT_OP_WRITE_RESP = 0x13; var ATT_OP_WRITE_CMD = 0x52; var ATT_OP_PREP_WRITE_REQ = 0x16; var ATT_OP_PREP_WRITE_RESP = 0x17; var ATT_OP_EXEC_WRITE_REQ = 0x18; var ATT_OP_EXEC_WRITE_RESP = 0x19; var ATT_OP_HANDLE_NOTIFY = 0x1b; var ATT_OP_HANDLE_IND = 0x1d; var ATT_OP_HANDLE_CNF = 0x1e; var ATT_OP_SIGNED_WRITE_CMD = 0xd2; var GATT_PRIM_SVC_UUID = 0x2800; var GATT_INCLUDE_UUID = 0x2802; var GATT_CHARAC_UUID = 0x2803; var GATT_CLIENT_CHARAC_CFG_UUID = 0x2902; var GATT_SERVER_CHARAC_CFG_UUID = 0x2903; var ATT_ECODE_SUCCESS = 0x00; var ATT_ECODE_INVALID_HANDLE = 0x01; var ATT_ECODE_READ_NOT_PERM = 0x02; var ATT_ECODE_WRITE_NOT_PERM = 0x03; var ATT_ECODE_INVALID_PDU = 0x04; var ATT_ECODE_AUTHENTICATION = 0x05; var ATT_ECODE_REQ_NOT_SUPP = 0x06; var ATT_ECODE_INVALID_OFFSET = 0x07; var ATT_ECODE_AUTHORIZATION = 0x08; var ATT_ECODE_PREP_QUEUE_FULL = 0x09; var ATT_ECODE_ATTR_NOT_FOUND = 0x0a; var ATT_ECODE_ATTR_NOT_LONG = 0x0b; var ATT_ECODE_INSUFF_ENCR_KEY_SIZE = 0x0c; var ATT_ECODE_INVAL_ATTR_VALUE_LEN = 0x0d; var ATT_ECODE_UNLIKELY = 0x0e; var ATT_ECODE_INSUFF_ENC = 0x0f; var ATT_ECODE_UNSUPP_GRP_TYPE = 0x10; var ATT_ECODE_INSUFF_RESOURCES = 0x11; var ATT_CID = 0x0004; var Gatt = function() { this.maxMtu = 256; this._mtu = 23; this._preparedWriteRequest = null; this.setServices([]); this.onAclStreamDataBinded = this.onAclStreamData.bind(this); this.onAclStreamEndBinded = this.onAclStreamEnd.bind(this); }; util.inherits(Gatt, events.EventEmitter); Gatt.prototype.setServices = function(services) { var deviceName = process.env.BLENO_DEVICE_NAME || os.hostname(); // base services and characteristics var allServices = [ { uuid: '1800', characteristics: [ { uuid: '2a00', properties: ['read'], secure: [], value: new Buffer(deviceName), descriptors: [] }, { uuid: '2a01', properties: ['read'], secure: [], value: new Buffer([0x80, 0x00]), descriptors: [] } ] }, { uuid: '1801', characteristics: [ { uuid: '2a05', properties: ['indicate'], secure: [], value: new Buffer([0x00, 0x00, 0x00, 0x00]), descriptors: [] } ] } ].concat(services); this._handles = []; var handle = 0; var i; var j; for (i = 0; i < allServices.length; i++) { var service = allServices[i]; handle++; var serviceHandle = handle; this._handles[serviceHandle] = { type: 'service', uuid: service.uuid, attribute: service, startHandle: serviceHandle // endHandle filled in below }; for (j = 0; j < service.characteristics.length; j++) { var characteristic = service.characteristics[j]; var properties = 0; var secure = 0; if (characteristic.properties.indexOf('read') !== -1) { properties |= 0x02; if (characteristic.secure.indexOf('read') !== -1) { secure |= 0x02; } } if (characteristic.properties.indexOf('writeWithoutResponse') !== -1) { properties |= 0x04; if (characteristic.secure.indexOf('writeWithoutResponse') !== -1) { secure |= 0x04; } } if (characteristic.properties.indexOf('write') !== -1) { properties |= 0x08; if (characteristic.secure.indexOf('write') !== -1) { secure |= 0x08; } } if (characteristic.properties.indexOf('notify') !== -1) { properties |= 0x10; if (characteristic.secure.indexOf('notify') !== -1) { secure |= 0x10; } } if (characteristic.properties.indexOf('indicate') !== -1) { properties |= 0x20; if (characteristic.secure.indexOf('indicate') !== -1) { secure |= 0x20; } } handle++; var characteristicHandle = handle; handle++; var characteristicValueHandle = handle; this._handles[characteristicHandle] = { type: 'characteristic', uuid: characteristic.uuid, properties: properties, secure: secure, attribute: characteristic, startHandle: characteristicHandle, valueHandle: characteristicValueHandle }; this._handles[characteristicValueHandle] = { type: 'characteristicValue', handle: characteristicValueHandle, value: characteristic.value }; if (properties & 0x30) { // notify or indicate // add client characteristic configuration descriptor handle++; var clientCharacteristicConfigurationDescriptorHandle = handle; this._handles[clientCharacteristicConfigurationDescriptorHandle] = { type: 'descriptor', handle: clientCharacteristicConfigurationDescriptorHandle, uuid: '2902', attribute: characteristic, properties: (0x02 | 0x04 | 0x08), // read/write secure: (secure & 0x10) ? (0x02 | 0x04 | 0x08) : 0, value: new Buffer([0x00, 0x00]) }; } for (var k = 0; k < characteristic.descriptors.length; k++) { var descriptor = characteristic.descriptors[k]; handle++; var descriptorHandle = handle; this._handles[descriptorHandle] = { type: 'descriptor', handle: descriptorHandle, uuid: descriptor.uuid, attribute: descriptor, properties: 0x02, // read only secure: 0x00, value: descriptor.value }; } } this._handles[serviceHandle].endHandle = handle; } var debugHandles = []; for (i = 0; i < this._handles.length; i++) { handle = this._handles[i]; debugHandles[i] = {}; for(j in handle) { if (Buffer.isBuffer(handle[j])) { debugHandles[i][j] = handle[j] ? 'Buffer(\'' + handle[j].toString('hex') + '\', \'hex\')' : null; } else if (j !== 'attribute') { debugHandles[i][j] = handle[j]; } } } debug('handles = ' + JSON.stringify(debugHandles, null, 2)); }; Gatt.prototype.setAclStream = function(aclStream) { this._mtu = 23; this._preparedWriteRequest = null; this._aclStream = aclStream; this._aclStream.on('data', this.onAclStreamDataBinded); this._aclStream.on('end', this.onAclStreamEndBinded); }; Gatt.prototype.onAclStreamData = function(cid, data) { if (cid !== ATT_CID) { return; } this.handleRequest(data); }; Gatt.prototype.onAclStreamEnd = function() { this._aclStream.removeListener('data', this.onAclStreamDataBinded); this._aclStream.removeListener('end', this.onAclStreamEndBinded); for (var i = 0; i < this._handles.length; i++) { if (this._handles[i] && this._handles[i].type === 'descriptor' && this._handles[i].uuid === '2902' && this._handles[i].value.readUInt16LE(0) !== 0) { this._handles[i].value = new Buffer([0x00, 0x00]); if (this._handles[i].attribute && this._handles[i].attribute.emit) { this._handles[i].attribute.emit('unsubscribe'); } } } }; Gatt.prototype.send = function(data) { debug('send: ' + data.toString('hex')); this._aclStream.write(ATT_CID, data); }; Gatt.prototype.errorResponse = function(opcode, handle, status) { var buf = new Buffer(5); buf.writeUInt8(ATT_OP_ERROR, 0); buf.writeUInt8(opcode, 1); buf.writeUInt16LE(handle, 2); buf.writeUInt8(status, 4); return buf; }; Gatt.prototype.handleRequest = function(request) { debug('handing request: ' + request.toString('hex')); var requestType = request[0]; var response = null; switch(requestType) { case ATT_OP_MTU_REQ: response = this.handleMtuRequest(request); break; case ATT_OP_FIND_INFO_REQ: response = this.handleFindInfoRequest(request); break; case ATT_OP_FIND_BY_TYPE_REQ: response = this.handleFindByTypeRequest(request); break; case ATT_OP_READ_BY_TYPE_REQ: response = this.handleReadByTypeRequest(request); break; case ATT_OP_READ_REQ: case ATT_OP_READ_BLOB_REQ: response = this.handleReadOrReadBlobRequest(request); break; case ATT_OP_READ_BY_GROUP_REQ: response = this.handleReadByGroupRequest(request); break; case ATT_OP_WRITE_REQ: case ATT_OP_WRITE_CMD: response = this.handleWriteRequestOrCommand(request); break; case ATT_OP_PREP_WRITE_REQ: response = this.handlePrepareWriteRequest(request); break; case ATT_OP_EXEC_WRITE_REQ: response = this.handleExecuteWriteRequest(request); break; case ATT_OP_HANDLE_CNF: response = this.handleConfirmation(request); break; default: case ATT_OP_READ_MULTI_REQ: case ATT_OP_SIGNED_WRITE_CMD: response = this.errorResponse(requestType, 0x0000, ATT_ECODE_REQ_NOT_SUPP); break; } if (response) { debug('response: ' + response.toString('hex')); this.send(response); } }; Gatt.prototype.handleMtuRequest = function(request) { var mtu = request.readUInt16LE(1); if (mtu < 23) { mtu = 23; } else if (mtu > this.maxMtu) { mtu = this.maxMtu; } this._mtu = mtu; this.emit('mtuChange', this._mtu); var response = new Buffer(3); response.writeUInt8(ATT_OP_MTU_RESP, 0); response.writeUInt16LE(mtu, 1); return response; }; Gatt.prototype.handleFindInfoRequest = function(request) { var response = null; var startHandle = request.readUInt16LE(1); var endHandle = request.readUInt16LE(3); var infos = []; var uuid = null; var i; for (i = startHandle; i <= endHandle; i++) { var handle = this._handles[i]; if (!handle) { break; } uuid = null; if ('service' === handle.type) { uuid = '2800'; } else if ('includedService' === handle.type) { uuid = '2802'; } else if ('characteristic' === handle.type) { uuid = '2803'; } else if ('characteristicValue' === handle.type) { uuid = this._handles[i - 1].uuid; } else if ('descriptor' === handle.type) { uuid = handle.uuid; } if (uuid) { infos.push({ handle: i, uuid: uuid }); } } if (infos.length) { var uuidSize = infos[0].uuid.length / 2; var numInfo = 1; for (i = 1; i < infos.length; i++) { if (infos[0].uuid.length !== infos[i].uuid.length) { break; } numInfo++; } var lengthPerInfo = (uuidSize === 2) ? 4 : 18; var maxInfo = Math.floor((this._mtu - 2) / lengthPerInfo); numInfo = Math.min(numInfo, maxInfo); response = new Buffer(2 + numInfo * lengthPerInfo); response[0] = ATT_OP_FIND_INFO_RESP; response[1] = (uuidSize === 2) ? 0x01 : 0x2; for (i = 0; i < numInfo; i++) { var info = infos[i]; response.writeUInt16LE(info.handle, 2 + i * lengthPerInfo); uuid = new Buffer(info.uuid.match(/.{1,2}/g).reverse().join(''), 'hex'); for (var j = 0; j < uuid.length; j++) { response[2 + i * lengthPerInfo + 2 + j] = uuid[j]; } } } else { response = this.errorResponse(ATT_OP_FIND_INFO_REQ, startHandle, ATT_ECODE_ATTR_NOT_FOUND); } return response; }; Gatt.prototype.handleFindByTypeRequest = function(request) { var response = null; var startHandle = request.readUInt16LE(1); var endHandle = request.readUInt16LE(3); var uuid = request.slice(5, 7).toString('hex').match(/.{1,2}/g).reverse().join(''); var value = request.slice(7).toString('hex').match(/.{1,2}/g).reverse().join(''); var handles = []; var handle; for (var i = startHandle; i <= endHandle; i++) { handle = this._handles[i]; if (!handle) { break; } if ('2800' === uuid && handle.type === 'service' && handle.uuid === value) { handles.push({ start: handle.startHandle, end: handle.endHandle }); } } if (handles.length) { var lengthPerHandle = 4; var numHandles = handles.length; var maxHandles = Math.floor((this._mtu - 1) / lengthPerHandle); numHandles = Math.min(numHandles, maxHandles); response = new Buffer(1 + numHandles * lengthPerHandle); response[0] = ATT_OP_FIND_BY_TYPE_RESP; for (i = 0; i < numHandles; i++) { handle = handles[i]; response.writeUInt16LE(handle.start, 1 + i * lengthPerHandle); response.writeUInt16LE(handle.end, 1 + i * lengthPerHandle + 2); } } else { response = this.errorResponse(ATT_OP_FIND_BY_TYPE_REQ, startHandle, ATT_ECODE_ATTR_NOT_FOUND); } return response; }; Gatt.prototype.handleReadByGroupRequest = function(request) { var response = null; var startHandle = request.readUInt16LE(1); var endHandle = request.readUInt16LE(3); var uuid = request.slice(5).toString('hex').match(/.{1,2}/g).reverse().join(''); debug('read by group: startHandle = 0x' + startHandle.toString(16) + ', endHandle = 0x' + endHandle.toString(16) + ', uuid = 0x' + uuid.toString(16)); if ('2800' === uuid || '2802' === uuid) { var services = []; var type = ('2800' === uuid) ? 'service' : 'includedService'; var i; for (i = startHandle; i <= endHandle; i++) { var handle = this._handles[i]; if (!handle) { break; } if (handle.type === type) { services.push(handle); } } if (services.length) { var uuidSize = services[0].uuid.length / 2; var numServices = 1; for (i = 1; i < services.length; i++) { if (services[0].uuid.length !== services[i].uuid.length) { break; } numServices++; } var lengthPerService = (uuidSize === 2) ? 6 : 20; var maxServices = Math.floor((this._mtu - 2) / lengthPerService); numServices = Math.min(numServices, maxServices); response = new Buffer(2 + numServices * lengthPerService); response[0] = ATT_OP_READ_BY_GROUP_RESP; response[1] = lengthPerService; for (i = 0; i < numServices; i++) { var service = services[i]; response.writeUInt16LE(service.startHandle, 2 + i * lengthPerService); response.writeUInt16LE(service.endHandle, 2 + i * lengthPerService + 2); var serviceUuid = new Buffer(service.uuid.match(/.{1,2}/g).reverse().join(''), 'hex'); for (var j = 0; j < serviceUuid.length; j++) { response[2 + i * lengthPerService + 4 + j] = serviceUuid[j]; } } } else { response = this.errorResponse(ATT_OP_READ_BY_GROUP_REQ, startHandle, ATT_ECODE_ATTR_NOT_FOUND); } } else { response = this.errorResponse(ATT_OP_READ_BY_GROUP_REQ, startHandle, ATT_ECODE_UNSUPP_GRP_TYPE); } return response; }; Gatt.prototype.handleReadByTypeRequest = function(request) { var response = null; var requestType = request[0]; var startHandle = request.readUInt16LE(1); var endHandle = request.readUInt16LE(3); var uuid = request.slice(5).toString('hex').match(/.{1,2}/g).reverse().join(''); var i; var handle; debug('read by type: startHandle = 0x' + startHandle.toString(16) + ', endHandle = 0x' + endHandle.toString(16) + ', uuid = 0x' + uuid.toString(16)); if ('2803' === uuid) { var characteristics = []; for (i = startHandle; i <= endHandle; i++) { handle = this._handles[i]; if (!handle) { break; } if (handle.type === 'characteristic') { characteristics.push(handle); } } if (characteristics.length) { var uuidSize = characteristics[0].uuid.length / 2; var numCharacteristics = 1; for (i = 1; i < characteristics.length; i++) { if (characteristics[0].uuid.length !== characteristics[i].uuid.length) { break; } numCharacteristics++; } var lengthPerCharacteristic = (uuidSize === 2) ? 7 : 21; var maxCharacteristics = Math.floor((this._mtu - 2) / lengthPerCharacteristic); numCharacteristics = Math.min(numCharacteristics, maxCharacteristics); response = new Buffer(2 + numCharacteristics * lengthPerCharacteristic); response[0] = ATT_OP_READ_BY_TYPE_RESP; response[1] = lengthPerCharacteristic; for (i = 0; i < numCharacteristics; i++) { var characteristic = characteristics[i]; response.writeUInt16LE(characteristic.startHandle, 2 + i * lengthPerCharacteristic); response.writeUInt8(characteristic.properties, 2 + i * lengthPerCharacteristic + 2); response.writeUInt16LE(characteristic.valueHandle, 2 + i * lengthPerCharacteristic + 3); var characteristicUuid = new Buffer(characteristic.uuid.match(/.{1,2}/g).reverse().join(''), 'hex'); for (var j = 0; j < characteristicUuid.length; j++) { response[2 + i * lengthPerCharacteristic + 5 + j] = characteristicUuid[j]; } } } else { response = this.errorResponse(ATT_OP_READ_BY_TYPE_REQ, startHandle, ATT_ECODE_ATTR_NOT_FOUND); } } else { var handleAttribute = null; var valueHandle = null; var secure = false; for (i = startHandle; i <= endHandle; i++) { handle = this._handles[i]; if (!handle) { break; } if (handle.type === 'characteristic' && handle.uuid === uuid) { handleAttribute = handle.attribute; valueHandle = handle.valueHandle; secure = handle.secure & 0x02; break; } else if (handle.type === 'descriptor' && handle.uuid === uuid) { valueHandle = i; secure = handle.secure & 0x02; break; } } if (secure && !this._aclStream.encrypted) { response = this.errorResponse(ATT_OP_READ_BY_TYPE_REQ, startHandle, ATT_ECODE_AUTHENTICATION); } else if (valueHandle) { var callback = (function(valueHandle) { return function(result, data) { var callbackResponse = null; if (ATT_ECODE_SUCCESS === result) { var dataLength = Math.min(data.length, this._mtu - 4); callbackResponse = new Buffer(4 + dataLength); callbackResponse[0] = ATT_OP_READ_BY_TYPE_RESP; callbackResponse[1] = dataLength + 2; callbackResponse.writeUInt16LE(valueHandle, 2); for (i = 0; i < dataLength; i++) { callbackResponse[4 + i] = data[i]; } } else { callbackResponse = this.errorResponse(requestType, valueHandle, result); } debug('read by type response: ' + callbackResponse.toString('hex')); this.send(callbackResponse); }.bind(this); }.bind(this))(valueHandle); var data = this._handles[valueHandle].value; if (data) { callback(ATT_ECODE_SUCCESS, data); } else if (handleAttribute) { handleAttribute.emit('readRequest', 0, callback); } else { callback(ATT_ECODE_UNLIKELY); } } else { response = this.errorResponse(ATT_OP_READ_BY_TYPE_REQ, startHandle, ATT_ECODE_ATTR_NOT_FOUND); } } return response; }; Gatt.prototype.handleReadOrReadBlobRequest = function(request) { var response = null; var requestType = request[0]; var valueHandle = request.readUInt16LE(1); var offset = (requestType === ATT_OP_READ_BLOB_REQ) ? request.readUInt16LE(3) : 0; var handle = this._handles[valueHandle]; var i; if (handle) { var result = null; var data = null; var handleType = handle.type; var callback = (function(requestType, valueHandle) { return function(result, data) { var callbackResponse = null; if (ATT_ECODE_SUCCESS === result) { var dataLength = Math.min(data.length, this._mtu - 1); callbackResponse = new Buffer(1 + dataLength); callbackResponse[0] = (requestType === ATT_OP_READ_BLOB_REQ) ? ATT_OP_READ_BLOB_RESP : ATT_OP_READ_RESP; for (i = 0; i < dataLength; i++) { callbackResponse[1 + i] = data[i]; } } else { callbackResponse = this.errorResponse(requestType, valueHandle, result); } debug('read response: ' + callbackResponse.toString('hex')); this.send(callbackResponse); }.bind(this); }.bind(this))(requestType, valueHandle); if (handleType === 'service' || handleType === 'includedService') { result = ATT_ECODE_SUCCESS; data = new Buffer(handle.uuid.match(/.{1,2}/g).reverse().join(''), 'hex'); } else if (handleType === 'characteristic') { var uuid = new Buffer(handle.uuid.match(/.{1,2}/g).reverse().join(''), 'hex'); result = ATT_ECODE_SUCCESS; data = new Buffer(3 + uuid.length); data.writeUInt8(handle.properties, 0); data.writeUInt16LE(handle.valueHandle, 1); for (i = 0; i < uuid.length; i++) { data[i + 3] = uuid[i]; } } else if (handleType === 'characteristicValue' || handleType === 'descriptor') { var handleProperties = handle.properties; var handleSecure = handle.secure; var handleAttribute = handle.attribute; if (handleType === 'characteristicValue') { handleProperties = this._handles[valueHandle - 1].properties; handleSecure = this._handles[valueHandle - 1].secure; handleAttribute = this._handles[valueHandle - 1].attribute; } if (handleProperties & 0x02) { if (handleSecure & 0x02 && !this._aclStream.encrypted) { result = ATT_ECODE_AUTHENTICATION; } else { data = handle.value; if (data) { result = ATT_ECODE_SUCCESS; } else { handleAttribute.emit('readRequest', offset, callback); } } } else { result = ATT_ECODE_READ_NOT_PERM; // non-readable } } if (data && typeof data === 'string') { data = new Buffer(data); } if (result === ATT_ECODE_SUCCESS && data && offset) { if (data.length < offset) { result = ATT_ECODE_INVALID_OFFSET; data = null; } else { data = data.slice(offset); } } if (result !== null) { callback(result, data); } } else { response = this.errorResponse(requestType, valueHandle, ATT_ECODE_INVALID_HANDLE); } return response; }; Gatt.prototype.handleWriteRequestOrCommand = function(request) { var response = null; var requestType = request[0]; var withoutResponse = (requestType === ATT_OP_WRITE_CMD); var valueHandle = request.readUInt16LE(1); var data = request.slice(3); var offset = 0; var handle = this._handles[valueHandle]; if (handle) { if (handle.type === 'characteristicValue') { handle = this._handles[valueHandle - 1]; } var handleProperties = handle.properties; var handleSecure = handle.secure; if (handleProperties && (withoutResponse ? (handleProperties & 0x04) : (handleProperties & 0x08))) { var callback = (function(requestType, valueHandle, withoutResponse) { return function(result) { if (!withoutResponse) { var callbackResponse = null; if (ATT_ECODE_SUCCESS === result) { callbackResponse = new Buffer([ATT_OP_WRITE_RESP]); } else { callbackResponse = this.errorResponse(requestType, valueHandle, result); } debug('write response: ' + callbackResponse.toString('hex')); this.send(callbackResponse); } }.bind(this); }.bind(this))(requestType, valueHandle, withoutResponse); if (handleSecure & (withoutResponse ? 0x04 : 0x08) && !this._aclStream.encrypted) { response = this.errorResponse(requestType, valueHandle, ATT_ECODE_AUTHENTICATION); } else if (handle.type === 'descriptor' || handle.uuid === '2902') { var result = null; if (data.length !== 2) { result = ATT_ECODE_INVAL_ATTR_VALUE_LEN; } else { var value = data.readUInt16LE(0); var handleAttribute = handle.attribute; handle.value = data; if (value & 0x0003) { var updateValueCallback = (function(valueHandle, attribute) { return function(data) { var dataLength = Math.min(data.length, this._mtu - 3); var useNotify = attribute.properties.indexOf('notify') !== -1; var useIndicate = attribute.properties.indexOf('indicate') !== -1; var i; if (useNotify) { var notifyMessage = new Buffer(3 + dataLength); notifyMessage.writeUInt8(ATT_OP_HANDLE_NOTIFY, 0); notifyMessage.writeUInt16LE(valueHandle, 1); for (i = 0; i < dataLength; i++) { notifyMessage[3 + i] = data[i]; } debug('notify message: ' + notifyMessage.toString('hex')); this.send(notifyMessage); attribute.emit('notify'); } else if (useIndicate) { var indicateMessage = new Buffer(3 + dataLength); indicateMessage.writeUInt8(ATT_OP_HANDLE_IND, 0); indicateMessage.writeUInt16LE(valueHandle, 1); for (i = 0; i < dataLength; i++) { indicateMessage[3 + i] = data[i]; } this._lastIndicatedAttribute = attribute; debug('indicate message: ' + indicateMessage.toString('hex')); this.send(indicateMessage); } }.bind(this); }.bind(this))(valueHandle - 1, handleAttribute); if (handleAttribute.emit) { handleAttribute.emit('subscribe', this._mtu - 3, updateValueCallback); } } else { handleAttribute.emit('unsubscribe'); } result = ATT_ECODE_SUCCESS; } callback(result); } else { handle.attribute.emit('writeRequest', data, offset, withoutResponse, callback); } } else { response = this.errorResponse(requestType, valueHandle, ATT_ECODE_WRITE_NOT_PERM); } } else { response = this.errorResponse(requestType, valueHandle, ATT_ECODE_INVALID_HANDLE); } return response; }; Gatt.prototype.handlePrepareWriteRequest = function(request) { var response = null; var requestType = request[0]; var valueHandle = request.readUInt16LE(1); var offset = request.readUInt16LE(3); var data = request.slice(5); var handle = this._handles[valueHandle]; if (handle) { if (handle.type === 'characteristicValue') { handle = this._handles[valueHandle - 1]; var handleProperties = handle.properties; var handleSecure = handle.secure; if (handleProperties && (handleProperties & 0x08)) { if ((handleSecure & 0x08) && !this._aclStream.encrypted) { response = this.errorResponse(requestType, valueHandle, ATT_ECODE_AUTHENTICATION); } else if (this._preparedWriteRequest) { if (this._preparedWriteRequest.handle !== handle) { response = this.errorResponse(requestType, valueHandle, ATT_ECODE_UNLIKELY); } else if (offset === (this._preparedWriteRequest.offset + this._preparedWriteRequest.data.length)) { this._preparedWriteRequest.data = Buffer.concat([ this._preparedWriteRequest.data, data ]); response = new Buffer(request.length); request.copy(response); response[0] = ATT_OP_PREP_WRITE_RESP; } else { response = this.errorResponse(requestType, valueHandle, ATT_ECODE_INVALID_OFFSET); } } else { this._preparedWriteRequest = { handle: handle, valueHandle: valueHandle, offset: offset, data: data }; response = new Buffer(request.length); request.copy(response); response[0] = ATT_OP_PREP_WRITE_RESP; } } else { response = this.errorResponse(requestType, valueHandle, ATT_ECODE_WRITE_NOT_PERM); } } else { response = this.errorResponse(requestType, valueHandle, ATT_ECODE_ATTR_NOT_LONG); } } else { response = this.errorResponse(requestType, valueHandle, ATT_ECODE_INVALID_HANDLE); } return response; }; Gatt.prototype.handleExecuteWriteRequest = function(request) { var response = null; var requestType = request[0]; var flag = request[1]; if (this._preparedWriteRequest) { var valueHandle = this._preparedWriteRequest.valueHandle; if (flag === 0x00) { response = new Buffer([ATT_OP_EXEC_WRITE_RESP]); } else if (flag === 0x01) { var callback = (function(requestType, valueHandle) { return function(result) { var callbackResponse = null; if (ATT_ECODE_SUCCESS === result) { callbackResponse = new Buffer([ATT_OP_EXEC_WRITE_RESP]); } else { callbackResponse = this.errorResponse(requestType, valueHandle, result); } debug('execute write response: ' + callbackResponse.toString('hex')); this.send(callbackResponse); }.bind(this); }.bind(this))(requestType, this._preparedWriteRequest.valueHandle); this._preparedWriteRequest.handle.attribute.emit('writeRequest', this._preparedWriteRequest.data, this._preparedWriteRequest.offset, false, callback); } else { response = this.errorResponse(requestType, 0x0000, ATT_ECODE_UNLIKELY); } this._preparedWriteRequest = null; } else { response = this.errorResponse(requestType, 0x0000, ATT_ECODE_UNLIKELY); } return response; }; Gatt.prototype.handleConfirmation = function(request) { if (this._lastIndicatedAttribute) { if (this._lastIndicatedAttribute.emit) { this._lastIndicatedAttribute.emit('indicate'); } this._lastIndicatedAttribute = null; } }; module.exports = Gatt;
{ "content_hash": "fe4f3208ab666ce679b6dcbf357f49d5", "timestamp": "", "source": "github", "line_count": 1045, "max_line_length": 156, "avg_line_length": 29.87177033492823, "alnum_prop": 0.5912032291132753, "repo_name": "sandeepmistry/bleno", "id": "818e217699b0ae1283caef242bb9da6e97e14ab7", "size": "31216", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/hci-socket/gatt.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "120969" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width" /> <link rel="shortcut icon" type="image/x-icon" href="../../../../../../favicon.ico" /> <title>com.google.android.gms.security | Android Developers</title> <!-- STYLESHEETS --> <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto+Condensed"> <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:light,regular,medium,thin,italic,mediumitalic,bold" title="roboto"> <link href="../../../../../../assets/css/default.css?v=2" rel="stylesheet" type="text/css"> <!-- FULLSCREEN STYLESHEET --> <link href="../../../../../../assets/css/fullscreen.css" rel="stylesheet" class="fullscreen" type="text/css"> <!-- JAVASCRIPT --> <script src="http://www.google.com/jsapi" type="text/javascript"></script> <script src="../../../../../../assets/js/android_3p-bundle.js" type="text/javascript"></script> <script type="text/javascript"> var toRoot = "../../../../../../"; var metaTags = []; var devsite = false; </script> <script src="../../../../../../assets/js/docs.js?v=2" type="text/javascript"></script> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-5831155-1', 'android.com'); ga('create', 'UA-49880327-2', 'android.com', {'name': 'universal'}); // New tracker); ga('send', 'pageview'); ga('universal.send', 'pageview'); // Send page view for new tracker. </script> </head> <body class="gc-documentation develop"> <div id="doc-api-level" class="" style="display:none"></div> <a name="top"></a> <a name="top"></a> <!-- Header --> <div id="header-wrapper"> <div id="header"> <div class="wrap" id="header-wrap"> <div class="col-3 logo"> <a href="../../../../../../index.html"> <img src="../../../../../../assets/images/dac_logo.png" srcset="../../../../../../assets/images/dac_logo@2x.png 2x" width="123" height="25" alt="Android Developers" /> </a> <div class="btn-quicknav" id="btn-quicknav"> <a href="#" class="arrow-inactive">Quicknav</a> <a href="#" class="arrow-active">Quicknav</a> </div> </div> <ul class="nav-x col-9"> <li class="design"> <a href="../../../../../../design/index.html" zh-tw-lang="設計" zh-cn-lang="设计" ru-lang="Проектирование" ko-lang="디자인" ja-lang="設計" es-lang="Diseñar" >Design</a></li> <li class="develop"><a href="../../../../../../develop/index.html" zh-tw-lang="開發" zh-cn-lang="开发" ru-lang="Разработка" ko-lang="개발" ja-lang="開発" es-lang="Desarrollar" >Develop</a></li> <li class="distribute last"><a href="../../../../../../distribute/googleplay/index.html" zh-tw-lang="發佈" zh-cn-lang="分发" ru-lang="Распространение" ko-lang="배포" ja-lang="配布" es-lang="Distribuir" >Distribute</a></li> </ul> <div class="menu-container"> <div class="moremenu"> <div id="more-btn"></div> </div> <div class="morehover" id="moremenu"> <div class="top"></div> <div class="mid"> <div class="header">Links</div> <ul> <li><a href="https://play.google.com/apps/publish/" target="_googleplay">Google Play Developer Console</a></li> <li><a href="http://android-developers.blogspot.com/">Android Developers Blog</a></li> <li><a href="../../../../../../about/index.html">About Android</a></li> </ul> <div class="header">Android Sites</div> <ul> <li><a href="http://www.android.com">Android.com</a></li> <li class="active"><a>Android Developers</a></li> <li><a href="http://source.android.com">Android Open Source Project</a></li> </ul> <br class="clearfix" /> </div><!-- end 'mid' --> <div class="bottom"></div> </div><!-- end 'moremenu' --> <div class="search" id="search-container"> <div class="search-inner"> <div id="search-btn"></div> <div class="left"></div> <form onsubmit="return submit_search()"> <input id="search_autocomplete" type="text" value="" autocomplete="off" name="q" onfocus="search_focus_changed(this, true)" onblur="search_focus_changed(this, false)" onkeydown="return search_changed(event, true, '../../../../../../')" onkeyup="return search_changed(event, false, '../../../../../../')" /> </form> <div class="right"></div> <a class="close hide">close</a> <div class="left"></div> <div class="right"></div> </div><!-- end search-inner --> </div><!-- end search-container --> <div class="search_filtered_wrapper reference"> <div class="suggest-card reference no-display"> <ul class="search_filtered"> </ul> </div> </div> <div class="search_filtered_wrapper docs"> <div class="suggest-card dummy no-display">&nbsp;</div> <div class="suggest-card develop no-display"> <ul class="search_filtered"> </ul> <div class="child-card guides no-display"> </div> <div class="child-card training no-display"> </div> <div class="child-card samples no-display"> </div> </div> <div class="suggest-card design no-display"> <ul class="search_filtered"> </ul> </div> <div class="suggest-card distribute no-display"> <ul class="search_filtered"> </ul> </div> </div> </div><!-- end menu-container (search and menu widget) --> <!-- Expanded quicknav --> <div id="quicknav" class="col-13"> <ul> <li class="about"> <ul> <li><a href="../../../../../../about/index.html">About</a></li> <li><a href="../../../../../../wear/index.html">Wear</a></li> <li><a href="../../../../../../tv/index.html">TV</a></li> <li><a href="../../../../../../auto/index.html">Auto</a></li> </ul> </li> <li class="design"> <ul> <li><a href="../../../../../../design/index.html">Get Started</a></li> <li><a href="../../../../../../design/devices.html">Devices</a></li> <li><a href="../../../../../../design/style/index.html">Style</a></li> <li><a href="../../../../../../design/patterns/index.html">Patterns</a></li> <li><a href="../../../../../../design/building-blocks/index.html">Building Blocks</a></li> <li><a href="../../../../../../design/downloads/index.html">Downloads</a></li> <li><a href="../../../../../../design/videos/index.html">Videos</a></li> </ul> </li> <li class="develop"> <ul> <li><a href="../../../../../../training/index.html" zh-tw-lang="訓練課程" zh-cn-lang="培训" ru-lang="Курсы" ko-lang="교육" ja-lang="トレーニング" es-lang="Capacitación" >Training</a></li> <li><a href="../../../../../../guide/index.html" zh-tw-lang="API 指南" zh-cn-lang="API 指南" ru-lang="Руководства по API" ko-lang="API 가이드" ja-lang="API ガイド" es-lang="Guías de la API" >API Guides</a></li> <li><a href="../../../../../../reference/packages.html" zh-tw-lang="參考資源" zh-cn-lang="参考" ru-lang="Справочник" ko-lang="참조문서" ja-lang="リファレンス" es-lang="Referencia" >Reference</a></li> <li><a href="../../../../../../sdk/index.html" zh-tw-lang="相關工具" zh-cn-lang="工具" ru-lang="Инструменты" ko-lang="도구" ja-lang="ツール" es-lang="Herramientas" >Tools</a> </li> <li><a href="../../../../../../google/index.html">Google Services</a> </li> </ul> </li> <li class="distribute last"> <ul> <li><a href="../../../../../../distribute/googleplay/index.html">Google Play</a></li> <li><a href="../../../../../../distribute/essentials/index.html">Essentials</a></li> <li><a href="../../../../../../distribute/users/index.html">Get Users</a></li> <li><a href="../../../../../../distribute/engage/index.html">Engage &amp; Retain</a></li> <li><a href="../../../../../../distribute/monetize/index.html">Monetize</a></li> <li><a href="../../../../../../distribute/tools/index.html">Tools &amp; Reference</a></li> <li><a href="../../../../../../distribute/stories/index.html">Developer Stories</a></li> </ul> </li> </ul> </div><!-- /Expanded quicknav --> </div><!-- end header-wrap.wrap --> </div><!-- end header --> <!-- Secondary x-nav --> <div id="nav-x"> <div class="wrap"> <ul class="nav-x col-9 develop" style="width:100%"> <li class="training"><a href="../../../../../../training/index.html" zh-tw-lang="訓練課程" zh-cn-lang="培训" ru-lang="Курсы" ko-lang="교육" ja-lang="トレーニング" es-lang="Capacitación" >Training</a></li> <li class="guide"><a href="../../../../../../guide/index.html" zh-tw-lang="API 指南" zh-cn-lang="API 指南" ru-lang="Руководства по API" ko-lang="API 가이드" ja-lang="API ガイド" es-lang="Guías de la API" >API Guides</a></li> <li class="reference"><a href="../../../../../../reference/packages.html" zh-tw-lang="參考資源" zh-cn-lang="参考" ru-lang="Справочник" ko-lang="참조문서" ja-lang="リファレンス" es-lang="Referencia" >Reference</a></li> <li class="tools"><a href="../../../../../../sdk/index.html" zh-tw-lang="相關工具" zh-cn-lang="工具" ru-lang="Инструменты" ko-lang="도구" ja-lang="ツール" es-lang="Herramientas" >Tools</a></li> <li class="google"><a href="../../../../../../google/index.html" >Google Services</a> </li> </ul> </div> </div> <!-- /Sendondary x-nav DEVELOP --> <div id="searchResults" class="wrap" style="display:none;"> <h2 id="searchTitle">Results</h2> <div id="leftSearchControl" class="search-control">Loading...</div> </div> </div> <!--end header-wrapper --> <div id="sticky-header"> <div> <a class="logo" href="#top"></a> <a class="top" href="#top"></a> <ul class="breadcrumb"> <li class="current">com.google.android.gms.security</li> </ul> </div> </div> <div class="wrap clearfix" id="body-content"> <div class="col-4" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement"> <div id="devdoc-nav"> <div id="api-nav-header"> <div id="api-level-toggle"> <label for="apiLevelCheckbox" class="disabled" title="Select your target API level to dim unavailable APIs">API level: </label> <div class="select-wrapper"> <select id="apiLevelSelector"> <!-- option elements added by buildApiLevelSelector() --> </select> </div> </div><!-- end toggle --> <div id="api-nav-title">Android APIs</div> </div><!-- end nav header --> <script> var SINCE_DATA = [ ]; buildApiLevelSelector(); </script> <div id="swapper"> <div id="nav-panels"> <div id="resize-packages-nav"> <div id="packages-nav" class="scroll-pane"> <ul> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/package-summary.html">com.google.android.gms</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/actions/package-summary.html">com.google.android.gms.actions</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/ads/package-summary.html">com.google.android.gms.ads</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/ads/doubleclick/package-summary.html">com.google.android.gms.ads.doubleclick</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/ads/identifier/package-summary.html">com.google.android.gms.ads.identifier</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/ads/mediation/package-summary.html">com.google.android.gms.ads.mediation</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/ads/mediation/admob/package-summary.html">com.google.android.gms.ads.mediation.admob</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/ads/mediation/customevent/package-summary.html">com.google.android.gms.ads.mediation.customevent</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/ads/purchase/package-summary.html">com.google.android.gms.ads.purchase</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/ads/search/package-summary.html">com.google.android.gms.ads.search</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/analytics/package-summary.html">com.google.android.gms.analytics</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/analytics/ecommerce/package-summary.html">com.google.android.gms.analytics.ecommerce</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/appindexing/package-summary.html">com.google.android.gms.appindexing</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/appstate/package-summary.html">com.google.android.gms.appstate</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/auth/package-summary.html">com.google.android.gms.auth</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/auth/api/package-summary.html">com.google.android.gms.auth.api</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/cast/package-summary.html">com.google.android.gms.cast</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/common/package-summary.html">com.google.android.gms.common</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/common/annotation/package-summary.html">com.google.android.gms.common.annotation</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/common/api/package-summary.html">com.google.android.gms.common.api</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/common/data/package-summary.html">com.google.android.gms.common.data</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/common/images/package-summary.html">com.google.android.gms.common.images</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/drive/package-summary.html">com.google.android.gms.drive</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/drive/events/package-summary.html">com.google.android.gms.drive.events</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/drive/metadata/package-summary.html">com.google.android.gms.drive.metadata</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/drive/query/package-summary.html">com.google.android.gms.drive.query</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/drive/widget/package-summary.html">com.google.android.gms.drive.widget</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/fitness/package-summary.html">com.google.android.gms.fitness</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/fitness/data/package-summary.html">com.google.android.gms.fitness.data</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/fitness/request/package-summary.html">com.google.android.gms.fitness.request</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/fitness/result/package-summary.html">com.google.android.gms.fitness.result</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/fitness/service/package-summary.html">com.google.android.gms.fitness.service</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/games/package-summary.html">com.google.android.gms.games</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/games/achievement/package-summary.html">com.google.android.gms.games.achievement</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/games/event/package-summary.html">com.google.android.gms.games.event</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/games/leaderboard/package-summary.html">com.google.android.gms.games.leaderboard</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/games/multiplayer/package-summary.html">com.google.android.gms.games.multiplayer</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/games/multiplayer/realtime/package-summary.html">com.google.android.gms.games.multiplayer.realtime</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/games/multiplayer/turnbased/package-summary.html">com.google.android.gms.games.multiplayer.turnbased</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/games/quest/package-summary.html">com.google.android.gms.games.quest</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/games/request/package-summary.html">com.google.android.gms.games.request</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/games/snapshot/package-summary.html">com.google.android.gms.games.snapshot</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/gcm/package-summary.html">com.google.android.gms.gcm</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/identity/intents/package-summary.html">com.google.android.gms.identity.intents</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/identity/intents/model/package-summary.html">com.google.android.gms.identity.intents.model</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/location/package-summary.html">com.google.android.gms.location</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/maps/package-summary.html">com.google.android.gms.maps</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/maps/model/package-summary.html">com.google.android.gms.maps.model</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/panorama/package-summary.html">com.google.android.gms.panorama</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/plus/package-summary.html">com.google.android.gms.plus</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/plus/model/moments/package-summary.html">com.google.android.gms.plus.model.moments</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/plus/model/people/package-summary.html">com.google.android.gms.plus.model.people</a></li> <li class="selected api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/security/package-summary.html">com.google.android.gms.security</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/tagmanager/package-summary.html">com.google.android.gms.tagmanager</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/wallet/package-summary.html">com.google.android.gms.wallet</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/wallet/fragment/package-summary.html">com.google.android.gms.wallet.fragment</a></li> <li class="api apilevel-"> <a href="../../../../../../reference/com/google/android/gms/wearable/package-summary.html">com.google.android.gms.wearable</a></li> </ul><br/> </div> <!-- end packages-nav --> </div> <!-- end resize-packages --> <div id="classes-nav" class="scroll-pane"> <ul> <li><h2>Interfaces</h2> <ul> <li class="api apilevel-"><a href="../../../../../../reference/com/google/android/gms/security/ProviderInstaller.ProviderInstallListener.html">ProviderInstaller.ProviderInstallListener</a></li> </ul> </li> <li><h2>Classes</h2> <ul> <li class="api apilevel-"><a href="../../../../../../reference/com/google/android/gms/security/ProviderInstaller.html">ProviderInstaller</a></li> </ul> </li> </ul><br/> </div><!-- end classes --> </div><!-- end nav-panels --> <div id="nav-tree" style="display:none" class="scroll-pane"> <div id="tree-list"></div> </div><!-- end nav-tree --> </div><!-- end swapper --> <div id="nav-swap"> <a class="fullscreen">fullscreen</a> <a href='#' onclick='swapNav();return false;'><span id='tree-link'>Use Tree Navigation</span><span id='panel-link' style='display:none'>Use Panel Navigation</span></a> </div> </div> <!-- end devdoc-nav --> </div> <!-- end side-nav --> <script type="text/javascript"> // init fullscreen based on user pref var fullscreen = readCookie("fullscreen"); if (fullscreen != 0) { if (fullscreen == "false") { toggleFullscreen(false); } else { toggleFullscreen(true); } } // init nav version for mobile if (isMobile) { swapNav(); // tree view should be used on mobile $('#nav-swap').hide(); } else { chooseDefaultNav(); if ($("#nav-tree").is(':visible')) { init_default_navtree("../../../../../../"); } } // scroll the selected page into view $(document).ready(function() { scrollIntoView("packages-nav"); scrollIntoView("classes-nav"); }); </script> <div class="col-12" id="doc-col"> <div id="api-info-block"> <div class="api-level"> </div> </div> <div id="jd-header"> package <h1>com.google.android.gms.security</h1> </div><!-- end header --> <div id="naMessage"></div> <div id="jd-content" class="api apilevel-"> <h2>Interfaces</h2> <div class="jd-sumtable"> <table class="jd-sumtable-expando"> <tr class="alt-color api apilevel-" > <td class="jd-linkcol"><a href="../../../../../../reference/com/google/android/gms/security/ProviderInstaller.ProviderInstallListener.html">ProviderInstaller.ProviderInstallListener</a></td> <td class="jd-descrcol" width="100%">Callback for notification of the result of provider installation.&nbsp;</td> </tr> </table> </div> <h2>Classes</h2> <div class="jd-sumtable"> <table class="jd-sumtable-expando"> <tr class="alt-color api apilevel-" > <td class="jd-linkcol"><a href="../../../../../../reference/com/google/android/gms/security/ProviderInstaller.html">ProviderInstaller</a></td> <td class="jd-descrcol" width="100%">A utility class for installing a dynamically updatable <code><a href="http://developer.android.com/reference/java/security/Provider.html">Provider</a></code> to replace the platform default provider.&nbsp;</td> </tr> </table> </div> <div id="footer" class="wrap" > <div id="copyright"> Except as noted, this content is licensed under <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache 2.0</a>. For details and restrictions, see the <a href="../../../../../../license.html"> Content License</a>. </div> <div id="build_info"> Android GmsCore 1501030&nbsp;r &mdash; <script src="../../../../../../timestamp.js" type="text/javascript"></script> <script>document.write(BUILD_TIMESTAMP)</script> </div> <div id="footerlinks"> <p> <a href="../../../../../../about/index.html">About Android</a>&nbsp;&nbsp;|&nbsp; <a href="../../../../../../legal.html">Legal</a>&nbsp;&nbsp;|&nbsp; <a href="../../../../../../support.html">Support</a> </p> </div> </div> <!-- end footer --> </div><!-- end jd-content --> </div><!-- doc-content --> </div> <!-- end body-content --> </body> </html>
{ "content_hash": "5a553ff99d3de8e5d45103b4ce069d3b", "timestamp": "", "source": "github", "line_count": 731, "max_line_length": 219, "avg_line_length": 37.65663474692202, "alnum_prop": 0.5477531151233335, "repo_name": "gudnam/bringluck", "id": "02907e384ae7dcc13ea28a3fd6330f07d6b3e4d9", "size": "27903", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "google_play_services/docs/reference/com/google/android/gms/security/package-summary.html", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "236794" }, { "name": "HTML", "bytes": "37081177" }, { "name": "Java", "bytes": "974734" }, { "name": "JavaScript", "bytes": "604192" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <resources> <!-- From: file:/C:/Users/Centurion/AndroidStudioProjects/generalsbuzz/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/19.1.0/res/values-uk/values.xml --> <eat-comment/> <string msgid="4600421777120114993" name="abc_action_bar_home_description">"Перейти на головний"</string> <string msgid="1594238315039666878" name="abc_action_bar_up_description">"Перейти вгору"</string> <string msgid="3588849162933574182" name="abc_action_menu_overflow_description">"Інші опції"</string> <string msgid="4076576682505996667" name="abc_action_mode_done">"Готово"</string> <string msgid="7468859129482906941" name="abc_activity_chooser_view_see_all">"Переглянути всі"</string> <string msgid="2031811694353399454" name="abc_activitychooserview_choose_application">"Вибрати програму"</string> <string msgid="3691816814315814921" name="abc_searchview_description_clear">"Очистити запит"</string> <string msgid="2550479030709304392" name="abc_searchview_description_query">"Пошуковий запит"</string> <string msgid="8264924765203268293" name="abc_searchview_description_search">"Пошук"</string> <string msgid="8928215447528550784" name="abc_searchview_description_submit">"Надіслати запит"</string> <string msgid="893419373245838918" name="abc_searchview_description_voice">"Голосовий пошук"</string> <string msgid="3421042268587513524" name="abc_shareactionprovider_share_with">"Надіслати через"</string> <string msgid="7165123711973476752" name="abc_shareactionprovider_share_with_application">"Надіслати через %s"</string> </resources>
{ "content_hash": "b5dc691e1c5704d87d51fcd1e94ce18f", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 180, "avg_line_length": 91.72222222222223, "alnum_prop": 0.7637795275590551, "repo_name": "kkworden/generalsbuzz", "id": "772d65bd8ff2baa9093f09578846e3ae0a805ae9", "size": "1812", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "build/intermediates/res/debug/values-uk/values.xml", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3223" }, { "name": "HTML", "bytes": "903" }, { "name": "Java", "bytes": "435485" } ], "symlink_target": "" }
""" State Space Model Author: Chad Fulton License: Simplified-BSD """ from __future__ import division, absolute_import, print_function from statsmodels.compat.python import long import numpy as np import pandas as pd from scipy.stats import norm from .simulation_smoother import SimulationSmoother from .kalman_smoother import KalmanSmoother, SmootherResults from .kalman_filter import (KalmanFilter, FilterResults, INVERT_UNIVARIATE, SOLVE_LU) import statsmodels.tsa.base.tsa_model as tsbase import statsmodels.base.wrapper as wrap from statsmodels.tools.numdiff import (_get_epsilon, approx_hess_cs, approx_fprime_cs, approx_fprime) from statsmodels.tools.decorators import cache_readonly, resettable_cache from statsmodels.tools.eval_measures import aic, bic, hqic from statsmodels.tools.tools import pinv_extended, Bunch from statsmodels.tools.sm_exceptions import PrecisionWarning import statsmodels.genmod._prediction as pred from statsmodels.genmod.families.links import identity import warnings class MLEModel(tsbase.TimeSeriesModel): r""" State space model for maximum likelihood estimation Parameters ---------- endog : array_like The observed time-series process :math:`y` k_states : int The dimension of the unobserved state process. exog : array_like, optional Array of exogenous regressors, shaped nobs x k. Default is no exogenous regressors. dates : array-like of datetime, optional An array-like object of datetime objects. If a Pandas object is given for endog, it is assumed to have a DateIndex. freq : str, optional The frequency of the time-series. A Pandas offset or 'B', 'D', 'W', 'M', 'A', or 'Q'. This is optional if dates are given. **kwargs Keyword arguments may be used to provide default values for state space matrices or for Kalman filtering options. See `Representation`, and `KalmanFilter` for more details. Attributes ---------- ssm : KalmanFilter Underlying state space representation. Notes ----- This class wraps the state space model with Kalman filtering to add in functionality for maximum likelihood estimation. In particular, it adds the concept of updating the state space representation based on a defined set of parameters, through the `update` method or `updater` attribute (see below for more details on which to use when), and it adds a `fit` method which uses a numerical optimizer to select the parameters that maximize the likelihood of the model. The `start_params` `update` method must be overridden in the child class (and the `transform` and `untransform` methods, if needed). See Also -------- MLEResults statsmodels.tsa.statespace.kalman_filter.KalmanFilter statsmodels.tsa.statespace.representation.Representation """ def __init__(self, endog, k_states, exog=None, dates=None, freq=None, **kwargs): # Initialize the model base super(MLEModel, self).__init__(endog=endog, exog=exog, dates=dates, freq=freq, missing='none') # Store kwargs to recreate model self._init_kwargs = kwargs # Prepared the endog array: C-ordered, shape=(nobs x k_endog) self.endog, self.exog = self.prepare_data() # Dimensions self.nobs = self.endog.shape[0] self.k_states = k_states # Initialize the state-space representation self.initialize_statespace(**kwargs) def prepare_data(self): """ Prepare data for use in the state space representation """ endog = np.array(self.data.orig_endog, order='C') exog = self.data.orig_exog if exog is not None: exog = np.array(exog) # Base class may allow 1-dim data, whereas we need 2-dim if endog.ndim == 1: endog.shape = (endog.shape[0], 1) # this will be C-contiguous return endog, exog def initialize_statespace(self, **kwargs): """ Initialize the state space representation Parameters ---------- **kwargs Additional keyword arguments to pass to the state space class constructor. """ # (Now self.endog is C-ordered and in long format (nobs x k_endog). To # get F-ordered and in wide format just need to transpose) endog = self.endog.T # Instantiate the state space object self.ssm = SimulationSmoother(endog.shape[0], self.k_states, **kwargs) # Bind the data to the model self.ssm.bind(endog) # Other dimensions, now that `ssm` is available self.k_endog = self.ssm.k_endog def __setitem__(self, key, value): return self.ssm.__setitem__(key, value) def __getitem__(self, key): return self.ssm.__getitem__(key) def set_filter_method(self, filter_method=None, **kwargs): """ Set the filtering method The filtering method controls aspects of which Kalman filtering approach will be used. Parameters ---------- filter_method : integer, optional Bitmask value to set the filter method to. See notes for details. **kwargs Keyword arguments may be used to influence the filter method by setting individual boolean flags. See notes for details. Notes ----- This method is rarely used. See the corresponding function in the `KalmanFilter` class for details. """ self.ssm.set_filter_method(filter_method, **kwargs) def set_inversion_method(self, inversion_method=None, **kwargs): """ Set the inversion method The Kalman filter may contain one matrix inversion: that of the forecast error covariance matrix. The inversion method controls how and if that inverse is performed. Parameters ---------- inversion_method : integer, optional Bitmask value to set the inversion method to. See notes for details. **kwargs Keyword arguments may be used to influence the inversion method by setting individual boolean flags. See notes for details. Notes ----- This method is rarely used. See the corresponding function in the `KalmanFilter` class for details. """ self.ssm.set_inversion_method(inversion_method, **kwargs) def set_stability_method(self, stability_method=None, **kwargs): """ Set the numerical stability method The Kalman filter is a recursive algorithm that may in some cases suffer issues with numerical stability. The stability method controls what, if any, measures are taken to promote stability. Parameters ---------- stability_method : integer, optional Bitmask value to set the stability method to. See notes for details. **kwargs Keyword arguments may be used to influence the stability method by setting individual boolean flags. See notes for details. Notes ----- This method is rarely used. See the corresponding function in the `KalmanFilter` class for details. """ self.ssm.set_stability_method(stability_method, **kwargs) def set_conserve_memory(self, conserve_memory=None, **kwargs): """ Set the memory conservation method By default, the Kalman filter computes a number of intermediate matrices at each iteration. The memory conservation options control which of those matrices are stored. Parameters ---------- conserve_memory : integer, optional Bitmask value to set the memory conservation method to. See notes for details. **kwargs Keyword arguments may be used to influence the memory conservation method by setting individual boolean flags. Notes ----- This method is rarely used. See the corresponding function in the `KalmanFilter` class for details. """ self.ssm.set_conserve_memory(conserve_memory, **kwargs) def set_smoother_output(self, smoother_output=None, **kwargs): """ Set the smoother output The smoother can produce several types of results. The smoother output variable controls which are calculated and returned. Parameters ---------- smoother_output : integer, optional Bitmask value to set the smoother output to. See notes for details. **kwargs Keyword arguments may be used to influence the smoother output by setting individual boolean flags. Notes ----- This method is rarely used. See the corresponding function in the `KalmanSmoother` class for details. """ self.ssm.set_smoother_output(smoother_output, **kwargs) def initialize_known(self, initial_state, initial_state_cov): self.ssm.initialize_known(initial_state, initial_state_cov) def initialize_approximate_diffuse(self, variance=None): self.ssm.initialize_approximate_diffuse(variance) def initialize_stationary(self): self.ssm.initialize_stationary() @property def initialization(self): return self.ssm.initialization @property def initial_variance(self): return self.ssm.initial_variance @initial_variance.setter def initial_variance(self, value): self.ssm.initial_variance = value @property def loglikelihood_burn(self): return self.ssm.loglikelihood_burn @loglikelihood_burn.setter def loglikelihood_burn(self, value): self.ssm.loglikelihood_burn = value @property def tolerance(self): return self.ssm.tolerance @tolerance.setter def tolerance(self, value): self.ssm.tolerance = value def fit(self, start_params=None, transformed=True, cov_type='opg', cov_kwds=None, method='lbfgs', maxiter=50, full_output=1, disp=5, callback=None, return_params=False, optim_score=None, optim_complex_step=None, optim_hessian=None, flags=None, **kwargs): """ Fits the model by maximum likelihood via Kalman filter. Parameters ---------- start_params : array_like, optional Initial guess of the solution for the loglikelihood maximization. If None, the default is given by Model.start_params. transformed : boolean, optional Whether or not `start_params` is already transformed. Default is True. cov_type : str, optional The `cov_type` keyword governs the method for calculating the covariance matrix of parameter estimates. Can be one of: - 'opg' for the outer product of gradient estimator - 'oim' for the observed information matrix estimator, calculated using the method of Harvey (1989) - 'approx' for the observed information matrix estimator, calculated using a numerical approximation of the Hessian matrix. - 'robust' for an approximate (quasi-maximum likelihood) covariance matrix that may be valid even in the presense of some misspecifications. Intermediate calculations use the 'oim' method. - 'robust_approx' is the same as 'robust' except that the intermediate calculations use the 'approx' method. - 'none' for no covariance matrix calculation. cov_kwds : dict or None, optional A dictionary of arguments affecting covariance matrix computation. **opg, oim, approx, robust, robust_approx** - 'approx_complex_step' : boolean, optional - If True, numerical approximations are computed using complex-step methods. If False, numerical approximations are computed using finite difference methods. Default is True. - 'approx_centered' : boolean, optional - If True, numerical approximations computed using finite difference methods use a centered approximation. Default is False. method : str, optional The `method` determines which solver from `scipy.optimize` is used, and it can be chosen from among the following strings: - 'newton' for Newton-Raphson, 'nm' for Nelder-Mead - 'bfgs' for Broyden-Fletcher-Goldfarb-Shanno (BFGS) - 'lbfgs' for limited-memory BFGS with optional box constraints - 'powell' for modified Powell's method - 'cg' for conjugate gradient - 'ncg' for Newton-conjugate gradient - 'basinhopping' for global basin-hopping solver The explicit arguments in `fit` are passed to the solver, with the exception of the basin-hopping solver. Each solver has several optional arguments that are not the same across solvers. See the notes section below (or scipy.optimize) for the available arguments and for the list of explicit arguments that the basin-hopping solver supports. maxiter : int, optional The maximum number of iterations to perform. full_output : boolean, optional Set to True to have all available output in the Results object's mle_retvals attribute. The output is dependent on the solver. See LikelihoodModelResults notes section for more information. disp : boolean, optional Set to True to print convergence messages. callback : callable callback(xk), optional Called after each iteration, as callback(xk), where xk is the current parameter vector. return_params : boolean, optional Whether or not to return only the array of maximizing parameters. Default is False. optim_score : {'harvey', 'approx'} or None, optional The method by which the score vector is calculated. 'harvey' uses the method from Harvey (1989), 'approx' uses either finite difference or complex step differentiation depending upon the value of `optim_complex_step`, and None uses the built-in gradient approximation of the optimizer. Default is None. This keyword is only relevant if the optimization method uses the score. optim_complex_step : bool, optional Whether or not to use complex step differentiation when approximating the score; if False, finite difference approximation is used. Default is True. This keyword is only relevant if `optim_score` is set to 'harvey' or 'approx'. optim_hessian : {'opg','oim','approx'}, optional The method by which the Hessian is numerically approximated. 'opg' uses outer product of gradients, 'oim' uses the information matrix formula from Harvey (1989), and 'approx' uses numerical approximation. This keyword is only relevant if the optimization method uses the Hessian matrix. **kwargs Additional keyword arguments to pass to the optimizer. Returns ------- MLEResults See also -------- statsmodels.base.model.LikelihoodModel.fit MLEResults """ if start_params is None: start_params = self.start_params transformed = True # Update the score method if optim_score is None and method == 'lbfgs': kwargs.setdefault('approx_grad', True) kwargs.setdefault('epsilon', 1e-5) elif optim_score is None: optim_score = 'approx' # Check for complex step differentiation if optim_complex_step is None: optim_complex_step = not self.ssm._complex_endog elif optim_complex_step and self.ssm._complex_endog: raise ValueError('Cannot use complex step derivatives when data' ' or parameters are complex.') # Unconstrain the starting parameters if transformed: start_params = self.untransform_params(np.array(start_params)) # Maximum likelihood estimation if flags is None: flags = {} flags.update({ 'transformed': False, 'score_method': optim_score, 'approx_complex_step': optim_complex_step }) if optim_hessian is not None: flags['hessian_method'] = optim_hessian fargs = (flags,) mlefit = super(MLEModel, self).fit(start_params, method=method, fargs=fargs, maxiter=maxiter, full_output=full_output, disp=disp, callback=callback, skip_hessian=True, **kwargs) # Just return the fitted parameters if requested if return_params: return self.transform_params(mlefit.params) # Otherwise construct the results class if desired else: res = self.smooth(mlefit.params, transformed=False, cov_type=cov_type, cov_kwds=cov_kwds) res.mlefit = mlefit res.mle_retvals = mlefit.mle_retvals res.mle_settings = mlefit.mle_settings return res def filter(self, params, transformed=True, complex_step=False, cov_type=None, cov_kwds=None, return_ssm=False, results_class=None, results_wrapper_class=None, **kwargs): """ Kalman filtering Parameters ---------- params : array_like Array of parameters at which to evaluate the loglikelihood function. transformed : boolean, optional Whether or not `params` is already transformed. Default is True. return_ssm : boolean,optional Whether or not to return only the state space output or a full results object. Default is to return a full results object. cov_type : str, optional See `MLEResults.fit` for a description of covariance matrix types for results object. cov_kwds : dict or None, optional See `MLEResults.get_robustcov_results` for a description required keywords for alternative covariance estimators **kwargs Additional keyword arguments to pass to the Kalman filter. See `KalmanFilter.filter` for more details. """ params = np.array(params, ndmin=1) if not transformed: params = self.transform_params(params) self.update(params, transformed=True, complex_step=complex_step) # Save the parameter names self.data.param_names = self.param_names if complex_step: kwargs['inversion_method'] = INVERT_UNIVARIATE | SOLVE_LU # Get the state space output result = self.ssm.filter(complex_step=complex_step, **kwargs) # Wrap in a results object if not return_ssm: result_kwargs = {} if cov_type is not None: result_kwargs['cov_type'] = cov_type if cov_kwds is not None: result_kwargs['cov_kwds'] = cov_kwds if results_class is None: results_class = MLEResults if results_wrapper_class is None: results_wrapper_class = MLEResultsWrapper result = results_wrapper_class( results_class(self, params, result, **result_kwargs) ) return result def smooth(self, params, transformed=True, complex_step=False, cov_type=None, cov_kwds=None, return_ssm=False, results_class=None, results_wrapper_class=None, **kwargs): """ Kalman smoothing Parameters ---------- params : array_like Array of parameters at which to evaluate the loglikelihood function. transformed : boolean, optional Whether or not `params` is already transformed. Default is True. return_ssm : boolean,optional Whether or not to return only the state space output or a full results object. Default is to return a full results object. cov_type : str, optional See `MLEResults.fit` for a description of covariance matrix types for results object. cov_kwds : dict or None, optional See `MLEResults.get_robustcov_results` for a description required keywords for alternative covariance estimators **kwargs Additional keyword arguments to pass to the Kalman filter. See `KalmanFilter.filter` for more details. """ params = np.array(params, ndmin=1) if not transformed: params = self.transform_params(params) self.update(params, transformed=True, complex_step=complex_step) # Save the parameter names self.data.param_names = self.param_names if complex_step: kwargs['inversion_method'] = INVERT_UNIVARIATE | SOLVE_LU # Get the state space output result = self.ssm.smooth(complex_step=complex_step, **kwargs) # Wrap in a results object if not return_ssm: result_kwargs = {} if cov_type is not None: result_kwargs['cov_type'] = cov_type if cov_kwds is not None: result_kwargs['cov_kwds'] = cov_kwds if results_class is None: results_class = MLEResults if results_wrapper_class is None: results_wrapper_class = MLEResultsWrapper result = results_wrapper_class( results_class(self, params, result, **result_kwargs) ) return result def loglike(self, params, *args, **kwargs): """ Loglikelihood evaluation Parameters ---------- params : array_like Array of parameters at which to evaluate the loglikelihood function. transformed : boolean, optional Whether or not `params` is already transformed. Default is True. **kwargs Additional keyword arguments to pass to the Kalman filter. See `KalmanFilter.filter` for more details. Notes ----- [1]_ recommend maximizing the average likelihood to avoid scale issues; this is done automatically by the base Model fit method. References ---------- .. [1] Koopman, Siem Jan, Neil Shephard, and Jurgen A. Doornik. 1999. Statistical Algorithms for Models in State Space Using SsfPack 2.2. Econometrics Journal 2 (1): 107-60. doi:10.1111/1368-423X.00023. See Also -------- update : modifies the internal state of the state space model to reflect new params """ # We need to handle positional arguments in two ways, in case this was # called by a Scipy optimization routine if len(args) > 0: argnames = ['transformed', 'complex_step'] # the fit() method will pass a dictionary if isinstance(args[0], dict): flags = args[0] # otherwise, a user may have just used positional arguments... else: flags = dict(zip(argnames, args)) transformed = flags.get('transformed', True) complex_step = flags.get('complex_step', True) for name, value in flags.items(): if name in kwargs: raise TypeError("loglike() got multiple values for keyword" " argument '%s'" % name) else: transformed = kwargs.pop('transformed', True) complex_step = kwargs.pop('complex_step', True) if not transformed: params = self.transform_params(params) self.update(params, transformed=True, complex_step=complex_step) if complex_step: kwargs['inversion_method'] = INVERT_UNIVARIATE | SOLVE_LU loglike = self.ssm.loglike(complex_step=complex_step, **kwargs) # Koopman, Shephard, and Doornik recommend maximizing the average # likelihood to avoid scale issues, but the averaging is done # automatically in the base model `fit` method return loglike def loglikeobs(self, params, transformed=True, complex_step=False, **kwargs): """ Loglikelihood evaluation Parameters ---------- params : array_like Array of parameters at which to evaluate the loglikelihood function. transformed : boolean, optional Whether or not `params` is already transformed. Default is True. **kwargs Additional keyword arguments to pass to the Kalman filter. See `KalmanFilter.filter` for more details. Notes ----- [1]_ recommend maximizing the average likelihood to avoid scale issues; this is done automatically by the base Model fit method. References ---------- .. [1] Koopman, Siem Jan, Neil Shephard, and Jurgen A. Doornik. 1999. Statistical Algorithms for Models in State Space Using SsfPack 2.2. Econometrics Journal 2 (1): 107-60. doi:10.1111/1368-423X.00023. See Also -------- update : modifies the internal state of the Model to reflect new params """ if not transformed: params = self.transform_params(params) # If we're using complex-step differentiation, then we can't use # Cholesky factorization if complex_step: kwargs['inversion_method'] = INVERT_UNIVARIATE | SOLVE_LU self.update(params, transformed=True, complex_step=complex_step) return self.ssm.loglikeobs(complex_step=complex_step, **kwargs) def simulation_smoother(self, simulation_output=None, **kwargs): r""" Retrieve a simulation smoother for the state space model. Parameters ---------- simulation_output : int, optional Determines which simulation smoother output is calculated. Default is all (including state and disturbances). **kwargs Additional keyword arguments, used to set the simulation output. See `set_simulation_output` for more details. Returns ------- SimulationSmoothResults """ return self.ssm.simulation_smoother( simulation_output=simulation_output, **kwargs) def _forecasts_error_partial_derivatives(self, params, transformed=True, approx_complex_step=None, approx_centered=False, res=None, **kwargs): params = np.array(params, ndmin=1) # We can't use complex-step differentiation with non-transformed # parameters if approx_complex_step is None: approx_complex_step = transformed if not transformed and approx_complex_step: raise ValueError("Cannot use complex-step approximations to" " calculate the observed_information_matrix" " with untransformed parameters.") # If we're using complex-step differentiation, then we can't use # Cholesky factorization if approx_complex_step: kwargs['inversion_method'] = INVERT_UNIVARIATE | SOLVE_LU # Get values at the params themselves if res is None: self.update(params, transformed=transformed, complex_step=approx_complex_step) res = self.ssm.filter(complex_step=approx_complex_step, **kwargs) # Setup n = len(params) # Compute partial derivatives w.r.t. forecast error and forecast # error covariance partials_forecasts_error = ( np.zeros((self.k_endog, self.nobs, n)) ) partials_forecasts_error_cov = ( np.zeros((self.k_endog, self.k_endog, self.nobs, n)) ) if approx_complex_step: epsilon = _get_epsilon(params, 2, None, n) increments = np.identity(n) * 1j * epsilon for i, ih in enumerate(increments): self.update(params + ih, transformed=transformed, complex_step=True) _res = self.ssm.filter(complex_step=True, **kwargs) partials_forecasts_error[:, :, i] = ( _res.forecasts_error.imag / epsilon[i] ) partials_forecasts_error_cov[:, :, :, i] = ( _res.forecasts_error_cov.imag / epsilon[i] ) elif not approx_centered: epsilon = _get_epsilon(params, 2, None, n) ei = np.zeros((n,), float) for i in range(n): ei[i] = epsilon[i] self.update(params + ei, transformed=transformed, complex_step=False) _res = self.ssm.filter(complex_step=False, **kwargs) partials_forecasts_error[:, :, i] = ( _res.forecasts_error - res.forecasts_error) / epsilon[i] partials_forecasts_error_cov[:, :, :, i] = ( _res.forecasts_error_cov - res.forecasts_error_cov) / epsilon[i] ei[i] = 0.0 else: epsilon = _get_epsilon(params, 3, None, n) / 2. ei = np.zeros((n,), float) for i in range(n): ei[i] = epsilon[i] self.update(params + ei, transformed=transformed, complex_step=False) _res1 = self.ssm.filter(complex_step=False, **kwargs) self.update(params - ei, transformed=transformed, complex_step=False) _res2 = self.ssm.filter(complex_step=False, **kwargs) partials_forecasts_error[:, :, i] = ( (_res1.forecasts_error - _res2.forecasts_error) / (2 * epsilon[i])) partials_forecasts_error_cov[:, :, :, i] = ( (_res1.forecasts_error_cov - _res2.forecasts_error_cov) / (2 * epsilon[i])) ei[i] = 0.0 return partials_forecasts_error, partials_forecasts_error_cov def observed_information_matrix(self, params, transformed=True, approx_complex_step=None, approx_centered=False, **kwargs): """ Observed information matrix Parameters ---------- params : array_like, optional Array of parameters at which to evaluate the loglikelihood function. **kwargs Additional keyword arguments to pass to the Kalman filter. See `KalmanFilter.filter` for more details. Notes ----- This method is from Harvey (1989), which shows that the information matrix only depends on terms from the gradient. This implementation is partially analytic and partially numeric approximation, therefore, because it uses the analytic formula for the information matrix, with numerically computed elements of the gradient. References ---------- Harvey, Andrew C. 1990. Forecasting, Structural Time Series Models and the Kalman Filter. Cambridge University Press. """ params = np.array(params, ndmin=1) # Setup n = len(params) # We can't use complex-step differentiation with non-transformed # parameters if approx_complex_step is None: approx_complex_step = transformed if not transformed and approx_complex_step: raise ValueError("Cannot use complex-step approximations to" " calculate the observed_information_matrix" " with untransformed parameters.") # Get values at the params themselves self.update(params, transformed=transformed, complex_step=approx_complex_step) # If we're using complex-step differentiation, then we can't use # Cholesky factorization if approx_complex_step: kwargs['inversion_method'] = INVERT_UNIVARIATE | SOLVE_LU res = self.ssm.filter(complex_step=approx_complex_step, **kwargs) dtype = self.ssm.dtype # Save this for inversion later inv_forecasts_error_cov = res.forecasts_error_cov.copy() partials_forecasts_error, partials_forecasts_error_cov = ( self._forecasts_error_partial_derivatives( params, transformed=transformed, approx_complex_step=approx_complex_step, approx_centered=approx_centered, res=res, **kwargs)) # Compute the information matrix tmp = np.zeros((self.k_endog, self.k_endog, self.nobs, n), dtype=dtype) information_matrix = np.zeros((n, n), dtype=dtype) for t in range(self.ssm.loglikelihood_burn, self.nobs): inv_forecasts_error_cov[:, :, t] = ( np.linalg.inv(res.forecasts_error_cov[:, :, t]) ) for i in range(n): tmp[:, :, t, i] = np.dot( inv_forecasts_error_cov[:, :, t], partials_forecasts_error_cov[:, :, t, i] ) for i in range(n): for j in range(n): information_matrix[i, j] += ( 0.5 * np.trace(np.dot(tmp[:, :, t, i], tmp[:, :, t, j])) ) information_matrix[i, j] += np.inner( partials_forecasts_error[:, t, i], np.dot(inv_forecasts_error_cov[:, :, t], partials_forecasts_error[:, t, j]) ) return information_matrix / (self.nobs - self.ssm.loglikelihood_burn) def opg_information_matrix(self, params, transformed=True, approx_complex_step=None, **kwargs): """ Outer product of gradients information matrix Parameters ---------- params : array_like, optional Array of parameters at which to evaluate the loglikelihood function. **kwargs Additional arguments to the `loglikeobs` method. References ---------- Berndt, Ernst R., Bronwyn Hall, Robert Hall, and Jerry Hausman. 1974. Estimation and Inference in Nonlinear Structural Models. NBER Chapters. National Bureau of Economic Research, Inc. """ # We can't use complex-step differentiation with non-transformed # parameters if approx_complex_step is None: approx_complex_step = transformed if not transformed and approx_complex_step: raise ValueError("Cannot use complex-step approximations to" " calculate the observed_information_matrix" " with untransformed parameters.") score_obs = self.score_obs(params, transformed=transformed, approx_complex_step=approx_complex_step, **kwargs).transpose() return ( np.inner(score_obs, score_obs) / (self.nobs - self.ssm.loglikelihood_burn) ) def _score_complex_step(self, params, **kwargs): # the default epsilon can be too small # inversion_method = INVERT_UNIVARIATE | SOLVE_LU epsilon = _get_epsilon(params, 2., None, len(params)) kwargs['transformed'] = True kwargs['complex_step'] = True return approx_fprime_cs(params, self.loglike, epsilon=epsilon, kwargs=kwargs) def _score_finite_difference(self, params, approx_centered=False, **kwargs): kwargs['transformed'] = True return approx_fprime(params, self.loglike, kwargs=kwargs, centered=approx_centered) def _score_harvey(self, params, approx_complex_step=True, **kwargs): score_obs = self._score_obs_harvey( params, approx_complex_step=approx_complex_step, **kwargs) return np.sum(score_obs, axis=0) def _score_obs_harvey(self, params, approx_complex_step=True, approx_centered=False, **kwargs): """ Score Parameters ---------- params : array_like, optional Array of parameters at which to evaluate the loglikelihood function. **kwargs Additional keyword arguments to pass to the Kalman filter. See `KalmanFilter.filter` for more details. Notes ----- This method is from Harvey (1989), section 3.4.5 References ---------- Harvey, Andrew C. 1990. Forecasting, Structural Time Series Models and the Kalman Filter. Cambridge University Press. """ params = np.array(params, ndmin=1) n = len(params) # Get values at the params themselves self.update(params, transformed=True, complex_step=approx_complex_step) if approx_complex_step: kwargs['inversion_method'] = INVERT_UNIVARIATE | SOLVE_LU res = self.ssm.filter(complex_step=approx_complex_step, **kwargs) dtype = self.ssm.dtype # Get forecasts error partials partials_forecasts_error, partials_forecasts_error_cov = ( self._forecasts_error_partial_derivatives( params, transformed=True, approx_complex_step=approx_complex_step, approx_centered=approx_centered, res=res, **kwargs)) # Compute partial derivatives w.r.t. likelihood function partials = np.zeros((self.nobs, n)) k_endog = self.k_endog for t in range(self.nobs): for i in range(n): inv_forecasts_error_cov = np.linalg.inv( res.forecasts_error_cov[:, :, t]) partials[t, i] += np.trace(np.dot( np.dot(inv_forecasts_error_cov, partials_forecasts_error_cov[:, :, t, i]), (np.eye(k_endog) - np.dot(inv_forecasts_error_cov, np.outer(res.forecasts_error[:, t], res.forecasts_error[:, t]))))) # 2 * dv / di * F^{-1} v_t # where x = F^{-1} v_t or F x = v partials[t, i] += 2 * np.dot( partials_forecasts_error[:, t, i], np.dot(inv_forecasts_error_cov, res.forecasts_error[:, t])) return -partials / 2. def score(self, params, *args, **kwargs): """ Compute the score function at params. Parameters ---------- params : array_like Array of parameters at which to evaluate the score. *args, **kwargs Additional arguments to the `loglike` method. Returns ---------- score : array Score, evaluated at `params`. Notes ----- This is a numerical approximation, calculated using first-order complex step differentiation on the `loglike` method. Both \*args and \*\*kwargs are necessary because the optimizer from `fit` must call this function and only supports passing arguments via \*args (for example `scipy.optimize.fmin_l_bfgs`). """ params = np.array(params, ndmin=1) # We were given one positional argument if this was called by a Scipy # optimization routine if len(args) > 0: argnames = ['transformed', 'method', 'approx_complex_step', 'approx_centered'] # the fit() method will pass a dictionary if isinstance(args[0], dict): flags = args[0] flags['method'] = flags.get('score_method', 'approx') # otherwise, a user may have just used positional arguments... else: flags = dict(zip(argnames, args)) transformed = flags.get('transformed', True) method = flags.get('method', 'approx') approx_complex_step = flags.get('approx_complex_step', None) approx_centered = flags.get('approx_centered', True) for name, value in flags.items(): if name in kwargs: raise TypeError("score() got multiple values for keyword" " argument '%s'" % name) else: transformed = kwargs.pop('transformed', True) method = kwargs.pop('method', 'approx') approx_complex_step = kwargs.pop('approx_complex_step', None) approx_centered = kwargs.pop('approx_centered', False) if approx_complex_step is None: approx_complex_step = not self.ssm._complex_endog if approx_complex_step and self.ssm._complex_endog: raise ValueError('Cannot use complex step derivatives when data' ' or parameters are complex.') if not transformed: transform_score = self.transform_jacobian(params) params = self.transform_params(params) if method == 'harvey': score = self._score_harvey( params, approx_complex_step=approx_complex_step, **kwargs) elif method == 'approx' and approx_complex_step: score = self._score_complex_step(params, **kwargs) elif method == 'approx': score = self._score_finite_difference( params, approx_centered=approx_centered, **kwargs) else: raise NotImplementedError('Invalid score method.') if not transformed: score = np.dot(transform_score, score) return score def score_obs(self, params, method='approx', transformed=True, approx_complex_step=None, approx_centered=False, **kwargs): """ Compute the score per observation, evaluated at params Parameters ---------- params : array_like Array of parameters at which to evaluate the score. **kwargs Additional arguments to the `loglike` method. Returns ---------- score : array (nobs, k_vars) Score per observation, evaluated at `params`. Notes ----- This is a numerical approximation, calculated using first-order complex step differentiation on the `loglikeobs` method. """ params = np.array(params, ndmin=1) if not transformed and approx_complex_step: raise ValueError("Cannot use complex-step approximations to" " calculate the score at each observation" " with untransformed parameters.") if approx_complex_step is None: approx_complex_step = not self.ssm._complex_endog if approx_complex_step and self.ssm._complex_endog: raise ValueError('Cannot use complex step derivatives when data' ' or parameters are complex.') if method == 'harvey': score = self._score_obs_harvey( params, transformed=transformed, approx_complex_step=approx_complex_step, **kwargs) elif method == 'approx' and approx_complex_step: # the default epsilon can be too small epsilon = _get_epsilon(params, 2., None, len(params)) kwargs['complex_step'] = True kwargs['transformed'] = True score = approx_fprime_cs(params, self.loglikeobs, epsilon=epsilon, kwargs=kwargs) elif method == 'approx': kwargs['transformed'] = transformed score = approx_fprime(params, self.loglikeobs, kwargs=kwargs, centered=approx_centered) else: raise NotImplementedError('Invalid scoreobs method.') return score def hessian(self, params, *args, **kwargs): """ Hessian matrix of the likelihood function, evaluated at the given parameters Parameters ---------- params : array_like Array of parameters at which to evaluate the hessian. *args, **kwargs Additional arguments to the `loglike` method. Returns ------- hessian : array Hessian matrix evaluated at `params` Notes ----- This is a numerical approximation. Both \*args and \*\*kwargs are necessary because the optimizer from `fit` must call this function and only supports passing arguments via \*args (for example `scipy.optimize.fmin_l_bfgs`). """ # We were given one positional argument if this was called by a Scipy # optimization routine if len(args) > 0: argnames = ['transformed', 'method', 'approx_complex_step', 'approx_centered'] # the fit() method will pass a dictionary if isinstance(args[0], dict): flags = args[0] flags['method'] = flags.get('hessian_method', 'approx') # otherwise, a user may have just used positional arguments... else: flags = dict(zip(argnames, args)) transformed = flags.get('transformed', True) method = flags.get('method', 'approx') approx_complex_step = flags.get('approx_complex_step', None) approx_centered = flags.get('approx_centered', True) for name, value in flags.items(): if name in kwargs: raise TypeError("hessian() got multiple values for keyword" " argument '%s'" % name) else: transformed = kwargs.pop('transformed', False) method = kwargs.pop('method', 'approx') approx_complex_step = kwargs.pop('approx_complex_step', None) approx_centered = kwargs.pop('approx_centered', False) if not transformed and approx_complex_step: raise ValueError("Cannot use complex-step approximations to" " calculate the hessian with untransformed" " parameters.") if approx_complex_step is None: approx_complex_step = not self.ssm._complex_endog if approx_complex_step and self.ssm._complex_endog: raise ValueError('Cannot use complex step derivatives when data' ' or parameters are complex.') if method == 'oim': hessian = self._hessian_oim( params, transformed=transformed, approx_complex_step=approx_complex_step, approx_centered=approx_centered, **kwargs) elif method == 'opg': hessian = self._hessian_opg( params, transformed=transformed, approx_complex_step=approx_complex_step, approx_centered=approx_centered, **kwargs) elif method == 'approx' and approx_complex_step: return self._hessian_complex_step( params, transformed=transformed, **kwargs) elif method == 'approx': return self._hessian_finite_difference( params, transformed=transformed, approx_centered=approx_centered, **kwargs) else: raise NotImplementedError('Invalid Hessian calculation method.') return hessian def _hessian_oim(self, params, **kwargs): """ Hessian matrix computed using the Harvey (1989) information matrix """ return -self.observed_information_matrix(params, **kwargs) def _hessian_opg(self, params, **kwargs): """ Hessian matrix computed using the outer product of gradients information matrix """ return -self.opg_information_matrix(params, **kwargs) def _hessian_finite_difference(self, params, approx_centered=False, **kwargs): params = np.array(params, ndmin=1) warnings.warn('Calculation of the Hessian using finite differences' ' is usually subject to substantial approximation' ' errors.', PrecisionWarning) if not approx_centered: epsilon = _get_epsilon(params, 3, None, len(params)) else: epsilon = _get_epsilon(params, 4, None, len(params)) / 2 hessian = approx_fprime(params, self._score_finite_difference, epsilon=epsilon, kwargs=kwargs, centered=approx_centered) return hessian / (self.nobs - self.ssm.loglikelihood_burn) def _hessian_complex_step(self, params, **kwargs): """ Hessian matrix computed by second-order complex-step differentiation on the `loglike` function. """ # the default epsilon can be too small epsilon = _get_epsilon(params, 3., None, len(params)) kwargs['transformed'] = True kwargs['complex_step'] = True hessian = approx_hess_cs( params, self.loglike, epsilon=epsilon, kwargs=kwargs) return hessian / (self.nobs - self.ssm.loglikelihood_burn) @property def start_params(self): """ (array) Starting parameters for maximum likelihood estimation. """ if hasattr(self, '_start_params'): return self._start_params else: raise NotImplementedError @property def param_names(self): """ (list of str) List of human readable parameter names (for parameters actually included in the model). """ if hasattr(self, '_param_names'): return self._param_names else: try: names = ['param.%d' % i for i in range(len(self.start_params))] except NotImplementedError: names = [] return names def transform_jacobian(self, unconstrained, approx_centered=False): """ Jacobian matrix for the parameter transformation function Parameters ---------- unconstrained : array_like Array of unconstrained parameters used by the optimizer. Returns ------- jacobian : array Jacobian matrix of the transformation, evaluated at `unconstrained` Notes ----- This is a numerical approximation using finite differences. Note that in general complex step methods cannot be used because it is not guaranteed that the `transform_params` method is a real function (e.g. if Cholesky decomposition is used). See Also -------- transform_params """ return approx_fprime(unconstrained, self.transform_params, centered=approx_centered) def transform_params(self, unconstrained): """ Transform unconstrained parameters used by the optimizer to constrained parameters used in likelihood evaluation Parameters ---------- unconstrained : array_like Array of unconstrained parameters used by the optimizer, to be transformed. Returns ------- constrained : array_like Array of constrained parameters which may be used in likelihood evalation. Notes ----- This is a noop in the base class, subclasses should override where appropriate. """ return np.array(unconstrained, ndmin=1) def untransform_params(self, constrained): """ Transform constrained parameters used in likelihood evaluation to unconstrained parameters used by the optimizer Parameters ---------- constrained : array_like Array of constrained parameters used in likelihood evalution, to be transformed. Returns ------- unconstrained : array_like Array of unconstrained parameters used by the optimizer. Notes ----- This is a noop in the base class, subclasses should override where appropriate. """ return np.array(constrained, ndmin=1) def update(self, params, transformed=True, complex_step=False): """ Update the parameters of the model Parameters ---------- params : array_like Array of new parameters. transformed : boolean, optional Whether or not `params` is already transformed. If set to False, `transform_params` is called. Default is True. Returns ------- params : array_like Array of parameters. Notes ----- Since Model is a base class, this method should be overridden by subclasses to perform actual updating steps. """ params = np.array(params, ndmin=1) if not transformed: params = self.transform_params(params) return params def simulate(self, params, nsimulations, measurement_shocks=None, state_shocks=None, initial_state=None): r""" Simulate a new time series following the state space model Parameters ---------- params : array_like Array of model parameters. nsimulations : int The number of observations to simulate. If the model is time-invariant this can be any number. If the model is time-varying, then this number must be less than or equal to the number measurement_shocks : array_like, optional If specified, these are the shocks to the measurement equation, :math:`\varepsilon_t`. If unspecified, these are automatically generated using a pseudo-random number generator. If specified, must be shaped `nsimulations` x `k_endog`, where `k_endog` is the same as in the state space model. state_shocks : array_like, optional If specified, these are the shocks to the state equation, :math:`\eta_t`. If unspecified, these are automatically generated using a pseudo-random number generator. If specified, must be shaped `nsimulations` x `k_posdef` where `k_posdef` is the same as in the state space model. initial_state : array_like, optional If specified, this is the state vector at time zero, which should be shaped (`k_states` x 1), where `k_states` is the same as in the state space model. If unspecified, but the model has been initialized, then that initialization is used. If unspecified and the model has not been initialized, then a vector of zeros is used. Note that this is not included in the returned `simulated_states` array. Returns ------- simulated_obs : array An (nsimulations x k_endog) array of simulated observations. """ self.update(params) simulated_obs, simulated_states = self.ssm.simulate( nsimulations, measurement_shocks, state_shocks, initial_state) # Simulated obs is (nobs x k_endog); don't want to squeeze in # case of nsimulations = 1 if simulated_obs.shape[1] == 1: simulated_obs = simulated_obs[:, 0] return simulated_obs def impulse_responses(self, params, steps=1, impulse=0, orthogonalized=False, cumulative=False, **kwargs): """ Impulse response function Parameters ---------- params : array_like Array of model parameters. steps : int, optional The number of steps for which impulse responses are calculated. Default is 1. Note that the initial impulse is not counted as a step, so if `steps=1`, the output will have 2 entries. impulse : int or array_like If an integer, the state innovation to pulse; must be between 0 and `k_posdef-1`. Alternatively, a custom impulse vector may be provided; must be shaped `k_posdef x 1`. orthogonalized : boolean, optional Whether or not to perform impulse using orthogonalized innovations. Note that this will also affect custum `impulse` vectors. Default is False. cumulative : boolean, optional Whether or not to return cumulative impulse responses. Default is False. **kwargs If the model is time-varying and `steps` is greater than the number of observations, any of the state space representation matrices that are time-varying must have updated values provided for the out-of-sample steps. For example, if `design` is a time-varying component, `nobs` is 10, and `steps` is 15, a (`k_endog` x `k_states` x 5) matrix must be provided with the new design matrix values. Returns ------- impulse_responses : array Responses for each endogenous variable due to the impulse given by the `impulse` argument. A (steps + 1 x k_endog) array. Notes ----- Intercepts in the measurement and state equation are ignored when calculating impulse responses. """ self.update(params) irfs = self.ssm.impulse_responses( steps, impulse, orthogonalized, cumulative, **kwargs) # IRF is (nobs x k_endog); don't want to squeeze in case of steps = 1 if irfs.shape[1] == 1: irfs = irfs[:, 0] return irfs @classmethod def from_formula(cls, formula, data, subset=None): """ Not implemented for state space models """ raise NotImplementedError class MLEResults(tsbase.TimeSeriesModelResults): r""" Class to hold results from fitting a state space model. Parameters ---------- model : MLEModel instance The fitted model instance params : array Fitted parameters filter_results : KalmanFilter instance The underlying state space model and Kalman filter output Attributes ---------- model : Model instance A reference to the model that was fit. filter_results : KalmanFilter instance The underlying state space model and Kalman filter output nobs : float The number of observations used to fit the model. params : array The parameters of the model. scale : float This is currently set to 1.0 and not used by the model or its results. See Also -------- MLEModel statsmodels.tsa.statespace.kalman_filter.FilterResults statsmodels.tsa.statespace.representation.FrozenRepresentation """ def __init__(self, model, params, results, cov_type='opg', cov_kwds=None, **kwargs): self.data = model.data tsbase.TimeSeriesModelResults.__init__(self, model, params, normalized_cov_params=None, scale=1.) # Save the state space representation output self.filter_results = results if isinstance(results, SmootherResults): self.smoother_results = results else: self.smoother_results = None # Dimensions self.nobs = model.nobs # Setup covariance matrix notes dictionary if not hasattr(self, 'cov_kwds'): self.cov_kwds = {} self.cov_type = cov_type # Setup the cache self._cache = resettable_cache() # Handle covariance matrix calculation if cov_kwds is None: cov_kwds = {} self._cov_approx_complex_step = ( cov_kwds.pop('approx_complex_step', True)) self._cov_approx_centered = cov_kwds.pop('approx_centered', False) try: self._rank = None self._get_robustcov_results(cov_type=cov_type, use_self=True, **cov_kwds) except np.linalg.LinAlgError: self._rank = 0 k_params = len(self.params) self.cov_params_default = np.zeros((k_params, k_params)) * np.nan self.cov_kwds['cov_type'] = ( 'Covariance matrix could not be calculated: singular.' ' information matrix.') self.model.update(self.params) # References of filter and smoother output extra_arrays = [ 'filtered_state', 'filtered_state_cov', 'predicted_state', 'predicted_state_cov', 'forecasts', 'forecasts_error', 'forecasts_error_cov', 'standardized_forecasts_error', 'scaled_smoothed_estimator', 'scaled_smoothed_estimator_cov', 'smoothing_error', 'smoothed_state', 'smoothed_state_cov', 'smoothed_state_autocov', 'smoothed_measurement_disturbance', 'smoothed_state_disturbance', 'smoothed_measurement_disturbance_cov', 'smoothed_state_disturbance_cov'] for name in extra_arrays: setattr(self, name, getattr(self.filter_results, name, None)) # Handle removing data self._data_attr_model = getattr(self, '_data_attr_model', []) self._data_attr_model.extend(['ssm']) self._data_attr.extend(extra_arrays) self._data_attr.extend(['filter_results', 'smoother_results']) self.data_in_cache = getattr(self, 'data_in_cache', []) self.data_in_cache.extend([]) def _get_robustcov_results(self, cov_type='opg', **kwargs): """ Create new results instance with specified covariance estimator as default Note: creating new results instance currently not supported. Parameters ---------- cov_type : string the type of covariance matrix estimator to use. See Notes below kwargs : depends on cov_type Required or optional arguments for covariance calculation. See Notes below. Returns ------- results : results instance This method creates a new results instance with the requested covariance as the default covariance of the parameters. Inferential statistics like p-values and hypothesis tests will be based on this covariance matrix. Notes ----- The following covariance types and required or optional arguments are currently available: - 'opg' for the outer product of gradient estimator - 'oim' for the observed information matrix estimator, calculated using the method of Harvey (1989) - 'approx' for the observed information matrix estimator, calculated using a numerical approximation of the Hessian matrix. Uses complex step approximation by default, or uses finite differences if `approx_complex_step=False` in the `cov_kwds` dictionary. - 'robust' for an approximate (quasi-maximum likelihood) covariance matrix that may be valid even in the presense of some misspecifications. Intermediate calculations use the 'oim' method. - 'robust_approx' is the same as 'robust' except that the intermediate calculations use the 'approx' method. - 'none' for no covariance matrix calculation. """ import statsmodels.stats.sandwich_covariance as sw use_self = kwargs.pop('use_self', False) if use_self: res = self else: raise NotImplementedError res = self.__class__( self.model, self.params, normalized_cov_params=self.normalized_cov_params, scale=self.scale) # Set the new covariance type res.cov_type = cov_type res.cov_kwds = {} # Calculate the new covariance matrix approx_complex_step = self._cov_approx_complex_step if approx_complex_step: approx_type_str = 'complex-step' elif self._cov_approx_centered: approx_type_str = 'centered finite differences' else: approx_type_str = 'finite differences' k_params = len(self.params) if k_params == 0: res.cov_params_default = np.zeros((0, 0)) res._rank = 0 res.cov_kwds['description'] = ( 'No parameters estimated.') elif cov_type == 'custom': res.cov_type = kwargs['custom_cov_type'] res.cov_params_default = kwargs['custom_cov_params'] res.cov_kwds['description'] = kwargs['custom_description'] res._rank = np.linalg.matrix_rank(res.cov_params_default) elif cov_type == 'none': res.cov_params_default = np.zeros((k_params, k_params)) * np.nan res._rank = np.nan res.cov_kwds['description'] = ( 'Covariance matrix not calculated.') elif self.cov_type == 'approx': res.cov_params_default = res.cov_params_approx res.cov_kwds['description'] = ( 'Covariance matrix calculated using numerical (%s)' ' differentiation.' % approx_type_str) elif self.cov_type == 'oim': res.cov_params_default = res.cov_params_oim res.cov_kwds['description'] = ( 'Covariance matrix calculated using the observed information' ' matrix (%s) described in Harvey (1989).' % approx_type_str) elif self.cov_type == 'opg': res.cov_params_default = res.cov_params_opg res.cov_kwds['description'] = ( 'Covariance matrix calculated using the outer product of' ' gradients (%s).' % approx_type_str ) elif self.cov_type == 'robust' or self.cov_type == 'robust_oim': res.cov_params_default = res.cov_params_robust_oim res.cov_kwds['description'] = ( 'Quasi-maximum likelihood covariance matrix used for' ' robustness to some misspecifications; calculated using the' ' observed information matrix (%s) described in' ' Harvey (1989).' % approx_type_str) elif self.cov_type == 'robust_approx': res.cov_params_default = res.cov_params_robust res.cov_kwds['description'] = ( 'Quasi-maximum likelihood covariance matrix used for' ' robustness to some misspecifications; calculated using' ' numerical (%s) differentiation.' % approx_type_str) else: raise NotImplementedError('Invalid covariance matrix type.') return res @cache_readonly def aic(self): """ (float) Akaike Information Criterion """ # return -2*self.llf + 2*self.params.shape[0] return aic(self.llf, self.nobs, self.params.shape[0]) @cache_readonly def bic(self): """ (float) Bayes Information Criterion """ # return -2*self.llf + self.params.shape[0]*np.log(self.nobs) return bic(self.llf, self.nobs, self.params.shape[0]) def _cov_params_approx(self, approx_complex_step=True, approx_centered=False): nobs = (self.model.nobs - self.filter_results.loglikelihood_burn) if approx_complex_step: evaluated_hessian = self.model._hessian_complex_step( self.params, transformed=True ) else: evaluated_hessian = self.model._hessian_finite_difference( self.params, transformed=True, approx_centered=approx_centered ) self.model.update(self.params) neg_cov, singular_values = pinv_extended(nobs * evaluated_hessian) if self._rank is None: self._rank = np.linalg.matrix_rank(np.diag(singular_values)) return -neg_cov @cache_readonly def cov_params_approx(self): """ (array) The variance / covariance matrix. Computed using the numerical Hessian approximated by complex step or finite differences methods. """ return self._cov_params_approx(self._cov_approx_complex_step, self._cov_approx_centered) def _cov_params_oim(self, approx_complex_step=True, approx_centered=False): nobs = (self.model.nobs - self.filter_results.loglikelihood_burn) cov_params, singular_values = pinv_extended( nobs * self.model.observed_information_matrix( self.params, transformed=True, approx_complex_step=approx_complex_step, approx_centered=approx_centered) ) self.model.update(self.params) if self._rank is None: self._rank = np.linalg.matrix_rank(np.diag(singular_values)) return cov_params @cache_readonly def cov_params_oim(self): """ (array) The variance / covariance matrix. Computed using the method from Harvey (1989). """ return self._cov_params_oim(self._cov_approx_complex_step, self._cov_approx_centered) def _cov_params_opg(self, approx_complex_step=True, approx_centered=False): nobs = (self.model.nobs - self.filter_results.loglikelihood_burn) cov_params, singular_values = pinv_extended( nobs * self.model.opg_information_matrix( self.params, transformed=True, approx_complex_step=approx_complex_step, approx_centered=approx_centered) ) self.model.update(self.params) if self._rank is None: self._rank = np.linalg.matrix_rank(np.diag(singular_values)) return cov_params @cache_readonly def cov_params_opg(self): """ (array) The variance / covariance matrix. Computed using the outer product of gradients method. """ return self._cov_params_opg(self._cov_approx_complex_step, self._cov_approx_centered) @cache_readonly def cov_params_robust(self): """ (array) The QMLE variance / covariance matrix. Alias for `cov_params_robust_oim` """ return self.cov_params_robust_oim def _cov_params_robust_oim(self, approx_complex_step=True, approx_centered=False): nobs = (self.model.nobs - self.filter_results.loglikelihood_burn) cov_opg = self._cov_params_opg(approx_complex_step=approx_complex_step, approx_centered=approx_centered) evaluated_hessian = ( nobs * self.model.observed_information_matrix( self.params, transformed=True, approx_complex_step=approx_complex_step, approx_centered=approx_centered) ) self.model.update(self.params) cov_params, singular_values = pinv_extended( np.dot(np.dot(evaluated_hessian, cov_opg), evaluated_hessian) ) if self._rank is None: self._rank = np.linalg.matrix_rank(np.diag(singular_values)) return cov_params @cache_readonly def cov_params_robust_oim(self): """ (array) The QMLE variance / covariance matrix. Computed using the method from Harvey (1989) as the evaluated hessian. """ return self._cov_params_robust_oim(self._cov_approx_complex_step, self._cov_approx_centered) def _cov_params_robust_approx(self, approx_complex_step=True, approx_centered=False): nobs = (self.model.nobs - self.filter_results.loglikelihood_burn) cov_opg = self._cov_params_opg(approx_complex_step=approx_complex_step, approx_centered=approx_centered) if approx_complex_step: evaluated_hessian = nobs * self.model._hessian_complex_step( self.params, transformed=True ) else: evaluated_hessian = nobs * self.model._hessian_finite_difference( self.params, transformed=True, approx_centered=approx_centered ) self.model.update(self.params) cov_params, singular_values = pinv_extended( np.dot(np.dot(evaluated_hessian, cov_opg), evaluated_hessian) ) if self._rank is None: self._rank = np.linalg.matrix_rank(np.diag(singular_values)) return cov_params @cache_readonly def cov_params_robust_approx(self): """ (array) The QMLE variance / covariance matrix. Computed using the numerical Hessian as the evaluated hessian. """ return self._cov_params_robust_approx(self._cov_approx_complex_step, self._cov_approx_centered) @cache_readonly def fittedvalues(self): """ (array) The predicted values of the model. An (nobs x k_endog) array. """ # This is a (k_endog x nobs array; don't want to squeeze in case of # the corner case where nobs = 1 (mostly a concern in the predict or # forecast functions, but here also to maintain consistency) fittedvalues = self.filter_results.forecasts if fittedvalues.shape[0] == 1: fittedvalues = fittedvalues[0, :] else: fittedvalues = fittedvalues.T return fittedvalues @cache_readonly def hqic(self): """ (float) Hannan-Quinn Information Criterion """ # return -2*self.llf + 2*np.log(np.log(self.nobs))*self.params.shape[0] return hqic(self.llf, self.nobs, self.params.shape[0]) @cache_readonly def llf_obs(self): """ (float) The value of the log-likelihood function evaluated at `params`. """ return self.model.loglikeobs(self.params) @cache_readonly def llf(self): """ (float) The value of the log-likelihood function evaluated at `params`. """ return self.llf_obs[self.filter_results.loglikelihood_burn:].sum() @cache_readonly def loglikelihood_burn(self): """ (float) The number of observations during which the likelihood is not evaluated. """ return self.filter_results.loglikelihood_burn @cache_readonly def pvalues(self): """ (array) The p-values associated with the z-statistics of the coefficients. Note that the coefficients are assumed to have a Normal distribution. """ return norm.sf(np.abs(self.zvalues)) * 2 @cache_readonly def resid(self): """ (array) The model residuals. An (nobs x k_endog) array. """ # This is a (k_endog x nobs array; don't want to squeeze in case of # the corner case where nobs = 1 (mostly a concern in the predict or # forecast functions, but here also to maintain consistency) resid = self.filter_results.forecasts_error if resid.shape[0] == 1: resid = resid[0, :] else: resid = resid.T return resid @cache_readonly def zvalues(self): """ (array) The z-statistics for the coefficients. """ return self.params / self.bse def test_normality(self, method): """ Test for normality of standardized residuals. Null hypothesis is normality. Parameters ---------- method : string {'jarquebera'} or None The statistical test for normality. Must be 'jarquebera' for Jarque-Bera normality test. If None, an attempt is made to select an appropriate test. Notes ----- If the first `d` loglikelihood values were burned (i.e. in the specified model, `loglikelihood_burn=d`), then this test is calculated ignoring the first `d` residuals. In the case of missing data, the maintained hypothesis is that the data are missing completely at random. This test is then run on the standardized residuals excluding those corresponding to missing observations. See Also -------- statsmodels.stats.stattools.jarque_bera """ if method is None: method = 'jarquebera' if method == 'jarquebera': from statsmodels.stats.stattools import jarque_bera d = self.loglikelihood_burn output = [] for i in range(self.model.k_endog): resid = self.filter_results.standardized_forecasts_error[i, d:] mask = ~np.isnan(resid) output.append(jarque_bera(resid[mask])) else: raise NotImplementedError('Invalid normality test method.') return np.array(output) def test_heteroskedasticity(self, method, alternative='two-sided', use_f=True): r""" Test for heteroskedasticity of standardized residuals Tests whether the sum-of-squares in the first third of the sample is significantly different than the sum-of-squares in the last third of the sample. Analogous to a Goldfeld-Quandt test. The null hypothesis is of no heteroskedasticity. Parameters ---------- method : string {'breakvar'} or None The statistical test for heteroskedasticity. Must be 'breakvar' for test of a break in the variance. If None, an attempt is made to select an appropriate test. alternative : string, 'increasing', 'decreasing' or 'two-sided' This specifies the alternative for the p-value calculation. Default is two-sided. use_f : boolean, optional Whether or not to compare against the asymptotic distribution (chi-squared) or the approximate small-sample distribution (F). Default is True (i.e. default is to compare against an F distribution). Returns ------- output : array An array with `(test_statistic, pvalue)` for each endogenous variable. The array is then sized `(k_endog, 2)`. If the method is called as `het = res.test_heteroskedasticity()`, then `het[0]` is an array of size 2 corresponding to the first endogenous variable, where `het[0][0]` is the test statistic, and `het[0][1]` is the p-value. Notes ----- The null hypothesis is of no heteroskedasticity. That means different things depending on which alternative is selected: - Increasing: Null hypothesis is that the variance is not increasing throughout the sample; that the sum-of-squares in the later subsample is *not* greater than the sum-of-squares in the earlier subsample. - Decreasing: Null hypothesis is that the variance is not decreasing throughout the sample; that the sum-of-squares in the earlier subsample is *not* greater than the sum-of-squares in the later subsample. - Two-sided: Null hypothesis is that the variance is not changing throughout the sample. Both that the sum-of-squares in the earlier subsample is not greater than the sum-of-squares in the later subsample *and* that the sum-of-squares in the later subsample is not greater than the sum-of-squares in the earlier subsample. For :math:`h = [T/3]`, the test statistic is: .. math:: H(h) = \sum_{t=T-h+1}^T \tilde v_t^2 \Bigg / \sum_{t=d+1}^{d+1+h} \tilde v_t^2 where :math:`d` is the number of periods in which the loglikelihood was burned in the parent model (usually corresponding to diffuse initialization). This statistic can be tested against an :math:`F(h,h)` distribution. Alternatively, :math:`h H(h)` is asymptotically distributed according to :math:`\chi_h^2`; this second test can be applied by passing `asymptotic=True` as an argument. See section 5.4 of [1]_ for the above formula and discussion, as well as additional details. TODO - Allow specification of :math:`h` References ---------- .. [1] Harvey, Andrew C. 1990. Forecasting, Structural Time Series Models and the Kalman Filter. Cambridge University Press. """ if method is None: method = 'breakvar' if method == 'breakvar': # Store some values squared_resid = self.filter_results.standardized_forecasts_error**2 d = self.loglikelihood_burn test_statistics = [] p_values = [] for i in range(self.model.k_endog): h = int(np.round((self.nobs - d) / 3)) numer_resid = squared_resid[i, -h:] numer_resid = numer_resid[~np.isnan(numer_resid)] numer_dof = len(numer_resid) denom_resid = squared_resid[i, d:d+h] denom_resid = denom_resid[~np.isnan(denom_resid)] denom_dof = len(denom_resid) if numer_dof < 2: warnings.warn('Early subset of data for variable %d' ' has too few non-missing observations to' ' calculate test statistic.' % i) numer_resid = np.nan if denom_dof < 2: warnings.warn('Later subset of data for variable %d' ' has too few non-missing observations to' ' calculate test statistic.' % i) denom_resid = np.nan test_statistic = np.sum(numer_resid) / np.sum(denom_resid) # Setup functions to calculate the p-values if use_f: from scipy.stats import f pval_lower = lambda test_statistics: f.cdf( test_statistics, numer_dof, denom_dof) pval_upper = lambda test_statistics: f.sf( test_statistics, numer_dof, denom_dof) else: from scipy.stats import chi2 pval_lower = lambda test_statistics: chi2.cdf( numer_dof * test_statistics, denom_dof) pval_upper = lambda test_statistics: chi2.sf( numer_dof * test_statistics, denom_dof) # Calculate the one- or two-sided p-values alternative = alternative.lower() if alternative in ['i', 'inc', 'increasing']: p_value = pval_upper(test_statistic) elif alternative in ['d', 'dec', 'decreasing']: test_statistic = 1. / test_statistic p_value = pval_upper(test_statistic) elif alternative in ['2', '2-sided', 'two-sided']: p_value = 2 * np.minimum( pval_lower(test_statistic), pval_upper(test_statistic) ) else: raise ValueError('Invalid alternative.') test_statistics.append(test_statistic) p_values.append(p_value) output = np.c_[test_statistics, p_values] else: raise NotImplementedError('Invalid heteroskedasticity test' ' method.') return output def test_serial_correlation(self, method, lags=None): """ Ljung-box test for no serial correlation of standardized residuals Null hypothesis is no serial correlation. Parameters ---------- method : string {'ljungbox','boxpierece'} or None The statistical test for serial correlation. If None, an attempt is made to select an appropriate test. lags : None, int or array_like If lags is an integer then this is taken to be the largest lag that is included, the test result is reported for all smaller lag length. If lags is a list or array, then all lags are included up to the largest lag in the list, however only the tests for the lags in the list are reported. If lags is None, then the default maxlag is 12*(nobs/100)^{1/4} Returns ------- output : array An array with `(test_statistic, pvalue)` for each endogenous variable and each lag. The array is then sized `(k_endog, 2, lags)`. If the method is called as `ljungbox = res.test_serial_correlation()`, then `ljungbox[i]` holds the results of the Ljung-Box test (as would be returned by `statsmodels.stats.diagnostic.acorr_ljungbox`) for the `i` th endogenous variable. Notes ----- If the first `d` loglikelihood values were burned (i.e. in the specified model, `loglikelihood_burn=d`), then this test is calculated ignoring the first `d` residuals. Output is nan for any endogenous variable which has missing values. See Also -------- statsmodels.stats.diagnostic.acorr_ljungbox """ if method is None: method = 'ljungbox' if method == 'ljungbox' or method == 'boxpierce': from statsmodels.stats.diagnostic import acorr_ljungbox d = self.loglikelihood_burn output = [] # Default lags for acorr_ljungbox is 40, but may not always have # that many observations if lags is None: lags = min(40, self.nobs - d - 1) for i in range(self.model.k_endog): results = acorr_ljungbox( self.filter_results.standardized_forecasts_error[i][d:], lags=lags, boxpierce=(method == 'boxpierce')) if method == 'ljungbox': output.append(results[0:2]) else: output.append(results[2:]) output = np.c_[output] else: raise NotImplementedError('Invalid serial correlation test' ' method.') return output def get_prediction(self, start=None, end=None, dynamic=False, **kwargs): """ In-sample prediction and out-of-sample forecasting Parameters ---------- start : int, str, or datetime, optional Zero-indexed observation number at which to start forecasting, i.e., the first forecast is start. Can also be a date string to parse or a datetime type. Default is the the zeroth observation. end : int, str, or datetime, optional Zero-indexed observation number at which to end forecasting, i.e., the last forecast is end. Can also be a date string to parse or a datetime type. However, if the dates index does not have a fixed frequency, end must be an integer index if you want out of sample prediction. Default is the last observation in the sample. dynamic : boolean, int, str, or datetime, optional Integer offset relative to `start` at which to begin dynamic prediction. Can also be an absolute date string to parse or a datetime type (these are not interpreted as offsets). Prior to this observation, true endogenous values will be used for prediction; starting with this observation and continuing through the end of prediction, forecasted endogenous values will be used instead. **kwargs Additional arguments may required for forecasting beyond the end of the sample. See `FilterResults.predict` for more details. Returns ------- forecast : array Array of out of in-sample predictions and / or out-of-sample forecasts. An (npredict x k_endog) array. """ if start is None: start = 0 # Handle start and end (e.g. dates) start = self.model._get_predict_start(start) end, out_of_sample = self.model._get_predict_end(end) # Handle string dynamic dates = self.data.dates if isinstance(dynamic, str): if dates is None: raise ValueError("Got a string for dynamic and dates is None") dtdynamic = self.model._str_to_date(dynamic) try: dynamic_start = self.model._get_dates_loc(dates, dtdynamic) dynamic = dynamic_start - start except KeyError: raise ValueError("Dynamic must be in dates. Got %s | %s" % (str(dynamic), str(dtdynamic))) # Perform the prediction # This is a (k_endog x npredictions) array; don't want to squeeze in # case of npredictions = 1 prediction_results = self.filter_results.predict( start, end+out_of_sample+1, dynamic, **kwargs ) # Return a new mlemodel.PredictionResults object if self.data.dates is None: row_labels = self.data.row_labels else: row_labels = self.data.predict_dates return PredictionResultsWrapper( PredictionResults(self, prediction_results, row_labels=row_labels)) def get_forecast(self, steps=1, **kwargs): """ Out-of-sample forecasts Parameters ---------- steps : int, str, or datetime, optional If an integer, the number of steps to forecast from the end of the sample. Can also be a date string to parse or a datetime type. However, if the dates index does not have a fixed frequency, steps must be an integer. Default **kwargs Additional arguments may required for forecasting beyond the end of the sample. See `FilterResults.predict` for more details. Returns ------- forecast : array Array of out of sample forecasts. A (steps x k_endog) array. """ if isinstance(steps, (int, long)): end = self.nobs+steps-1 else: end = steps return self.get_prediction(start=self.nobs, end=end, **kwargs) def predict(self, start=None, end=None, dynamic=False, **kwargs): """ In-sample prediction and out-of-sample forecasting Parameters ---------- start : int, str, or datetime, optional Zero-indexed observation number at which to start forecasting, i.e., the first forecast is start. Can also be a date string to parse or a datetime type. Default is the the zeroth observation. end : int, str, or datetime, optional Zero-indexed observation number at which to end forecasting, i.e., the last forecast is end. Can also be a date string to parse or a datetime type. However, if the dates index does not have a fixed frequency, end must be an integer index if you want out of sample prediction. Default is the last observation in the sample. dynamic : boolean, int, str, or datetime, optional Integer offset relative to `start` at which to begin dynamic prediction. Can also be an absolute date string to parse or a datetime type (these are not interpreted as offsets). Prior to this observation, true endogenous values will be used for prediction; starting with this observation and continuing through the end of prediction, forecasted endogenous values will be used instead. **kwargs Additional arguments may required for forecasting beyond the end of the sample. See `FilterResults.predict` for more details. Returns ------- forecast : array Array of out of in-sample predictions and / or out-of-sample forecasts. An (npredict x k_endog) array. """ # Perform the prediction prediction_results = self.get_prediction(start, end, dynamic, **kwargs) return prediction_results.predicted_mean def forecast(self, steps=1, **kwargs): """ Out-of-sample forecasts Parameters ---------- steps : int, str, or datetime, optional If an integer, the number of steps to forecast from the end of the sample. Can also be a date string to parse or a datetime type. However, if the dates index does not have a fixed frequency, steps must be an integer. Default **kwargs Additional arguments may required for forecasting beyond the end of the sample. See `FilterResults.predict` for more details. Returns ------- forecast : array Array of out of sample forecasts. A (steps x k_endog) array. """ if isinstance(steps, (int, long)): end = self.nobs+steps-1 else: end = steps return self.predict(start=self.nobs, end=end, **kwargs) def simulate(self, nsimulations, measurement_shocks=None, state_shocks=None, initial_state=None): r""" Simulate a new time series following the state space model Parameters ---------- nsimulations : int The number of observations to simulate. If the model is time-invariant this can be any number. If the model is time-varying, then this number must be less than or equal to the number measurement_shocks : array_like, optional If specified, these are the shocks to the measurement equation, :math:`\varepsilon_t`. If unspecified, these are automatically generated using a pseudo-random number generator. If specified, must be shaped `nsimulations` x `k_endog`, where `k_endog` is the same as in the state space model. state_shocks : array_like, optional If specified, these are the shocks to the state equation, :math:`\eta_t`. If unspecified, these are automatically generated using a pseudo-random number generator. If specified, must be shaped `nsimulations` x `k_posdef` where `k_posdef` is the same as in the state space model. initial_state : array_like, optional If specified, this is the state vector at time zero, which should be shaped (`k_states` x 1), where `k_states` is the same as in the state space model. If unspecified, but the model has been initialized, then that initialization is used. If unspecified and the model has not been initialized, then a vector of zeros is used. Note that this is not included in the returned `simulated_states` array. Returns ------- simulated_obs : array An (nsimulations x k_endog) array of simulated observations. """ return self.model.simulate(self.params, nsimulations, measurement_shocks, state_shocks, initial_state) def impulse_responses(self, steps=1, impulse=0, orthogonalized=False, cumulative=False, **kwargs): """ Impulse response function Parameters ---------- steps : int, optional The number of steps for which impulse responses are calculated. Default is 1. Note that the initial impulse is not counted as a step, so if `steps=1`, the output will have 2 entries. impulse : int or array_like If an integer, the state innovation to pulse; must be between 0 and `k_posdef-1`. Alternatively, a custom impulse vector may be provided; must be shaped `k_posdef x 1`. orthogonalized : boolean, optional Whether or not to perform impulse using orthogonalized innovations. Note that this will also affect custum `impulse` vectors. Default is False. cumulative : boolean, optional Whether or not to return cumulative impulse responses. Default is False. **kwargs If the model is time-varying and `steps` is greater than the number of observations, any of the state space representation matrices that are time-varying must have updated values provided for the out-of-sample steps. For example, if `design` is a time-varying component, `nobs` is 10, and `steps` is 15, a (`k_endog` x `k_states` x 5) matrix must be provided with the new design matrix values. Returns ------- impulse_responses : array Responses for each endogenous variable due to the impulse given by the `impulse` argument. A (steps + 1 x k_endog) array. Notes ----- Intercepts in the measurement and state equation are ignored when calculating impulse responses. """ return self.model.impulse_responses(self.params, steps, impulse, orthogonalized, cumulative, **kwargs) def plot_diagnostics(self, variable=0, lags=10, fig=None, figsize=None): """ Diagnostic plots for standardized residuals of one endogenous variable Parameters ---------- variable : integer, optional Index of the endogenous variable for which the diagnostic plots should be created. Default is 0. lags : integer, optional Number of lags to include in the correlogram. Default is 10. fig : Matplotlib Figure instance, optional If given, subplots are created in this figure instead of in a new figure. Note that the 2x2 grid will be created in the provided figure using `fig.add_subplot()`. figsize : tuple, optional If a figure is created, this argument allows specifying a size. The tuple is (width, height). Notes ----- Produces a 2x2 plot grid with the following plots (ordered clockwise from top left): 1. Standardized residuals over time 2. Histogram plus estimated density of standardized residulas, along with a Normal(0,1) density plotted for reference. 3. Normal Q-Q plot, with Normal reference line. 4. Correlogram See Also -------- statsmodels.graphics.gofplots.qqplot statsmodels.graphics.tsaplots.plot_acf """ from statsmodels.graphics.utils import _import_mpl, create_mpl_fig _import_mpl() fig = create_mpl_fig(fig, figsize) # Eliminate residuals associated with burned likelihoods d = self.loglikelihood_burn resid = self.filter_results.standardized_forecasts_error[variable, d:] # Top-left: residuals vs time ax = fig.add_subplot(221) if hasattr(self.data, 'dates') and self.data.dates is not None: x = self.data.dates[self.loglikelihood_burn:]._mpl_repr() else: x = np.arange(len(resid)) ax.plot(x, resid) ax.hlines(0, x[0], x[-1], alpha=0.5) ax.set_xlim(x[0], x[-1]) ax.set_title('Standardized residual') # Top-right: histogram, Gaussian kernel density, Normal density # Can only do histogram and Gaussian kernel density on the non-null # elements resid_nonmissing = resid[~(np.isnan(resid))] ax = fig.add_subplot(222) ax.hist(resid_nonmissing, normed=True, label='Hist') from scipy.stats import gaussian_kde, norm kde = gaussian_kde(resid_nonmissing) xlim = (-1.96*2, 1.96*2) x = np.linspace(xlim[0], xlim[1]) ax.plot(x, kde(x), label='KDE') ax.plot(x, norm.pdf(x), label='N(0,1)') ax.set_xlim(xlim) ax.legend() ax.set_title('Histogram plus estimated density') # Bottom-left: QQ plot ax = fig.add_subplot(223) from statsmodels.graphics.gofplots import qqplot qqplot(resid_nonmissing, line='s', ax=ax) ax.set_title('Normal Q-Q') # Bottom-right: Correlogram ax = fig.add_subplot(224) from statsmodels.graphics.tsaplots import plot_acf plot_acf(resid, ax=ax, lags=lags) ax.set_title('Correlogram') ax.set_ylim(-1, 1) return fig def summary(self, alpha=.05, start=None, title=None, model_name=None, display_params=True): """ Summarize the Model Parameters ---------- alpha : float, optional Significance level for the confidence intervals. Default is 0.05. start : int, optional Integer of the start observation. Default is 0. model_name : string The name of the model used. Default is to use model class name. Returns ------- summary : Summary instance This holds the summary table and text, which can be printed or converted to various output formats. See Also -------- statsmodels.iolib.summary.Summary """ from statsmodels.iolib.summary import Summary # Model specification results model = self.model if title is None: title = 'Statespace Model Results' if start is None: start = 0 if self.data.dates is not None: dates = self.data.dates d = dates[start] sample = ['%02d-%02d-%02d' % (d.month, d.day, d.year)] d = dates[-1] sample += ['- ' + '%02d-%02d-%02d' % (d.month, d.day, d.year)] else: sample = [str(start), ' - ' + str(self.model.nobs)] # Standardize the model name as a list of str if model_name is None: model_name = model.__class__.__name__ # Diagnostic tests results try: het = self.test_heteroskedasticity(method='breakvar') except: het = np.array([[np.nan]*2]) try: lb = self.test_serial_correlation(method='ljungbox') except: lb = np.array([[np.nan]*2]).reshape(1, 2, 1) try: jb = self.test_normality(method='jarquebera') except: jb = np.array([[np.nan]*4]) # Create the tables if not isinstance(model_name, list): model_name = [model_name] top_left = [('Dep. Variable:', None)] top_left.append(('Model:', [model_name[0]])) for i in range(1, len(model_name)): top_left.append(('', ['+ ' + model_name[i]])) top_left += [ ('Date:', None), ('Time:', None), ('Sample:', [sample[0]]), ('', [sample[1]]) ] top_right = [ ('No. Observations:', [self.model.nobs]), ('Log Likelihood', ["%#5.3f" % self.llf]), ('AIC', ["%#5.3f" % self.aic]), ('BIC', ["%#5.3f" % self.bic]), ('HQIC', ["%#5.3f" % self.hqic]) ] if hasattr(self, 'cov_type'): top_left.append(('Covariance Type:', [self.cov_type])) format_str = lambda array: [ ', '.join(['{0:.2f}'.format(i) for i in array]) ] diagn_left = [('Ljung-Box (Q):', format_str(lb[:, 0, -1])), ('Prob(Q):', format_str(lb[:, 1, -1])), ('Heteroskedasticity (H):', format_str(het[:, 0])), ('Prob(H) (two-sided):', format_str(het[:, 1])) ] diagn_right = [('Jarque-Bera (JB):', format_str(jb[:, 0])), ('Prob(JB):', format_str(jb[:, 1])), ('Skew:', format_str(jb[:, 2])), ('Kurtosis:', format_str(jb[:, 3])) ] summary = Summary() summary.add_table_2cols(self, gleft=top_left, gright=top_right, title=title) if len(self.params) > 0 and display_params: summary.add_table_params(self, alpha=alpha, xname=self.data.param_names, use_t=False) summary.add_table_2cols(self, gleft=diagn_left, gright=diagn_right, title="") # Add warnings/notes, added to text format only etext = [] if hasattr(self, 'cov_type') and 'description' in self.cov_kwds: etext.append(self.cov_kwds['description']) if self._rank < len(self.params): etext.append("Covariance matrix is singular or near-singular," " with condition number %6.3g. Standard errors may be" " unstable." % np.linalg.cond(self.cov_params())) if etext: etext = ["[{0}] {1}".format(i + 1, text) for i, text in enumerate(etext)] etext.insert(0, "Warnings:") summary.add_extra_txt(etext) return summary class MLEResultsWrapper(wrap.ResultsWrapper): _attrs = { 'zvalues': 'columns', 'cov_params_approx': 'cov', 'cov_params_default': 'cov', 'cov_params_oim': 'cov', 'cov_params_opg': 'cov', 'cov_params_robust': 'cov', 'cov_params_robust_approx': 'cov', 'cov_params_robust_oim': 'cov', } _wrap_attrs = wrap.union_dicts(tsbase.TimeSeriesResultsWrapper._wrap_attrs, _attrs) _methods = { 'forecast': 'dates', 'simulate': 'ynames', 'impulse_responses': 'ynames' } _wrap_methods = wrap.union_dicts( tsbase.TimeSeriesResultsWrapper._wrap_methods, _methods) wrap.populate_wrapper(MLEResultsWrapper, MLEResults) class PredictionResults(pred.PredictionResults): """ Parameters ---------- prediction_results : kalman_filter.PredictionResults instance Results object from prediction after fitting or filtering a state space model. row_labels : iterable Row labels for the predicted data. Attributes ---------- """ def __init__(self, model, prediction_results, row_labels=None): if model.model.k_endog == 1: endog = pd.Series(prediction_results.endog[:, 0], name=model.model.endog_names) else: endog = pd.DataFrame(prediction_results.endog.T, columns=model.model.endog_names) self.model = Bunch(data=model.data.__class__( endog=endog, predict_dates=getattr(model.data, 'predict_dates', None)), ) self.prediction_results = prediction_results # Get required values predicted_mean = self.prediction_results.forecasts if predicted_mean.shape[0] == 1: predicted_mean = predicted_mean[0, :] else: predicted_mean = predicted_mean.transpose() var_pred_mean = self.prediction_results.forecasts_error_cov if var_pred_mean.shape[0] == 1: var_pred_mean = var_pred_mean[0, 0, :] else: var_pred_mean = var_pred_mean.transpose() # Initialize super(PredictionResults, self).__init__(predicted_mean, var_pred_mean, dist='norm', row_labels=row_labels, link=identity()) @property def se_mean(self): if self.var_pred_mean.ndim == 1: se_mean = np.sqrt(self.var_pred_mean) else: se_mean = np.sqrt(self.var_pred_mean.T.diagonal()) return se_mean def conf_int(self, method='endpoint', alpha=0.05, **kwds): # TODO: this performs metadata wrapping, and that should be handled # by attach_* methods. However, they don't currently support # this use case. conf_int = super(PredictionResults, self).conf_int( method, alpha, **kwds) # Create a dataframe if self.model.data.predict_dates is not None: conf_int = pd.DataFrame(conf_int, index=self.model.data.predict_dates) else: conf_int = pd.DataFrame(conf_int) # Attach the endog names ynames = self.model.data.ynames if not type(ynames) == list: ynames = [ynames] names = (['lower %s' % name for name in ynames] + ['upper %s' % name for name in ynames]) conf_int.columns = names return conf_int def summary_frame(self, endog=0, what='all', alpha=0.05): # TODO: finish and cleanup # import pandas as pd from statsmodels.compat.collections import OrderedDict # ci_obs = self.conf_int(alpha=alpha, obs=True) # need to split ci_mean = self.conf_int(alpha=alpha).values to_include = OrderedDict() if self.predicted_mean.ndim == 1: yname = self.model.data.ynames to_include['mean'] = self.predicted_mean to_include['mean_se'] = self.se_mean k_endog = 1 else: yname = self.model.data.ynames[endog] to_include['mean'] = self.predicted_mean[:, endog] to_include['mean_se'] = self.se_mean[:, endog] k_endog = self.predicted_mean.shape[1] to_include['mean_ci_lower'] = ci_mean[:, endog] to_include['mean_ci_upper'] = ci_mean[:, k_endog + endog] self.table = to_include # OrderedDict doesn't work to preserve sequence # pandas dict doesn't handle 2d_array # data = np.column_stack(list(to_include.values())) # names = .... res = pd.DataFrame(to_include, index=self.row_labels, columns=to_include.keys()) res.columns.name = yname return res class PredictionResultsWrapper(wrap.ResultsWrapper): _attrs = { 'predicted_mean': 'dates', 'se_mean': 'dates', 't_values': 'dates', } _wrap_attrs = wrap.union_dicts(_attrs) _methods = {} _wrap_methods = wrap.union_dicts(_methods) wrap.populate_wrapper(PredictionResultsWrapper, PredictionResults)
{ "content_hash": "2084c50513c750296df8ca09820ed5f3", "timestamp": "", "source": "github", "line_count": 2862, "max_line_length": 79, "avg_line_length": 39.515373864430465, "alnum_prop": 0.579929792294837, "repo_name": "yl565/statsmodels", "id": "7b107bfad0e6f08b443f1d2f41b1096ea3401ed8", "size": "113093", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "statsmodels/tsa/statespace/mlemodel.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "AGS Script", "bytes": "457842" }, { "name": "Assembly", "bytes": "10035" }, { "name": "Batchfile", "bytes": "351" }, { "name": "C", "bytes": "12088" }, { "name": "HTML", "bytes": "148470" }, { "name": "Matlab", "bytes": "2609" }, { "name": "Python", "bytes": "9670281" }, { "name": "R", "bytes": "55204" }, { "name": "Stata", "bytes": "54989" } ], "symlink_target": "" }
- Creates a new image on which which each pixel’s value is calculated as a specified function of its value in the first band of a specified image. This function is specified by explicitly identifying the output value it associates with each of a selected sample set of input values. Other output values are then inferred by interpolating or extrapolating from these samples. ## Syntax #### Javascript ``` newImage = oldImage.interpolate( listOfTypicalInputs, listOfTypicalOutputs, extrapolationMethod ) ``` - *newImage* is the new image. - *oldImage* is the specified image. - *listOfTypicalInputs* is the specified input value samples, given as an array of Doubles in strictly increasing order. - *listOfTypicalOutputs* is the specified output value samples, given as an array of Doubles in an order corresponding to that of listOfTypicalOutputs. - *extrapolationMethod* is the method by which outputs are to be inferred for inputs above or below the range specified in listOfTypicalInputs, given as one of the following four strings. - "extrapolate" means extrapolate from the two nearest inputs. - "clamp" means use the nearest input. - "input" means use the pixel’s original value. - "mask" means mask the pixel. Argument names used in Docs: ``` newImage = oldImage.interpolate( x, y, behavior ) ``` ## Example #### Javascript ```javascript var AllFEATURES = ee.FeatureCollection( 'ft:1G3RZbWoTiCiYv_LEwc7xKZq8aYoPZlL5_KuVhyDM' ); // U.S. Cities var SomeFEATURES = AllFEATURES.filterMetadata('city_name', 'contains', 'Houston' ); var DistanceIMAGE = SomeFEATURES.distance( 800000 ); var DistanceEffectIMAGE = DistanceIMAGE.interpolate( [ 0.0, 100000.0, 200000.0, 300000.0, 400000.0 ], [ 0, 60, 90, 100, 75 ], 'extrapolate' ); Map.centerObject( SomeFEATURES, 5 ); Map.addLayer( DistanceIMAGE, {min:0, max:800000, palette:'0000dd,ff0000'}, 'Distance' ); Map.addLayer( DistanceEffectIMAGE, {min:0, max:100, palette:'0000dd,ff0000'}, 'Distance Effect' ); ```
{ "content_hash": "3b2563a96f82b987b386cd5680a7bdb0", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 374, "avg_line_length": 55, "alnum_prop": 0.7186602870813397, "repo_name": "EEYale/example-scripts", "id": "fa196f57adda1d6b076ae746f3c9d5bc5f3a9937", "size": "2114", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Images/image.interpolate.md", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
@class VMStream<T>; @interface NSArray<T> (Streaming) @property (nonatomic, readonly, strong, nonnull) VMStream<T> *stream; @end
{ "content_hash": "bd8642b37abda156bdf6dfdf257eb7f8", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 69, "avg_line_length": 18.857142857142858, "alnum_prop": 0.7272727272727273, "repo_name": "bobermaniac/VMUtils", "id": "dc4b6ed4609230bc5a17d20b886dc2e2c7ad40b3", "size": "315", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "VMUtils/Streaming/Extensions/NSArray+Streaming.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "34426" } ], "symlink_target": "" }
layout: post title: Forests Underwater by Takashi Amano (Lisbon Oceanarium - Portugal) --- <div class="message"> A new temporary exhibition highlights the tropical forests and the richness of its aquatic systems, through the largest "nature aquarium" in the world. The "nature aquarium" is 40 metres in length and holds 160,000 litres of fresh water, four tonnes of sand, 25 tonnes of volcanic rock from the Azores and 78 tree trunks from Scotland and Malaysia. It is populated with over 10,000 tropical fish and 46 species of aquatic plants. Credits: <a href="http://www.oceanario.pt">http://www.oceanario.pt</a> </div> <style>.embed-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; } .embed-container iframe, .embed-container object, .embed-container embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }</style><div class="embed-container"><iframe src="//www.youtube.com/embed/UgMrVaAaJ4U?rel=0&amp;showinfo=0" frameborder="0" allowfullscreen></iframe></div>
{ "content_hash": "b81e5b5ccc4047a566a2a8b6137890c2", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 413, "avg_line_length": 79.92307692307692, "alnum_prop": 0.7555341674687199, "repo_name": "ffsantos92/website", "id": "19ef87cdf4e419c7546f4be6ef0095a16beec32f", "size": "1043", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "_posts/2015-07-06-forests-underwater-lisbon-oceanarium-portugal.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "13333" }, { "name": "HTML", "bytes": "19783" } ], "symlink_target": "" }
import { moduleForComponent, test } from 'ember-qunit'; moduleForComponent('rendering-core', 'Integration | Component | rendering core', { integration: true }); test('it renders', function(assert) { // Set any properties with this.set('myProperty', 'value'); // Handle any actions with this.on('myAction', function(val) { ... }); //this.render(hbs`{{landscape-rendering}}`); assert.equal(true, true); // Template block usage: //this.render(hbs` // {{#landscape-rendering}} // template block text // {{/landscape-rendering}} // `); });
{ "content_hash": "0badc0cd5df4d14c2aecb5bc9c26f836", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 82, "avg_line_length": 25.772727272727273, "alnum_prop": 0.6507936507936508, "repo_name": "ExplorViz/explorviz-ui-frontend", "id": "c58085751a0c2a95676f05892566dcc205482775", "size": "567", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/integration/components/visualization/rendering/rendering-core.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1215" }, { "name": "HTML", "bytes": "10199" }, { "name": "JavaScript", "bytes": "253881" }, { "name": "Shell", "bytes": "573" } ], "symlink_target": "" }
module DbRefactor end
{ "content_hash": "c9917b079b9ab0242adeb36ef67b787a", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 17, "avg_line_length": 10.5, "alnum_prop": 0.9047619047619048, "repo_name": "rud/db_refactor", "id": "a632c22777131bc30385026c37227a8c556e3cf1", "size": "21", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/db_refactor.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "12155" } ], "symlink_target": "" }
YUI().use('node', 'event', function (Y) { var chkbx = Y.one("#id_cutoffdate_enabled"); chkbx.on("change", function (e) { if (e.target.get("checked")) { // alert("checked"); Y.one('#id_cutoffdate_day').set('selectedIndex',Y.one('#id_duedate_day').get('selectedIndex')); Y.one('#id_cutoffdate_month').set('selectedIndex',Y.one('#id_duedate_month').get('selectedIndex')); Y.one('#id_cutoffdate_year').set('selectedIndex',Y.one('#id_duedate_year').get('selectedIndex')); Y.one('#id_cutoffdate_hour').set('selectedIndex',Y.one('#id_duedate_hour').get('selectedIndex')); Y.one('#id_cutoffdate_minute').set('selectedIndex',Y.one('#id_duedate_minute').get('selectedIndex')); } }); });
{ "content_hash": "6640269da185ec19f1dbc3146d6781b0", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 104, "avg_line_length": 50.214285714285715, "alnum_prop": 0.6500711237553343, "repo_name": "8bitcoderookie/moodle-theme_clean_brg4", "id": "7e84887db8ed35ee280396835e9b12eb126f6da4", "size": "935", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "javascript/syncCutOffDate.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "4414" }, { "name": "JavaScript", "bytes": "14852" }, { "name": "PHP", "bytes": "45953" } ], "symlink_target": "" }
package com.cnpc.framework.utils; import net.sourceforge.pinyin4j.PinyinHelper; import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType; import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat; import net.sourceforge.pinyin4j.format.HanyuPinyinToneType; import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType; import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination; /** * 拼音工具类 * * @author jrn */ public class PingYinUtil { /** * 将字符串中的中文转化为拼音,其他字符不变 * * @param inputString * @return */ /* public static void main(String[] args){ System.out.println(PingYinUtil.getPingYin("性别")); System.out.println(PingYinUtil.getFirstSpell("性别")); System.out.println(PingYinUtil.getFullSpell("性别")); }*/ public static String getPingYin(String inputString) { HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat(); format.setCaseType(HanyuPinyinCaseType.LOWERCASE); format.setToneType(HanyuPinyinToneType.WITHOUT_TONE); format.setVCharType(HanyuPinyinVCharType.WITH_V); char[] input = inputString.trim().toCharArray(); String output = ""; try { for (int i = 0; i < input.length; i++) { if (Character.toString(input[i]).matches("[\\u4E00-\\u9FA5]+")) { String[] temp = PinyinHelper.toHanyuPinyinStringArray(input[i], format); output += temp[0]; } else output += Character.toString(input[i]); } } catch (BadHanyuPinyinOutputFormatCombination e) { e.printStackTrace(); } return output; } /** * 获取汉字串拼音首字母,英文字符不变 * @param chinese 汉字串 * @return 汉语拼音首字母 */ public static String getFirstSpell(String chinese) { StringBuffer pybf = new StringBuffer(); char[] arr = chinese.toCharArray(); HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat(); defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE); defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE); for (int i = 0; i < arr.length; i++) { if (arr[i] > 128) { try { String[] temp = PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat); if (temp != null) { pybf.append(temp[0].charAt(0)); } } catch (BadHanyuPinyinOutputFormatCombination e) { e.printStackTrace(); } } else { pybf.append(arr[i]); } } return pybf.toString().replaceAll("\\W", "").trim(); } /** * 获取汉字串拼音,英文字符不变 * @param chinese 汉字串 * @return 汉语拼音 */ public static String getFullSpell(String chinese) { StringBuffer pybf = new StringBuffer(); char[] arr = chinese.toCharArray(); HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat(); defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE); defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE); for (int i = 0; i < arr.length; i++) { if (arr[i] > 128) { try { pybf.append(PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat)[0]); } catch (BadHanyuPinyinOutputFormatCombination e) { e.printStackTrace(); } } else { pybf.append(arr[i]); } } return pybf.toString(); } }
{ "content_hash": "ecd1c8d0bd3196b4a46a618eacfe2e28", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 116, "avg_line_length": 39.12, "alnum_prop": 0.5516359918200409, "repo_name": "XilongPei/Openparts", "id": "5eb03b9cee8dd8dfccf08b009b3354a1f8f9a059", "size": "4068", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Openparts-framework/src/main/java/com/cnpc/framework/utils/PingYinUtil.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "696320" }, { "name": "HTML", "bytes": "50670152" }, { "name": "Java", "bytes": "953997" }, { "name": "JavaScript", "bytes": "3265610" }, { "name": "PHP", "bytes": "5041" } ], "symlink_target": "" }
namespace HanRuEdu.LDAL { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; [MetadataType(typeof(EDU_ZXJX_55_A03_XSSFXMBZ_metadata))] public partial class EDU_ZXJX_55_A03_XSSFXMBZ { public EDU_ZXJX_55_A03_XSSFXMBZ() { BZ = ""; } public class EDU_ZXJX_55_A03_XSSFXMBZ_metadata { [Required(ErrorMessage = "±ØÌî")] [Display(Name = "±àºÅ")] public Int32 ID { get; set; } [Required(ErrorMessage = "±ØÌî")] [Display(Name = "ѧУ")] public Int32 SCHOOLID { get; set; } [Required(ErrorMessage = "±ØÌî")] [Display(Name = "ѧÉú")] public Int32 XSID { get; set; } [Required(ErrorMessage = "±ØÌî")] [Display(Name = "ѧÆÚ")] public Int32 XQID { get; set; } [Required(ErrorMessage = "±ØÌî",AllowEmptyStrings = true)] [Display(Name = "±¸×¢")] [DisplayFormat(ConvertEmptyStringToNull = false)] public String BZ { get; set; } } } }
{ "content_hash": "f4096f3a7fe6e1c853682d1a154a89cc", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 70, "avg_line_length": 26.113636363636363, "alnum_prop": 0.5239338555265448, "repo_name": "shinkxw/DataAnalysisSystem", "id": "afb3cc0f49c00be4fb0e7f30d15c7db143211853", "size": "1149", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "export/model/HANRU/ZXJX/EDU_ZXJX_55_A03_XSSFXMBZ_MODEL.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "76" }, { "name": "C#", "bytes": "1875543" }, { "name": "Ruby", "bytes": "258851" } ], "symlink_target": "" }
package movement; import java.util.List; import core.SettingsError; import movement.map.DijkstraPathFinder; import movement.map.MapNode; import movement.map.MapRoute; import core.Coord; import core.Settings; /** * Map based movement model that uses predetermined paths within the map area. * Nodes using this model (can) stop on every route waypoint and find their * way to next waypoint using {@link DijkstraPathFinder}. There can be * different type of routes; see {@link #ROUTE_TYPE_S}. */ public class MapRouteMovement extends MapBasedMovement implements SwitchableMovement { /** Per node group setting used for selecting a route file ({@value}) */ public static final String ROUTE_FILE_S = "routeFile"; /** * Per node group setting used for selecting a route's type ({@value}). * Integer value from {@link MapRoute} class. */ public static final String ROUTE_TYPE_S = "routeType"; /** * Per node group setting for selecting which stop (counting from 0 from * the start of the route) should be the first one. By default, or if a * negative value is given, a random stop is selected. */ public static final String ROUTE_FIRST_STOP_S = "routeFirstStop"; /** the Dijkstra shortest path finder */ private DijkstraPathFinder pathFinder; /** Prototype's reference to all routes read for the group */ private List<MapRoute> allRoutes = null; /** next route's index to give by prototype */ private Integer nextRouteIndex = null; /** Index of the first stop for a group of nodes (or -1 for random) */ private int firstStopIndex = -1; /** Route of the movement model's instance */ private MapRoute route; /** * Creates a new movement model based on a Settings object's settings. * @param settings The Settings object where the settings are read from */ public MapRouteMovement(Settings settings) { super(settings); String fileName = settings.getSetting(ROUTE_FILE_S); int type = settings.getInt(ROUTE_TYPE_S); allRoutes = MapRoute.readRoutes(fileName, type, getMap()); nextRouteIndex = 0; pathFinder = new DijkstraPathFinder(getOkMapNodeTypes()); this.route = this.allRoutes.get(this.nextRouteIndex).replicate(); if (this.nextRouteIndex >= this.allRoutes.size()) { this.nextRouteIndex = 0; } if (settings.contains(ROUTE_FIRST_STOP_S)) { this.firstStopIndex = settings.getInt(ROUTE_FIRST_STOP_S); if (this.firstStopIndex >= this.route.getNrofStops()) { throw new SettingsError("Too high first stop's index (" + this.firstStopIndex + ") for route with only " + this.route.getNrofStops() + " stops"); } } } /** * Copyconstructor. Gives a route to the new movement model from the * list of routes and randomizes the starting position. * @param proto The MapRouteMovement prototype */ protected MapRouteMovement(MapRouteMovement proto) { super(proto); this.route = proto.allRoutes.get(proto.nextRouteIndex).replicate(); this.firstStopIndex = proto.firstStopIndex; if (firstStopIndex < 0) { /* set a random starting position on the route */ this.route.setNextIndex(rng.nextInt(route.getNrofStops()-1)); } else { /* use the one defined in the config file */ this.route.setNextIndex(this.firstStopIndex); } this.pathFinder = proto.pathFinder; proto.nextRouteIndex++; // give routes in order if (proto.nextRouteIndex >= proto.allRoutes.size()) { proto.nextRouteIndex = 0; } } @Override public Path getPath() { Path p = new Path(generateSpeed()); MapNode to = route.nextStop(); List<MapNode> nodePath = pathFinder.getShortestPath(lastMapNode, to); // this assertion should never fire if the map is checked in read phase assert nodePath.size() > 0 : "No path from " + lastMapNode + " to " + to + ". The simulation map isn't fully connected"; for (MapNode node : nodePath) { // create a Path from the shortest path p.addWaypoint(node.getLocation()); } lastMapNode = to; return p; } /** * Returns the first stop on the route */ @Override public Coord getInitialLocation() { if (lastMapNode == null) { lastMapNode = route.nextStop(); } return lastMapNode.getLocation().clone(); } @Override public Coord getLastLocation() { if (lastMapNode != null) { return lastMapNode.getLocation().clone(); } else { return null; } } @Override public MapRouteMovement replicate() { return new MapRouteMovement(this); } /** * Returns the list of stops on the route * @return The list of stops */ public List<MapNode> getStops() { return route.getStops(); } }
{ "content_hash": "0f28174ec4bf94c7c8d29013a771432e", "timestamp": "", "source": "github", "line_count": 156, "max_line_length": 78, "avg_line_length": 29.51923076923077, "alnum_prop": 0.7022801302931596, "repo_name": "gliu6/SocialLocalization-Project-Using-One-Simulator", "id": "1fd0823e3e62a024efba4438726d1be10fafe3db", "size": "4710", "binary": false, "copies": "15", "ref": "refs/heads/master", "path": "one1.4.1/movement/MapRouteMovement.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "708" }, { "name": "HTML", "bytes": "6418" }, { "name": "Java", "bytes": "655277" }, { "name": "Perl", "bytes": "65852" }, { "name": "Shell", "bytes": "382" } ], "symlink_target": "" }
package org.telegram.api.functions.account; import org.telegram.api.account.TLAccountTmpPassword; import org.telegram.tl.*; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * @author Ruben Bermudez * @version 1.0 * @brief TODO * @date 08 of August of 2016 */ public class TLRequestGetTmpPassword extends TLMethod<TLAccountTmpPassword> { public static final int CLASS_ID = 0x4a82327e; private TLBytes passwordHash; private int period; public TLRequestGetTmpPassword() { super(); } @Override public int getClassId() { return CLASS_ID; } @Override public TLAccountTmpPassword deserializeResponse(InputStream stream, TLContext context) throws IOException { final TLObject res = StreamingUtils.readTLObject(stream, context); if (res == null) { throw new IOException("Unable to parse response"); } if ((res instanceof TLAccountTmpPassword)) { return (TLAccountTmpPassword) res; } throw new IOException("Incorrect response type. Expected " + TLAccountTmpPassword.class.getCanonicalName() + ", got: " + res.getClass().getCanonicalName()); } @Override public void serializeBody(OutputStream stream) throws IOException { StreamingUtils.writeTLBytes(passwordHash, stream); StreamingUtils.writeInt(period, stream); } @Override public void deserializeBody(InputStream stream, TLContext context) throws IOException { passwordHash = StreamingUtils.readTLBytes(stream, context); period = StreamingUtils.readInt(stream); } @Override public String toString() { return "account.getTmpPassword#4a82327e"; } }
{ "content_hash": "44eb28de88773f4edada02d5121d38f0", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 116, "avg_line_length": 29.466666666666665, "alnum_prop": 0.6872171945701357, "repo_name": "rubenlagus/TelegramApi", "id": "b6e0348163cc03a15482c118db3d4fa5bbb1e65e", "size": "1768", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/telegram/api/functions/account/TLRequestGetTmpPassword.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "2393726" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name Isolepis senegalensis Steud. ### Remarks null
{ "content_hash": "7f447855f7febb25ea22dc5bbffcdf8e", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 12.153846153846153, "alnum_prop": 0.7215189873417721, "repo_name": "mdoering/backbone", "id": "d16b115c21b4108c96634eb9cb5a528dd91b40b6", "size": "225", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Poales/Cyperaceae/Schoenoplectiella/Schoenoplectiella senegalensis/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package org.apache.logging.log4j.core.config.xml; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import org.apache.logging.log4j.core.config.AbstractConfiguration; import org.apache.logging.log4j.core.config.Configuration; import org.apache.logging.log4j.core.config.ConfigurationSource; import org.apache.logging.log4j.core.config.ConfiguratonFileWatcher; import org.apache.logging.log4j.core.config.Node; import org.apache.logging.log4j.core.config.Reconfigurable; import org.apache.logging.log4j.core.config.plugins.util.PluginType; import org.apache.logging.log4j.core.config.plugins.util.ResolverUtil; import org.apache.logging.log4j.core.config.status.StatusConfiguration; import org.apache.logging.log4j.core.util.Closer; import org.apache.logging.log4j.core.util.FileWatcher; import org.apache.logging.log4j.core.util.Loader; import org.apache.logging.log4j.core.util.Patterns; import org.apache.logging.log4j.core.util.Throwables; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * Creates a Node hierarchy from an XML file. */ public class XmlConfiguration extends AbstractConfiguration implements Reconfigurable { private static final String XINCLUDE_FIXUP_LANGUAGE = "http://apache.org/xml/features/xinclude/fixup-language"; private static final String XINCLUDE_FIXUP_BASE_URIS = "http://apache.org/xml/features/xinclude/fixup-base-uris"; private static final String[] VERBOSE_CLASSES = new String[] {ResolverUtil.class.getName()}; private static final String LOG4J_XSD = "Log4j-config.xsd"; private final List<Status> status = new ArrayList<>(); private Element rootElement; private boolean strict; private String schemaResource; public XmlConfiguration(final ConfigurationSource configSource) { super(configSource); final File configFile = configSource.getFile(); byte[] buffer = null; try { final InputStream configStream = configSource.getInputStream(); try { buffer = toByteArray(configStream); } finally { Closer.closeSilently(configStream); } final InputSource source = new InputSource(new ByteArrayInputStream(buffer)); source.setSystemId(configSource.getLocation()); final DocumentBuilder documentBuilder = newDocumentBuilder(true); Document document; try { document = documentBuilder.parse(source); } catch (final Exception e) { // LOG4J2-1127 Throwable throwable = Throwables.getRootCause(e); if (throwable instanceof UnsupportedOperationException) { LOGGER.warn( "The DocumentBuilder {} does not support an operation: {}." + "Trying again without XInclude...", documentBuilder, e); document = newDocumentBuilder(false).parse(source); } else { throw e; } } rootElement = document.getDocumentElement(); final Map<String, String> attrs = processAttributes(rootNode, rootElement); final StatusConfiguration statusConfig = new StatusConfiguration().withVerboseClasses(VERBOSE_CLASSES) .withStatus(getDefaultStatus()); for (final Map.Entry<String, String> entry : attrs.entrySet()) { final String key = entry.getKey(); final String value = getStrSubstitutor().replace(entry.getValue()); if ("status".equalsIgnoreCase(key)) { statusConfig.withStatus(value); } else if ("dest".equalsIgnoreCase(key)) { statusConfig.withDestination(value); } else if ("shutdownHook".equalsIgnoreCase(key)) { isShutdownHookEnabled = !"disable".equalsIgnoreCase(value); } else if ("verbose".equalsIgnoreCase(key)) { statusConfig.withVerbosity(value); } else if ("packages".equalsIgnoreCase(key)) { pluginPackages.addAll(Arrays.asList(value.split(Patterns.COMMA_SEPARATOR))); } else if ("name".equalsIgnoreCase(key)) { setName(value); } else if ("strict".equalsIgnoreCase(key)) { strict = Boolean.parseBoolean(value); } else if ("schema".equalsIgnoreCase(key)) { schemaResource = value; } else if ("monitorInterval".equalsIgnoreCase(key)) { final int intervalSeconds = Integer.parseInt(value); if (intervalSeconds > 0) { getWatchManager().setIntervalSeconds(intervalSeconds); if (configFile != null) { FileWatcher watcher = new ConfiguratonFileWatcher(this, listeners); getWatchManager().watchFile(configFile, watcher); } } } else if ("advertiser".equalsIgnoreCase(key)) { createAdvertiser(value, configSource, buffer, "text/xml"); } } statusConfig.initialize(); } catch (final SAXException | IOException | ParserConfigurationException e) { LOGGER.error("Error parsing " + configSource.getLocation(), e); } if (strict && schemaResource != null && buffer != null) { InputStream is = null; try { is = Loader.getResourceAsStream(schemaResource, XmlConfiguration.class.getClassLoader()); } catch (final Exception ex) { LOGGER.error("Unable to access schema {}", this.schemaResource, ex); } if (is != null) { final Source src = new StreamSource(is, LOG4J_XSD); final SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = null; try { schema = factory.newSchema(src); } catch (final SAXException ex) { LOGGER.error("Error parsing Log4j schema", ex); } if (schema != null) { final Validator validator = schema.newValidator(); try { validator.validate(new StreamSource(new ByteArrayInputStream(buffer))); } catch (final IOException ioe) { LOGGER.error("Error reading configuration for validation", ioe); } catch (final SAXException ex) { LOGGER.error("Error validating configuration", ex); } } } } if (getName() == null) { setName(configSource.getLocation()); } } /** * Creates a new DocumentBuilder suitable for parsing a configuration file. * * @param xIncludeAware enabled XInclude * @return a new DocumentBuilder * @throws ParserConfigurationException */ static DocumentBuilder newDocumentBuilder(boolean xIncludeAware) throws ParserConfigurationException { final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); if (xIncludeAware) { enableXInclude(factory); } return factory.newDocumentBuilder(); } /** * Enables XInclude for the given DocumentBuilderFactory * * @param factory a DocumentBuilderFactory */ private static void enableXInclude(final DocumentBuilderFactory factory) { try { // Alternative: We set if a system property on the command line is set, for example: // -DLog4j.XInclude=true factory.setXIncludeAware(true); } catch (final UnsupportedOperationException e) { LOGGER.warn("The DocumentBuilderFactory [{}] does not support XInclude: {}", factory, e); } catch (@SuppressWarnings("ErrorNotRethrown") final AbstractMethodError | NoSuchMethodError err) { LOGGER.warn("The DocumentBuilderFactory [{}] is out of date and does not support XInclude: {}", factory, err); } try { // Alternative: We could specify all features and values with system properties like: // -DLog4j.DocumentBuilderFactory.Feature="http://apache.org/xml/features/xinclude/fixup-base-uris true" factory.setFeature(XINCLUDE_FIXUP_BASE_URIS, true); } catch (final ParserConfigurationException e) { LOGGER.warn("The DocumentBuilderFactory [{}] does not support the feature [{}]: {}", factory, XINCLUDE_FIXUP_BASE_URIS, e); } catch (@SuppressWarnings("ErrorNotRethrown") final AbstractMethodError err) { LOGGER.warn("The DocumentBuilderFactory [{}] is out of date and does not support setFeature: {}", factory, err); } try { factory.setFeature(XINCLUDE_FIXUP_LANGUAGE, true); } catch (final ParserConfigurationException e) { LOGGER.warn("The DocumentBuilderFactory [{}] does not support the feature [{}]: {}", factory, XINCLUDE_FIXUP_LANGUAGE, e); } catch (@SuppressWarnings("ErrorNotRethrown") final AbstractMethodError err) { LOGGER.warn("The DocumentBuilderFactory [{}] is out of date and does not support setFeature: {}", factory, err); } } @Override public void setup() { if (rootElement == null) { LOGGER.error("No logging configuration"); return; } constructHierarchy(rootNode, rootElement); if (status.size() > 0) { for (final Status s : status) { LOGGER.error("Error processing element {} ({}): {}", s.name, s.element, s.errorType); } return; } rootElement = null; } @Override public Configuration reconfigure() { try { final ConfigurationSource source = getConfigurationSource().resetInputStream(); if (source == null) { return null; } final XmlConfiguration config = new XmlConfiguration(source); return config.rootElement == null ? null : config; } catch (final IOException ex) { LOGGER.error("Cannot locate file {}", getConfigurationSource(), ex); } return null; } private void constructHierarchy(final Node node, final Element element) { processAttributes(node, element); final StringBuilder buffer = new StringBuilder(); final NodeList list = element.getChildNodes(); final List<Node> children = node.getChildren(); for (int i = 0; i < list.getLength(); i++) { final org.w3c.dom.Node w3cNode = list.item(i); if (w3cNode instanceof Element) { final Element child = (Element) w3cNode; final String name = getType(child); final PluginType<?> type = pluginManager.getPluginType(name); final Node childNode = new Node(node, name, type); constructHierarchy(childNode, child); if (type == null) { final String value = childNode.getValue(); if (!childNode.hasChildren() && value != null) { node.getAttributes().put(name, value); } else { status.add(new Status(name, element, ErrorType.CLASS_NOT_FOUND)); } } else { children.add(childNode); } } else if (w3cNode instanceof Text) { final Text data = (Text) w3cNode; buffer.append(data.getData()); } } final String text = buffer.toString().trim(); if (text.length() > 0 || (!node.hasChildren() && !node.isRoot())) { node.setValue(text); } } private String getType(final Element element) { if (strict) { final NamedNodeMap attrs = element.getAttributes(); for (int i = 0; i < attrs.getLength(); ++i) { final org.w3c.dom.Node w3cNode = attrs.item(i); if (w3cNode instanceof Attr) { final Attr attr = (Attr) w3cNode; if (attr.getName().equalsIgnoreCase("type")) { final String type = attr.getValue(); attrs.removeNamedItem(attr.getName()); return type; } } } } return element.getTagName(); } private Map<String, String> processAttributes(final Node node, final Element element) { final NamedNodeMap attrs = element.getAttributes(); final Map<String, String> attributes = node.getAttributes(); for (int i = 0; i < attrs.getLength(); ++i) { final org.w3c.dom.Node w3cNode = attrs.item(i); if (w3cNode instanceof Attr) { final Attr attr = (Attr) w3cNode; if (attr.getName().equals("xml:base")) { continue; } attributes.put(attr.getName(), attr.getValue()); } } return attributes; } @Override public String toString() { return getClass().getSimpleName() + "[location=" + getConfigurationSource() + "]"; } /** * The error that occurred. */ private enum ErrorType { CLASS_NOT_FOUND } /** * Status for recording errors. */ private static class Status { private final Element element; private final String name; private final ErrorType errorType; public Status(final String name, final Element element, final ErrorType errorType) { this.name = name; this.element = element; this.errorType = errorType; } @Override public String toString() { return "Status [name=" + name + ", element=" + element + ", errorType=" + errorType + "]"; } } }
{ "content_hash": "1e3aee85ca916116265569186aed3e7c", "timestamp": "", "source": "github", "line_count": 356, "max_line_length": 118, "avg_line_length": 42.68258426966292, "alnum_prop": 0.5890753537347811, "repo_name": "lburgazzoli/apache-logging-log4j2", "id": "ca2c0a07518509c6fc71b6e7ddb1eb3c01e02a4e", "size": "15995", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "log4j-core/src/main/java/org/apache/logging/log4j/core/config/xml/XmlConfiguration.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1024" }, { "name": "CSS", "bytes": "3981" }, { "name": "Groovy", "bytes": "198" }, { "name": "Java", "bytes": "6349226" }, { "name": "JavaScript", "bytes": "59116" }, { "name": "Shell", "bytes": "861" } ], "symlink_target": "" }
#include <iostream> #include <algorithm> #include <stxxl/vector> #include <stxxl/scan> #include <stxxl/stream> using stxxl::uint64; struct my_type // 24 bytes, not a power of 2 intentionally { uint64 key; uint64 load0; uint64 load1; my_type(uint64 i = 0) : key(i), load0(i + 1), load1(1 + 42) { } bool operator == (const my_type& b) const { return (key == b.key) && (load0 == b.load0) && (load1 == b.load1); } }; //! Verify contents of the vector template <typename VectorType> void check_vector(const VectorType& v) { typedef typename VectorType::value_type value_type; for (uint64 i = 0; i < v.size(); ++i) { STXXL_CHECK(v[i] == value_type(i)); } } //! Stream object generating lots of ValueTypes template <typename ValueType> class MyStream { uint64 i; public: typedef ValueType value_type; MyStream() : i(0) { } value_type operator * () const { return value_type(i); } MyStream& operator ++ () { ++i; return *this; } bool empty() const { return false; } }; template <typename ValueType> void test_vector_buf(uint64 size) { typedef typename stxxl::VECTOR_GENERATOR<ValueType>::result vector_type; typedef typename vector_type::iterator vector_iterator_type; { // fill vector using element access stxxl::scoped_print_timer tm("element access"); vector_type vec(size); for (uint64 i = 0; i < size; ++i) vec[i] = ValueType(i); check_vector(vec); } { // fill vector using iterator access stxxl::scoped_print_timer tm("iterator access"); vector_type vec(size); vector_iterator_type vi = vec.begin(); for (uint64 i = 0; i < size; ++i, ++vi) *vi = ValueType(i); check_vector(vec); } { // fill vector using vector_bufwriter stxxl::scoped_print_timer tm("vector_bufwriter"); vector_type vec(size); typename vector_type::bufwriter_type writer(vec.begin()); for (uint64 i = 0; i < size; ++i) writer << ValueType(i); writer.finish(); check_vector(vec); } { // fill empty vector using vector_bufwriter stxxl::scoped_print_timer tm("empty vector_bufwriter"); vector_type vec; typename vector_type::bufwriter_type writer(vec); for (uint64 i = 0; i < size; ++i) writer << ValueType(i); writer.finish(); check_vector(vec); } vector_type vec(size); { // fill vector using materialize stxxl::scoped_print_timer tm("materialize"); MyStream<ValueType> stream; stxxl::stream::materialize(stream, vec.begin(), vec.end()); check_vector(vec); } { // read vector using vector_bufreader stxxl::scoped_print_timer tm("vector_bufreader"); const vector_type& cvec = vec; typename vector_type::bufreader_type reader(cvec.begin(), cvec.end()); for (uint64 i = 0; i < size; ++i) { STXXL_CHECK(!reader.empty()); STXXL_CHECK(reader.size() == size - i); ValueType pv = *reader; ValueType v; reader >> v; STXXL_CHECK(v == ValueType(i)); STXXL_CHECK(pv == v); STXXL_CHECK(reader.size() == size - i - 1); } STXXL_CHECK(reader.empty()); // rewind reader and read again reader.rewind(); for (uint64 i = 0; i < size; ++i) { STXXL_CHECK(!reader.empty()); STXXL_CHECK(reader.size() == size - i); ValueType pv = *reader; ValueType v; reader >> v; STXXL_CHECK(v == ValueType(i)); STXXL_CHECK(pv == v); STXXL_CHECK(reader.size() == size - i - 1); } STXXL_CHECK(reader.empty()); } { // read vector using vector_bufreader_reverse stxxl::scoped_print_timer tm("vector_bufreader_reverse"); const vector_type& cvec = vec; typename vector_type::bufreader_reverse_type reader(cvec.begin(), cvec.end()); for (uint64 i = 0; i < size; ++i) { STXXL_CHECK(!reader.empty()); STXXL_CHECK(reader.size() == size - i); ValueType pv = *reader; ValueType v; reader >> v; STXXL_CHECK(v == ValueType(size - i - 1)); STXXL_CHECK(pv == v); STXXL_CHECK(reader.size() == size - i - 1); } STXXL_CHECK(reader.empty()); // rewind reader and read again reader.rewind(); for (uint64 i = 0; i < size; ++i) { STXXL_CHECK(!reader.empty()); STXXL_CHECK(reader.size() == size - i); ValueType pv = *reader; ValueType v; reader >> v; STXXL_CHECK(v == ValueType(size - i - 1)); STXXL_CHECK(pv == v); STXXL_CHECK(reader.size() == size - i - 1); } STXXL_CHECK(reader.empty()); } #if STXXL_HAVE_CXX11_RANGE_FOR_LOOP { // read vector using C++11 for loop construct stxxl::scoped_print_timer tm("C++11 for loop"); uint64 i = 0; for (auto it : vec) { STXXL_CHECK(it == ValueType(i)); ++i; } STXXL_CHECK(i == vec.size()); } { // read vector using C++11 for loop construct stxxl::scoped_print_timer tm("C++11 bufreader for loop"); typedef typename vector_type::bufreader_type bufreader_type; uint64 i = 0; for (auto it : bufreader_type(vec)) { STXXL_CHECK(it == ValueType(i)); ++i; } STXXL_CHECK(i == vec.size()); } #endif } int main(int argc, char* argv[]) { int size = (argc > 1) ? atoi(argv[1]) : 16; STXXL_MSG("Testing stxxl::vector<int> with even size"); test_vector_buf<int>(size * 1024 * 1024); STXXL_MSG("Testing stxxl::vector<int> with odd size"); test_vector_buf<int>(size * 1024 * 1024 + 501 + 42); STXXL_MSG("Testing stxxl::vector<uint64>"); test_vector_buf<uint64>(size * 1024 * 1024 + 501 + 42); STXXL_MSG("Testing stxxl::vector<my_type>"); test_vector_buf<my_type>(size * 1024 * 1024); return 0; }
{ "content_hash": "4ba96c92b99764519a5098c727226c17", "timestamp": "", "source": "github", "line_count": 275, "max_line_length": 86, "avg_line_length": 23.33818181818182, "alnum_prop": 0.5325646618884388, "repo_name": "sriram-mahavadi/extlp", "id": "a271b772597646ace3d25067d7ea1170f5053048", "size": "6891", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/containers/test_vector_buf.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "602721" }, { "name": "C++", "bytes": "1421669" }, { "name": "CSS", "bytes": "914" }, { "name": "Objective-C", "bytes": "6078" }, { "name": "Perl", "bytes": "20405" }, { "name": "Shell", "bytes": "2366" }, { "name": "Tcl", "bytes": "2254" }, { "name": "TeX", "bytes": "18166" } ], "symlink_target": "" }
import threading import roslib roslib.load_manifest('deadlockTest') import rospy import actionlib from deadlockTest.msg import CountdownAction, CountdownResult class SAS(): # These variables should be treated as a constant NODE_NAME = "simple_action_server_test" def __init__(self): # ROS initialization: rospy.init_node(self.NODE_NAME, log_level=rospy.DEBUG) #Parameters self.preempted = False self.countdown = 0 self.countdown_rate = rospy.Rate(rospy.get_param("~frequency")) #Thread stuff self.lock = threading.RLock() # Prepare Simple Action Server self.action_server = actionlib.SimpleActionServer( "deadlock", CountdownAction, execute_cb = self.execute_action, auto_start = False) self.action_server.register_preempt_callback(self.stop_action) self.action_server.start() def execute_action(self, goal): rospy.loginfo("──> Executing new action") # Create new async thread to deal with request with self.lock: self.countdown = goal.countdown thread = threading.Thread(target = self.run ) thread.start() rospy.loginfo("──> Waiting for action to finish") #Wait for thread to finish thread.join() rospy.loginfo("──> Cleaning up for next iteration") ##Clean up for next iteration before finishing this goal with self.lock: self.preempted = False #Prepare results rospy.loginfo("──> Preparing results") result = CountdownResult() result.remaining = self.countdown #Evaluate results if result.remaining < 0: rospy.logerr("──> Code should never reach this point") self.action_server.set_aborted(result) elif self.preempted : rospy.loginfo("──> Action preempted") self.action_server.set_preempted(result) else : rospy.loginfo("──> Action finished") self.action_server.set_succeeded(result) def stop_action(self): rospy.loginfo("──> Preempting action") with self.lock: self.preempted = True rospy.loginfo("──> Preempted!") def run(self): while self.countdown > 0 and not self.preempted and not rospy.is_shutdown(): rospy.loginfo("*** Counting down from {} ***".format(self.countdown)) self.countdown -= 1 self.countdown_rate.sleep() if __name__ == '__main__': node = SAS() rospy.loginfo(node.NODE_NAME + " running...") rospy.spin() rospy.loginfo(node.NODE_NAME + " stopped.") exit(0)
{ "content_hash": "6f70b3b8f3c9eb85d121f2fe33dfb2a1", "timestamp": "", "source": "github", "line_count": 97, "max_line_length": 84, "avg_line_length": 29.31958762886598, "alnum_prop": 0.5794655414908579, "repo_name": "miguelsdc/deadlockTest", "id": "9408ea4da478f04a5c6297b136a3d34c277ec56c", "size": "4068", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "scripts/sas.py", "mode": "33261", "license": "mit", "language": [ { "name": "C++", "bytes": "6828" }, { "name": "Python", "bytes": "3708" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <body> &nbsp; <div style="position:relative; width:300px; background:grey;"> <div style="position:absolute; left:0; bottom:0px; width:250px; background:lime;">abs.pos.</div> <div style="float:left; width:200px; height:200px; background:cyan;"></div> <script>document.body.offsetTop;</script> <div style="clear:both;"></div> </div> <script>document.body.offsetTop;</script> </body> </html>
{ "content_hash": "98b78f2b4b5b9ce71da65eea5d4a7e16", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 98, "avg_line_length": 32.76923076923077, "alnum_prop": 0.6901408450704225, "repo_name": "wilebeast/FireFox-OS", "id": "82ec493ad8cd958ec07fe82af1516364c8888ca7", "size": "426", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "B2G/gecko/layout/reftests/bugs/406568-1.html", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
 namespace Chloe.DbExpressions { /// <summary> /// User as T1 , (select * from User) as T1 /// </summary> [System.Diagnostics.DebuggerDisplay("Alias = {Alias}")] public class DbTableSegment { public DbTableSegment(DbExpression body, string alias, LockType @lock) { this.Body = body; this.Alias = alias; this.Lock = @lock; } /// <summary> /// User、(select * from User) /// </summary> public DbExpression Body { get; private set; } public string Alias { get; private set; } public LockType Lock { get; private set; } } }
{ "content_hash": "dff13ae27312f4d14cde7c884503ca1a", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 78, "avg_line_length": 27.375, "alnum_prop": 0.5464231354642314, "repo_name": "shuxinqin/Chloe", "id": "4dbacfda5418cfc2e7b7cc4392758f1405a2d2f9", "size": "661", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Chloe/DbExpressions/DbTableSegment.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "485" }, { "name": "C#", "bytes": "2203199" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "8b9f358d47cdc3a737e490db407257b9", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "d50fdc8c247b7b9b27fa8f80f9cd3400e9b9b15b", "size": "196", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Eltroplectris/Eltroplectris longicornu/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php /** * Created by PhpStorm. * User: Hélio * Date: 6/2/2015 * Time: 2:12 PM */ namespace ActiveInterfaces\Elements\Form{ abstract class ActiveElement { /** * @var HtmlElement */ public $html = null; public $label = null; public function __construct() { $this->html = new HtmlElement(); $this->buildHtmlElement(); } protected function buildHtmlElement() { $this->html->setContent( "You're using an undefined field type, this class exists and extends ActiveElement, but you need to overwrite the buildHtmlElement method"); } public function setLabel($label) { $labelElement = new HtmlElement(false,'label'); $labelElement->setProperty('for',$this->html->getProperty('name')); $labelElement->setContent($label); $this->label = $labelElement; } public function setValue($value = null) { } public function setName($name) { $this->html->setProperty('name',$name); $this->html->setProperty('id',$name); } public function getName(){ return 'undefined'; } public function __toString() { return (string)$this->label.$this->html; } } }
{ "content_hash": "c2a618c38a7ae86a2162278dd4df5c03", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 103, "avg_line_length": 23.032258064516128, "alnum_prop": 0.5175070028011205, "repo_name": "hjfigueira/ActiveInterfaces", "id": "4088f2ef56ca2012903ef88611b01da043ba23e1", "size": "1428", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Elements/Form/ActiveElement.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "35800" } ], "symlink_target": "" }
require 'test_helper' class DownloadRequestersBaseTest < ActiveSupport::TestCase test '.request initializes a new instance of the requester with the given args and calls the request method on it' do requester_mock = mock requester_mock.expects(:request) Download::Requesters::Base. expects(:new). with("arg1", "arg2"). returns(requester_mock) Download::Requesters::Base.request "arg1", "arg2" end end
{ "content_hash": "441ede4104490a54116c4d291ed10eb8", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 65, "avg_line_length": 27.8125, "alnum_prop": 0.7056179775280899, "repo_name": "unepwcmc/ProtectedPlanet", "id": "e7ef1200da99d3291e34e8eecef7deb8d0b19572", "size": "445", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/unit/download/requesters/base_test.rb", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CoffeeScript", "bytes": "2487" }, { "name": "Dockerfile", "bytes": "1026" }, { "name": "HTML", "bytes": "105487" }, { "name": "Haml", "bytes": "1959" }, { "name": "JavaScript", "bytes": "60249" }, { "name": "Jinja", "bytes": "67979" }, { "name": "Perl", "bytes": "10512" }, { "name": "Roff", "bytes": "114" }, { "name": "Ruby", "bytes": "646591" }, { "name": "SCSS", "bytes": "200131" }, { "name": "Shell", "bytes": "12563" }, { "name": "Vue", "bytes": "237929" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>AvNav-Android</title> <link href="../styles.css" rel="stylesheet" type="text/css"> </head> <body data-order="4000"> <h1>AvNav Android</h1> <p>After having the <a href="../beschreibung.html">AvNav web GUI for the Raspberry Pi</a>&nbsp; already in place for some years, there is now also a genuine android version. It requires android 4.4 (KitKat) or later.</p> <p>The latest version is available at <a href="../../downloads/release/latest">downloads</a>. Alternatively in the&nbsp; <a href="https://play.google.com/store/apps/details?id=de.wellenvogel.avnav.main">Play Store</a>.<br> You can find previous versions or daily builds via the&nbsp; <a href="../install.html">installation instructions</a>.</p> <p>Basically the app is packaging the WebApp (see <a href="../userdoc/index.html">User documentation</a>) into an android app. For Charts check the hints at <a href="../charts.html">creating/converting charts</a>.</p> <h2>Functions </h2> <p>(new since 20210424)</p> <p>Internally the app consists of a couple of functional entities.</p> <img src="software-android.png" alt="" class="fimage"> <p>The NMEA multiplexer handles NMEA0183 data from various sources. Beside the internal GPS data can be read from sources like TCP connections, UDP ports, USB devices, Bluetooth... Most sources support sending and receiving of NMEA data at the same time. You can configure multiple sources of each type (within the app configuration there is a "handler" for each data source).</p> <table style="width: 100%" border="1"> <tbody> <tr> <td>name within the app</td> <td>description</td> </tr> <tr> <td>InternalGPS</td> <td>The location data from the internal GPS will be sent to the multiplexer as NMEA data.</td> </tr> <tr> <td>TcpReader</td> <td>A TCP connection to an external system. AvNav acts as TCP client and will open up the connection.<br> You can either use a plain IP address or a hostname as destination (mdns names like avnav.local are supported).</td> </tr> <tr> <td>TcpWriter</td> <td>AvNav listens for connections from other apps or systems and sends out the NMEA data from the multiplexer. AvNav acts as TCP server.</td> </tr> <tr> <td>UdpReader</td> <td>AvNav receives UDP data at the configured port.</td> </tr> <tr> <td>UdpWriter</td> <td>AvNav sends out UDP data to the configured address and port.</td> </tr> <tr> <td>UsbConnection</td> <td>You can receive (and send) data via a connected USB serial converter device (requires USB OTG functionality of your Android device).</td> </tr> <tr> <td>Bluetooth</td> <td>Connection to a bluetooth device. You need to pair the device (outside AvNav) before you can use it.</td> </tr> <tr> <td>NMEA0183 service</td> <td>A connection to a system the provides its NMEA data as a TCP service via mdns (Bonjour/<a href="https://de.wikipedia.org/wiki/Avahi_%28Software%29">Avahi</a>) - like e.g. SignalK. <br> AvNav establishes a TCP connection to this device.</td> </tr> </tbody> </table> <br> <p>You can configure the NMEA multiplexer in a very flexible manner. For each connection you can define input and output filters or blacklists.</p> <p>Internally the multiplexer hands over its data to the other modules of the app. The decoder prepares the NMEA data for further usage inside the app.</p> <p>The app itself with the chart display and the dashboards can be used as a normal android app. Additionally you can activate the integrated web server. This allows access to all app functions from a browsers on the same or a different device (similar to the AvNav <a href="../beschreibung.html">server variant</a>).</p> <p>The display part of the app can be terminated while the multiplexer continues to run in background. So AvNav can act as a NMEA data provider for other navigation apps. You would configure a TcpWriter within AvNav and connect from the other app to localhost (127.0.0.1) and the configured port.</p> <h2></h2> <p></p> <p>The app can use the device's internal GPS. Additionally you can receive NMEA data via TCP/IP, bluetooth or by an USB-serial adapter if your device supports USB OTG. As a sender for NMEA data you can e.g. use the raspberry version - or any other NMEA0183-wifi gateway. You can also use a plain bluetooth GPS mouse if your device does not have an internal GPS.</p> <h2>Charts and stored Data</h2> <p>Charts are primarily expected in gemf <a href="../charts.html#chartformats">format</a>. Since version 20200325 you can also use mbtiles or xml files for online chart sources. Charts may be located in 2 directories: </p> <ul> <li> in the 'charts' folder within the app's working directory (choosen at start up). As this must be writable it will typically not be possible to put this on an SD card in newer android versions. </li> <li>in a freely selectable, different directory (also on an SD card) "additional charts dir" in the settings<br> In the external charts dir you cannot directly use mbtiles. They must be copied into the working directory using <a href="../userdoc/downloadpage.html">the app</a> .</li> </ul> Charts have to be copied to either directory or uploaded by the app. Initially there are some demo charts available, however they require an online internet connection. <p>If the chosen working directory is not yet present it will be created on first start up (default: internal-sd-card/avnav).</p> <p>Track and log data will be written to the track directory within the working directory.</p> <p>In the routes sub folder, routes will be stored in gpx format. Routes and tracks can be made available to other apps using the <a href="../userdoc/downloadpage.html">download</a> function. To save them you need to have a file manager installed.</p> <h2>Usage</h2> <p></p> <p>After first start up you will see an introduction page:</p> <img alt="" src="android-start-first.png" class="fimage"><br> After clicking ok you will see the main settings page.<br> <img src="android-settings-main.png" class="fimage"><br> Amongst other settings, you can select the working directory and the external charts directory. <br> A complete list of settings can be found <a href="#Settings">here</a>.<br> <br> <p> You can leave the settings page with the upper right button or by pressing the back button. You will get to the <a href="../userdoc/mainpage.html">main page</a> of the app.</p> <img src="android-mainpage.png" alt="" class="fimage"><br> In the screenshot a valid internal position is shown (green bubble), but currently no AIS data (red bubble).<br> To return to the android setting move to the <a href="../userdoc/settingspage.html">settings page</a> within the app and click the android button there.<br> On further starts,&nbsp; the app will directly present the main page.<br> <p> </p> <br> <h2>External Access</h2> <p> (new since 20210424).</p> <p>AvNav supports being accessed from other devices using a web browser. To provide this function you need to enable the WebServer in the settings of the app (<a href="../userdoc/statuspage.html">Status/Server Page</a> <img src="../viewerimages/icons-new/status.svg" alt="" class="inlineimage">).<br> You need to switch on "externalAccess" (only do this in trusted networks). With 'mdnsEnabled' a bonjour enabled app (like <a href="https://play.google.com/store/apps/details?id=de.wellenvogel.bonjourbrowser">BonjourBrowser</a>) can directly connect to the server.</p> <p>In previous versions AvNav was using different modes for that.<span style="color: #cccccc;"><br> </span></p> <span style="color: #cccccc;"> </span> <ul> <li><span style="color: #cccccc;">Normal</span></li> <li><span style="color: #cccccc;">External Browser</span></li> </ul> <span style="color: #cccccc;">In normal mode the browser is integrated and it behaves like a standard android app.<br> In external browser mode the app starts up a web server at a user definable port (default 34567). </span><br> <br> <h2>Background</h2> <p>The NMEA multiplexer (and the Web Server) of AvNav can run in background. You would e.g. use this if your display is on a different device.</p> <p>To enter the background mode open the close dialog on the main page <img src="../viewerimages/icons-new/ic_clear.svg" alt="" class="inlineimage">and select "BACKGROUND".</p> <p>Via the android notification (in the Android notification bar) you can bring back the app to foreground - or close it completely.</p> <br> <h2> <a id="Settings" name="Settings"></a>Settings</h2> <p>The settings are split into two separate categories:</p> <ul> <li>Specific Android settings</li> <li>Settings for the multiplexer and other main parts</li> </ul> <p>The android settings can be accessed via the <img src="../viewerimages/icons-new/ic_android.svg" alt="" class="inlineimage">button on the <a href="../userdoc/settingspage.html">settings page</a> or on the&nbsp; <a href="../userdoc/statuspage.html">server/status</a> page.</p> <h3></h3> <p> </p> <h3>Android Main Settings</h3> <table style="width: 100%" border="1"> <tbody> <tr> <td>Name</td> <td>Meaning</td> <td>Default</td> </tr> <tr> <td>working directory</td> <td>working directory for your data (sub folders charts,tracks, routes, user, layout)</td> <td>/storage/sdcard/avnav</td> </tr> <tr> <td>additional charts directory</td> <td>external chart directory (not for mbtiles), SD card recommended</td> <td>---</td> </tr> <tr> <td>show demo charts</td> <td>demo charts (only with internet connected)</td> <td>on</td> </tr> <tr> <td>Alarm sounds</td> <td>switch off alarm sounds. You may need to switch them off in your browser as well.</td> <td>on<br> </td> </tr> <tr> <td>Hide System Bars</td> <td>hide&nbsp; the top and bottom android bars</td> <td>off</td> </tr> <tr> <td>reset to defaults</td> <td>reset the multiplexer settings to defaults</td> <td><br> </td> </tr> </tbody> </table> <h3>Android Sound Settings</h3> <table style="width: 100%;" border="1"> <tbody> <tr> <td>Name</td> <td>Meaning</td> <td>Default</td> </tr> <tr> <td>Sound for XXX alarm</td> <td>select the sounds for the alarms</td> <td>built in<br> </td> </tr> <tr> <td>reset to defaults</td> <td>reset all sound settings to defaults</td> <td><br> </td> </tr> </tbody> </table> <p> </p> <br> <h3>Multiplexer Settings</h3> <p>(new since 20210424)</p> <p>The multiplexer settings are available on the <a href="../userdoc/statuspage.html">Status/Server Page</a> <img src="../viewerimages/icons-new/status.svg" alt="" class="inlineimage">. For each function (e.g. for each data source of the multiplexer) a so called 'handler' is available. You can check the status of the handlers and change their configuration.</p> <p>New data sources (or targets) can be added using the <img src="../viewerimages/icons-new/ic_add.svg" alt="" class="inlineimage">button. A select dialog will provide all handlers that can be currently added (you will e.g. see an USBConnection only if there is an USB device actually connected).</p> <img src="android-status-add.png" alt="" class="fimage"> <p>Next to handlers in the status list a <img src="../viewerimages/icons-new/ic_edit.svg" alt="" class="inlineimage"> button permits to to edit the configuration of the handler.<br> Most of the parameters shown in the edit dialog have a&nbsp; <img src="../viewerimages/icons-new/ic_help_outline.svg" alt="" class="inlineimage"> button providing a short help for the parameter. Using the <img src="../viewerimages/icons-new/ic_delete.svg" alt="" class="inlineimage">button you can reset the particular parameter to it's default value.</p> <p> Some of the parameters are common for multiple handlers:</p> <table style="width: 100%" border="1"> <tbody> <tr> <td>Name</td> <td>Description</td> <td>default</td> </tr> <tr> <td>enabled</td> <td>Activate/deactivate the handler.</td> <td>depends on handler</td> </tr> <tr> <td>name</td> <td>Name of the handler. Can be used in black lists.</td> <td>empty</td> </tr> <tr> <td>port</td> <td>TCP or UDP port</td> <td><br> </td> </tr> <tr> <td>filter/readerFilter/ sendFilter</td> <td>A NMEA filter. You can define the NMEA sentences to pass. Multiple filters have to be separated by comma.<br> For records starting with a $ the next 2 characters will be ignored (the talker id). A filter for all $XXRMC records will look like:<br> $RMC<br> For AIS only (no other NMEA data):<br> !<br> All RMC and RMB records:<br> $RMC,$RMB<br> If you want to invert the filter, prefix the expression with ^.<br> ^$RMB,^$APB</td> <td>empty</td> </tr> <tr> <td>blacklist</td> <td>A comma separated list of names. NMEA data from sources with those names will not be sent out.</td> <td>empty<br> </td> </tr> </tbody> </table> <p>The "Handlers" and their parameters:</p> <h4>Decoder</h4> <table style="width: 100%" border="1"> <tbody> <tr> <td>Parameter</td> <td>Description</td> <td>default</td> </tr> <tr> <td>ownMMSI</td> <td>Own MMSI, will be suppressed in AIS displays</td> <td>empty</td> </tr> <tr> <td>posAge</td> <td>Allowed age (in seconds) for the GPS position. After that time the position will be dropped if no new position has been received.</td> <td>10</td> </tr> <tr> <td>nmeaAge</td> <td>Allowed age (in seconds) for NMEA data (except position)</td> <td>600</td> </tr> <tr> <td>aisAge</td> <td>Allowed age for AIS Data</td> <td>1200</td> </tr> <tr> <td>readTimeout</td> <td>Timeout in seconds for the display whether valid data is available or not</td> <td>10</td> </tr> </tbody> </table> <h4>Route</h4> <table style="width: 100%" border="1"> <tbody> <tr> <td>Parameter</td> <td>Beschreibung</td> <td>default</td> </tr> <tr> <td>computeRMB</td> <td>if switched on RMB records will be created if the routing is active</td> <td>on</td> </tr> </tbody> </table> <h4>Track</h4> <table style="width: 100%" border="1"> <tbody> <tr> <td>Parameter</td> <td>Beschreibung</td> <td>default</td> </tr> <tr> <td>interval</td> <td>Interval in seconds for writing the track as gpx file.</td> <td>300</td> </tr> <tr> <td>distance</td> <td>Minimal distance between two trackpints in meters</td> <td>25</td> </tr> <tr> <td>minTime</td> <td>Minimal time in seconds before a new track point is written.</td> <td>10</td> </tr> <tr> <td>length</td> <td>Length of the shown track (in hours)</td> <td>25</td> </tr> </tbody> </table> <h4>Logger</h4> <p>NMEA logger</p> <h4>WebServer</h4> <img src="android-status-webserver.png" alt="" class="fimage"> <table style="width: 100%" border="1"> <tbody> <tr> <td>Parameter</td> <td>Description</td> <td>default</td> </tr> <tr> <td>port</td> <td>The TCP Port the server is listening on</td> <td>8080</td> </tr> <tr> <td>external</td> <td>If active external devices can connect (otherwise: only local apps)<br> <span style="color: red;">Hint: Be careful to only use this in a trusted network. There is no further protection against unauthorized access inside the app.</span></td> <td>off</td> </tr> <tr> <td>mdnsEnabled</td> <td>Announce the service via mnds (will allo Bonjour apps to find it)</td> <td>on</td> </tr> <tr> <td>mdnsService</td> <td>The name you will see in mdns.</td> <td>avnav-android</td> </tr> </tbody> </table> <h4>InternalGPS</h4> <p>The internal GPS of the device.</p> <h4>MDNSResolver</h4> <p>The handler for resolving and announcing mdns names.</p> <h4>TcpReader</h4> <table style="width: 100%" border="1"> <tbody> <tr> <td>Parameter</td> <td>Description</td> <td>default</td> </tr> <tr> <td>ipAddress</td> <td>The ip address or the hostname of the server you want to connect to. This can also be a MDNS name like avnav.local .</td> <td>---</td> </tr> <tr> <td>port</td> <td>The Ip port you want to connect to.</td> <td>---</td> </tr> <tr> <td>sendOut</td> <td>If active NMEA data will be sent out (otherwise received only) on this connection.</td> <td>off</td> </tr> <tr> <td>readTimeout</td> <td>Mark the connection as inactive if no NMEA data are received for this time (seconds).</td> <td>10</td> </tr> <tr> <td>writeTimeout</td> <td>Write timeout for one NMEA record (in seconds). Close and reopen the connection. Use 0 to disable writeTimeout.</td> <td>5</td> </tr> <tr> <td>connectTimeout</td> <td>Timeout for connecting (seconds, 0 - system-default).</td> <td>0</td> </tr> <tr> <td>closeOnTimeout</td> <td>Close (and reopen) the connection if no NMEA data has been received within readTimeout.</td> <td>on</td> </tr> </tbody> </table> <h4>TcpWriter</h4> <p>A TCPWriter provides NMEA data for other apps.</p> <img src="android-status-tcpwriter-intern.png" alt="" class="fimage"> <table style="width: 100%" border="1"> <tbody> <tr> <td>Parameter</td> <td>Description</td> <td>default</td> </tr> <tr> <td>port</td> <td>The IP port that the server will listen on</td> <td>---</td> </tr> <tr> <td>externalAccess</td> <td>If active other devices can connect. Otherwise only apps from the same device.<br> <span style="color: red;">Hint: Be careful to only use this in a trusted network. There is no further protection against unauthorized access inside the app.</span></td> <td>aus</td> </tr> <tr> <td>writeTimeout</td> <td>Write timeout for a NMEA record (in seconds). Close and reopen the connection, choose 0 to disable writeTimeout.</td> <td>5</td> </tr> <tr> <td>readData</td> <td>If active also read data from an established connection (otherwise write only)</td> <td>off</td> </tr> <tr> <td>mdnsEnabled</td> <td>Announce this service via mdns (type: _nmea-0183._tcp)</td> <td>on</td> </tr> <tr> <td>mdnsService</td> <td>The name of this service on mdns</td> <td><br> </td> </tr> </tbody> </table> <h4>UdpReader</h4> <p>An UDP Reader receives data from an UDP port.</p> <table style="width: 100%" border="1"> <tbody> <tr> <td>Parameter</td> <td>Description</td> <td>default</td> </tr> <tr> <td>port</td> <td>The UDP port the data will be received on.</td> <td>---</td> </tr> <tr> <td>externalAccess</td> <td>If active external devices can send data. Otherwise only apps from the same device.<br> <span style="color: red;">Hint: Be careful to only use this in a trusted network. There is no further protection against unauthorized access inside the app.</span></td> <td>off</td> </tr> <tr> <td>readTimeout</td> <td>Show the connection to be inactive if no NMEA data have been received for this time (seconds).</td> <td>10</td> </tr> </tbody> </table> <h4>UdpWriter</h4> <p>An UdpWriter will send out NMEA data via UDP to another app.</p> <table style="width: 100%" border="1"> <tbody> <tr> <td>Parameter</td> <td>Description</td> <td>default</td> </tr> <tr> <td>ipaddress</td> <td>The IP address or the hostname for the server you want to connect to. This can also be a MDNS name like avnav.local .</td> <td>---</td> </tr> <tr> <td>port</td> <td>The destination port</td> <td>---</td> </tr> <tr> <td>broadcast</td> <td>send the data as broadcast (requires the ipaddress to be a valid broadcast address)</td> <td>off</td> </tr> </tbody> </table> <h4>NMEA0183 Service</h4> <p>A NMEA0183 service mainly works like a TcpReader, without the need to define IP address and port of the origin. Instead you select the name of a MDNS service providing NMEA data from a list of detected services (type:&nbsp; _nmea-0183._tcp). If there is e.g. a SignalK server or an AvNav server (&gt; 20210415) in your network - they will announce their services this way (if configured to do so).</p> <p>Advantage of using a service: it will continue to work if you change your network topology.</p> <img src="android-status-add-nmea0183.png" alt="" class="fimage"> <table style="width: 100%" border="1"> <tbody> <tr> <td>Parameter</td> <td>Description</td> <td>default</td> </tr> <tr> <td>service</td> <td>The name of the service (select from a list of found services)</td> <td>---</td> </tr> <tr> <td>sendOut</td> <td>also send out NMEA data (otherwise read only)</td> <td>off<br> </td> </tr> <tr> <td>readTimeout</td> <td>Mark the connection as inactive if no NMEA data were received for this time (seconds).</td> <td>10</td> </tr> <tr> <td>writeTimeout</td> <td>Write timeout for a NMEA record (in seconds). Close and reopen the connection, choose 0 to disable writeTimeout.</td> <td>5</td> </tr> <tr> <td>connectTimeout</td> <td>Timeout for connecting (seconds, 0 - system-default).</td> <td>0</td> </tr> <tr> <td>closeOnTimeout</td> <td>Close (and reopen) the connection if no NMEA data were received within readTimeout.</td> <td>on</td> </tr> </tbody> </table> <h4>UsbConnection</h4> <p>AvNav will get activated when an USB device is connected. Typically it makes sense to start AvNav first and afterwards connect the USB device. This way you can allow permanent access to the USB device for AvNav. AvNav will immediately start up the configuration dialog for the newly connected device.</p> <p><img src="android-connect-usb.png" alt="" class="fimage"></p> <table style="width: 100%" border="1"> <tbody> <tr> <td>Parameter</td> <td>Description</td> <td>default</td> </tr> <tr> <td>device</td> <td>The USB device (more exact: the port it is connected to). Select from a list.</td> <td>---</td> </tr> <tr> <td>baud rate</td> <td>The serial baud rate.</td> <td>9600</td> </tr> <tr> <td>flowControl</td> <td>none|xon/xoff|rts/cts - flow control if supported by the adapter</td> <td>none</td> </tr> <tr> <td>sendOut</td> <td>also send out NMEA data (otherwise read only)</td> <td>off</td> </tr> <tr> <td>readTimeout</td> <td>Mark connection as inactive if no NMEA data were received for this time (seconds).</td> <td>10</td> </tr> </tbody> </table> <h4>Bluetooth</h4> Before you can use a bluetooth device you must pair it (outside of AvNav).<br> <table style="width: 100%" border="1"> <tbody> <tr> <td>Parameter</td> <td>Description</td> <td>default</td> </tr> <tr> <td>device</td> <td>The bluetooth device. When creating the handler you can select from a list of all paired devices. Only after saving the settings AvNav will actually try to connect to the device.</td> <td>---</td> </tr> <tr> <td>sendOut</td> <td>also send out NMEA data (otherwise read only)</td> <td>off</td> </tr> <tr> <td>readTimeout</td> <td>Mark the connection as inactive if no NMEA data were received for this time (seconds).</td> <td>10</td> </tr> </tbody> </table> <p><br> </p> <p></p> <p><br> </p> </body> </html>
{ "content_hash": "bd85031ab24bb9711d52b17fbdf11038", "timestamp": "", "source": "github", "line_count": 730, "max_line_length": 192, "avg_line_length": 38.23835616438356, "alnum_prop": 0.5639822311384968, "repo_name": "wellenvogel/avnav", "id": "8fcdbfa15df03504c7f399470495f66e2fffd1a4", "size": "27914", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/android/en_android.html", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1132" }, { "name": "C", "bytes": "110" }, { "name": "C#", "bytes": "42879" }, { "name": "CSS", "bytes": "2568" }, { "name": "Groovy", "bytes": "33083" }, { "name": "HTML", "bytes": "51569" }, { "name": "Inno Setup", "bytes": "2303" }, { "name": "Java", "bytes": "1074366" }, { "name": "JavaScript", "bytes": "1324088" }, { "name": "Less", "bytes": "57801" }, { "name": "PHP", "bytes": "4423" }, { "name": "Perl", "bytes": "1707" }, { "name": "PowerShell", "bytes": "7995" }, { "name": "Python", "bytes": "1193211" }, { "name": "Rich Text Format", "bytes": "105" }, { "name": "Shell", "bytes": "45976" } ], "symlink_target": "" }
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" tools:context=".ForceEngine"> <item android:id="@+id/action_clear" android:orderInCategory="100" android:showAsAction="ifRoom" android:icon="@drawable/ic_action_discard" android:title="@string/action_clear"/> <item android:id="@+id/action_settings" android:orderInCategory="100" android:showAsAction="ifRoom" android:icon="@drawable/ic_action_settings" android:title="@string/action_settings"/> </menu>
{ "content_hash": "b4c94bb312a4e7f3a7900428a2adfca2", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 64, "avg_line_length": 34.3125, "alnum_prop": 0.7249544626593807, "repo_name": "ericleong/forceengine", "id": "0e6b36f76eb249c0180b3eac69ea1797c21697ac", "size": "549", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Force Engine Android/app/src/main/res/menu/force_engine.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "249541" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Pharcidia lichenicola anon. ### Remarks null
{ "content_hash": "3960b9f92481ed2b61b7978223dc1b7f", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 27, "avg_line_length": 10.153846153846153, "alnum_prop": 0.7121212121212122, "repo_name": "mdoering/backbone", "id": "5262146f79971fbbc6003a6aa805da0f75fab3ed", "size": "183", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Dothideomycetes/Capnodiales/Mycosphaerellaceae/Pharcidia/Pharcidia lichenicola/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
#ifndef APP_LOGICSERVER_LOGIC_SUPPORT_H_ #define APP_LOGICSERVER_LOGIC_SUPPORT_H_ #include "app/logicserver/logic/config.h" namespace logic { void enrolls(); }; extern std::unique_ptr<pf_plugin::logic::System> g_logic_system; #endif //APP_LOGICSERVER_LOGIC_SUPPORT_H_
{ "content_hash": "b2998aa452e434eefd12cd52324427b1", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 64, "avg_line_length": 18.333333333333332, "alnum_prop": 0.7454545454545455, "repo_name": "viticm/pf_examples", "id": "dcf724b0ee5741e087a99382e340953e196b0a86", "size": "613", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "applications/logicserver/include/app/logicserver/logic/support.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "31788" }, { "name": "C++", "bytes": "308690" }, { "name": "CMake", "bytes": "3031" }, { "name": "Protocol Buffer", "bytes": "253" }, { "name": "Shell", "bytes": "808" } ], "symlink_target": "" }
<script src="../lib/tracery.js"></script> <script src="../lib/mousetrap.min.js"></script> <script src="../lib/jquery-1.11.1.min.js"></script> <script src="../lib/markov.js"></script> <script> var markov = new MarkovGenerator(2,7," ") var text = "unicorn raven sparrow scorpion coyote eagle owl lizard zebra duck kitten" markov.feed(text) function generate(){ var markovPet = markov.generate() markovPet = markovPet.split(" ")[0] var grammarObj = { "name": ["Arjun","Yuuma","Darcy","Mia","Chiaki","Izzi","Azra","Lina"], "animal": [markovPet], "mood": ["vexed","indignant","impassioned","wistful","astute","courteous"], "story": ["#hero# traveled with her pet #heroPet#. #hero# was never #mood#, for the #heroPet# was always too #mood#."], "origin": ["#[hero:#name#][heroPet:#animal#]story#"] } var grammar = tracery.createGrammar(grammarObj) var t = grammar.flatten("#origin#"); $('h1').text(t); } </script> <h1>Text will go here</h1> <button onclick="generate()">Generate</button>
{ "content_hash": "12163e6f2107e16d7613c7e193584055", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 124, "avg_line_length": 38.88461538461539, "alnum_prop": 0.6547972304648862, "repo_name": "toddwords/toddwords.github.io", "id": "48c16aad50f1854b834c1a84c0812068a88f5406", "size": "1011", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dla2/week4-bots/traceryMarkov.html", "mode": "33188", "license": "mit", "language": [ { "name": "AutoHotkey", "bytes": "253" }, { "name": "CSS", "bytes": "11901" }, { "name": "HTML", "bytes": "773324" }, { "name": "JavaScript", "bytes": "16634051" }, { "name": "Ruby", "bytes": "136" }, { "name": "SCSS", "bytes": "14408" } ], "symlink_target": "" }
package com.almende.dht; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.BitSet; import java.util.Random; import java.util.logging.Logger; /** * The Class Key. */ public final class Key implements Comparable<Key> { private static final Logger LOG = Logger.getLogger(Key.class.getName()); private BitSet val; /** * Instantiates a new key. * * @param val * the val */ public Key(final BitSet val) { this.val = val; } /** * Instantiates a new key. */ public Key() { this.val = new BitSet(Constants.BITLENGTH); } /** * Instantiates a new key. * * @param key * the key */ public Key(final String key) { this.val = BitSet.valueOf(hexToBytes(key)); } /** * Random. * * @return the key */ public static Key random() { final BitSet set = new BitSet(Constants.BITLENGTH); final Random rand = new Random(); for (int i = 0; i < Constants.BITLENGTH; i++) { set.set(i, rand.nextBoolean()); } return new Key(set); } /** * Random key of rank X. * * @param rank * the rank * @return the key */ public static Key random(int rank) { if (rank > Constants.BITLENGTH) { LOG.warning("Rank too high!"); rank = Constants.BITLENGTH; } final BitSet set = new BitSet(Constants.BITLENGTH); final Random rand = new Random(); for (int i = 0; i < rank - 2; i++) { set.set(i, rand.nextBoolean()); } set.set(rank - 1); return new Key(set); } /** * Digest. * * @param val * the val * @return the key */ public static Key digest(final String val) { try { MessageDigest md = MessageDigest.getInstance("SHA1"); return new Key(BitSet.valueOf(md.digest(val.getBytes("UTF-8")))); } catch (NoSuchAlgorithmException e) { LOG.severe("SHA1 unknown???!"); } catch (UnsupportedEncodingException e) { LOG.severe("UTF-8 unknown???!"); } return null; } /** * From hex string. * * @param val * the val * @return the key */ public static Key fromHexString(final String val) { return new Key(val); } /** * From string. * * @param val * the val * @return the key */ public static Key fromString(final String val) { return Key.digest(val); } /** * Gets the val. * * @return the val */ public BitSet getVal() { return val; } /** * Sets the val. * * @param val * the new val */ public void setVal(BitSet val) { this.val = val; } /** * Rank. * * @return the int */ public int rank() { return val.length(); } /** * Dist. * * @param o * the o * @return the key */ public Key dist(final Key o) { final BitSet res = ((BitSet) val.clone()); res.xor(o.val); return new Key(res); } /* * (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return val.hashCode(); } /* * (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(final Object o) { if (o == null) { return false; } if (!(o instanceof Key)) return false; if (o == this) return true; final Key other = (Key) o; return (val.equals(other.val)); } /* * (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return bytesToHex(val.toByteArray()); } // From: http://stackoverflow.com/a/9855338 final private static char[] hexArray = "0123456789ABCDEF".toCharArray(); private static String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for (int j = 0; j < bytes.length; j++) { int v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); } // From: http://stackoverflow.com/a/140861 private static byte[] hexToBytes(String s) { int len = s.length(); if (len %2 == 1){ throw new IllegalArgumentException("HexString uneven length:'"+s+"'"); } byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character .digit(s.charAt(i + 1), 16)); } return data; } /* * (non-Javadoc) * @see java.lang.Comparable#compareTo(java.lang.Object) */ @Override public int compareTo(Key o) { if (this.equals(o)) return 0; if (rank() > o.rank()) return 1; if (rank() < o.rank()) return -1; int index = dist(o).rank() - 1; return val.get(index) ? 1 : -1; } }
{ "content_hash": "ff74632381e599ed19d0670581080b1e", "timestamp": "", "source": "github", "line_count": 240, "max_line_length": 76, "avg_line_length": 19.15, "alnum_prop": 0.5953002610966057, "repo_name": "almende/dht", "id": "d637fb1f5645663f0ea47f9dde35c850f07cda24", "size": "4717", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/almende/dht/Key.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "50145" } ], "symlink_target": "" }
var mssql = require('mssql'), helpers = require('./helpers'), promises = require('../../utilities/promises'), log = require('../../logger'), connection, connectionPromise; module.exports = function (config, sql) { if(sql.noop) return promises.resolved(); if (!connectionPromise) { connection = new mssql.Connection(config); connectionPromise = connection.connect() .catch(function (err) { connectionPromise = undefined; throw err; }); } return connectionPromise.then(executeRequest); function executeRequest() { var request = new mssql.Request(connection); var statements = sql; if (sql.constructor !== Array) { statements = [sql]; } // We expect multiple results if there are multiple statements to be executed or if // 'multiple' results are explicitly requested request.multiple = statements.length > 1 || statements[0].multiple; var statement = '', params = []; // Combine the statements into a single statement statements.forEach(function(st) { statement += st.sql + '; '; if (st.parameters) { params = params.concat(st.parameters) } }); // Combine the parameter lists into a single list params.forEach(function (parameter) { var type = parameter.type || helpers.getMssqlType(parameter.value); if(type) request.input(parameter.name, type, parameter.value); else request.input(parameter.name, parameter.value); }); log.silly('Executing SQL statement ' + statement + ' with parameters ' + JSON.stringify(params)); return request.query(statement).catch(function (err) { log.debug('SQL statement failed - ' + err.message + ': ' + statement + ' with parameters ' + JSON.stringify(params)); if(err.number === 2627) { var error = new Error('An item with the same ID already exists'); error.duplicate = true; throw error; } return promises.rejected(err); }); } };
{ "content_hash": "ade02d819fec827771ec20c0d2b020d8", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 129, "avg_line_length": 33.88059701492537, "alnum_prop": 0.5647577092511014, "repo_name": "phvannor/azure-mobile-apps-node", "id": "6151066e342e673f7407eab20725270632554c9d", "size": "2491", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/data/sql/execute.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "529979" }, { "name": "SQLPL", "bytes": "1511" } ], "symlink_target": "" }
import numpy as np respuestas = [] tamaño = (int(input())) while tamaño: matriz = [] for _ in range(tamaño): matriz.append([int(x) for x in input().split()]) matriz = np.array(matriz, dtype=int) identidad = np.identity(tamaño, int) if np.array_equal(matriz, identidad): respuestas.append('SI') else: respuestas.append('NO') tamaño = int(input()) for respuesta in respuestas: print(respuesta)
{ "content_hash": "3714676a5c5d57cd4353ad9fe7189437", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 56, "avg_line_length": 25, "alnum_prop": 0.6222222222222222, "repo_name": "israelem/aceptaelreto", "id": "c7c54f2e1b1d56472ec43fa1f2853fa4a98295fc", "size": "455", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "codes/2018-05-07-identidad.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "63525" }, { "name": "HTML", "bytes": "7067" }, { "name": "Python", "bytes": "46514" } ], "symlink_target": "" }
package org.diorite.impl.plugin; import static org.diorite.utils.function.FunctionUtils.not; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.NoSuchElementException; import com.google.common.collect.ImmutableSet; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.diorite.impl.Main; import org.diorite.plugin.BasePlugin; import org.diorite.plugin.FakeDioritePlugin; import org.diorite.plugin.PluginException; import org.diorite.plugin.PluginLoader; import org.diorite.plugin.PluginManager; public class PluginManagerImpl implements PluginManager { private final Collection<BasePlugin> plugins = new ArrayList<>(20); private final Map<String, PluginLoader> pluginLoaders = new HashMap<>(5); @Override public void registerPluginLoader(final PluginLoader pluginLoader) { Main.debug("Registered plugin loader " + pluginLoader.getClass().getSimpleName() + " for extension " + pluginLoader.getFileExtension()); this.pluginLoaders.put(pluginLoader.getFileExtension(), pluginLoader); } @Override public void loadPlugin(final File file) throws PluginException { final PluginLoader pluginLoader = this.pluginLoaders.get(FilenameUtils.getExtension(file.getAbsolutePath())); if (pluginLoader == null) { Main.debug("Non-plugin file: " + file.getName()); return; } Main.debug("Loading plugin " + file.getName() + " with pluginloader: " + pluginLoader.getClass().getSimpleName()); this.plugins.add(pluginLoader.loadPlugin(file)); } @Override public void injectPlugin(final FakeDioritePlugin plugin) throws PluginException { if (this.getPlugin(plugin.getName()) != null) { throw new PluginException("Plugin with name " + plugin.getName() + " is arleady loaded!"); } Main.debug("Injecting plugin: " + plugin.getName()); this.plugins.add(plugin); plugin.init(null, this.pluginLoaders.get(FakePluginLoader.FAKE_PLUGIN_EXTENSION), null, null, null, null, null, null); } @Override public void enablePlugin(final BasePlugin plugin) throws PluginException { if (plugin == null) { throw new NullPointerException("plugin can't be null!"); } plugin.getPluginLoader().enablePlugin(plugin); } @Override public void disablePlugin(final BasePlugin plugin) throws PluginException { if (plugin == null) { throw new NullPointerException("plugin can't be null!"); } plugin.getPluginLoader().disablePlugin(plugin); } @Override public BasePlugin getPlugin(final String name) { try { return this.plugins.stream().filter(p -> p.getName().equalsIgnoreCase(name)).findFirst().get(); } catch (final NoSuchElementException ignored) { return null; } } @Override public Collection<BasePlugin> getPlugins() { return ImmutableSet.copyOf(this.plugins); } @Override public void enablePlugins() { this.plugins.stream().filter(not(BasePlugin::isEnabled)).forEach(plugin -> { try { this.enablePlugin(plugin); } catch (final PluginException e) { e.printStackTrace(); } }); } @Override public void disablePlugins() { this.plugins.stream().filter(BasePlugin::isEnabled).forEach(plugin -> { try { this.disablePlugin(plugin); } catch (final PluginException e) { e.printStackTrace(); } }); } @Override public String toString() { return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).appendSuper(super.toString()).append("plugins", this.plugins).append("pluginLoaders", this.pluginLoaders).toString(); } }
{ "content_hash": "9c412f38f29cc938253c509ba41fdc5a", "timestamp": "", "source": "github", "line_count": 134, "max_line_length": 192, "avg_line_length": 31.32089552238806, "alnum_prop": 0.6466523707410055, "repo_name": "joda17/Diorite-Core", "id": "0769a99ffe29759b96704e156a7a17582ebc4d54", "size": "4197", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/diorite/impl/plugin/PluginManagerImpl.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "993225" } ], "symlink_target": "" }
<?php /* netfunktheme single post */ ?> <?php get_header(); ?> <div id="container"> <?php global $netfunk_post_options; ?> <?php /* Posts Page Spash Image display # 0 = Splash Img | Hide Thumbnail # 1 = Splash Img + Show Thumbnail # 2 = No Splash | Hide Thumbnail # 3 = No Splash + Show Thumbnail */ // determine if we are using splash images if ( isset( $netfunk_post_options['posts_splash_type'] ) && ( $netfunk_post_options['posts_splash_type'] <= 1 ) ) { $splash_image = netfunktheme_catch_post_image(); ?> <div class="large-12 featured-entry hide-for-small"> <div class="featured-image-bg" style="background-image: url('<?php echo $splash_image ?>'); "></div> </div> <?php } ?> <?php if ( have_posts() ): while ( have_posts() ): the_post(); ?> <div class="content clearfix"> <div class="row"> <div class="small-12 <?php do_action('netfunktheme_sidenoside', 'post') ?> columns"> <h3> <?php the_title(); ?> </h3> <?php edit_post_link( __( '<i class="fa fa-pencil"></i> &nbsp; Edit this post', 'netfunktheme' ), '<div class="button secondary round tiny right edit-link">', '</div>' ) ?> <?php get_template_part( 'template/entry', 'meta' ); ?> <h2 class="show-for-small"> <?php echo the_title(); ?> </h2> <?php if ( (isset($netfunk_post_options['show_nav_above']) && $netfunk_post_options['show_nav_above'] == 'yes') or (!isset($netfunk_post_options['show_nav_above'])) ) { get_template_part( 'template/nav', 'above-single' ); } ?> <hr /> <?php get_template_part( 'entry' ); ?> <?php if ( (isset($netfunk_post_options['show_post_footer_meta']) && $netfunk_post_options['show_post_footer_meta'] == 'yes') or (!isset($netfunk_post_options['show_post_footer_meta'])) ) { get_template_part( 'template/entry-footer-single', get_post_format() ); } ?> <div class="small-12 clearfix"> <?php if ( (isset($netfunk_post_options['show_nav_below']) && $netfunk_post_options['show_nav_below'] == 'yes') or (!isset($netfunk_post_options['show_nav_below'])) ) { get_template_part( 'template/nav', 'below-single' ); } ?> </div> <div class="small-12 entry-comments"> <?php if ( (isset($netfunk_post_options['show_post_comments']) && $netfunk_post_options['show_post_comments'] == 'yes') or (!isset($netfunk_post_options['show_post_comments'])) ) { comments_template( '', true ); } ?> </div> <?php if ( (isset($netfunk_post_options['show_post_author']) && $netfunk_post_options['show_post_author'] == 'yes') or (!isset($netfunk_post_options['show_post_author']))) { do_action( 'netfunktheme_about_the_author'); } ?> </div> <?php if ( (isset($netfunk_post_options['show_posts_sidebar']) && $netfunk_post_options['show_posts_sidebar'] == 'yes') or (!isset($netfunk_post_options['show_posts_sidebar'])) ){ get_sidebar(); } ?> </div> </div> <?php if ( is_active_sidebar( 'home-bottom-widget-area' ) ) : ?> <?php if ( (isset($netfunk_post_options['show_post_bottom_content']) && $netfunk_post_options['show_post_bottom_content'] == 'yes') or (!isset($netfunk_post_options['show_post_bottom_content']))) { ?> <div class="page-bottom-content clearix"> <div class="row"> <div class="class-12 columns"> <?php if ( ! dynamic_sidebar( 'home-bottom-widget-area' ) ) : ?> <h4> You need to add some widgets... </h4> <?php endif; // end primary widget area ?> </div> </div> </div> <?php } ?> <?php endif; ?> <?php endwhile; ?> <?php endif; ?> </div> <?php get_footer(); ?>
{ "content_hash": "698270143cdab3ab253692a18771daec", "timestamp": "", "source": "github", "line_count": 173, "max_line_length": 201, "avg_line_length": 24.572254335260116, "alnum_prop": 0.5071747824041402, "repo_name": "PhilSanders/themefunk-wp-theme", "id": "ce417015976cd4c3b1f2c08a35ecad98811ba8bd", "size": "4251", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "single.php", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "101155" }, { "name": "JavaScript", "bytes": "83906" }, { "name": "PHP", "bytes": "458838" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="ProjectModuleManager"> <modules> <module fileurl="file://$PROJECT_DIR$/EventBusDemo.iml" filepath="$PROJECT_DIR$/EventBusDemo.iml" /> <module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" /> </modules> </component> </project>
{ "content_hash": "51213c9faac6dbfb3735bd250e29b147", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 106, "avg_line_length": 40.111111111111114, "alnum_prop": 0.6648199445983379, "repo_name": "quhong/EventBusDemo", "id": "824bde760053ba2ade95aa9c32de9ce8d3e96728", "size": "361", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": ".idea/modules.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "3039" } ], "symlink_target": "" }
""" :module: mom.security.codec :synopsis: Codecs to encode and decode keys and certificates in various formats. PEM key decoders ---------------- .. autofunction:: public_key_pem_decode .. autofunction:: private_key_pem_decode """ from __future__ import absolute_import from mom.security.codec import pem from mom.security.codec.pem import rsa from mom.security.codec.pem import x509 __author__ = "yesudeep@google.com (Yesudeep Mangalapilly)" def public_key_pem_decode(pem_key): """ Decodes a PEM-encoded public key/X.509 certificate string into internal representation. :param pem_key: The PEM-encoded key. Must be one of: 1. RSA public key. 2. X.509 certificate. :returns: A dictionary of key information. """ pem_key = pem_key.strip() if pem_key.startswith(pem.CERT_PEM_HEADER): key = x509.X509Certificate(pem_key).public_key elif pem_key.startswith(pem.PUBLIC_KEY_PEM_HEADER): key = rsa.RSAPublicKey(pem_key).public_key else: raise NotImplementedError("Only PEM X.509 certificates & public " "RSA keys can be read.") return key def private_key_pem_decode(pem_key): """ Decodes a PEM-encoded private key string into internal representation. :param pem_key: The PEM-encoded RSA private key. :returns: A dictionary of key information. """ pem_key = pem_key.strip() if (pem_key.startswith(pem.PRIVATE_KEY_PEM_HEADER) or pem_key.startswith(pem.RSA_PRIVATE_KEY_PEM_HEADER)): key = rsa.RSAPrivateKey(pem_key).private_key else: raise NotImplementedError("Only PEM private RSA keys can be read.") return key
{ "content_hash": "aa7e55ebe09d7fcd0fefc39789902200", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 80, "avg_line_length": 27.466666666666665, "alnum_prop": 0.6899271844660194, "repo_name": "gorakhargosh/mom", "id": "d8df39376d9f404adaf560bb4a2d97fac03712fe", "size": "2353", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "mom/security/codec/__init__.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "626298" }, { "name": "Shell", "bytes": "1902" } ], "symlink_target": "" }
package org.broadinstitute.sting.gatk.walkers.diffengine; import com.google.java.contract.Ensures; import com.google.java.contract.Invariant; import com.google.java.contract.Requires; import org.broadinstitute.sting.utils.Utils; import org.broadinstitute.sting.utils.exceptions.ReviewedStingException; /** * Created by IntelliJ IDEA. * User: depristo * Date: 7/4/11 * Time: 12:55 PM * * An interface that must be implemented to allow us to calculate differences * between structured objects */ @Invariant({ "name != null", "value != null", "parent != null || name.equals(\"ROOT\")", "value == null || value.getBinding() == this"}) public class DiffElement { public final static DiffElement ROOT = new DiffElement(); final private String name; final private DiffElement parent; final private DiffValue value; /** * For ROOT only */ private DiffElement() { this.name = "ROOT"; this.parent = null; this.value = new DiffValue(this, "ROOT"); } @Requires({"name != null", "parent != null", "value != null"}) public DiffElement(String name, DiffElement parent, DiffValue value) { if ( name.equals("ROOT") ) throw new IllegalArgumentException("Cannot use reserved name ROOT"); this.name = name; this.parent = parent; this.value = value; this.value.setBinding(this); } @Ensures({"result != null"}) public String getName() { return name; } public DiffElement getParent() { return parent; } @Ensures({"result != null"}) public DiffValue getValue() { return value; } public boolean isRoot() { return this == ROOT; } @Ensures({"result != null"}) @Override public String toString() { return getName() + "=" + getValue().toString(); } public String toString(int offset) { return (offset > 0 ? Utils.dupString(' ', offset) : 0) + getName() + "=" + getValue().toString(offset); } @Ensures({"result != null"}) public final String fullyQualifiedName() { if ( isRoot() ) return ""; else if ( parent.isRoot() ) return name; else return parent.fullyQualifiedName() + "." + name; } @Ensures({"result != null"}) public String toOneLineString() { return getName() + "=" + getValue().toOneLineString(); } @Ensures({"result != null"}) public DiffNode getValueAsNode() { if ( getValue().isCompound() ) return (DiffNode)getValue(); else throw new ReviewedStingException("Illegal request conversion of a DiffValue into a DiffNode: " + this); } public int size() { return 1 + getValue().size(); } }
{ "content_hash": "6eb5b81db24760bf8321df251d6e4223", "timestamp": "", "source": "github", "line_count": 102, "max_line_length": 115, "avg_line_length": 27.441176470588236, "alnum_prop": 0.602357984994641, "repo_name": "iontorrent/Torrent-Variant-Caller-stable", "id": "eb8a71c2cb13cb1c6826a524369461caec99af5c", "size": "3929", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/java/src/org/broadinstitute/sting/gatk/walkers/diffengine/DiffElement.java", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "13702" }, { "name": "C++", "bytes": "93650" }, { "name": "Java", "bytes": "7434523" }, { "name": "JavaScript", "bytes": "25002" }, { "name": "Perl", "bytes": "6761" }, { "name": "Python", "bytes": "1510" }, { "name": "R", "bytes": "37286" }, { "name": "Scala", "bytes": "480437" }, { "name": "Shell", "bytes": "901" }, { "name": "XML", "bytes": "8989" } ], "symlink_target": "" }
FactoryGirl.define do factory :participant do end end
{ "content_hash": "2ba12a71fc781a3244c6b3544159e049", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 25, "avg_line_length": 14.5, "alnum_prop": 0.7758620689655172, "repo_name": "TheBigBoss2005/SUL", "id": "15be7b38f06c511cb94aa0161c4946905c70f06c", "size": "128", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/factories/participants.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "216350" }, { "name": "CoffeeScript", "bytes": "844" }, { "name": "JavaScript", "bytes": "747162" }, { "name": "Ruby", "bytes": "99864" } ], "symlink_target": "" }
require 'rails_helper' RSpec.describe 'rake db:repopulate', type: :task do it 'resets the database and then poplates it' do expect(task.prerequisites).to include 'reset', 'populate' end end
{ "content_hash": "ef639cb2093d13064fbdd28a479dcfcf", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 61, "avg_line_length": 28.428571428571427, "alnum_prop": 0.7336683417085427, "repo_name": "crawfoal/greensteps", "id": "34d9e7b33e43ee472a41094f4d36926120c5292a", "size": "199", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/lib/tasks/db/repopulate_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "21270" }, { "name": "CoffeeScript", "bytes": "4662" }, { "name": "HTML", "bytes": "20478" }, { "name": "JavaScript", "bytes": "1277" }, { "name": "Ruby", "bytes": "189156" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using Traveller.Commands.Contracts; using Traveller.Core; using Traveller.Core.Contracts; using Traveller.Core.Factories; using Traveller.Core.Repository; using Traveller.Models; using Traveller.Models.Abstractions; namespace Traveller.Commands.Creating { public class CreateTicketCommand : CreateCommand { public CreateTicketCommand(ITravellerFactory factory, IDatabase database) : base(factory, database) { } public override string Execute(IList<string> parameters) { IJourney journey; decimal administrativeCosts; try { journey = base.Database.Journeys[int.Parse(parameters[0])]; administrativeCosts = decimal.Parse(parameters[1]); } catch { throw new ArgumentException("Failed to parse CreateTicket command parameters."); } var ticket = Factory.CreateTicket(journey, administrativeCosts); base.Database.Tickets.Add(ticket); return $"Ticket with ID {base.Database.Tickets.Count - 1} was created."; } } }
{ "content_hash": "1b8699572108be3378f3d1eecd8e3265", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 111, "avg_line_length": 31.18421052631579, "alnum_prop": 0.6514767932489451, "repo_name": "Xadera/Telerik-Academy-Alpha", "id": "87141076865dc423b6d56cdeefb55d1087edd586", "size": "1187", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Module 2/HQC Exam/Traveller/Commands/Creating/CreateTicketCommand.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "198" }, { "name": "C#", "bytes": "764282" }, { "name": "CSS", "bytes": "1146" }, { "name": "HTML", "bytes": "763" }, { "name": "JavaScript", "bytes": "22927" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Text; using FlatRedBall.Graphics; using FlatRedBall.Attributes; using Microsoft.Xna.Framework.Graphics; namespace FlatRedBall.Content.Saves { #region XML Docs /// <summary> /// An XML Serializable class representing the state of a Text. /// </summary> #endregion public class TextSave : TextSaveBase { #region Fields #if !MONODROID [ExternalInstance] internal Texture2D mFontTextureInstance; #endif internal string FontPatternText; #endregion #region Methods public static TextSave FromText(Text text) { TextSave textSave = new TextSave(); textSave.X = text.Position.X; textSave.Y = text.Position.Y; textSave.Z = text.Position.Z; textSave.RotationX = text.RotationX; textSave.RotationY = text.RotationY; textSave.RotationZ = text.RotationZ; textSave.RelativeX = text.RelativePosition.X; textSave.RelativeY = text.RelativePosition.Y; textSave.RelativeZ = text.RelativePosition.Z; textSave.RelativeRotationX = text.RelativeRotationX; textSave.RelativeRotationY = text.RelativeRotationY; textSave.RelativeRotationZ = text.RelativeRotationZ; textSave.DisplayText = text.DisplayText; textSave.Name = text.Name; textSave.MaxWidth = text.MaxWidth; textSave.MaxWidthBehavior = text.MaxWidthBehavior; textSave.Scale = text.Scale; textSave.Spacing = text.Spacing; textSave.NewLineDistance = text.NewLineDistance; textSave.VerticalAlignment = text.VerticalAlignment; textSave.HorizontalAlignment = text.HorizontalAlignment; textSave.Visible = text.Visible; textSave.CursorSelectable = text.CursorSelectable; if (text.Parent != null) { textSave.Parent = text.Parent.Name; } if (text.Font != null && text.Font != TextManager.DefaultFont) { textSave.FontFile = text.Font.mFontFile; if (text.Font.mTextures.Length == 1) { textSave.FontTexture = text.Font.Texture.Name; } else { textSave.FontTexture = ""; } } #if FRB_MDX //spriteSave.Fade = 255 - spriteToCreateSaveFrom.Alpha; //spriteSave.FadeRate = -spriteToCreateSaveFrom.AlphaRate; textSave.Red = text.Red; textSave.Green = text.Green; textSave.Blue = text.Blue; //spriteSave.TintRedRate = spriteToCreateSaveFrom.RedRate; //spriteSave.TintGreenRate = spriteToCreateSaveFrom.GreenRate; //spriteSave.TintBlueRate = spriteToCreateSaveFrom.BlueRate; textSave.ColorOperation = GraphicalEnumerations.TranslateColorOperation(text.ColorOperation); #elif FRB_XNA //spriteSave.Fade = (1 - spriteToCreateSaveFrom.Alpha) * 255.0f; //spriteSave.FadeRate = -spriteToCreateSaveFrom.AlphaRate * 255.0f; textSave.Red = text.Red * 255.0f; textSave.Green = text.Green * 255.0f; textSave.Blue = text.Blue * 255.0f; //spriteSave.TintRedRate = spriteToCreateSaveFrom.RedRate * 255.0f; //spriteSave.TintGreenRate = spriteToCreateSaveFrom.GreenRate * 255.0f; //spriteSave.TintBlueRate = spriteToCreateSaveFrom.BlueRate * 255.0f; textSave.ColorOperation = GraphicalEnumerations.ColorOperationToFlatRedBallMdxString(text.ColorOperation); #endif return textSave; } public Text ToText(string contentManagerName) { Text text = new Text(); text.X = X; text.Y = Y; text.Z = Z; text.RotationX = RotationX; text.RotationY = RotationY; text.RotationZ = RotationZ; text.RelativePosition.X = RelativeX; text.RelativePosition.Y = RelativeY; text.RelativePosition.Z = RelativeZ; text.RelativeRotationX = RelativeRotationX; text.RelativeRotationY = RelativeRotationY; text.RelativeRotationZ = RelativeRotationZ; text.DisplayText = DisplayText; text.Name = Name; text.Scale = Scale; text.Spacing = Spacing; text.NewLineDistance = NewLineDistance; text.MaxWidth = MaxWidth; text.MaxWidthBehavior = MaxWidthBehavior; text.VerticalAlignment = VerticalAlignment; text.HorizontalAlignment = HorizontalAlignment; text.Visible = Visible; text.CursorSelectable = CursorSelectable; #if !SILVERLIGHT #if !MONODROID if (this.mFontTextureInstance != null) { BitmapFont bitmapFont = new BitmapFont( mFontTextureInstance, FontPatternText); text.Font = bitmapFont; } else #endif if (!string.IsNullOrEmpty(FontFile)) { BitmapFont bitmapFont = null; if (!string.IsNullOrEmpty(FontTexture)) { bitmapFont = new BitmapFont( FontTexture, FontFile, contentManagerName); } else { bitmapFont = new BitmapFont( FontFile, contentManagerName); } text.Font = bitmapFont; } else { text.Font = TextManager.DefaultFont; } #endif #if FRB_XNA //valueToDivideBy = 255; #endif //sprite.Alpha = (255 - Fade) / valueToDivideBy; //sprite.AlphaRate = -FadeRate / valueToDivideBy; //sprite.BlendOperation = GraphicalEnumerations.TranslateBlendOperation(BlendOperation); //sprite.RedRate = TintRedRate / valueToDivideBy; //sprite.GreenRate = TintGreenRate / valueToDivideBy; //sprite.BlueRate = TintBlueRate / valueToDivideBy; var colorOperation = ColorOperation; #if MONODROID if (colorOperation == "SelectArg2") { colorOperation = "Modulate"; } #endif GraphicalEnumerations.SetColors(text, Red, Green, Blue, colorOperation); return text; } #endregion } }
{ "content_hash": "44572c16543c345d4ff2ee71d6a0265e", "timestamp": "", "source": "github", "line_count": 231, "max_line_length": 100, "avg_line_length": 29.17748917748918, "alnum_prop": 0.5744807121661721, "repo_name": "GorillaOne/FlatRedBall", "id": "ed8c2c2b61ba7544897642c17d7cb5c88cfaa184", "size": "6740", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Engines/FlatRedBallXNA/FlatRedBall/Content/Saves/TextSave.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1314" }, { "name": "C", "bytes": "335451" }, { "name": "C#", "bytes": "16797833" }, { "name": "C++", "bytes": "321530" }, { "name": "CSS", "bytes": "6282" }, { "name": "HLSL", "bytes": "66557" }, { "name": "HTML", "bytes": "56466" }, { "name": "Logos", "bytes": "167589" }, { "name": "Objective-C", "bytes": "361" }, { "name": "Smalltalk", "bytes": "12" }, { "name": "XSLT", "bytes": "24694" } ], "symlink_target": "" }
set -e if (( ${ENABLE_HDFS} )); then if (id -u hdfs >& /dev/null); then HDFS_ADMIN=hdfs elif (id -u hadoop >& /dev/null); then HDFS_ADMIN=hadoop else echo 'Cannot find HDFS administrative user.' exit 1 fi # Location of HDFS metadata on namenode export HDFS_NAME_DIR=/hadoop/dfs/name # If disks are mounted use all of them for HDFS data MOUNTED_DISKS=($(find /mnt -maxdepth 1 -mindepth 1 -name "pd*")) if [[ ${#MOUNTED_DISKS[@]} -eq 0 ]]; then MOUNTED_DISKS=('') fi # Location of HDFS data blocks on datanodes; for each mounted disk, add the # path /mnt/diskname/hadoop/dfs/data as a data directory, or if no mounted # disks exist, just go with the absolute path /hadoop/dfs/data. HDFS_DATA_DIRS="${MOUNTED_DISKS[@]/%//hadoop/dfs/data}" # Do not create HDFS_NAME_DIR, or Hadoop will think it is already formatted mkdir -p /hadoop/dfs ${HDFS_DATA_DIRS} chown ${HDFS_ADMIN}:hadoop -L -R /hadoop/dfs ${HDFS_DATA_DIRS} # Make sure the data dirs have the expected permissions. chmod ${HDFS_DATA_DIRS_PERM} ${HDFS_DATA_DIRS} # Set general Hadoop environment variables # Calculate the memory allocations, MB, using 'free -m'. Floor to nearest MB. TOTAL_MEM=$(free -m | awk '/^Mem:/{print $2}') NAMENODE_MEM_MB=$(python -c "print int(${TOTAL_MEM} * \ ${HDFS_MASTER_MEMORY_FRACTION} / 2)") SECONDARYNAMENODE_MEM_MB=${NAMENODE_MEM_MB} cat << EOF >> ${HADOOP_CONF_DIR}/hadoop-env.sh # Increase the maximum NameNode / SecondaryNameNode heap. HADOOP_NAMENODE_OPTS="-Xmx${NAMENODE_MEM_MB}m \${HADOOP_NAMENODE_OPTS}" HADOOP_SECONDARYNAMENODE_OPTS="-Xmx${SECONDARYNAMENODE_MEM_MB}m \${HADOOP_SECONDARYNAMENODE_OPTS}" EOF # Increase maximum number of files for HDFS MAX_FILES=16384 ulimit -n ${MAX_FILES} cat << EOF > /etc/security/limits.d/hadoop.conf ${HDFS_ADMIN} hard nofile ${MAX_FILES} ${HDFS_ADMIN} soft nofile ${MAX_FILES} EOF export HDFS_DATA_DIRS="${HDFS_DATA_DIRS// /,}" bdconfig merge_configurations \ --configuration_file ${HADOOP_CONF_DIR}/hdfs-site.xml \ --source_configuration_file hdfs-template.xml \ --resolve_environment_variables \ --create_if_absent \ --clobber fi
{ "content_hash": "25bb08ee87ceae15b68f7dac40ad96a1", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 98, "avg_line_length": 33.333333333333336, "alnum_prop": 0.6790909090909091, "repo_name": "project-flink/bdutil-flink", "id": "060a90520ec8c10f4e3b249140842dfaa88b79a0", "size": "2817", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "libexec/configure_hdfs.sh", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PigLatin", "bytes": "3923" }, { "name": "Shell", "bytes": "189051" } ], "symlink_target": "" }
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.18444 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Namespace My 'NOTE: This file is auto-generated; do not modify it directly. To make changes, ' or if you encounter build errors in this file, go to the Project Designer ' (go to Project Properties or double-click the My Project node in ' Solution Explorer), and make changes on the Application tab. ' Partial Friend Class MyApplication <Global.System.Diagnostics.DebuggerStepThroughAttribute()> _ Public Sub New() MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows) Me.IsSingleInstance = false Me.EnableVisualStyles = true Me.SaveMySettingsOnExit = true Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses End Sub <Global.System.Diagnostics.DebuggerStepThroughAttribute()> _ Protected Overrides Sub OnCreateMainForm() Me.MainForm = Global.PA_10_W_Weinert.frmBankAccounts End Sub End Class End Namespace
{ "content_hash": "adcb2ca75693d8495b766c74a57f322d", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 112, "avg_line_length": 39.18421052631579, "alnum_prop": 0.6165211551376762, "repo_name": "winny-/CPS-240", "id": "3b8351a148a6a09fb7fbe39bb7dd3eaeb770b5b2", "size": "1491", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Assignments/PA 10 W Weinert/PA 5 W Weinert/My Project/Application.Designer.vb", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "2858" }, { "name": "Visual Basic", "bytes": "631523" } ], "symlink_target": "" }
<head> {% capture canonical %}{{ site.url }}{% if site.permalink contains '.html' %}{{ page.url }}{% elsif site.permalink contains category_dir %}{{ '/' | page.url | remove:'index.html' | '/' }}{% else %}{{ page.url | remove:'index.html' | '/' }}{% endif %}{% endcapture %} <link href="//gmpg.org/xfn/11" rel="profile"> <meta http-equiv="content-type" content="text/html; charset=utf-8">{% if page.article %} <link rel="canonical" href="{{ canonical }}" /> <meta name="description" content="{% if page.quote %}{{ page.quote }}{% else %}{{ page.content | strip_html | truncatewords: 20 }}{% endif %}" /> <meta property="og:description" content="{% if page.quote %}{{ page.quote }}{% else %}{{ page.content | strip_html | truncatewords: 20 }}{% endif %}" /> <meta itemprop="image" content="{% if page.image.url %}{{ site.url }}{{ page.image.url }}{% else %}{{ site.url }}{{ site.icon }}{% endif %}" /> <meta property="og:image" content="{% if page.image.url %}{{ site.url }}{{ page.image.url }}{% else %}{{ site.url }}{{ site.icon }}{% endif %}" /> <meta property="og:title" content="{{ page.title }}" /> <meta property="og:type" content="article" /> <meta property="og:url" content="{{ canonical }}" /> <meta property="og:site_name" content="{{ site.title }}" />{% endif %} <title>{% if page.title == "Home" %}{{ site.title }} &middot; {{ site.tagline }}{% else %}{{ page.title }} &middot; {{ site.title }}{% endif %}</title> <meta name="mobile-web-app-capable" content="yes"> <meta name="HandheldFriendly" content="True" /> <meta name="MobileOptimized" content="320" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" type="text/css" media="only screen and (min-width: 900px)" href="/assets/css/desktop.css" /> <link rel="stylesheet" type="text/css" media="only screen and (max-width: 899px)" href="/assets/css/mobile.css" /> <link href="/assets/css/genericons.css" type="text/css" rel="stylesheet" /> <link href="/assets/css/syntax.css" type="text/css" rel="stylesheet" /> <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Fenix:400,400italic"> <link rel="apple-touch-icon" href="{{ site.url }}{{ site.icon }}"> <link rel="shortcut icon" href="{{ site.url }}/assets/images/favicon.ico"> <link rel="alternate" type="application/rss+xml" title="RSS" href="{{ site.url }}/atom.xml"> <meta name="google-site-verification" content="dxHJfJrwqWqaCiGZcfJ6xGM5n15rRRgS6ae699FLo3w" /> <script type="text/javascript" src="/assets/js/jquery-2.1.0.min.js"></script> <script type="text/javascript" src="/assets/js/jquery.stellar.min.js"></script> </head>
{ "content_hash": "b71b38b91aa1f0e9a2a6152bb48c4e4c", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 267, "avg_line_length": 85.96774193548387, "alnum_prop": 0.6390243902439025, "repo_name": "QuickScythe/QuickScythe.github.io", "id": "fcd42529e78c2a2769515f3b688fd99850b4e09d", "size": "2665", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_includes/head.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "13332" }, { "name": "HTML", "bytes": "18273" }, { "name": "JavaScript", "bytes": "6219" }, { "name": "Ruby", "bytes": "79" } ], "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_91) on Mon Sep 05 17:05:33 CST 2016 --> <title>Stat (ZooKeeper 3.4.6 API)</title> <meta name="date" content="2016-09-05"> <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="Stat (ZooKeeper 3.4.6 API)"; } } 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,"i11":10,"i12":10,"i13":10,"i14":10,"i15":10,"i16":10,"i17":10,"i18":10,"i19":10,"i20":10,"i21":10,"i22":10,"i23":10,"i24":10,"i25":10,"i26":10,"i27":10,"i28":9,"i29":10,"i30":10}; var tabs = {65535:["t0","All Methods"],1:["t1","Static 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="class-use/Stat.html">Use</a></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/apache/zookeeper/data/Id.html" title="class in org.apache.zookeeper.data"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../org/apache/zookeeper/data/StatPersisted.html" title="class in org.apache.zookeeper.data"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/apache/zookeeper/data/Stat.html" target="_top">Frames</a></li> <li><a href="Stat.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>Field&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>Field&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.apache.zookeeper.data</div> <h2 title="Class Stat" class="title">Class Stat</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li><a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">java.lang.Object</a></li> <li> <ul class="inheritance"> <li>org.apache.zookeeper.data.Stat</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd>org.apache.jute.Record</dd> </dl> <hr> <br> <pre>public class <span class="typeNameLabel">Stat</span> extends <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a> implements org.apache.jute.Record</pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== 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/apache/zookeeper/data/Stat.html#Stat--">Stat</a></span>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../../org/apache/zookeeper/data/Stat.html#Stat-long-long-long-long-int-int-int-long-int-int-long-">Stat</a></span>(long&nbsp;czxid, long&nbsp;mzxid, long&nbsp;ctime, long&nbsp;mtime, int&nbsp;version, int&nbsp;cversion, int&nbsp;aversion, long&nbsp;ephemeralOwner, int&nbsp;dataLength, int&nbsp;numChildren, long&nbsp;pzxid)</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="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></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>int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/zookeeper/data/Stat.html#compareTo-java.lang.Object-">compareTo</a></span>(<a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a>&nbsp;peer_)</code>&nbsp;</td> </tr> <tr id="i1" class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/zookeeper/data/Stat.html#deserialize-org.apache.jute.InputArchive-java.lang.String-">deserialize</a></span>(org.apache.jute.InputArchive&nbsp;a_, <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;tag)</code>&nbsp;</td> </tr> <tr id="i2" class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/zookeeper/data/Stat.html#equals-java.lang.Object-">equals</a></span>(<a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a>&nbsp;peer_)</code>&nbsp;</td> </tr> <tr id="i3" class="rowColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/zookeeper/data/Stat.html#getAversion--">getAversion</a></span>()</code>&nbsp;</td> </tr> <tr id="i4" class="altColor"> <td class="colFirst"><code>long</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/zookeeper/data/Stat.html#getCtime--">getCtime</a></span>()</code>&nbsp;</td> </tr> <tr id="i5" class="rowColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/zookeeper/data/Stat.html#getCversion--">getCversion</a></span>()</code>&nbsp;</td> </tr> <tr id="i6" class="altColor"> <td class="colFirst"><code>long</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/zookeeper/data/Stat.html#getCzxid--">getCzxid</a></span>()</code>&nbsp;</td> </tr> <tr id="i7" class="rowColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/zookeeper/data/Stat.html#getDataLength--">getDataLength</a></span>()</code>&nbsp;</td> </tr> <tr id="i8" class="altColor"> <td class="colFirst"><code>long</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/zookeeper/data/Stat.html#getEphemeralOwner--">getEphemeralOwner</a></span>()</code>&nbsp;</td> </tr> <tr id="i9" class="rowColor"> <td class="colFirst"><code>long</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/zookeeper/data/Stat.html#getMtime--">getMtime</a></span>()</code>&nbsp;</td> </tr> <tr id="i10" class="altColor"> <td class="colFirst"><code>long</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/zookeeper/data/Stat.html#getMzxid--">getMzxid</a></span>()</code>&nbsp;</td> </tr> <tr id="i11" class="rowColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/zookeeper/data/Stat.html#getNumChildren--">getNumChildren</a></span>()</code>&nbsp;</td> </tr> <tr id="i12" class="altColor"> <td class="colFirst"><code>long</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/zookeeper/data/Stat.html#getPzxid--">getPzxid</a></span>()</code>&nbsp;</td> </tr> <tr id="i13" class="rowColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/zookeeper/data/Stat.html#getVersion--">getVersion</a></span>()</code>&nbsp;</td> </tr> <tr id="i14" class="altColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/zookeeper/data/Stat.html#hashCode--">hashCode</a></span>()</code>&nbsp;</td> </tr> <tr id="i15" class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/zookeeper/data/Stat.html#readFields-java.io.DataInput-">readFields</a></span>(<a href="http://docs.oracle.com/javase/6/docs/api/java/io/DataInput.html?is-external=true" title="class or interface in java.io">DataInput</a>&nbsp;in)</code>&nbsp;</td> </tr> <tr id="i16" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/zookeeper/data/Stat.html#serialize-org.apache.jute.OutputArchive-java.lang.String-">serialize</a></span>(org.apache.jute.OutputArchive&nbsp;a_, <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;tag)</code>&nbsp;</td> </tr> <tr id="i17" class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/zookeeper/data/Stat.html#setAversion-int-">setAversion</a></span>(int&nbsp;m_)</code>&nbsp;</td> </tr> <tr id="i18" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/zookeeper/data/Stat.html#setCtime-long-">setCtime</a></span>(long&nbsp;m_)</code>&nbsp;</td> </tr> <tr id="i19" class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/zookeeper/data/Stat.html#setCversion-int-">setCversion</a></span>(int&nbsp;m_)</code>&nbsp;</td> </tr> <tr id="i20" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/zookeeper/data/Stat.html#setCzxid-long-">setCzxid</a></span>(long&nbsp;m_)</code>&nbsp;</td> </tr> <tr id="i21" class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/zookeeper/data/Stat.html#setDataLength-int-">setDataLength</a></span>(int&nbsp;m_)</code>&nbsp;</td> </tr> <tr id="i22" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/zookeeper/data/Stat.html#setEphemeralOwner-long-">setEphemeralOwner</a></span>(long&nbsp;m_)</code>&nbsp;</td> </tr> <tr id="i23" class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/zookeeper/data/Stat.html#setMtime-long-">setMtime</a></span>(long&nbsp;m_)</code>&nbsp;</td> </tr> <tr id="i24" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/zookeeper/data/Stat.html#setMzxid-long-">setMzxid</a></span>(long&nbsp;m_)</code>&nbsp;</td> </tr> <tr id="i25" class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/zookeeper/data/Stat.html#setNumChildren-int-">setNumChildren</a></span>(int&nbsp;m_)</code>&nbsp;</td> </tr> <tr id="i26" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/zookeeper/data/Stat.html#setPzxid-long-">setPzxid</a></span>(long&nbsp;m_)</code>&nbsp;</td> </tr> <tr id="i27" class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/zookeeper/data/Stat.html#setVersion-int-">setVersion</a></span>(int&nbsp;m_)</code>&nbsp;</td> </tr> <tr id="i28" class="altColor"> <td class="colFirst"><code>static <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/zookeeper/data/Stat.html#signature--">signature</a></span>()</code>&nbsp;</td> </tr> <tr id="i29" class="rowColor"> <td class="colFirst"><code><a href="http://docs.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/zookeeper/data/Stat.html#toString--">toString</a></span>()</code>&nbsp;</td> </tr> <tr id="i30" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../org/apache/zookeeper/data/Stat.html#write-java.io.DataOutput-">write</a></span>(<a href="http://docs.oracle.com/javase/6/docs/api/java/io/DataOutput.html?is-external=true" title="class or interface in java.io">DataOutput</a>&nbsp;out)</code>&nbsp;</td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.<a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a></h3> <code><a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#getClass--" title="class or interface in java.lang">getClass</a>, <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#notify--" title="class or interface in java.lang">notify</a>, <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#notifyAll--" title="class or interface in java.lang">notifyAll</a>, <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#wait--" title="class or interface in java.lang">wait</a>, <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#wait-long-" title="class or interface in java.lang">wait</a>, <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#wait-long-int-" title="class or interface in java.lang">wait</a></code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="Stat--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>Stat</h4> <pre>public&nbsp;Stat()</pre> </li> </ul> <a name="Stat-long-long-long-long-int-int-int-long-int-int-long-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>Stat</h4> <pre>public&nbsp;Stat(long&nbsp;czxid, long&nbsp;mzxid, long&nbsp;ctime, long&nbsp;mtime, int&nbsp;version, int&nbsp;cversion, int&nbsp;aversion, long&nbsp;ephemeralOwner, int&nbsp;dataLength, int&nbsp;numChildren, long&nbsp;pzxid)</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="getCzxid--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getCzxid</h4> <pre>public&nbsp;long&nbsp;getCzxid()</pre> </li> </ul> <a name="setCzxid-long-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setCzxid</h4> <pre>public&nbsp;void&nbsp;setCzxid(long&nbsp;m_)</pre> </li> </ul> <a name="getMzxid--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getMzxid</h4> <pre>public&nbsp;long&nbsp;getMzxid()</pre> </li> </ul> <a name="setMzxid-long-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setMzxid</h4> <pre>public&nbsp;void&nbsp;setMzxid(long&nbsp;m_)</pre> </li> </ul> <a name="getCtime--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getCtime</h4> <pre>public&nbsp;long&nbsp;getCtime()</pre> </li> </ul> <a name="setCtime-long-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setCtime</h4> <pre>public&nbsp;void&nbsp;setCtime(long&nbsp;m_)</pre> </li> </ul> <a name="getMtime--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getMtime</h4> <pre>public&nbsp;long&nbsp;getMtime()</pre> </li> </ul> <a name="setMtime-long-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setMtime</h4> <pre>public&nbsp;void&nbsp;setMtime(long&nbsp;m_)</pre> </li> </ul> <a name="getVersion--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getVersion</h4> <pre>public&nbsp;int&nbsp;getVersion()</pre> </li> </ul> <a name="setVersion-int-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setVersion</h4> <pre>public&nbsp;void&nbsp;setVersion(int&nbsp;m_)</pre> </li> </ul> <a name="getCversion--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getCversion</h4> <pre>public&nbsp;int&nbsp;getCversion()</pre> </li> </ul> <a name="setCversion-int-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setCversion</h4> <pre>public&nbsp;void&nbsp;setCversion(int&nbsp;m_)</pre> </li> </ul> <a name="getAversion--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getAversion</h4> <pre>public&nbsp;int&nbsp;getAversion()</pre> </li> </ul> <a name="setAversion-int-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setAversion</h4> <pre>public&nbsp;void&nbsp;setAversion(int&nbsp;m_)</pre> </li> </ul> <a name="getEphemeralOwner--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getEphemeralOwner</h4> <pre>public&nbsp;long&nbsp;getEphemeralOwner()</pre> </li> </ul> <a name="setEphemeralOwner-long-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setEphemeralOwner</h4> <pre>public&nbsp;void&nbsp;setEphemeralOwner(long&nbsp;m_)</pre> </li> </ul> <a name="getDataLength--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getDataLength</h4> <pre>public&nbsp;int&nbsp;getDataLength()</pre> </li> </ul> <a name="setDataLength-int-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setDataLength</h4> <pre>public&nbsp;void&nbsp;setDataLength(int&nbsp;m_)</pre> </li> </ul> <a name="getNumChildren--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getNumChildren</h4> <pre>public&nbsp;int&nbsp;getNumChildren()</pre> </li> </ul> <a name="setNumChildren-int-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setNumChildren</h4> <pre>public&nbsp;void&nbsp;setNumChildren(int&nbsp;m_)</pre> </li> </ul> <a name="getPzxid--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getPzxid</h4> <pre>public&nbsp;long&nbsp;getPzxid()</pre> </li> </ul> <a name="setPzxid-long-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setPzxid</h4> <pre>public&nbsp;void&nbsp;setPzxid(long&nbsp;m_)</pre> </li> </ul> <a name="serialize-org.apache.jute.OutputArchive-java.lang.String-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>serialize</h4> <pre>public&nbsp;void&nbsp;serialize(org.apache.jute.OutputArchive&nbsp;a_, <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;tag) throws <a href="http://docs.oracle.com/javase/6/docs/api/java/io/IOException.html?is-external=true" title="class or interface in java.io">IOException</a></pre> <dl> <dt><span class="overrideSpecifyLabel">Specified by:</span></dt> <dd><code>serialize</code>&nbsp;in interface&nbsp;<code>org.apache.jute.Record</code></dd> <dt><span class="throwsLabel">Throws:</span></dt> <dd><code><a href="http://docs.oracle.com/javase/6/docs/api/java/io/IOException.html?is-external=true" title="class or interface in java.io">IOException</a></code></dd> </dl> </li> </ul> <a name="deserialize-org.apache.jute.InputArchive-java.lang.String-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>deserialize</h4> <pre>public&nbsp;void&nbsp;deserialize(org.apache.jute.InputArchive&nbsp;a_, <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;tag) throws <a href="http://docs.oracle.com/javase/6/docs/api/java/io/IOException.html?is-external=true" title="class or interface in java.io">IOException</a></pre> <dl> <dt><span class="overrideSpecifyLabel">Specified by:</span></dt> <dd><code>deserialize</code>&nbsp;in interface&nbsp;<code>org.apache.jute.Record</code></dd> <dt><span class="throwsLabel">Throws:</span></dt> <dd><code><a href="http://docs.oracle.com/javase/6/docs/api/java/io/IOException.html?is-external=true" title="class or interface in java.io">IOException</a></code></dd> </dl> </li> </ul> <a name="toString--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>toString</h4> <pre>public&nbsp;<a href="http://docs.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;toString()</pre> <dl> <dt><span class="overrideSpecifyLabel">Overrides:</span></dt> <dd><code><a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#toString--" title="class or interface in java.lang">toString</a></code>&nbsp;in class&nbsp;<code><a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a></code></dd> </dl> </li> </ul> <a name="write-java.io.DataOutput-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>write</h4> <pre>public&nbsp;void&nbsp;write(<a href="http://docs.oracle.com/javase/6/docs/api/java/io/DataOutput.html?is-external=true" title="class or interface in java.io">DataOutput</a>&nbsp;out) throws <a href="http://docs.oracle.com/javase/6/docs/api/java/io/IOException.html?is-external=true" title="class or interface in java.io">IOException</a></pre> <dl> <dt><span class="throwsLabel">Throws:</span></dt> <dd><code><a href="http://docs.oracle.com/javase/6/docs/api/java/io/IOException.html?is-external=true" title="class or interface in java.io">IOException</a></code></dd> </dl> </li> </ul> <a name="readFields-java.io.DataInput-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>readFields</h4> <pre>public&nbsp;void&nbsp;readFields(<a href="http://docs.oracle.com/javase/6/docs/api/java/io/DataInput.html?is-external=true" title="class or interface in java.io">DataInput</a>&nbsp;in) throws <a href="http://docs.oracle.com/javase/6/docs/api/java/io/IOException.html?is-external=true" title="class or interface in java.io">IOException</a></pre> <dl> <dt><span class="throwsLabel">Throws:</span></dt> <dd><code><a href="http://docs.oracle.com/javase/6/docs/api/java/io/IOException.html?is-external=true" title="class or interface in java.io">IOException</a></code></dd> </dl> </li> </ul> <a name="compareTo-java.lang.Object-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>compareTo</h4> <pre>public&nbsp;int&nbsp;compareTo(<a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a>&nbsp;peer_) throws <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/ClassCastException.html?is-external=true" title="class or interface in java.lang">ClassCastException</a></pre> <dl> <dt><span class="throwsLabel">Throws:</span></dt> <dd><code><a href="http://docs.oracle.com/javase/6/docs/api/java/lang/ClassCastException.html?is-external=true" title="class or interface in java.lang">ClassCastException</a></code></dd> </dl> </li> </ul> <a name="equals-java.lang.Object-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>equals</h4> <pre>public&nbsp;boolean&nbsp;equals(<a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a>&nbsp;peer_)</pre> <dl> <dt><span class="overrideSpecifyLabel">Overrides:</span></dt> <dd><code><a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#equals-java.lang.Object-" title="class or interface in java.lang">equals</a></code>&nbsp;in class&nbsp;<code><a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a></code></dd> </dl> </li> </ul> <a name="hashCode--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>hashCode</h4> <pre>public&nbsp;int&nbsp;hashCode()</pre> <dl> <dt><span class="overrideSpecifyLabel">Overrides:</span></dt> <dd><code><a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true#hashCode--" title="class or interface in java.lang">hashCode</a></code>&nbsp;in class&nbsp;<code><a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a></code></dd> </dl> </li> </ul> <a name="signature--"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>signature</h4> <pre>public static&nbsp;<a href="http://docs.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;signature()</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="class-use/Stat.html">Use</a></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/apache/zookeeper/data/Id.html" title="class in org.apache.zookeeper.data"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../org/apache/zookeeper/data/StatPersisted.html" title="class in org.apache.zookeeper.data"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?org/apache/zookeeper/data/Stat.html" target="_top">Frames</a></li> <li><a href="Stat.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>Field&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>Field&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 ======= --> <p class="legalCopy"><small>Copyright &copy; 2016 The Apache Software Foundation</small></p> </body> </html>
{ "content_hash": "420d731741fe2e3bb79d1f17b0ebb156", "timestamp": "", "source": "github", "line_count": 744, "max_line_length": 932, "avg_line_length": 41.70564516129032, "alnum_prop": 0.6569016081729995, "repo_name": "yining0417/zookeeper", "id": "8eaa55606524f2277ff2edeb47fbe9acb0a39899", "size": "31029", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "build/zookeeper/docs/api/org/apache/zookeeper/data/Stat.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "17832" }, { "name": "C", "bytes": "2536896" }, { "name": "C++", "bytes": "3824604" }, { "name": "CSS", "bytes": "123620" }, { "name": "Groff", "bytes": "8962732" }, { "name": "HTML", "bytes": "9117211" }, { "name": "Java", "bytes": "14374935" }, { "name": "JavaScript", "bytes": "1013423" }, { "name": "M4", "bytes": "309820" }, { "name": "Makefile", "bytes": "561108" }, { "name": "Mako", "bytes": "54712" }, { "name": "Perl", "bytes": "907440" }, { "name": "Perl6", "bytes": "288032" }, { "name": "Python", "bytes": "716992" }, { "name": "Shell", "bytes": "1672732" }, { "name": "XS", "bytes": "531976" }, { "name": "XSLT", "bytes": "24096" } ], "symlink_target": "" }
<html> <head> <meta name="viewport" content="width=device-width, initial-scale=1" charset="UTF-8"> <title>render</title> <link href="../../../images/logo-icon.svg" rel="icon" type="image/svg"> <script>var pathToRoot = "../../../";</script> <script type="text/javascript" src="../../../scripts/sourceset_dependencies.js" async="async"></script> <link href="../../../styles/style.css" rel="Stylesheet"> <link href="../../../styles/logo-styles.css" rel="Stylesheet"> <link href="../../../styles/jetbrains-mono.css" rel="Stylesheet"> <link href="../../../styles/main.css" rel="Stylesheet"> <script type="text/javascript" src="../../../scripts/clipboard.js" async="async"></script> <script type="text/javascript" src="../../../scripts/navigation-loader.js" async="async"></script> <script type="text/javascript" src="../../../scripts/platform-content-handler.js" async="async"></script> <script type="text/javascript" src="../../../scripts/main.js" async="async"></script> </head> <body> <div id="container"> <div id="leftColumn"> <div id="logo"></div> <div id="paneSearch"></div> <div id="sideMenu"></div> </div> <div id="main"> <div id="leftToggler"><span class="icon-toggler"></span></div> <script type="text/javascript" src="../../../scripts/pages.js"></script> <script type="text/javascript" src="../../../scripts/main.js"></script> <div class="main-content" id="content" pageIds="org.hexworks.zircon.internal.application/LibgdxGame/render/#/PointingToDeclaration//-488323337"> <div class="navigation-wrapper" id="navigation-wrapper"> <div class="breadcrumbs"><a href="../../index.html">zircon.jvm.libgdx</a>/<a href="../index.html">org.hexworks.zircon.internal.application</a>/<a href="index.html">LibgdxGame</a>/<a href="render.html">render</a></div> <div class="pull-right d-flex"> <div id="searchBar"></div> </div> </div> <div class="cover "> <h1 class="cover"><span>render</span></h1> </div> <div class="divergent-group" data-filterable-current=":zircon.jvm.libgdx:dokkaHtml/main" data-filterable-set=":zircon.jvm.libgdx:dokkaHtml/main"><div class="with-platform-tags"><span class="pull-right"></span></div> <div> <div class="platform-hinted " data-platform-hinted="data-platform-hinted"><div class="content sourceset-depenent-content" data-active="" data-togglable=":zircon.jvm.libgdx:dokkaHtml/main"><div class="symbol monospace">open override fun <a href="render.html">render</a>()<span class="top-right-position"><span class="copy-icon"></span><div class="copy-popup-wrapper popup-to-left"><span class="copy-popup-icon"></span><span>Content copied to clipboard</span></div></span></div></div></div> </div> </div> <h2 class="">Sources</h2> <div class="table" data-togglable="Sources"><a data-name="%5Borg.hexworks.zircon.internal.application%2FLibgdxGame%2Frender%2F%23%2FPointingToDeclaration%2F%5D%2FSource%2F-488323337" anchor-label="https://github.com/Hexworks/zircon/tree/master/zircon.jvm.libgdx/src/main/kotlin/org/hexworks/zircon/internal/application/LibgdxGame.kt#L49" id="%5Borg.hexworks.zircon.internal.application%2FLibgdxGame%2Frender%2F%23%2FPointingToDeclaration%2F%5D%2FSource%2F-488323337" data-filterable-set=":zircon.jvm.libgdx:dokkaHtml/main"></a> <div class="table-row" data-filterable-current=":zircon.jvm.libgdx:dokkaHtml/main" data-filterable-set=":zircon.jvm.libgdx:dokkaHtml/main"> <div class="main-subrow keyValue "> <div class=""><span class="inline-flex"><a href="https://github.com/Hexworks/zircon/tree/master/zircon.jvm.libgdx/src/main/kotlin/org/hexworks/zircon/internal/application/LibgdxGame.kt#L49">(source)</a><span class="anchor-wrapper"><span class="anchor-icon" pointing-to="%5Borg.hexworks.zircon.internal.application%2FLibgdxGame%2Frender%2F%23%2FPointingToDeclaration%2F%5D%2FSource%2F-488323337"></span> <div class="copy-popup-wrapper "><span class="copy-popup-icon"></span><span>Link copied to clipboard</span></div> </span></span></div> <div></div> </div> </div> </div> </div> <div class="footer"><span class="go-to-top-icon"><a href="#content"></a></span><span>© 2020 Copyright</span><span class="pull-right"><span>Sponsored and developed by dokka</span><a href="https://github.com/Kotlin/dokka"><span class="padded-icon"></span></a></span></div> </div> </div> </body> </html>
{ "content_hash": "53180b12b468e0ee6d3567dac0f2975e", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 537, "avg_line_length": 76.44262295081967, "alnum_prop": 0.6487239974265494, "repo_name": "Hexworks/zircon", "id": "500dcaadccd999704ca76c9f857d577186671aca", "size": "4664", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/2020.2.0-RELEASE-KOTLIN/zircon.jvm.libgdx/zircon.jvm.libgdx/org.hexworks.zircon.internal.application/-libgdx-game/render.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "121457" }, { "name": "Kotlin", "bytes": "1792092" }, { "name": "Shell", "bytes": "152" } ], "symlink_target": "" }
project_path: /web/tools/chrome-devtools/_project.yaml book_path: /web/tools/chrome-devtools/_book.yaml description: If you find yourself typing the same JavaScript expressions into the Console repeatedly, try Live Expressions instead. {# wf_updated_on: 2020-07-10 #} {# wf_published_on: 2019-04-18 #} {# wf_blink_components: Platform>DevTools #} # Watch JavaScript Expression Values In Real-Time With Live Expressions {: .page-title } {% include "web/_shared/contributors/kaycebasques.html" %} If you find yourself typing the same JavaScript expression in the Console repeatedly, you might find it easier to create a **Live Expression**. With **Live Expressions** you type an expression once and then pin it to the top of your Console. The value of the expression updates in near real-time. ## Create a Live Expression {: #create } [icon]: /web/tools/chrome-devtools/console/images/createliveexpression.png 1. [Open the Console](/web/tools/chrome-devtools/console/reference#open). 1. Click **Create Live Expression** ![Create Live Expression][icon]{: .inline-icon }. The **Live Expression** text box appears. <figure> <img src="/web/tools/chrome-devtools/console/images/liveexpressiontextbox.png" alt="Typing document.activeElement into the Live Expression text box."/> <figcaption> <b>Figure 1</b> Typing <code>document.activeElement</code> into the <b>Live Expression</b> text box. </figcaption> </figure> 1. Type <kbd>Control</kbd>+<kbd>Enter</kbd> or <kbd>Command</kbd>+<kbd>Enter</kbd> (Mac) to save the expression, or click outside of the **Live Expression** text box. ## Feedback {: #feedback } {% include "web/_shared/helpful.html" %}
{ "content_hash": "21e640b4261f8405703b8cd25e514a98", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 131, "avg_line_length": 45.078947368421055, "alnum_prop": 0.723292469352014, "repo_name": "myakura/WebFundamentals", "id": "9a47b5c82180bbfd81129ae01d2f1ee21c25f365", "size": "1713", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/content/en/tools/chrome-devtools/console/live-expressions.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "35431" }, { "name": "HTML", "bytes": "4129367" }, { "name": "JavaScript", "bytes": "273072" }, { "name": "Python", "bytes": "256072" }, { "name": "Shell", "bytes": "5080" }, { "name": "Smarty", "bytes": "3872" } ], "symlink_target": "" }
require 'shellwords' # These should probably be deleted when the old templates are removed. # They are only used here. default["bcpc"]["hadoop"]["mapreduce"]["map"]["output"]["compress"] = true default["bcpc"]["hadoop"]["mapred"]["map"]["output"]["compress"]["codec"] = "org.apache.hadoop.io.compress.SnappyCodec" default["bcpc"]["hadoop"]["yarn"]["app"]["mapreduce"]["am"]["log"]["level"] = "DEBUG" default["bcpc"]["hadoop"]["yarn"]["app"]["mapreduce"]["am"]["staging-dir"] = "/user" default[:bcpc][:hadoop][:mapreduce][:site_xml].tap do |site_xml| site_xml['mapreduce.admin.map.child.java.opts'] = '-server -Djava.net.preferIPv4Stack=true -Dhdp.version=' + node[:bcpc][:hadoop][:distribution][:release].to_s hdp_path = File.join('/usr/hdp', node[:bcpc][:hadoop][:distribution][:active_release]) hdp_apps_path = File.join('/hdp/apps', node[:bcpc][:hadoop][:distribution][:active_release]) site_xml['mapreduce.admin.user.env'] = 'LD_LIBRARY_PATH=' + [ File.join(hdp_path, 'hadoop', 'lib', 'native'), File.join(hdp_path, 'hadoop', 'lib', 'native', 'Linux-amd64-64'), ].map{ |s| s.shellescape }.join(':') site_xml['mapreduce.framework.name'] = node["bcpc"]["hadoop"]["mapreduce"]["framework"]["name"] site_xml['mapreduce.application.classpath'] = [ '$PWD/mr-framework/hadoop/share/hadoop/mapreduce/*', '$PWD/mr-framework/hadoop/share/hadoop/mapreduce/lib/*', '$PWD/mr-framework/hadoop/share/hadoop/common/*', '$PWD/mr-framework/hadoop/share/hadoop/common/lib/*', '$PWD/mr-framework/hadoop/share/hadoop/yarn/*', '$PWD/mr-framework/hadoop/share/hadoop/yarn/lib/*', '$PWD/mr-framework/hadoop/share/hadoop/hdfs/*', '$PWD/mr-framework/hadoop/share/hadoop/hdfs/lib/*', "#{hdp_path}/hadoop/lib/hadoop-lzo-0.6.0." + "#{node[:bcpc][:hadoop][:distribution][:active_release]}.jar", '$HADOOP_CONF_DIR', ].join(',') site_xml['mapreduce.application.framework.path'] = File.join(hdp_apps_path, 'mapreduce', 'mapreduce.tar.gz#mr-framework') site_xml['mapreduce.map.output.compress'] = true site_xml['mapred.map.output.compress.codec'] = "org.apache.hadoop.io.compress.SnappyCodec" site_xml['yarn.app.mapreduce.am.log.level'] = node["bcpc"]["hadoop"]["yarn"]["app"]["mapreduce"]["am"]["log"]["level"] site_xml['yarn.app.mapreduce.am.staging-dir'] = node["bcpc"]["hadoop"]["yarn"]["app"]["mapreduce"]["am"]["staging-dir"] site_xml['mapreduce.job.acl-view-job'] = '*' site_xml['mapreduce.cluster.acls.enabled'] = true end
{ "content_hash": "3dd279b379732aa414abdca5e19fe6b5", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 119, "avg_line_length": 40.515625, "alnum_prop": 0.6374855379868878, "repo_name": "cbaenziger/chef-bach", "id": "c0f187489c9538bd307ae8690a5de0dae2396e8a", "size": "2593", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "cookbooks/bcpc-hadoop/attributes/mapred.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "285421" }, { "name": "Python", "bytes": "12012" }, { "name": "Ruby", "bytes": "839039" }, { "name": "Shell", "bytes": "151919" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ClipM { public partial class ConfigForm : Form { public ConfigForm() { InitializeComponent(); } } }
{ "content_hash": "7dd31e5f91e07f75c51431b886b7535e", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 42, "avg_line_length": 18.7, "alnum_prop": 0.6871657754010695, "repo_name": "kixx/clipm", "id": "9b794a24a35f6bc8e701d122e07267272c330ef2", "size": "376", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ClipM/ConfigForm.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "22542" } ], "symlink_target": "" }
import { Injectable } from "@angular/core"; import { select, Store } from "@ngrx/store"; import { Observable } from "rxjs"; import { getWatchTime, LazyTestStateSlice, IncrementSecondsAction } from "./lazy-test.store"; @Injectable() export class LazyTestService { watchTime: Observable<number>; constructor(private store: Store<LazyTestStateSlice>) { this.watchTime = this.store.pipe(select(getWatchTime)); } updateSeconds() { this.store.dispatch(new IncrementSecondsAction()); } }
{ "content_hash": "7cd5ebcf032a52942c2042a560460643", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 59, "avg_line_length": 23.136363636363637, "alnum_prop": 0.7190569744597249, "repo_name": "DorianGrey/ng-webpack-template", "id": "9e0398a032ca9040904ec0b1347ddaca569cefbb", "size": "509", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/app/+lazy-test/lazy-test.service.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4082" }, { "name": "HTML", "bytes": "4282" }, { "name": "JavaScript", "bytes": "89899" }, { "name": "TypeScript", "bytes": "44835" } ], "symlink_target": "" }
import copy import xmlrpc.client as xmlrpc from .errors import SAMPHubError from .utils import ServerProxyPool from .lockfile_helpers import get_main_running_hub __all__ = ['SAMPHubProxy'] class SAMPHubProxy: """ Proxy class to simplify the client interaction with a SAMP hub (via the standard profile). """ def __init__(self): self.proxy = None self._connected = False @property def is_connected(self): """ Whether the hub proxy is currently connected to a hub. """ return self._connected def connect(self, hub=None, hub_params=None, pool_size=20): """ Connect to the current SAMP Hub. Parameters ---------- hub : `~astropy.samp.SAMPHubServer`, optional The hub to connect to. hub_params : dict, optional Optional dictionary containing the lock-file content of the Hub with which to connect. This dictionary has the form ``{<token-name>: <token-string>, ...}``. pool_size : int, optional The number of socket connections opened to communicate with the Hub. """ self._connected = False self.lockfile = {} if hub is not None and hub_params is not None: raise ValueError("Cannot specify both hub and hub_params") if hub_params is None: if hub is not None: if not hub.is_running: raise SAMPHubError("Hub is not running") else: hub_params = hub.params else: hub_params = get_main_running_hub() try: url = hub_params["samp.hub.xmlrpc.url"].replace("\\", "") self.proxy = ServerProxyPool(pool_size, xmlrpc.ServerProxy, url, allow_none=1) self.ping() self.lockfile = copy.deepcopy(hub_params) self._connected = True except xmlrpc.ProtocolError as p: # 401 Unauthorized if p.errcode == 401: raise SAMPHubError("Unauthorized access. Basic Authentication " "required or failed.") else: raise SAMPHubError(f"Protocol Error {p.errcode}: {p.errmsg}") def disconnect(self): """ Disconnect from the current SAMP Hub. """ self.proxy = None self._connected = False self.lockfile = {} def server_close(self): self.proxy.server_close() @property def _samp_hub(self): """ Property to abstract away the path to the hub, which allows this class to be used for other profiles. """ return self.proxy.samp.hub def ping(self): """ Proxy to ``ping`` SAMP Hub method (Standard Profile only). """ return self._samp_hub.ping() def set_xmlrpc_callback(self, private_key, xmlrpc_addr): """ Proxy to ``setXmlrpcCallback`` SAMP Hub method (Standard Profile only). """ return self._samp_hub.setXmlrpcCallback(private_key, xmlrpc_addr) def register(self, secret): """ Proxy to ``register`` SAMP Hub method. """ return self._samp_hub.register(secret) def unregister(self, private_key): """ Proxy to ``unregister`` SAMP Hub method. """ return self._samp_hub.unregister(private_key) def declare_metadata(self, private_key, metadata): """ Proxy to ``declareMetadata`` SAMP Hub method. """ return self._samp_hub.declareMetadata(private_key, metadata) def get_metadata(self, private_key, client_id): """ Proxy to ``getMetadata`` SAMP Hub method. """ return self._samp_hub.getMetadata(private_key, client_id) def declare_subscriptions(self, private_key, subscriptions): """ Proxy to ``declareSubscriptions`` SAMP Hub method. """ return self._samp_hub.declareSubscriptions(private_key, subscriptions) def get_subscriptions(self, private_key, client_id): """ Proxy to ``getSubscriptions`` SAMP Hub method. """ return self._samp_hub.getSubscriptions(private_key, client_id) def get_registered_clients(self, private_key): """ Proxy to ``getRegisteredClients`` SAMP Hub method. """ return self._samp_hub.getRegisteredClients(private_key) def get_subscribed_clients(self, private_key, mtype): """ Proxy to ``getSubscribedClients`` SAMP Hub method. """ return self._samp_hub.getSubscribedClients(private_key, mtype) def notify(self, private_key, recipient_id, message): """ Proxy to ``notify`` SAMP Hub method. """ return self._samp_hub.notify(private_key, recipient_id, message) def notify_all(self, private_key, message): """ Proxy to ``notifyAll`` SAMP Hub method. """ return self._samp_hub.notifyAll(private_key, message) def call(self, private_key, recipient_id, msg_tag, message): """ Proxy to ``call`` SAMP Hub method. """ return self._samp_hub.call(private_key, recipient_id, msg_tag, message) def call_all(self, private_key, msg_tag, message): """ Proxy to ``callAll`` SAMP Hub method. """ return self._samp_hub.callAll(private_key, msg_tag, message) def call_and_wait(self, private_key, recipient_id, message, timeout): """ Proxy to ``callAndWait`` SAMP Hub method. """ return self._samp_hub.callAndWait(private_key, recipient_id, message, timeout) def reply(self, private_key, msg_id, response): """ Proxy to ``reply`` SAMP Hub method. """ return self._samp_hub.reply(private_key, msg_id, response)
{ "content_hash": "ed7fd7daf93bb64d77774f55b1b5b720", "timestamp": "", "source": "github", "line_count": 198, "max_line_length": 79, "avg_line_length": 30.414141414141415, "alnum_prop": 0.5705745599468615, "repo_name": "dhomeier/astropy", "id": "f6d9f8a82f03d651897e9f6c07f704961cfc806b", "size": "6088", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "astropy/samp/hub_proxy.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "10891881" }, { "name": "C++", "bytes": "55147" }, { "name": "HTML", "bytes": "1172" }, { "name": "Lex", "bytes": "181654" }, { "name": "M4", "bytes": "18016" }, { "name": "Makefile", "bytes": "51059" }, { "name": "Python", "bytes": "10582251" }, { "name": "Shell", "bytes": "17024" }, { "name": "TeX", "bytes": "853" } ], "symlink_target": "" }
'use strict'; // ##Dependencias do módulo var config = global.config, lodash = require('lodash'), multiparty = require('connect-multiparty'), compression = require('compression'), morgan = require('morgan'), body_parser = require('body-parser'), method_override = require('method-override'), cookie_parser = require('cookie-parser'), cookie_session = require('cookie-session'), flash = require('connect-flash'), ejs = require('ejs'), ejs_layouts = require('express-ejs-layouts'), helpers = require(config.paths.helpers + 'loader.js'), router = require(config.paths.components + 'router.js'), i18n = require(config.paths.components + 'i18n.js'), auth = require(config.paths.components + 'auth.js'), serve_static = require('serve-static'), serve_favicon = require('serve-favicon'); // ##Configuración module.exports = function(app) { // Configuramos o servidor para que mostre o stack en caso de error app.set('showStackError', true); // Configuramos o porto app.set('port', config.port); // Prettify HTML. app.locals.pretty = true; // Configuramos express para que comprima os arquivos antes // de envialos ó cliente. app.use(compression({ // Filtramos só os arquivos que queremos que se compriman. filter: function() { return (/json|text|javascript|css/).text; }, // Sinalamos o nivel de comprensión que se aplicará ó recursos // do 0 o 10, de menor a maior. level: 9 })); // Buscamos recursos státicos que podan responder a consulta e se non cargamos // o necesario para tratar de responder a consulta app.use(serve_favicon(config.paths.webroot + '/favicon.ico')); app.use(serve_static(config.paths.webroot)); // Configuramos o directorio das vistas e o motor de plantilla que vamos a utilizar. app.set('views', config.paths.root + '/app/views'); app.engine('ejs', ejs.renderFile); app.set('view engine', 'ejs'); app.set('layout', 'template'); app.use(ejs_layouts); // ##Configuramos os middlewares dos que vai a facer uso o servidor. // CookieParser para manexar as cookies dunha forma máis sinxela. app.use(cookie_parser()); // Os encargados de recoller información enviada mediante POST, PUT... app.use(body_parser.json()); app.use(body_parser.urlencoded({extended: false})); // Activamos a opción de recoller arquivos enviados dende formularios // é decir datos enviados mediante enctype multipart/form-data. app.use(multiparty()); // MethodOverride é realmente útil para enviar datos mediante métodos non soportados // polo navegador como PUT, DELETE... simplemente engadindo ?_method=PUT a URL. app.use(method_override()); // Activamos o almacenamento de sesions na base de datos. app.use(cookie_session({ secret: config.sessions.secret, name: config.sessions.name })); // Activamos o uso de mensaxes "flash" para notificacións app.use(flash()); app.use(function(req, res, next) { res.locals.flash = req.flash(); next(); }); // Engadimos a consulta á resposta para poder acceder a ela dende as vistas ou controladores. app.use(function(req, res, next) { res.locals.req = req; next(); }); // Engadimos lodash ós locals para acceder a el dende as vistas app.use(function(req, res, next) { res.locals._ = lodash; next(); }); // Helpers, os axudantes que utilizaremos para a xeneración de vistas e máis cousas. app.use(helpers()); // Sistema de internacionalización app.use(i18n.init()); // Sistema de autenticación app.use(auth.init()); // Lanzamos o enrutador para redireccionar cada consulta o controlador correspondente app.use(router.init(app)); // Se estamos en entorno de desenrolo activamos o logger para ver // as consultas que se fan en cada momento. if (process.env.NODE_ENV === 'development') { app.use(morgan('dev')); } };
{ "content_hash": "07590ea43be2aff9682b34dc39dee9a1", "timestamp": "", "source": "github", "line_count": 116, "max_line_length": 97, "avg_line_length": 35.224137931034484, "alnum_prop": 0.6573666177190406, "repo_name": "freckless/renting.js", "id": "df7cd6b3481448019870b5e66aac348bbdd7143c", "size": "4251", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "config/express.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "74245" }, { "name": "JavaScript", "bytes": "154195" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Trionic5Tools { /// <summary> /// Holds information about the status of the fuel maps while autotuning /// </summary> public class FuelMapInformation { private FuelMap m_OriginalFuelMap = new FuelMap(); private FuelMap m_AlteredFuelMap = new FuelMap(); private FuelMap m_ChangesFuelMap = new FuelMap(); private FuelMap m_DifferenceFuelMap = new FuelMap(); private double[] m_differenceMapInPercentages = new double[16 * 16]; private IdleFuelMap m_IdleOriginalFuelMap = new IdleFuelMap(); private IdleFuelMap m_IdleAlteredFuelMap = new IdleFuelMap(); private IdleFuelMap m_IdleChangesFuelMap = new IdleFuelMap(); private IdleFuelMap m_IdleDifferenceFuelMap = new IdleFuelMap(); private double[] m_IdledifferenceMapInPercentages = new double[12 * 8]; /// <summary> /// Gets the percentual differences for each cell in the fuelmap after running autotune /// </summary> /// <returns></returns> public double[] GetDifferencesInPercentages() { // fill the array for (int i = 0; i < (16 * 16); i++) { double diff = Convert.ToInt32(m_AlteredFuelMap.GetByteAtPosition(i)) - Convert.ToInt32(m_OriginalFuelMap.GetByteAtPosition(i)); double original = Convert.ToInt32(m_OriginalFuelMap.GetByteAtPosition(i)); m_differenceMapInPercentages[i] = (diff * 100)/ original; if (m_differenceMapInPercentages[i] == Double.NaN) m_differenceMapInPercentages[i] = 0; } return m_differenceMapInPercentages; } /// <summary> /// Gets the percentual differences for each cell in the IDLE fuelmap after running autotune /// </summary> /// <returns></returns> public double[] GetIdleDifferencesInPercentages() { // fill the array for (int i = 0; i < (12 * 8); i++) { double diff = Convert.ToInt32(m_IdleAlteredFuelMap.GetByteAtPosition(i)) - Convert.ToInt32(m_IdleOriginalFuelMap.GetByteAtPosition(i)); double original = Convert.ToInt32(m_IdleOriginalFuelMap.GetByteAtPosition(i)); m_IdledifferenceMapInPercentages[i] = (diff * 100) / original; if (m_IdledifferenceMapInPercentages[i] == Double.NaN) m_IdledifferenceMapInPercentages[i] = 0; } return m_IdledifferenceMapInPercentages; } /// <summary> /// Sets the initial fuel map information. Should be called before starting autotune /// </summary> /// <param name="map"></param> public void SetOriginalFuelMap(byte[] map) { m_OriginalFuelMap.FuelMapData = map; m_AlteredFuelMap.FuelMapData = map; m_ChangesFuelMap.Initialize(); m_DifferenceFuelMap.Initialize(); } /// <summary> /// Sets the initial IDLE fuel map information. Should be called before starting autotune /// </summary> /// <param name="map"></param> public void SetIdleOriginalFuelMap(byte[] map) { m_IdleOriginalFuelMap.IdleFuelMapData = map; m_IdleAlteredFuelMap.IdleFuelMapData = map; m_IdleChangesFuelMap.Initialize(); m_IdleDifferenceFuelMap.Initialize(); } public byte[] GetOriginalFuelMap() { return m_OriginalFuelMap.FuelMapData; } public byte[] GetIdleOriginalFuelMap() { return m_IdleOriginalFuelMap.IdleFuelMapData; } /// <summary> /// Updates the altered fuelmap and the changes table while running autotune /// </summary> /// <param name="x_index"></param> /// <param name="y_index"></param> /// <param name="offset"></param> /// <returns></returns> public bool UpdateFuelMap(int x_index, int y_index, int offset) { // offset is the REAL new value for the fuelmap bool retval = false; // first check if the fuelmap has not been changed yet at that point int numberOfMeasurements = m_ChangesFuelMap.GetByteAtXY(x_index, y_index); if (numberOfMeasurements < 255) // max 255 measurements { // set the altered fuel map at this position with offset given byte originalValue = m_OriginalFuelMap.GetByteAtXY(x_index, y_index); //Console.WriteLine("Update fuelmap: " + originalValue.ToString("D3") + " to " + offset.ToString("D3")); // calculate new average value int newAverage = m_AlteredFuelMap.GetByteAtXY(x_index, y_index); newAverage *= numberOfMeasurements; newAverage += offset; newAverage /= (numberOfMeasurements + 1); m_AlteredFuelMap.SetByteXY(x_index, y_index, /*Convert.ToByte(offset)*/ Convert.ToByte(newAverage)); numberOfMeasurements++; m_ChangesFuelMap.SetByteXY(x_index, y_index, Convert.ToByte(numberOfMeasurements)); byte newvalue = Convert.ToByte(/*offset*/ newAverage); newvalue -= originalValue; m_DifferenceFuelMap.SetByteXY(x_index, y_index, newvalue); retval = true; } return retval; } /// <summary> /// Updates the altered IDLE fuelmap and the changes table while running autotune /// </summary> /// <param name="x_index"></param> /// <param name="y_index"></param> /// <param name="offset"></param> /// <returns></returns> public bool UpdateIdleFuelMap(int x_index, int y_index, int offset) { // offset is the REAL new value for the idle fuelmap bool retval = false; // first check if the fuelmap has not been changed yet at that point int numberOfMeasurements = m_IdleChangesFuelMap.GetByteAtXY(x_index, y_index); if (numberOfMeasurements < 255) // max 255 measurements { // set the altered fuel map at this position with offset given byte originalValue = m_IdleOriginalFuelMap.GetByteAtXY(x_index, y_index); //Console.WriteLine("Update fuelmap: " + originalValue.ToString("D3") + " to " + offset.ToString("D3")); // calculate new average value int newAverage = m_IdleAlteredFuelMap.GetByteAtXY(x_index, y_index); newAverage *= numberOfMeasurements; newAverage += offset; newAverage /= (numberOfMeasurements + 1); m_IdleAlteredFuelMap.SetByteXY(x_index, y_index, /*Convert.ToByte(offset)*/ Convert.ToByte(newAverage)); numberOfMeasurements++; m_IdleChangesFuelMap.SetByteXY(x_index, y_index, Convert.ToByte(numberOfMeasurements)); byte newvalue = Convert.ToByte(/*offset*/ newAverage); newvalue -= originalValue; m_IdleDifferenceFuelMap.SetByteXY(x_index, y_index, newvalue); retval = true; } return retval; } } }
{ "content_hash": "cd39258595682eb6a5e89777d9678e26", "timestamp": "", "source": "github", "line_count": 176, "max_line_length": 151, "avg_line_length": 42.41477272727273, "alnum_prop": 0.5914266577361018, "repo_name": "Just4pLeisure/T5SuiteII", "id": "771569aead5527d89be04a7cb89e921442bd6798", "size": "7467", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Trionic5Tools/FuelMapInformation.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2326" }, { "name": "C", "bytes": "22421" }, { "name": "C#", "bytes": "6474454" }, { "name": "Smalltalk", "bytes": "372674" }, { "name": "Stata", "bytes": "5642" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>ieee754: 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.8.1 / ieee754 - 8.10.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> ieee754 <small> 8.10.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-09-18 16:51:43 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-09-18 16:51:43 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 2 Virtual package relying on perl coq 8.8.1 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.07.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.07.1 Official release 4.07.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.5 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/ieee754&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/IEEE754&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.10&quot; &amp; &lt; &quot;8.11~&quot;} ] tags: [ &quot;keyword: floating-point arithmetic&quot; &quot;keyword: IEEE&quot; &quot;category: Computer Science/Data Types and Data Structures&quot; &quot;category: Computer Science/Semantics and Compilation/Semantics&quot; &quot;date: 1997&quot; ] authors: [ &quot;Patrick Loiseleur&quot; ] bug-reports: &quot;https://github.com/coq-contribs/ieee754/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/ieee754.git&quot; synopsis: &quot;A formalisation of the IEEE754 norm on floating-point arithmetic&quot; description: &quot;&quot;&quot; This library contains a non-verified implementation of binary floating-point addition and multiplication operators inspired by the IEEE-754 standard. It is today outdated. See the attached 1997 report rapport-stage-dea.ps.gz for a discussion (in French) of this work. For the state of the art at the time of updating this notice, see e.g. &quot;Flocq: A Unified Library for Proving Floating-point Algorithms in Coq&quot; by S. Boldo and G. Melquiond, 2011.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/ieee754/archive/v8.10.0.tar.gz&quot; checksum: &quot;md5=dca74fbeedf9b4e624fa425643bcbeb8&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-ieee754.8.10.0 coq.8.8.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.8.1). The following dependencies couldn&#39;t be met: - coq-ieee754 -&gt; coq &gt;= 8.10 -&gt; ocaml &gt;= 4.09.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints 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-ieee754.8.10.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": "e34ce32529ddc47cb74223d7c967d8fb", "timestamp": "", "source": "github", "line_count": 180, "max_line_length": 159, "avg_line_length": 41.12777777777778, "alnum_prop": 0.5569363771444009, "repo_name": "coq-bench/coq-bench.github.io", "id": "81c27bee4c5a0e9684897c90ccfa6701127b460b", "size": "7428", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.07.1-2.0.6/released/8.8.1/ieee754/8.10.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
jui.define("chart.brush.rangebar", [], function() { /** * @class chart.brush.rangebar * @extends chart.brush.core */ var RangeBarBrush = function(chart, axis, brush) { var g, height, half_height, barHeight; var outerPadding, innerPadding; var borderColor, borderWidth, borderOpacity; this.drawBefore = function() { g = chart.svg.group(); outerPadding = brush.outerPadding; innerPadding = brush.innerPadding; height = axis.y.rangeBand(); half_height = height - (outerPadding * 2); barHeight = (half_height - (brush.target.length - 1) * innerPadding) / brush.target.length; borderColor = chart.theme("barBorderColor"); borderWidth = chart.theme("barBorderWidth"); borderOpacity = chart.theme("barBorderOpacity"); } this.draw = function() { this.eachData(function(i, data) { var group = chart.svg.group(), startY = this.offset("y", i) - (half_height / 2); for(var j = 0; j < brush.target.length; j++) { var value = data[brush.target[j]], startX = axis.x(value[1]), zeroX = axis.x(value[0]); var r = chart.svg.rect({ x : zeroX, y : startY, height : barHeight, width : Math.abs(zeroX - startX), fill : this.color(j), stroke : borderColor, "stroke-width" : borderWidth, "stroke-opacity" : borderOpacity }); this.addEvent(r, i, j); group.append(r); startY += barHeight + innerPadding; } g.append(group); }); return g; } } RangeBarBrush.setup = function() { return { /** @cfg {Number} [outerPadding=2] Determines the outer margin of a bar. */ outerPadding: 2, /** @cfg {Number} [innerPadding=1] Determines the inner margin of a bar. */ innerPadding: 1 }; } return RangeBarBrush; }, "chart.brush.core");
{ "content_hash": "22cb4b54759d3bf4d11839a52399dc59", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 94, "avg_line_length": 26.619718309859156, "alnum_prop": 0.5915343915343916, "repo_name": "nizbridge/nizbridge.github.io", "id": "e8e7590f475ea8e8ea82193d6833c93e2e24532c", "size": "1890", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "project/bonereport/js/chart/brush/rangebar.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "99421" }, { "name": "HTML", "bytes": "62104" }, { "name": "JavaScript", "bytes": "1000556" }, { "name": "Ruby", "bytes": "72" }, { "name": "SCSS", "bytes": "10563" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Omphalopsis bakeri Murrill ### Remarks null
{ "content_hash": "d537722dee58795b0a6363dfbfc87c0a", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 26, "avg_line_length": 10.076923076923077, "alnum_prop": 0.7175572519083969, "repo_name": "mdoering/backbone", "id": "de9b21b24dfd7a2538c0925bf2a5ca2d163d0903", "size": "181", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Mycenaceae/Omphalopsis/Omphalopsis bakeri/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
window.cls = window.cls || {}; cls.CSSTokenizer = function() { const CR = "\r"; const LF = "\n"; const BS = "\\"; const OP_BRACKET = "{"; const CL_BRACKET = "}" ; const _escapes_re = /\\[0-9a-f]{1,6}/i; this._EOL_buffer = ""; this._buffer = ""; this._current_pos = 0; this._escape_sequence = ""; this.ontoken = function(){}; this._token_type = cls.CSSTokenizer.types.WHITESPACE; this._token_buffer = ""; this._sq_brackets = []; this._state_handler = {}; this._state_cache = []; this._quote_literal = ""; this.normalize_token = function(token) { // check dom.js and helpers.js for trim. // There are some inherent limitations in fromCharCode wrt // multibyte sequences, but this should work for all CSS keywords. return token.replace(_escapes_re, function(s,p1,p2){ return String.fromCharCode(parseInt(p1,16)) }); } this.tokenize = function(input_buffer, ontoken) { this._state_handler = this._state_handlers.BEFORE_RULE; this._buffer = input_buffer; this._emitToken = ontoken; while ( this._state_handler !== this._state_handlers.EOF) { this._state_handler.apply(this); } this._state_handlers.EOF.apply(this); }; this._init_state = function() { this._handle_escape_status(); if (this._is_EOF()) { return true; } if (this._is_EOL()) { return true; } if (this._is_string()) { return true; } if (this._is_comment()) { return true; } return false; }; this._handle_escape_status = function() { var c = this._buffer.charAt(this._current_pos); // if the current character is \, begin new escape sequence, unless // it is a literal if (c === "\\") { if (this._escape_sequence === "\\") { this._escape_sequence = ""; return; } this._escape_sequence = c; return; } if (c in this._WHITESPACE) { this._escape_sequence = ""; return; }; if (c in this._EOL_CHARS) { return; }; if ( (c in this._HEX_NUMBERS) && (this._escape_sequence.length) && (this._escape_sequence.length < 7) ) { this._escape_sequence += c; return; } this._escape_sequence = ""; return; }; this._is_string = function() { var c = this._buffer.charAt(this._current_pos); if (c in this._QUOTES) { this._state_cache.unshift(this._state_handler); this._quote_literal = c; this._state_handler = this._state_handlers.QUOTED_STRING; this._token_buffer+=c; this._current_pos++; return true; } return false; } this._is_comment = function() { var c = this._buffer.charAt(this._current_pos); if (this._quote_literal) { return false; } if ((c === "/")) { var c2 = this._buffer.charAt(this._current_pos+1); if (c2 && (c2 === "*")) { this._state_cache.unshift(this._state_handler) this._current_pos+=2; this._emitToken(this._token_type,this._token_buffer); this._token_buffer = "/*" this._state_handler = this._state_handlers.COMMENT; return true; } } return false; } this._is_EOF = function() { if (this._current_pos >= this._buffer.length) { this._state_handler = this._state_handlers.EOF; return true; } return false; } this._is_EOL = function() { var c = this._buffer.charAt(this._current_pos); if (c === CR || c === LF) { this._state_cache.unshift(this._state_handler); this._state_handler = this._state_handlers.EOL; return true; } return false; } this._WHITESPACE = { ' ': 1, '\t': 1, }; this._HEX_NUMBERS = { '1' : 1, '2' : 1, '3' : 1, '4' : 1, '5' : 1, '6' : 1, '7' : 1, '8' : 1, '9' : 1, '0' : 1, 'a' : 1, 'b' : 1, 'c' : 1, 'd' : 1, 'e' : 1, 'f' : 1, 'A' : 1, 'B' : 1, 'C' : 1, 'D' : 1, 'E' : 1, 'F' : 1 }; this._QUOTES = { '"': 1, '\'': 1 }; this._EOL_CHARS = { '\n': 1, '\r': 1 } this._PUNCTUATION = { '.': 1, ',': 1, ';': 1, ':': 1, } this._BRACES = { '(': 1, ')': 1, '{': 1, '}': 1, } this._state_handlers = { EOF: function(){ // Currently, this doesn't try to balance output braces, brackets and strings this._emitToken(this._token_type, this._token_buffer) this._emitToken(999,"") return false; }, EOL: function() { this._handle_escape_status(); // First invocation, guarantees that we // leave this state with empty token buffer var c = this._buffer.charAt(this._current_pos); if (this._token_buffer.length) { this._emitToken(this._token_type,this._token_buffer) this._token_buffer = ""; } if (c === CR) { // If in quote context && no escape, close quote // otherwise, keep open // current token type is kept, but if unmatched quote, emit_with_error // if next == LF emit CRLF token, advance cursor by two // else emit CR, advance cursor this._EOL_buffer += "\r"; this._current_pos++; if (!this._is_EOF()) { if (this._buffer.charAt(this._current_pos) == LF) { this._EOL_buffer += LF; this._current_pos++; } } this._emitToken(cls.CSSTokenizer.types.EOL_DATA, this._EOL_buffer); this._EOL_buffer = ""; this._state_handler = this._state_cache.shift(); return false; } // At this stage, we only have LF this._EOL_buffer += LF; this._current_pos++; // Bad lineshift, next line is garbage if ((!this._escape_sequence) && (this._quote_literal)) { this._quote_literal=""; this._state_cache.shift(); // Throw away the string handler } this._emitToken(cls.CSSTokenizer.types.EOL_DATA,LF); this._EOL_buffer = ""; // Switch to whatever state we were in prior to EOL this._state_handler = this._state_cache.shift(); return false; }, COMMENT: function() { this._token_type = cls.CSSTokenizer.types.COMMENT; if (this._is_EOF()) { return false; } if (this._is_EOL()) { return false; } var c = this._buffer.charAt(this._current_pos++) if (c === "*") { if (this._buffer.charAt(this._current_pos) == "/") { this._current_pos++; this._token_buffer+="*/"; this._emitToken(this._token_type,this._token_buffer); this._token_buffer = ""; this._state_handler = this._state_cache.shift(); return false; } } this._token_buffer += c; return false; }, BEFORE_RULE: function() { this._token_type = cls.CSSTokenizer.types.WHITESPACE; if (this._init_state()) { return false; } var c = this._buffer.charAt(this._current_pos++) if (c in this._WHITESPACE) { this._token_buffer += c; return false; } // Leaving state, emit whatever we now have as selector, even if it's just whitespace this._emitToken(this._token_type, this._token_buffer); this._token_buffer = c; if (c === "@") { this._state_handler = this._state_handlers.BEFORE_AT_RULE; return false; } if (c === "{") { this._state_handler = this._state_handlers.PROPERTY; this._emitToken(cls.CSSTokenizer.types.DECLARATION_BLOCK_START, "{"); this._token_buffer = ""; return false; } this._state_handler = this._state_handlers.SELECTOR; return false; }, SELECTOR: function() { this._token_type = cls.CSSTokenizer.types.SELECTOR; if (this._init_state()) { return false; } var c = this._buffer.charAt(this._current_pos++); if (c === "{") { this._emitToken(this._token_type ,this._token_buffer) this._state_handler = this._state_handlers.BEFORE_PROPERTY; this._emitToken(cls.CSSTokenizer.types.DECLARATION_BLOCK_START, "{"); this._token_buffer = ""; return false; } this._token_buffer+=c; return false; }, BEFORE_PROPERTY: function() { if (this._init_state()) { return false; } var c = this._buffer.charAt(this._current_pos++); if (c in this._WHITESPACE) { this._token_buffer += c; return false; } if (c === ";") { this._emitToken(cls.CSSTokenizer.types.DECLARATION_TERMINATOR, c) this._token_buffer = ""; return false; } if (c === ":") { this._emitToken(cls.CSSTokenizer.types.PROPERTY_SEPARATOR,c); this._token_buffer = ""; this._state_handler = this._state_handlers.PROPERTY_VALUE; return false; } if (c === "}") { this._emitToken(cls.CSSTokenizer.types.WHITESPACE, this._token_buffer); this._emitToken(cls.CSSTokenizer.types.DECLARATION_BLOCK_END,c) this._token_buffer = ""; this._state_handler = this._state_handlers.BEFORE_RULE; return false; } this._emitToken(cls.CSSTokenizer.types.WHITESPACE, this._token_buffer); this._token_buffer = c; this._state_handler = this._state_handlers.PROPERTY; return false; }, PROPERTY: function() { this._token_type = cls.CSSTokenizer.types.PROPERTY; if (this._init_state()) { return false; } var c = this._buffer.charAt(this._current_pos++); if (c === "}") { this._emitToken(cls.CSSTokenizer.types.PROPERTY, this._token_buffer); this._emitToken(cls.CSSTokenizer.types.DECLARATION_BLOCK_END, "}") this._token_buffer = ""; this._state_handler = this._state_handlers.BEFORE_RULE; return false; } if (c == ";") { this._emitToken(cls.CSSTokenizer.types.PROPERTY, this._token_buffer); this._emitToken(cls.CSSTokenizer.types.DECLARATION_TERMINATOR, ";") this._token_buffer = ""; this._state_handler == this._state_handlers.BEFORE_PROPERTY; return false; } if (c !== ":") { this._token_buffer += c; return false; } this._emitToken(cls.CSSTokenizer.types.PROPERTY, this._token_buffer); this._emitToken(cls.CSSTokenizer.types.PROPERTY_SEPARATOR, ":"); this._token_buffer = ""; this._state_handler = this._state_handlers.PROPERTY_VALUE; return false; }, PROPERTY_VALUE: function() { this._token_type = cls.CSSTokenizer.types.PROPERTY_VALUE; if (this._init_state()) { return false; } var c = this._buffer.charAt(this._current_pos++); if (c === ";") { this._emitToken(this._token_type, this._token_buffer); this._emitToken(cls.CSSTokenizer.types.DECLARATION_TERMINATOR, ";") this._token_buffer = ""; this._state_handler = this._state_handlers.BEFORE_PROPERTY; return false; } if (c === "}") { this._emitToken(this.token_type, this._token_buffer); this._emitToken(cls.CSSTokenizer.types.DECLARATION_BLOCK_END, "}") this._token_buffer = ""; this._state_handler = this._state_handlers.BEFORE_RULE; return false; } this._token_buffer+=c; return false; }, BEFORE_AT_RULE: function() { this._token_type = cls.CSSTokenizer.types.AT_RULE; if (this._init_state()) { return false; } // Buffer contains @ var c = this._buffer.charAt(this._current_pos); var needle = "charset"; var haystack = this._buffer.substr(this._current_pos, needle.length); if (needle == haystack) { this._current_pos += needle.length; this._token_buffer += needle; this._state_handler = this._state_handlers.CHARSET_RULE; return false; } this._current_pos++; this._token_buffer+=c; this._state_handler = this._state_handlers.AT_RULE; return false; }, CHARSET_RULE: function() { this._token_type = cls.CSSTokenizer.types.AT_RULE; if (this._init_state()) { return false; } var c = this._buffer.charAt(this._current_pos++); this._token_buffer +=c; if (c === ";") { this._emitToken(this._token_type, this._token_buffer) this._state_handler = this._state_handlers.BEFORE_RULE; this._token_buffer = ""; return false; } return false; }, AT_RULE: function() { if (this._init_state()) { return false; } var c = this._buffer.charAt(this._current_pos++); if ( c === ";") { this._emitToken(cls.CSSTokenizer.types.AT_RULE, this._token_buffer) this._emitToken(cls.CSSTokenizer.types.DECLARATION_TERMINATOR, ";") this._state_handler = this._state_handlers.BEFORE_RULE; this._token_buffer = ""; return false; } if ( c === "{") { this._emitToken(cls.CSSTokenizer.types.AT_RULE, this._token_buffer); this._emitToken(cls.CSSTokenizer.types.DECLARATION_BLOCK_START, "{"); // Fix for DFL-1844, if (this.normalize_token(this._token_buffer).trim().toLowerCase() == "@font-face") { this._state_handler = this._state_handlers.BEFORE_PROPERTY; } else { this._state_handler = this._state_handlers.BEFORE_RULE; } this._token_buffer = ""; return false; } this._token_buffer+=c; return false; }, QUOTED_STRING: function() { this._handle_escape_status(); if (this._is_EOF()) { return false; } if (this._is_EOL()) { return false; } var c = this._buffer.charAt(this._current_pos++); if (c === this._quote_literal) { this._state_handler = this._state_cache.shift(); this._token_buffer+=c; this._quote_literal = ""; return false; } this._token_buffer +=c; return false; } } } cls.CSSTokenizer.types = { SELECTOR : 1, AT_RULE : 2, WHITESPACE : 4, PROPERTY : 101, PROPERTY_SEPARATOR : 102, PROPERTY_VALUE : 103, DECLARATION_TERMINATOR : 104, DECLARATION_BLOCK_START : 105, DECLARATION_BLOCK_END : 106, COMMENT : 201, SGML_COMMENT_DELIM : 202, INVALID : 401, INVALID_SELECTOR : 402, INVALID_PROPERTY : 403, INVALID_PROPERTY_VALUE : 404, EOL_DATA : 500, EOF : 999 };
{ "content_hash": "3386bb637e91d8787d967c96e5f27556", "timestamp": "", "source": "github", "line_count": 589, "max_line_length": 93, "avg_line_length": 26.960950764006792, "alnum_prop": 0.5054156171284635, "repo_name": "operasoftware/dragonfly", "id": "2280523220735b257b3a42c89d3bb072323e3e19", "size": "15882", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/syntaxhighlight/css/tokenizer.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "3848248" }, { "name": "PHP", "bytes": "4120" }, { "name": "Python", "bytes": "31116" }, { "name": "Shell", "bytes": "39" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <title>Chapter 7: Master George and Uncle Tom | Uncle Tom's Cabin (Told to the Children) | Harriet Beecher Stowe | Lit2Go ETC</title> <link rel="stylesheet" href="http://etc.usf.edu/lit2go/css/screenless.css" type="text/css" media="screen" title="no title" charset="utf-8"> <link rel="stylesheet" href="http://etc.usf.edu/lit2go/css/printless.css" type="text/css" media="print" title="no title" charset="utf-8"> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript" defer src="http://etc.usf.edu/lit2go/js/js.min.js"></script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-5574891-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); $(document).ready(function() { $('img').unveil(); $('#contactable').contactable({ url: 'http://etc.usf.edu/lit2go/welcome/feedback/', subject: 'Lit2Go Feedback — Chapter 7: Master George and Uncle Tom | Uncle Tom\'s Cabin (Told to the Children) | Harriet Beecher Stowe — http://etc.usf.edu/lit2go/88/uncle-toms-cabin-told-to-the-children/1496/chapter-7-master-george-and-uncle-tom/' }); }); </script> </head> <body> <div class="page"> <header> <h1> <a href="http://etc.usf.edu/lit2go/">Lit<span class="blue">2</span>Go</a> </h1> <ul> <li id="search"><form action="http://etc.usf.edu/lit2go/search/"><input type="text" name="q" placeholder="Search" value=""></form></li> </ul> </header> <nav id="shell"> <ul> <li><a href="http://etc.usf.edu/lit2go/authors/" class="">Authors</a></li> <li><a href="http://etc.usf.edu/lit2go/books/" class="selected">Books</a></li> <li><a href="http://etc.usf.edu/lit2go/genres/" class="">Genres</a></li> <li><a href="http://etc.usf.edu/lit2go/collections/" class="">Collections</a></li> <li><a href="http://etc.usf.edu/lit2go/readability/" class="">Readability</a></li> </ul> </nav> <section id="content"> <div id="contactable"><!-- contactable html placeholder --></div> <div id="page_content"> <header> <h2> <a href="http://etc.usf.edu/lit2go/88/uncle-toms-cabin-told-to-the-children/">Uncle Tom's Cabin (Told to the Children)</a> </h2> <h3> by <a href="http://etc.usf.edu/lit2go/authors/98/harriet-beecher-stowe/">Harriet Beecher Stowe</a> </h3> <h4> Chapter 7: Master George and Uncle Tom </h4> </header> <div id="default"> <details open> <summary> Additional Information </summary> <div id="columns"> <ul> <li> <strong>Year Published:</strong> 1852 </li> <li> <strong>Language:</strong> English </li> <li> <strong>Country of Origin:</strong> United States of America </li> <li> <strong>Source:</strong> Stowe, H. B. (1852). <em>Uncle Tom's Cabin (Told to the Children).</em> H. E. Marshall, (Ed.). </li> </ul> </div> <div id="columns"> <ul> <li> <strong>Readability:</strong> <ul> <li> Flesch–Kincaid Level: <a href="http://etc.usf.edu/lit2go/readability/flesch_kincaid_grade_level/3/" title="Flesch–Kincaid Grade Level 3.7">3.7</a> </li> </ul> </li> <li> <strong>Word Count:</strong> 1,169 </li> </ul> </div> <div id="columns"> <ul> <li> <strong>Genre:</strong> <a href="http://etc.usf.edu/lit2go/genres/11/historical-fiction/">Historical Fiction</a> </li> <li> <strong>Keywords:</strong> 19th century literature, american literature </li> <li> <a class="btn" data-toggle="modal" href="#cite_this" >✎ Cite This</a> </li> <li> <!-- AddThis Button BEGIN --> <div class="addthis_toolbox addthis_default_style "> <a addthis:ui_delay="500" href="http://www.addthis.com/bookmark.php?v=250&amp;pub=roywinkelman" class="addthis_button_compact">Share</a> <span class="addthis_separator">|</span> <a class="addthis_button_preferred_1"></a> <a class="addthis_button_preferred_2"></a> <a class="addthis_button_preferred_3"></a> <a class="addthis_button_preferred_4"></a> </div> <script type="text/javascript">$($.getScript("http://s7.addthis.com/js/250/addthis_widget.js?pub=roywinkelman"))</script> <!-- <script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js?pub=roywinkelman"></script> --> <!-- AddThis Button END --> </li> </ul> </div> <h4>Downloads</h4> <ul id="downloads"> <li> <a href="http://etc.usf.edu/lit2go/audio/mp3/uncle-toms-cabin-told-to-the-children-008-chapter-7-master-george-and-uncle-tom.1496.mp3">Audio</a> </li> <li> <a href="http://etc.usf.edu/lit2go/pdf/passage/1496/uncle-toms-cabin-told-to-the-children-008-chapter-7-master-george-and-uncle-tom.pdf">Passage PDF</a> </li> <li><a href="http://etc.usf.edu/lit2go/pdf/student_activity/1496/1496-1.pdf">Student Activity</a></li> </ul> <hr> </details> <div class="modal hide" id="cite_this"> <script> $($('#myTab a').click(function (e) {e.preventDefault();$('#myTab a[href="#apa"]').tab('show');})); </script> <nav> <ul id="myTab"> <li class="active"> <a href="#apa" data-toggle="tab">APA</a> </li> <li> <a href="#mla" data-toggle="tab">MLA</a> </li> <li> <a href="#chicago" data-toggle="tab">Chicago</a> </li> </ul> </nav> <div class="tab-content"> <div class="content tab-pane hide active" id="apa"> <p class="citation"> Stowe, H. (1852). Chapter 7: Master George and Uncle Tom. <em>Uncle Tom's Cabin (Told to the Children)</em> (Lit2Go Edition). Retrieved February 15, 2016, from <span class="faux_link">http://etc.usf.edu/lit2go/88/uncle-toms-cabin-told-to-the-children/1496/chapter-7-master-george-and-uncle-tom/</span> </p> </div> <div class="content tab-pane" id="mla"> <p class="citation"> Stowe, Harriet Beecher. "Chapter 7: Master George and Uncle Tom." <em>Uncle Tom's Cabin (Told to the Children)</em>. Lit2Go Edition. 1852. Web. <<span class="faux_link">http://etc.usf.edu/lit2go/88/uncle-toms-cabin-told-to-the-children/1496/chapter-7-master-george-and-uncle-tom/</span>>. February 15, 2016. </p> </div> <div class="content tab-pane" id="chicago"> <p class="citation"> Harriet Beecher Stowe, "Chapter 7: Master George and Uncle Tom," <em>Uncle Tom's Cabin (Told to the Children)</em>, Lit2Go Edition, (1852), accessed February 15, 2016, <span class="faux_link">http://etc.usf.edu/lit2go/88/uncle-toms-cabin-told-to-the-children/1496/chapter-7-master-george-and-uncle-tom/</span>. </p> </div> </div> </div> <span class="top"> <nav class="passage"> <ul> <li><a href="http://etc.usf.edu/lit2go/88/uncle-toms-cabin-told-to-the-children/1495/chapter-6-uncle-tom-says-good-bye/" title="Chapter 6: Uncle Tom Says Good-Bye" class="back">Back</a></li> <li><a href="http://etc.usf.edu/lit2go/88/uncle-toms-cabin-told-to-the-children/1498/chapter-8-uncle-tom-meets-eva/" title="Chapter 8: Uncle Tom Meets Eva" class="next">Next</a></li> </ul> </nav> </span> <div id="shrink_wrap"> <div id="i_apologize_for_the_soup"> <audio controls style="width:99%;"> <source src="http://etc.usf.edu/lit2go/audio/mp3/uncle-toms-cabin-told-to-the-children-008-chapter-7-master-george-and-uncle-tom.1496.mp3" type="audio/mpeg" /> <source src="http://etc.usf.edu/lit2go/audio/ogg/uncle-toms-cabin-told-to-the-children-008-chapter-7-master-george-and-uncle-tom.1496.ogg" type="audio/ogg" /> The embedded audio player requires a modern internet browser. You should visit <a href="http://browsehappy.com/">Browse Happy</a> and update your internet browser today! </audio> <p> Haley and Tom had rattled along the dusty road for about a mile, when Haley pulled up at a blacksmith&#39;s shop. He got out to have something done to a pair of handcuffs, leaving Tom in the cart.</p> <p> &nbsp; Tom was sitting there, very mournfully, when suddenly he heard the quick, short click of a horse&#39;s hoof behind him. Almost before he knew what was happening, George Shelby sprang into the cart. He threw his arms round Tom&#39;s neck, sobbing and scolding.</p> <p> &nbsp; &#39;I declare it&#39;s real mean. I don&#39;t care what they say, any of them. It&#39;s a nasty, mean shame. If I were a man, they shouldn&#39;t do it&mdash;they should not!&#39;</p> <p> &nbsp; &#39;Oh, Mas&#39;r George, this does me good,&#39; said Tom.&#39; I couldn&#39;t bear to go off without seein&#39; ye. It does me real good, ye can&#39;t tell.&#39;</p> <p> &nbsp; Here Tom made a movement with his feet, and George&#39;s eyes fell on the chains.</p> <p> &nbsp; &#39;What a shame,&#39; he cried. &#39; I&#39;ll knock that old fellow down, I will.&#39;</p> <p> &nbsp; &#39;No, you won&#39;t, Mas&#39;r George; and you must not talk so loud. It won&#39;t help me any, to anger him.&#39;</p> <p> &nbsp; &#39;Well, I won&#39;t then, for your sake. But only to think of it&mdash;isn&#39;t it a shame? They never sent for me, nor sent me any word. If it hadn&#39;t been for Tom Lincoln, I shouldn&#39;t have heard of it. I tell you, I blew them up well, all of them, at home.&#39;</p> <p> &nbsp; &#39;That wasn&#39;t right, I&#39;m feared, Mas&#39;r George.&#39;</p> <p> &nbsp; &#39;Can&#39;t help it. I say it&#39;s a shame. Look here, Uncle Tom,&#39; said he, turning his back to the shop, and speaking in a mysterious tone, &#39;I&#39;ve brought you my dollar.&#39;</p> <p> &nbsp; &#39;Oh, I couldn&#39;t think of takin&#39; it, Mas&#39;r George, noways in the world,&#39; said Tom.</p> <p> &nbsp; &#39;But you shall take it,&#39; said George. &#39;Look here, I told Aunt Chloe I&#39;d do it. She advise, me just to make a hole in it, and put a string through. You can hang it round your neck, and keep it out of sight, else this mean scamp will take it away. I tell you, Tom, I want to blow him up. It would do me good.&#39;</p> <p> &nbsp; &#39;No, don&#39;t, Mas&#39;r George, for it won&#39;t do me any good.&#39;</p> <p> &nbsp; &#39;Well, I won&#39;t for your sake,&#39; said George, busily tying his dollar round Tom&#39;s neck. &#39;There, now button your coat tight over it, and keep it safe. Remember every time you see it, that I&#39;m coming after you some day, to bring you back. Aunt Chloe and I have been talking about it: I told her not to fear. I&#39;ll see to it. I&#39;ll tease father&#39;s life out, if he doesn&#39;t see to it.&#39;</p> <p> &nbsp; &#39;Oh, Mas&#39;r George, ye mustn&#39;t talk so &#39;bout your father.&#39;</p> <p> &nbsp; &#39;Dear me, Uncle Tom, I don&#39;t mean anything bad.&#39;</p> <p> &nbsp; &#39;And now, Mas&#39;r George,&#39; said Tom, &#39;ye must be a good boy. &#39;Member how many hearts is set on ye. Always keep close to your mother. Don&#39;t be getting into any o&#39; them foolish ways boys has of getting too big to mind their mothers. Tell ye what, Mas&#39;r George, the Lord gives a good many things twice over, but he don&#39;t give ye a mother but once. Ye&#39;ll never see such another woman, Mas&#39;r George&mdash;not if ye live to be a hundred years old. So, now, you hold on to her, and grow up, and be a comfort to her, there&#39;s my own good boy&mdash;you will now&mdash;won&#39;t ye?&#39;</p> <p> &nbsp; &#39;Yes, I will, Uncle Tom,&#39; said George seriously.</p> <p> &nbsp; &#39;And be careful of yer speaking, Mas&#39;r George. Young boys, when they comes to your age, is wilful sometimes&mdash;it&#39;s natural they should be. But real gentlemen such as I hopes you&#39;ll be, never lets fall words that isn&#39;t &#39;spectful to their parents. Ye an&#39;t offended, Mas&#39;r George?&#39;</p> <p> &nbsp; &#39;No, indeed, Uncle Tom, you always give me good advice.&#39;</p> <p> &nbsp; &#39;I&#39;se older, you know,&#39; said Tom, stroking George&#39;s curly head with his large strong hand, but speaking in a voice as tender as a mother&#39;s.</p> <p> &nbsp; &#39;Oh, Mas&#39;r George, you has everything&mdash;learning, reading, writing&mdash;and you&#39;ll grow up to be a great, learned, good man. All the people on the place, and your father and mother, &#39;ll be proud of ye. Be a good mas&#39;r like your father, and be a Christian like your mother, Mas&#39;r George.&#39;</p> <p> &nbsp; &#39;I&#39;ll be real good, Uncle Tom, I tell you,&#39; said George. &#39;And don&#39;t you be discouraged. I&#39;ll have you back yet. As I told Aunt Chloe this morning, I&#39;ll build your house over again. You shall have a room for a parlour, with a carpet on it, when I&#39;m a man. Oh, you&#39;ll have good times yet.&#39;</p> <p> &nbsp; Haley now came to the shop door with the handcuffs in his hand.</p> <p> &nbsp; &#39;Look here, now, mister,&#39; said George, looking at him very grandly, &#39;I shall let father and mother know how you treat Uncle Tom.&#39;</p> <p> &nbsp; &#39;You&#39;re welcome,&#39; replied he.</p> <p> &nbsp; &#39;I should think you&#39;d be ashamed to spend all your life buying men and women, and chaining them like cattle! I should think you&#39;d feel mean,&#39; said George.</p> <p> &nbsp; &#39;So long as you grand folks wants to buy men and women, I&#39;m as good as they,&#39; said Haley. &#39;It isn&#39;t any meaner to sell them than to buy them.&#39;</p> <p> &nbsp; &#39;I&#39;ll never do either, when I&#39;m a man,&#39; said George. &#39;I&#39;m ashamed this day. Good-bye, Uncle Tom,&#39; he added, &#39;don&#39;t get down-hearted.&#39;</p> <p> &nbsp; &#39;Good-bye, Mas&#39;r George,&#39; said Tom. &#39;God Almighty bless you.&#39;</p> <p> &nbsp; Away George went, and Tom looked after him until the clatter of his horse&#39;s heels died away. It was the last sound or sight of his home. But over his heart there seemed to be a warm spot where George had placed that precious dollar. Tom put up his hand and held it close to his heart.</p> <p> &nbsp; Haley came to the cart, threw the handcuffs in, and jumping up on to the seat, drove off again.</p> <p> &nbsp; All day long, they drove over the rough country roads. Late in the evening they arrived at a town called Washington. Haley went to a comfortable inn for the night, but poor Tom was sent to prison with handcuffs on his wrists, and heavy chains on his ankles. This was not because he had done anything wicked, but only that he happened to be a black man and a slave.</p> </div> </div> <span class="bottom"> <nav class="passage"> <ul> <li><a href="http://etc.usf.edu/lit2go/88/uncle-toms-cabin-told-to-the-children/1495/chapter-6-uncle-tom-says-good-bye/" title="Chapter 6: Uncle Tom Says Good-Bye" class="back">Back</a></li> <li><a href="http://etc.usf.edu/lit2go/88/uncle-toms-cabin-told-to-the-children/1498/chapter-8-uncle-tom-meets-eva/" title="Chapter 8: Uncle Tom Meets Eva" class="next">Next</a></li> </ul> </nav> </span> </div> </div> </section> <footer screen> <div id="footer-text"> <p> This collection of children's literature is a part of the <a href="http://etc.usf.edu/">Educational Technology Clearinghouse</a> and is funded by various <a href="http://etc.usf.edu/lit2go/welcome/funding/">grants</a>. </p> <p> Copyright &copy; 2006&mdash;2016 by the <a href="http://fcit.usf.edu/">Florida Center for Instructional Technology</a>, <a href="http://www.coedu.usf.edu/">College of Education</a>, <a href="http://www.usf.edu/">University of South Florida</a>. </p> </div> <ul id="footer-links"> <li><a href="http://etc.usf.edu/lit2go/welcome/license/">License</a></li> <li><a href="http://etc.usf.edu/lit2go/welcome/credits/">Credits</a></li> <li><a href="http://etc.usf.edu/lit2go/welcome/faq/">FAQ</a></li> <li><a href="http://etc.usf.edu/lit2go/giving/">Giving</a></li> </ul> </footer> <footer print> <div id="footer-text"> <p>This document was downloaded from <a href="http://etc.usf.edu/lit2go/">Lit2Go</a>, a free online collection of stories and poems in Mp3 (audiobook) format published by the <a href="http://fcit.usf.edu/">Florida Center for Instructional Technology</a>. For more information, including classroom activities, readability data, and original sources, please visit <a href="http://etc.usf.edu/lit2go/88/uncle-toms-cabin-told-to-the-children/1496/chapter-7-master-george-and-uncle-tom/">http://etc.usf.edu/lit2go/88/uncle-toms-cabin-told-to-the-children/1496/chapter-7-master-george-and-uncle-tom/</a>.</p> </div> <div id="book-footer"> <p>Lit2Go: <em>Uncle Tom's Cabin (Told to the Children)</em></p> <p>Chapter 7: Master George and Uncle Tom</p> </div> </footer> <script type="text/javascript" defer src="http://etc.usf.edu/lit2go/js/details.js"></script> </div> </body> </html>
{ "content_hash": "0299046edb0b8dac945d98fd4ede8769", "timestamp": "", "source": "github", "line_count": 303, "max_line_length": 634, "avg_line_length": 61.08910891089109, "alnum_prop": 0.6148568341437061, "repo_name": "adrianosb/maprecude_team_adriano_barbosa_and_andre_matsuda", "id": "9c7a5e9c60c821240b5c1c83d8124c232b918ef1", "size": "18520", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "HtmlToText/lit2go.ok/88/uncle-toms-cabin-told-to-the-children/1496/chapter-7-master-george-and-uncle-tom/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "145411809" }, { "name": "Java", "bytes": "6677" } ], "symlink_target": "" }
#include "test/ServerFixture.hh" #include "gazebo/msgs/msgs.hh" using namespace gazebo; class PhysicsEngineTest : public ServerFixture { public: void OnPhysicsMsgResponse(ConstResponsePtr &_msg); public: void PhysicsEngineParam(const std::string &_physicsEngine); public: static msgs::Physics physicsPubMsg; public: static msgs::Physics physicsResponseMsg; }; msgs::Physics PhysicsEngineTest::physicsPubMsg; msgs::Physics PhysicsEngineTest::physicsResponseMsg; ///////////////////////////////////////////////// void PhysicsEngineTest::OnPhysicsMsgResponse(ConstResponsePtr &_msg) { if (_msg->type() == physicsPubMsg.GetTypeName()) physicsResponseMsg.ParseFromString(_msg->serialized_data()); } ///////////////////////////////////////////////// void PhysicsEngineTest::PhysicsEngineParam(const std::string &_physicsEngine) { physicsPubMsg.Clear(); physicsResponseMsg.Clear(); Load("worlds/empty.world", false); physics::WorldPtr world = physics::get_world("default"); ASSERT_TRUE(world != NULL); transport::NodePtr physicsNode; physicsNode = transport::NodePtr(new transport::Node()); physicsNode->Init(); transport::PublisherPtr physicsPub = physicsNode->Advertise<msgs::Physics>("~/physics"); transport::PublisherPtr requestPub = physicsNode->Advertise<msgs::Request>("~/request"); transport::SubscriberPtr responsePub = physicsNode->Subscribe("~/response", &PhysicsEngineTest::OnPhysicsMsgResponse, this); msgs::Physics_Type type; if (_physicsEngine == "ode") type = msgs::Physics::ODE; else if (_physicsEngine == "bullet") type = msgs::Physics::BULLET; else if (_physicsEngine == "dart") type = msgs::Physics::DART; else type = msgs::Physics::ODE; physicsPubMsg.set_type(type); physicsPubMsg.set_max_step_size(0.01); physicsPubMsg.set_real_time_update_rate(500); physicsPubMsg.set_real_time_factor(1.2); physicsPub->Publish(physicsPubMsg); msgs::Request *requestMsg = msgs::CreateRequest("physics_info", ""); requestPub->Publish(*requestMsg); int waitCount = 0, maxWaitCount = 3000; while (physicsResponseMsg.ByteSize() == 0 && ++waitCount < maxWaitCount) common::Time::MSleep(10); ASSERT_LT(waitCount, maxWaitCount); EXPECT_DOUBLE_EQ(physicsResponseMsg.max_step_size(), physicsPubMsg.max_step_size()); EXPECT_DOUBLE_EQ(physicsResponseMsg.real_time_update_rate(), physicsPubMsg.real_time_update_rate()); EXPECT_DOUBLE_EQ(physicsResponseMsg.real_time_factor(), physicsPubMsg.real_time_factor()); physicsNode->Fini(); } TEST_F(PhysicsEngineTest, PhysicsEngineParamODE) { PhysicsEngineParam("ode"); } #ifdef HAVE_BULLET TEST_F(PhysicsEngineTest, PhysicsEngineParamBullet) { PhysicsEngineParam("bullet"); } #endif // HAVE_BULLET #ifdef HAVE_DART TEST_F(PhysicsEngineTest, PhysicsEngineParamDART) { PhysicsEngineParam("dart"); } #endif // HAVE_DART int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
{ "content_hash": "50f0a2dbc8f2817a7a887c234db78495", "timestamp": "", "source": "github", "line_count": 105, "max_line_length": 77, "avg_line_length": 28.676190476190477, "alnum_prop": 0.7047492527399535, "repo_name": "jonbinney/gazebo_ros_wrapper", "id": "0b35831c39e824b4efd84b3f952836d5e2f16501", "size": "3636", "binary": false, "copies": "1", "ref": "refs/heads/indigo-devel", "path": "gazebo/physics/PhysicsEngine_TEST.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "565866" }, { "name": "C++", "bytes": "8280611" }, { "name": "CSS", "bytes": "12592" }, { "name": "JavaScript", "bytes": "25255" } ], "symlink_target": "" }
package org.springframework.social.salesforce.api.impl; import org.junit.Test; import org.springframework.social.salesforce.api.ResultItem; import java.util.List; import static org.junit.Assert.assertEquals; import static org.springframework.http.HttpMethod.GET; import static org.springframework.http.MediaType.APPLICATION_JSON; import static org.springframework.test.web.client.match.RequestMatchers.method; import static org.springframework.test.web.client.match.RequestMatchers.requestTo; import static org.springframework.test.web.client.response.ResponseCreators.withSuccess; /** * @author Umut Utkan */ public class SearchTemplateTest extends AbstractSalesforceTest { @Test public void search() { mockServer.expect(requestTo("https://na7.salesforce.com/services/data/v23.0/search?q=FIND+%7Bxxx*%7D+IN+ALL+FIELDS+RETURNING+Contact%2C+Account")) .andExpect(method(GET)) .andRespond(withSuccess(loadResource("search.json"), APPLICATION_JSON)); List<ResultItem> results = salesforce.searchOperations().search("FIND {xxx*} IN ALL FIELDS RETURNING Contact, Account"); assertEquals(4, results.size()); assertEquals("Contact", results.get(0).getType()); assertEquals("Contact", results.get(1).getType()); assertEquals("Account", results.get(2).getType()); assertEquals("Account", results.get(3).getType()); } }
{ "content_hash": "6eeec2afb5cf0cfa56718476c052a032", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 154, "avg_line_length": 42.96969696969697, "alnum_prop": 0.7404795486600846, "repo_name": "silanis/spring-social-salesforce", "id": "6d758c06cb4ac6ac2d458fa139001c712a46f4ae", "size": "1418", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/org/springframework/social/salesforce/api/impl/SearchTemplateTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "114694" } ], "symlink_target": "" }
- Welcome, introductions (5mins) - Agenda, Ground Rules overview (10mins) - Define the Objective (20mins) - Identify Role and User Types (10mins) - Brainstorm Features (150mins) - Review Assumptions & Constraings (10mins) - Prioritize Features (20mins) - Define Core Feature Set (15mins) ##Ground Rules: - Be nice, open, and considerate - Show mutual respect - Actively participate - Stay on task - Listen to other...do not interrupt - There are no bad ideas today; we will honor brainstorming without being attached to our own viewpoint - Be free to speak our mind without fear of reprisal
{ "content_hash": "9e01ba47404f12b7d8a378c7e218254a", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 103, "avg_line_length": 34.76470588235294, "alnum_prop": 0.7648054145516074, "repo_name": "osmyn/AgileRequirementsWorkshop", "id": "12b85d0b9f426f9a35938d36748fbcc8e5f46bb7", "size": "641", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Workshop Agenda.md", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
class ConditionVariable : private NonCopyable { public: void lock() { m.lock(); } bool trylock() { return m.trylock(); } void unlock() { m.unlock(); } void wait() { c.wait(m); } bool timedWait(int millisecond) { return c.timedWait(m, millisecond); } void notifyOne() { c.notifyOne(); } void notifyAll() { c.notifyAll(); } private: Mutex m; Condition c; }; #endif
{ "content_hash": "dd37f545b690874d1f97d705f5827345", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 72, "avg_line_length": 20.833333333333332, "alnum_prop": 0.6506666666666666, "repo_name": "CltKitakami/MyLib", "id": "724c60842b703a3a357c1a53915d2b56e269c66a", "size": "523", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "thread/ConditionVariable.hpp", "mode": "33261", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "4065" }, { "name": "C", "bytes": "333616" }, { "name": "C++", "bytes": "483997" }, { "name": "CMake", "bytes": "8312" }, { "name": "Shell", "bytes": "270" } ], "symlink_target": "" }
<div [draggable] role="small-popup-processes" class="small-popup-processes"> <header> <h2>{{map.name}} versions</h2> <i role="closing" class="pmap-15" (click)="closeWindow()"></i> </header> <section> <div class="pmap-table"> <div class="thead-wrapper"> <div class="thead pm-font"> <div class="tr"> <div class="cell ver-cell">Version</div> <div class="cell ver-cell">User</div> <div class="cell ver-cell">Date</div> <div class="cell ver-cell">Executions</div> <div class="cell ver-cell"></div> </div> </div> </div> <div class="tbody-wrapper"> <div class="tbody pm-font "> <div class="tr" *ngFor="let version of versions; let versionIndex = index"> <div class="cell ver-cell">{{ versionIndex }}</div> <div class="cell ver-cell">{{ version.lastEditor }}</div> <div class="cell ver-cell"><span class="date date-cell">{{ version.date | date:'short' }}</span></div> <div class="cell ver-cell">{{ version.executions.length }}</div> <div class="cell ver-cell"><button type="button" (click)="openExecutions(version)"><i class="pmap-24"></i></button></div> </div> </div> </div> </div> </section> <footer> <button class="btn-event btn-no-icon" (click)="closeWindow()" type="button">Close</button> </footer> </div>
{ "content_hash": "069ec9cfb93c69b44f275767d88f6a5d", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 133, "avg_line_length": 41.457142857142856, "alnum_prop": 0.5568573397656789, "repo_name": "ProductionMap/production-map-console", "id": "debff768542f5a70eeea56654652d56484ad52de", "size": "1451", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/app/map-managment/left-panel/map-explorer/popups/map-versions/map-versions.component.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "217256" }, { "name": "HTML", "bytes": "95203" }, { "name": "JavaScript", "bytes": "2317" }, { "name": "TypeScript", "bytes": "171611" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd"> <id>amag-designer</id> <formats> <format>war</format> </formats> <files> <file> <source>src/main/assembly/jbpm.xml</source> <outputDirectory>/profiles/</outputDirectory> <filtered>true</filtered> </file> </files> <includeBaseDirectory>false</includeBaseDirectory> <dependencySets> <dependencySet> <includes> <include>org.jboss.drools:jbpm-designer:war</include> </includes> <outputDirectory>.</outputDirectory> <unpack>true</unpack> <unpackOptions> <excludes> <exclude>profiles/jbpm.xml</exclude> </excludes> </unpackOptions> <useStrictFiltering>true</useStrictFiltering> </dependencySet> </dependencySets> </assembly>
{ "content_hash": "80d49af4404387e1ead85261bbf59237", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 141, "avg_line_length": 27.15, "alnum_prop": 0.6611418047882136, "repo_name": "chtiJBUG/drools-platform-parent", "id": "baa190a5669c334df11e9251b9fe28c1d6e40caa", "size": "1086", "binary": false, "copies": "1", "ref": "refs/heads/0.5.x", "path": "drools-platform-governance/drools-platform-designer/src/main/assembly/assembly-designer.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "44" }, { "name": "CSS", "bytes": "21138" }, { "name": "HTML", "bytes": "78571" }, { "name": "Java", "bytes": "640990" }, { "name": "JavaScript", "bytes": "79342" }, { "name": "Shell", "bytes": "54" } ], "symlink_target": "" }
using System.Text; namespace com.google.zxing.client.result { /// <summary> /// @author Sean Owen /// </summary> public sealed class TelParsedResult : ParsedResult { private readonly string number; private readonly string telURI; private readonly string title; public TelParsedResult(string number, string telURI, string title) : base(ParsedResultType.TEL) { this.number = number; this.telURI = telURI; this.title = title; } public string Number { get { return number; } } public string TelURI { get { return telURI; } } public string Title { get { return title; } } public override string DisplayResult { get { StringBuilder result = new StringBuilder(20); maybeAppend(number, result); maybeAppend(title, result); return result.ToString(); } } } }
{ "content_hash": "acfe28eae41a6e83ee73101e7f47af35", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 98, "avg_line_length": 15.639344262295081, "alnum_prop": 0.589098532494759, "repo_name": "smart-make/zxing", "id": "af017bebb26d4f2917ba10d10b09871eb5379e9b", "size": "1565", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "csharp/client/result/TelParsedResult.cs", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "ActionScript", "bytes": "1305274" }, { "name": "C", "bytes": "157019" }, { "name": "C#", "bytes": "767375" }, { "name": "C++", "bytes": "2095498" }, { "name": "Java", "bytes": "2136191" }, { "name": "JavaScript", "bytes": "66378" }, { "name": "Objective-C", "bytes": "411772" }, { "name": "Prolog", "bytes": "10866" }, { "name": "Python", "bytes": "1723495" }, { "name": "Ruby", "bytes": "4508" }, { "name": "Scilab", "bytes": "92" }, { "name": "Shell", "bytes": "1222" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Sticta exampliata Meyen & Flot. ### Remarks null
{ "content_hash": "230ce2bc714aa49cab265c5e36605b9e", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 10.461538461538462, "alnum_prop": 0.6985294117647058, "repo_name": "mdoering/backbone", "id": "28f0d172aba85c0c0e460375e01cd3a6f55bb5d5", "size": "191", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Lecanoromycetes/Peltigerales/Lobariaceae/Sticta/Sticta exampliata/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
/** * @file sgesv.c * * PLASMA computational routines * Release Date: November, 15th 2009 * PLASMA is a software package provided by Univ. of Tennessee, * Univ. of California Berkeley and Univ. of Colorado Denver * * @version 2.4.2 * @author Jakub Kurzak * @author Mathieu Faverge * @date 2010-11-15 * @generated s Thu Sep 15 12:09:15 2011 * **/ #include "common.h" /***************************************************************************//** * * @ingroup float * * PLASMA_sgesv - Computes the solution to a system of linear equations A * X = B, * where A is an N-by-N matrix and X and B are N-by-NRHS matrices. * The tile LU decomposition with partial tile pivoting and row interchanges is used to factor A. * The factored form of A is then used to solve the system of equations A * X = B. * ******************************************************************************* * * @param[in] N * The number of linear equations, i.e., the order of the matrix A. N >= 0. * * @param[in] NRHS * The number of right hand sides, i.e., the number of columns of the matrix B. * NRHS >= 0. * * @param[in,out] A * On entry, the N-by-N coefficient matrix A. * On exit, the tile L and U factors from the factorization. * * @param[in] LDA * The leading dimension of the array A. LDA >= max(1,N). * * @param[out] IPIV * On exit, the pivot indices that define the permutations. * * @param[in,out] B * On entry, the N-by-NRHS matrix of right hand side matrix B. * On exit, if return value = 0, the N-by-NRHS solution matrix X. * * @param[in] LDB * The leading dimension of the array B. LDB >= max(1,N). * ******************************************************************************* * * @return * \retval PLASMA_SUCCESS successful exit * \retval <0 if -i, the i-th argument had an illegal value * \retval >0 if i, U(i,i) is exactly zero. The factorization has been completed, * but the factor U is exactly singular, so the solution could not be computed. * ******************************************************************************* * * @sa PLASMA_sgesv_Tile * @sa PLASMA_sgesv_Tile_Async * @sa PLASMA_cgesv * @sa PLASMA_dgesv * @sa PLASMA_sgesv * ******************************************************************************/ int PLASMA_sgesv(int N, int NRHS, float *A, int LDA, int *IPIV, float *B, int LDB) { int NB, IB, IBNB, NT; int status; plasma_context_t *plasma; PLASMA_sequence *sequence = NULL; PLASMA_request request = PLASMA_REQUEST_INITIALIZER; PLASMA_desc descA, descB; plasma = plasma_context_self(); if (plasma == NULL) { plasma_error("PLASMA_sgesv", "PLASMA not initialized"); return PLASMA_ERR_NOT_INITIALIZED; } /* Check input arguments */ if (N < 0) { plasma_error("PLASMA_sgesv", "illegal value of N"); return -1; } if (NRHS < 0) { plasma_error("PLASMA_sgesv", "illegal value of NRHS"); return -2; } if (LDA < max(1, N)) { plasma_error("PLASMA_sgesv", "illegal value of LDA"); return -4; } if (LDB < max(1, N)) { plasma_error("PLASMA_sgesv", "illegal value of LDB"); return -8; } /* Quick return */ if (min(N, NRHS) == 0) return PLASMA_SUCCESS; /* Tune NB & IB depending on M, N & NRHS; Set NBNB */ status = plasma_tune(PLASMA_FUNC_SGESV, N, N, NRHS); if (status != PLASMA_SUCCESS) { plasma_error("PLASMA_sgesv", "plasma_tune() failed"); return status; } /* Set NT & NTRHS */ NB = PLASMA_NB; IB = PLASMA_IB; IBNB = IB*NB; NT = (N%NB==0) ? (N/NB) : (N/NB+1); plasma_sequence_create(plasma, &sequence); if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) { plasma_sooplap2tile( descA, A, NB, NB, LDA, N, 0, 0, N, N , plasma_desc_mat_free(&(descA)) ); plasma_sooplap2tile( descB, B, NB, NB, LDB, NRHS, 0, 0, N, NRHS, plasma_desc_mat_free(&(descA)); plasma_desc_mat_free(&(descB))); } else { plasma_siplap2tile( descA, A, NB, NB, LDA, N, 0, 0, N, N ); plasma_siplap2tile( descB, B, NB, NB, LDB, NRHS, 0, 0, N, NRHS); } /* Call the tile interface */ PLASMA_sgesv_Tile_Async(&descA, IPIV, &descB, sequence, &request); if ( PLASMA_TRANSLATION == PLASMA_OUTOFPLACE ) { plasma_sooptile2lap( descA, A, NB, NB, LDA, N ); plasma_sooptile2lap( descB, B, NB, NB, LDB, NRHS ); plasma_dynamic_sync(); plasma_desc_mat_free(&descA); plasma_desc_mat_free(&descB); } else { plasma_siptile2lap( descA, A, NB, NB, LDA, N ); plasma_siptile2lap( descB, B, NB, NB, LDB, NRHS ); plasma_dynamic_sync(); } status = sequence->status; plasma_sequence_destroy(plasma, sequence); return status; } /***************************************************************************//** * * @ingroup float_Tile * * PLASMA_sgesv_Tile - Solves a system of linear equations using the tile LU factorization. * Tile equivalent of PLASMA_sgetrf(). * Operates on matrices stored by tiles. * All matrices are passed through descriptors. * All dimensions are taken from the descriptors. * ******************************************************************************* * * @param[in,out] A * On entry, the N-by-N coefficient matrix A. * On exit, the tile L and U factors from the factorization. * * @param[out] IPIV * On exit, the pivot indices that define the permutations. * * @param[in,out] B * On entry, the N-by-NRHS matrix of right hand side matrix B. * On exit, if return value = 0, the N-by-NRHS solution matrix X. * ******************************************************************************* * * @return * \retval PLASMA_SUCCESS successful exit * \retval >0 if i, U(i,i) is exactly zero. The factorization has been completed, * but the factor U is exactly singular, so the solution could not be computed. * ******************************************************************************* * * @sa PLASMA_sgesv * @sa PLASMA_sgesv_Tile_Async * @sa PLASMA_cgesv_Tile * @sa PLASMA_dgesv_Tile * @sa PLASMA_sgesv_Tile * @sa PLASMA_scgesv_Tile * ******************************************************************************/ int PLASMA_sgesv_Tile(PLASMA_desc *A, int *IPIV, PLASMA_desc *B) { plasma_context_t *plasma; PLASMA_sequence *sequence = NULL; PLASMA_request request = PLASMA_REQUEST_INITIALIZER; int status; plasma = plasma_context_self(); if (plasma == NULL) { plasma_fatal_error("PLASMA_sgesv_Tile", "PLASMA not initialized"); return PLASMA_ERR_NOT_INITIALIZED; } plasma_sequence_create(plasma, &sequence); PLASMA_sgesv_Tile_Async(A, IPIV, B, sequence, &request); plasma_dynamic_sync(); status = sequence->status; plasma_sequence_destroy(plasma, sequence); return status; } /***************************************************************************//** * * @ingroup float_Tile_Async * * PLASMA_sgesv_Tile_Async - Solves a system of linear equations using the tile * LU factorization. * Non-blocking equivalent of PLASMA_sgesv_Tile(). * May return before the computation is finished. * Allows for pipelining of operations ar runtime. * ******************************************************************************* * * @param[in] sequence * Identifies the sequence of function calls that this call belongs to * (for completion checks and exception handling purposes). * * @param[out] request * Identifies this function call (for exception handling purposes). * ******************************************************************************* * * @sa PLASMA_sgesv * @sa PLASMA_sgesv_Tile * @sa PLASMA_cgesv_Tile_Async * @sa PLASMA_dgesv_Tile_Async * @sa PLASMA_sgesv_Tile_Async * @sa PLASMA_scgesv_Tile_Async * ******************************************************************************/ int PLASMA_sgesv_Tile_Async(PLASMA_desc *A, int *IPIV, PLASMA_desc *B, PLASMA_sequence *sequence, PLASMA_request *request) { PLASMA_desc descA = *A; PLASMA_desc descB = *B; plasma_context_t *plasma; plasma = plasma_context_self(); if (plasma == NULL) { plasma_fatal_error("PLASMA_sgesv_Tile", "PLASMA not initialized"); return PLASMA_ERR_NOT_INITIALIZED; } if (sequence == NULL) { plasma_fatal_error("PLASMA_sgesv_Tile", "NULL sequence"); return PLASMA_ERR_UNALLOCATED; } if (request == NULL) { plasma_fatal_error("PLASMA_sgesv_Tile", "NULL request"); return PLASMA_ERR_UNALLOCATED; } /* Check sequence status */ if (sequence->status == PLASMA_SUCCESS) request->status = PLASMA_SUCCESS; else return plasma_request_fail(sequence, request, PLASMA_ERR_SEQUENCE_FLUSHED); /* Check descriptors for correctness */ if (plasma_desc_check(&descA) != PLASMA_SUCCESS) { plasma_error("PLASMA_sgesv_Tile", "invalid first descriptor"); return plasma_request_fail(sequence, request, PLASMA_ERR_ILLEGAL_VALUE); } if (plasma_desc_check(&descB) != PLASMA_SUCCESS) { plasma_error("PLASMA_sgesv_Tile", "invalid third descriptor"); return plasma_request_fail(sequence, request, PLASMA_ERR_ILLEGAL_VALUE); } /* Check input arguments */ if (descA.nb != descA.mb || descB.nb != descB.mb) { plasma_error("PLASMA_sgesv_Tile", "only square tiles supported"); return plasma_request_fail(sequence, request, PLASMA_ERR_ILLEGAL_VALUE); } /* Quick return */ /* if (min(N, NRHS) == 0) return PLASMA_SUCCESS; */ plasma_dynamic_call_3( plasma_psbarrier_tl2pnl, PLASMA_desc, descA, PLASMA_sequence*, sequence, PLASMA_request*, request); plasma_dynamic_call_4(plasma_psgetrf_rectil, PLASMA_desc, descA, int*, IPIV, PLASMA_sequence*, sequence, PLASMA_request*, request); /* swap */ plasma_dynamic_call_3( plasma_psbarrier_tl2pnl, PLASMA_desc, descB, PLASMA_sequence*, sequence, PLASMA_request*, request); plasma_dynamic_call_5( plasma_pslaswp, PLASMA_desc, descB, int *, IPIV, int, 1, PLASMA_sequence*, sequence, PLASMA_request*, request); plasma_parallel_call_9( plasma_pstrsm, PLASMA_enum, PlasmaLeft, PLASMA_enum, PlasmaLower, PLASMA_enum, PlasmaNoTrans, PLASMA_enum, PlasmaUnit, float, 1.0, PLASMA_desc, descA, PLASMA_desc, descB, PLASMA_sequence*, sequence, PLASMA_request*, request); plasma_parallel_call_9( plasma_pstrsm, PLASMA_enum, PlasmaLeft, PLASMA_enum, PlasmaUpper, PLASMA_enum, PlasmaNoTrans, PLASMA_enum, PlasmaNonUnit, float, 1.0, PLASMA_desc, descA, PLASMA_desc, descB, PLASMA_sequence*, sequence, PLASMA_request*, request); return PLASMA_SUCCESS; }
{ "content_hash": "0b9b0873f3abe095ea2a8c8d4bd525e2", "timestamp": "", "source": "github", "line_count": 337, "max_line_length": 137, "avg_line_length": 33.92878338278932, "alnum_prop": 0.547577400734651, "repo_name": "joao-lima/plasma-kaapi", "id": "4e5eb4794e4a67c6d3bcc75b27afdd1dff5b35f1", "size": "11434", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "compute/sgesv.c", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "8491080" }, { "name": "C++", "bytes": "100356" }, { "name": "FORTRAN", "bytes": "2823643" }, { "name": "JavaScript", "bytes": "20219" }, { "name": "Objective-C", "bytes": "31848" }, { "name": "Python", "bytes": "7172" }, { "name": "Ruby", "bytes": "6767" }, { "name": "Shell", "bytes": "20350" } ], "symlink_target": "" }
<?php namespace CosmoW\Riak; use ArrayAccess; /** * ArrayIterator is used to encapsulate document results from commands. * * @since 1.0 * @author Jonathan H. Wage <jonwage@gmail.com> */ class ArrayIterator implements Iterator, ArrayAccess { /** * @var array */ private $elements; /** * @var array */ private $commandResult; /** * Constructor. * * @param array $elements */ public function __construct(array $elements = array()) { $this->elements = $elements; } /** * @see http://php.net/manual/en/countable.count.php */ public function count() { return count($this->elements); } /** * @see http://php.net/manual/en/iterator.current.php */ public function current() { return current($this->elements); } /** * Return the first element in the array, or false if the array is empty. * * @see http://php.net/manual/en/function.reset.php * @return array|object|boolean */ public function first() { return reset($this->elements); } /** * Get the full result document for the Riak command (if available). * * @since 1.1 * @return array|null */ public function getCommandResult() { return $this->commandResult; } /** * Set the full result document for the Riak command. * * @since 1.1 * @param array $commandResult */ public function setCommandResult(array $commandResult) { $this->commandResult = $commandResult; } /** * @see Iterator::getSingleResult() */ public function getSingleResult() { reset($this->elements); $result = key($this->elements) !== null ? current($this->elements) : null; reset($this->elements); return $result; } /** * @see http://php.net/manual/en/iterator.key.php */ public function key() { return key($this->elements); } /** * Return the last element in the array, or false if the array is empty. * * @see http://php.net/manual/en/function.end.php * @return array|object|boolean */ public function last() { return end($this->elements); } /** * @see http://php.net/manual/en/iterator.next.php */ public function next() { next($this->elements); } /** * @see http://php.net/manual/en/arrayaccess.offsetexists.php */ public function offsetExists($offset) { return isset($this->elements[$offset]); } /** * @see http://php.net/manual/en/arrayaccess.offsetget.php */ public function offsetGet($offset) { return isset($this->elements[$offset]) ? $this->elements[$offset] : null; } /** * @see http://php.net/manual/en/arrayaccess.offsetset.php */ public function offsetSet($offset, $value) { if ($offset === null) { $this->elements[] = $value; } else { $this->elements[$offset] = $value; } } /** * @see http://php.net/manual/en/arrayaccess.offsetunset.php */ public function offsetUnset($offset) { unset($this->elements[$offset]); } /** * Alias of {@link ArrayIterator::rewind()}. */ public function reset() { reset($this->elements); } /** * @see http://php.net/manual/en/iterator.rewind.php */ public function rewind() { reset($this->elements); } /** * @see Iterator::toArray() */ public function toArray() { return $this->elements; } /** * @see http://php.net/manual/en/iterator.valid.php */ public function valid() { return key($this->elements) !== null; } }
{ "content_hash": "70b5d2e21ac4a62dbee0862c82402e14", "timestamp": "", "source": "github", "line_count": 191, "max_line_length": 82, "avg_line_length": 20.329842931937172, "alnum_prop": 0.5439093484419264, "repo_name": "cosmow/riak", "id": "81776177320cb75e68661d1adb82f0159fbf93a0", "size": "4864", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/CosmoW/Riak/ArrayIterator.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "426359" } ], "symlink_target": "" }
* Initial release of iOS SDK alpha.
{ "content_hash": "1dafbfe7f2b6aab41c3e88a8c43acb9c", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 35, "avg_line_length": 36, "alnum_prop": 0.75, "repo_name": "wrld3d/ios-api", "id": "c8a2d0a83cca7c976f19527a359dbca71be7d795", "size": "77", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CHANGELOG.md", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "1404" }, { "name": "C++", "bytes": "1266" }, { "name": "Objective-C", "bytes": "162529" }, { "name": "Objective-C++", "bytes": "232575" }, { "name": "Ruby", "bytes": "2491" }, { "name": "Shell", "bytes": "2343" } ], "symlink_target": "" }
// Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). package org.pantsbuild.tools.junit; import java.io.File; import java.io.FileWriter; import java.io.FilterWriter; import java.io.IOException; import java.io.Writer; import java.net.InetAddress; import java.net.UnknownHostException; import java.text.SimpleDateFormat; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.TimeUnit; import javax.xml.bind.JAXB; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlValue; import com.google.common.base.Charsets; import com.google.common.base.Function; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.junit.runner.Description; import org.junit.runner.Result; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunListener; /** * A run listener that creates ant junit xml report compatible output describing a junit run. */ class AntJunitXmlReportListener extends RunListener { /** * A JAXB bean describing a test case exception. These may indicate either an assertion failure * or an uncaught test exception. */ @XmlRootElement static class Exception { private final String message; private final String type; private final String stacktrace; Exception() { // for JAXB message = null; type = null; stacktrace = null; } Exception(Failure failure) { message = failure.getMessage(); type = failure.getException().getClass().getName(); stacktrace = failure.getTrace(); } @XmlAttribute public String getMessage() { return message; } @XmlAttribute public String getType() { return type; } @XmlValue public String getStacktrace() { return stacktrace; } } /** * A JAXB bean describing an individual test method. */ @XmlRootElement(name = "testcase") static class TestCase { private final String classname; private final String name; private String time; private Exception failure; private Exception error; private long startNs; TestCase() { // for JAXB classname = null; name = null; } TestCase(Description test) { classname = test.getClassName(); name = test.getMethodName(); } @XmlAttribute public String getClassname() { return classname; } @XmlAttribute public String getName() { return name; } @XmlAttribute public String getTime() { return time; } @XmlElement public Exception getFailure() { return failure; } public void setFailure(Exception failure) { this.failure = failure; } @XmlElement public Exception getError() { return error; } public void setError(Exception error) { this.error = error; } public void started() { startNs = System.nanoTime(); } public void finished() { time = convertTimeSpanNs(System.nanoTime() - startNs); } } /** * A JAXB bean describing an individual system property. */ @XmlRootElement(name = "property") static class Property { private final String name; private final String value; Property() { // for JAXB name = null; value = null; } Property(String name, String value) { this.name = name; this.value = value; } @XmlAttribute public String getName() { return name; } @XmlAttribute public String getValue() { return value; } } /** * A JAXB bean describing a test class. */ @XmlRootElement(name = "testsuite") static class TestSuite { private final String name; private int errors; private int failures; private String hostname; private int tests; private String time; private String timestamp; private final List<Property> properties = ImmutableList.copyOf( Iterables.transform(System.getProperties().entrySet(), new Function<Entry<Object, Object>, Property>() { @Override public Property apply(Entry<Object, Object> entry) { return new Property(entry.getKey().toString(), entry.getValue().toString()); } })); private final List<TestCase> testCases = Lists.newArrayList(); private String out; private String err; private long startNs; TestSuite() { // for JAXB name = null; } TestSuite(Description test) { name = test.getClassName(); try { hostname = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { hostname = "localhost"; } } @XmlAttribute public int getErrors() { return errors; } @XmlAttribute public int getFailures() { return failures; } @XmlAttribute public String getHostname() { return hostname; } @XmlAttribute public String getName() { return name; } @XmlAttribute public int getTests() { return tests; } @XmlAttribute public String getTime() { return time; } @XmlAttribute public String getTimestamp() { return timestamp; } @XmlElementRef @XmlElementWrapper(name = "properties") public List<Property> getProperties() { return properties; } @XmlElementRef public List<TestCase> getTestCases() { return testCases; } @XmlElement(name = "system-out") public String getOut() { return out; } public void setOut(String out) { this.out = out; } @XmlElement(name = "system-err") public String getErr() { return err; } public void setErr(String err) { this.err = err; } public void started() { if (startNs == 0) { timestamp = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(new Date()); startNs = System.nanoTime(); } } public void finished() { if (++tests == testCases.size()) { time = convertTimeSpanNs(System.nanoTime() - startNs); } } public void incrementFailures() { failures++; } public void incrementErrors() { errors++; } public boolean wasStarted() { return startNs > 0; } } private final Map<Class<?>, TestSuite> suites = Maps.newHashMap(); private final Map<Description, TestCase> cases = Maps.newHashMap(); private final File outdir; private final StreamSource streamSource; AntJunitXmlReportListener(File outdir, StreamSource streamSource) { this.outdir = outdir; this.streamSource = streamSource; } private void createSuites(Iterable<Description> tests) { for (Description test : tests) { createSuites(test.getChildren()); if (Util.isRunnable(test)) { Class<?> testClass = test.getTestClass(); TestSuite suite = suites.get(testClass); if (suite == null) { suite = new TestSuite(test); suites.put(testClass, suite); } TestCase testCase = new TestCase(test); suite.testCases.add(testCase); cases.put(test, testCase); } } } @Override public void testStarted(Description description) throws java.lang.Exception { createSuites(Collections.singletonList(description)); suites.get(description.getTestClass()).started(); cases.get(description).started(); } @Override public void testFailure(Failure failure) throws java.lang.Exception { Exception exception = new Exception(failure); Description description = failure.getDescription(); TestSuite suite = suites.get(description.getTestClass()); TestCase testCase = cases.get(description); if (Util.isAssertionFailure(failure)) { testCase.setFailure(exception); suite.incrementFailures(); } else { testCase.setError(exception); suite.incrementErrors(); } } @Override public void testFinished(Description description) throws java.lang.Exception { cases.get(description).finished(); suites.get(description.getTestClass()).finished(); } @Override public void testRunFinished(Result result) throws java.lang.Exception { for (Entry<Class<?>, TestSuite> entry : suites.entrySet()) { Class<?> testClass = entry.getKey(); TestSuite suite = entry.getValue(); if (suite.wasStarted()) { suite.setOut(new String(streamSource.readOut(testClass), Charsets.UTF_8)); suite.setErr(new String(streamSource.readErr(testClass), Charsets.UTF_8)); Writer xmlOut = new FileWriter(new File(outdir, String.format("TEST-%s.xml", suite.name))); // Only output valid XML1.0 characters - JAXB does not handle this. JAXB.marshal(suite, new XmlWriter(xmlOut) { @Override protected void handleInvalid(int c) throws IOException { out.write(' '); } }); } } } private abstract static class XmlWriter extends FilterWriter { protected XmlWriter(Writer out) { super(out); } @Override public void write(char[] cbuf, int off, int len) throws IOException { for (int i = off; i < len; i++) { write(cbuf[i]); } } @Override public void write(String str, int off, int len) throws IOException { for (int i = off; i < len; i++) { write(str.charAt(i)); } } @Override public void write(int c) throws IOException { // Only output valid XML1.0 characters by default. // See the spec here: http://www.w3.org/TR/2000/REC-xml-20001006#NT-Char // This is a complex boolean expression but it follows the spec referenced above exactly and // so it seems to provide clarity. // SUPPRESS CHECKSTYLE RegexpSinglelineJava if (c == 0x9 || c == 0xA || c == 0xD || ((0x20 <= c) && (c <= 0xD7FF)) || ((0xE000 <= c) && (c <= 0xFFFD)) || ((0x10000 <= c) && (c <= 0x10FFFF))) { out.write(c); } else { handleInvalid(c); } } /** * Subclasses can handle invalid XML 1.0 characters as appropriate. * * @param c The invalid character. * @throws IOException If there is a problem using this stream while handling the invalid * character. */ protected abstract void handleInvalid(int c) throws IOException; } private static String convertTimeSpanNs(long timespanNs) { return String.format("%f", timespanNs / (double) TimeUnit.SECONDS.toNanos(1)); } }
{ "content_hash": "e5a8f79acf46360792b645552085588a", "timestamp": "", "source": "github", "line_count": 442, "max_line_length": 99, "avg_line_length": 24.997737556561084, "alnum_prop": 0.6406009593628382, "repo_name": "pgroudas/pants", "id": "8362091bf5da0d19275f9ba1063892ccbb92798d", "size": "11049", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/java/org/pantsbuild/tools/junit/AntJunitXmlReportListener.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "767" }, { "name": "CSS", "bytes": "10984" }, { "name": "GAP", "bytes": "4818" }, { "name": "HTML", "bytes": "68090" }, { "name": "Java", "bytes": "297674" }, { "name": "JavaScript", "bytes": "10157" }, { "name": "Protocol Buffer", "bytes": "6172" }, { "name": "Python", "bytes": "2868194" }, { "name": "Scala", "bytes": "105948" }, { "name": "Shell", "bytes": "39579" }, { "name": "Thrift", "bytes": "2824" } ], "symlink_target": "" }
.class Landroid/support/v4/media/RatingCompatKitkat; .super Ljava/lang/Object; .source "RatingCompatKitkat.java" # annotations .annotation build Landroid/support/annotation/RequiresApi; value = 0x13 .end annotation # direct methods .method constructor <init>()V .registers 1 .prologue .line 23 invoke-direct {p0}, Ljava/lang/Object;-><init>()V return-void .end method .method public static getPercentRating(Ljava/lang/Object;)F .registers 2 .param p0, "ratingObj" # Ljava/lang/Object; .prologue .line 65 check-cast p0, Landroid/media/Rating; .end local p0 # "ratingObj":Ljava/lang/Object; invoke-virtual {p0}, Landroid/media/Rating;->getPercentRating()F move-result v0 return v0 .end method .method public static getRatingStyle(Ljava/lang/Object;)I .registers 2 .param p0, "ratingObj" # Ljava/lang/Object; .prologue .line 49 check-cast p0, Landroid/media/Rating; .end local p0 # "ratingObj":Ljava/lang/Object; invoke-virtual {p0}, Landroid/media/Rating;->getRatingStyle()I move-result v0 return v0 .end method .method public static getStarRating(Ljava/lang/Object;)F .registers 2 .param p0, "ratingObj" # Ljava/lang/Object; .prologue .line 61 check-cast p0, Landroid/media/Rating; .end local p0 # "ratingObj":Ljava/lang/Object; invoke-virtual {p0}, Landroid/media/Rating;->getStarRating()F move-result v0 return v0 .end method .method public static hasHeart(Ljava/lang/Object;)Z .registers 2 .param p0, "ratingObj" # Ljava/lang/Object; .prologue .line 53 check-cast p0, Landroid/media/Rating; .end local p0 # "ratingObj":Ljava/lang/Object; invoke-virtual {p0}, Landroid/media/Rating;->hasHeart()Z move-result v0 return v0 .end method .method public static isRated(Ljava/lang/Object;)Z .registers 2 .param p0, "ratingObj" # Ljava/lang/Object; .prologue .line 45 check-cast p0, Landroid/media/Rating; .end local p0 # "ratingObj":Ljava/lang/Object; invoke-virtual {p0}, Landroid/media/Rating;->isRated()Z move-result v0 return v0 .end method .method public static isThumbUp(Ljava/lang/Object;)Z .registers 2 .param p0, "ratingObj" # Ljava/lang/Object; .prologue .line 57 check-cast p0, Landroid/media/Rating; .end local p0 # "ratingObj":Ljava/lang/Object; invoke-virtual {p0}, Landroid/media/Rating;->isThumbUp()Z move-result v0 return v0 .end method .method public static newHeartRating(Z)Ljava/lang/Object; .registers 2 .param p0, "hasHeart" # Z .prologue .line 29 invoke-static {p0}, Landroid/media/Rating;->newHeartRating(Z)Landroid/media/Rating; move-result-object v0 return-object v0 .end method .method public static newPercentageRating(F)Ljava/lang/Object; .registers 2 .param p0, "percent" # F .prologue .line 41 invoke-static {p0}, Landroid/media/Rating;->newPercentageRating(F)Landroid/media/Rating; move-result-object v0 return-object v0 .end method .method public static newStarRating(IF)Ljava/lang/Object; .registers 3 .param p0, "starRatingStyle" # I .param p1, "starRating" # F .prologue .line 37 invoke-static {p0, p1}, Landroid/media/Rating;->newStarRating(IF)Landroid/media/Rating; move-result-object v0 return-object v0 .end method .method public static newThumbRating(Z)Ljava/lang/Object; .registers 2 .param p0, "thumbIsUp" # Z .prologue .line 33 invoke-static {p0}, Landroid/media/Rating;->newThumbRating(Z)Landroid/media/Rating; move-result-object v0 return-object v0 .end method .method public static newUnratedRating(I)Ljava/lang/Object; .registers 2 .param p0, "ratingStyle" # I .prologue .line 25 invoke-static {p0}, Landroid/media/Rating;->newUnratedRating(I)Landroid/media/Rating; move-result-object v0 return-object v0 .end method
{ "content_hash": "bd179b3f870dc339672eb5c5d0911c9f", "timestamp": "", "source": "github", "line_count": 183, "max_line_length": 92, "avg_line_length": 22.147540983606557, "alnum_prop": 0.6782630150505798, "repo_name": "AresS31/SCI", "id": "20972c5aa1fad86d93ca1c93eff86a7aeacae6fc", "size": "4053", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "payloads/smali/support/v4/media/RatingCompatKitkat.smali", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "4276" }, { "name": "Python", "bytes": "48120" }, { "name": "Smali", "bytes": "15529276" } ], "symlink_target": "" }
require 'rails_helper' RSpec.describe Contact, type: :model do pending "add some examples to (or delete) #{__FILE__}" end # == Schema Information # # Table name: contacts # # id :integer not null, primary key # name :string # email :string # subject :string # message :text # created_at :datetime not null # updated_at :datetime not null #
{ "content_hash": "72ec3fb20d27b583286c1806b6941866", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 56, "avg_line_length": 22.27777777777778, "alnum_prop": 0.600997506234414, "repo_name": "BigGillyStyle/dealer", "id": "07bee994dd4a2a715156787d058dc13bd66e8429", "size": "401", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/models/contact_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3905" }, { "name": "HTML", "bytes": "26389" }, { "name": "JavaScript", "bytes": "1948" }, { "name": "Ruby", "bytes": "113268" } ], "symlink_target": "" }
#ifndef PNGImageEncoder_h #define PNGImageEncoder_h #include "wtf/Vector.h" class SkBitmap; namespace WebCore { class ImageData; // Interface for encoding PNG data. This is a wrapper around libpng. class PNGImageEncoder { public: static bool encode(const SkBitmap&, Vector<unsigned char>* output); static bool encode(const ImageData&, Vector<unsigned char>* output); }; } // namespace WebCore #endif
{ "content_hash": "30f8c68f693be171cab8a498bfaf2dc8", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 72, "avg_line_length": 18.130434782608695, "alnum_prop": 0.7458033573141487, "repo_name": "indashnet/InDashNet.Open.UN2000", "id": "a8f0ea53d0e2b55796009e2ce17ad74a18ac4332", "size": "1980", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "android/external/chromium_org/third_party/WebKit/Source/core/platform/image-encoders/skia/PNGImageEncoder.h", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php namespace Zotlabs\Tests\Unit\includes; use Zotlabs\Tests\Unit\UnitTestCase; /** * @brief Unit Test case for include/feedutils.php file. */ class FeedutilsTest extends UnitTestCase { public function test_normalise_id() { $this->assertEquals('id', normalise_id('id')); $this->assertEquals('id', normalise_id('X-ZOT:id')); $this->assertEquals('id id2', normalise_id('X-ZOT:id X-ZOT:id2')); $this->assertEmpty(normalise_id('')); } public function test_encode_rel_links() { // invalid params return empty array $this->assertEquals([], encode_rel_links('string')); $this->assertEquals([], encode_rel_links([])); $b = ['attribs' => ['' => [ 'rel' => 'rel_value', 'type' => 'type_value', 'href' => 'href_value' ]]]; $blink1 = ['link1' => $b]; $bresult[] = $b['attribs']['']; $this->assertEquals($bresult, encode_rel_links($blink1)); } /* public function test_encode_rel_links_fail() { $a = [ 'key' => 'value']; $this->assertFalse(encode_rel_links($a)); //Illegal string offset 'attribs' }*/ public function test_atom_author() { $this->assertEquals('', atom_author('', 'nick', 'name', 'uri', 72, 72, 'png', 'photourl')); $a = '<tag> <id>uri</id> <name>nick</name> <uri>uri</uri> <link rel="photo" type="png" media:width="72" media:height="72" href="http://photourl" /> <link rel="avatar" type="png" media:width="72" media:height="72" href="http://photourl" /> <poco:preferredUsername>nick</poco:preferredUsername> <poco:displayName>name<poco:displayName> </tag>'; $this->assertXmlStringEqualsXmlString($a, atom_author('tag', 'nick', 'name', 'uri', 72, 72, 'png', 'http://photourl')); } }
{ "content_hash": "3a993a7e2d47cebd10cfec8b0196f34e", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 121, "avg_line_length": 30.30909090909091, "alnum_prop": 0.629874025194961, "repo_name": "phellmes/hubzilla", "id": "932a1b3a17d714ee2f0c31bf761ece705d38603e", "size": "1667", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/unit/includes/FeedutilsText.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3156" }, { "name": "CSS", "bytes": "968235" }, { "name": "Clojure", "bytes": "2274" }, { "name": "Gherkin", "bytes": "529" }, { "name": "Go", "bytes": "16039" }, { "name": "HTML", "bytes": "4536731" }, { "name": "JavaScript", "bytes": "1505581" }, { "name": "Makefile", "bytes": "3596" }, { "name": "PHP", "bytes": "10004442" }, { "name": "Python", "bytes": "37904" }, { "name": "Ruby", "bytes": "6412" }, { "name": "Shell", "bytes": "79104" }, { "name": "Smarty", "bytes": "604444" } ], "symlink_target": "" }
package com.amazonaws.services.iot.model; import java.io.Serializable; /** * <p> * Describes an action to republish to another topic. * </p> */ public class RepublishAction implements Serializable, Cloneable { /** * <p> * The ARN of the IAM role that grants access. * </p> */ private String roleArn; /** * <p> * The name of the MQTT topic. * </p> */ private String topic; /** * <p> * The ARN of the IAM role that grants access. * </p> * * @param roleArn * The ARN of the IAM role that grants access. */ public void setRoleArn(String roleArn) { this.roleArn = roleArn; } /** * <p> * The ARN of the IAM role that grants access. * </p> * * @return The ARN of the IAM role that grants access. */ public String getRoleArn() { return this.roleArn; } /** * <p> * The ARN of the IAM role that grants access. * </p> * * @param roleArn * The ARN of the IAM role that grants access. * @return Returns a reference to this object so that method calls can be * chained together. */ public RepublishAction withRoleArn(String roleArn) { setRoleArn(roleArn); return this; } /** * <p> * The name of the MQTT topic. * </p> * * @param topic * The name of the MQTT topic. */ public void setTopic(String topic) { this.topic = topic; } /** * <p> * The name of the MQTT topic. * </p> * * @return The name of the MQTT topic. */ public String getTopic() { return this.topic; } /** * <p> * The name of the MQTT topic. * </p> * * @param topic * The name of the MQTT topic. * @return Returns a reference to this object so that method calls can be * chained together. */ public RepublishAction withTopic(String topic) { setTopic(topic); return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getRoleArn() != null) sb.append("RoleArn: " + getRoleArn() + ","); if (getTopic() != null) sb.append("Topic: " + getTopic()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof RepublishAction == false) return false; RepublishAction other = (RepublishAction) obj; if (other.getRoleArn() == null ^ this.getRoleArn() == null) return false; if (other.getRoleArn() != null && other.getRoleArn().equals(this.getRoleArn()) == false) return false; if (other.getTopic() == null ^ this.getTopic() == null) return false; if (other.getTopic() != null && other.getTopic().equals(this.getTopic()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getRoleArn() == null) ? 0 : getRoleArn().hashCode()); hashCode = prime * hashCode + ((getTopic() == null) ? 0 : getTopic().hashCode()); return hashCode; } @Override public RepublishAction clone() { try { return (RepublishAction) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException( "Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
{ "content_hash": "3e6a9c4c1ea8ddbe958cec0206ddebea", "timestamp": "", "source": "github", "line_count": 168, "max_line_length": 77, "avg_line_length": 24.761904761904763, "alnum_prop": 0.5223557692307692, "repo_name": "trasa/aws-sdk-java", "id": "b23de2dc8074d6c5fe0a1c5da38be4fdae4c7c54", "size": "4744", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-iot/src/main/java/com/amazonaws/services/iot/model/RepublishAction.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "100011199" }, { "name": "Scilab", "bytes": "2354" } ], "symlink_target": "" }
{generate_api_description(/user_groups/{user_group_id}:patch)} ## Usage examples {start_tabs} {tab|python} {generate_code_example(python)|/user_groups/{user_group_id}:patch|example} {tab|curl} {generate_code_example(curl)|/user_groups/{user_group_id}:patch|example} {end_tabs} ## Parameters {generate_api_arguments_table|zulip.yaml|/user_groups/{user_group_id}:patch} ## Response #### Example response A typical successful JSON response may look like: {generate_code_example|/user_groups/{user_group_id}:patch|fixture(200)} An example JSON response when the user group ID is invalid: {generate_code_example|/user_groups/{user_group_id}:patch|fixture(400)}
{ "content_hash": "b351b251e164cd03fb06f31eeef886ed", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 76, "avg_line_length": 22.333333333333332, "alnum_prop": 0.744776119402985, "repo_name": "showell/zulip", "id": "7ff04f0846abd1e2b9d8b461991b851a8e0233b5", "size": "693", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "templates/zerver/api/update-user-group.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "433235" }, { "name": "Dockerfile", "bytes": "2941" }, { "name": "Emacs Lisp", "bytes": "157" }, { "name": "HTML", "bytes": "634357" }, { "name": "Handlebars", "bytes": "235334" }, { "name": "JavaScript", "bytes": "3341135" }, { "name": "Perl", "bytes": "8594" }, { "name": "Puppet", "bytes": "79720" }, { "name": "Python", "bytes": "8120030" }, { "name": "Ruby", "bytes": "8480" }, { "name": "Shell", "bytes": "133132" }, { "name": "TypeScript", "bytes": "20603" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <ti:app xmlns:ti="http://ti.appcelerator.org"> <id>com.gebaegabi.snapcontacts2</id> <name>Snap Contacts</name> <version>1.0</version> <publisher>Geovane</publisher> <url>http://</url> <description>not specified</description> <copyright>2013 by Geovane</copyright> <icon>appicon.png</icon> <persistent-wifi>false</persistent-wifi> <prerendered-icon>false</prerendered-icon> <statusbar-style>default</statusbar-style> <statusbar-hidden>false</statusbar-hidden> <fullscreen>false</fullscreen> <navbar-hidden>false</navbar-hidden> <analytics>true</analytics> <guid>c8757214-7f4f-49e7-90af-a8120420c4f1</guid> <property name="ti.ui.defaultunit" type="string">system</property> <iphone> <orientations device="iphone"> <orientation>Ti.UI.PORTRAIT</orientation> </orientations> <orientations device="ipad"> <orientation>Ti.UI.PORTRAIT</orientation> <orientation>Ti.UI.UPSIDE_PORTRAIT</orientation> <orientation>Ti.UI.LANDSCAPE_LEFT</orientation> <orientation>Ti.UI.LANDSCAPE_RIGHT</orientation> </orientations> </iphone> <android xmlns:android="http://schemas.android.com/apk/res/android"/> <mobileweb> <precache/> <splash> <enabled>true</enabled> <inline-css-images>true</inline-css-images> </splash> <theme>default</theme> </mobileweb> <modules> <module platform="iphone">ti.imagefactory</module> <module platform="android">ti.imagefactory</module> </modules> <deployment-targets> <target device="iphone">true</target> <target device="ipad">false</target> <target device="android">true</target> <target device="blackberry">false</target> <target device="mobileweb">true</target> <target device="tizen">false</target> </deployment-targets> <sdk-version>3.1.3.GA</sdk-version> <plugins> <plugin version="1.0">ti.alloy</plugin> </plugins> <property name="ti.deploytype">test</property> </ti:app>
{ "content_hash": "ba79035ec1947f3537fbe9af98c4b7de", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 73, "avg_line_length": 38, "alnum_prop": 0.6403508771929824, "repo_name": "Geeosp/SnapContacts", "id": "10d77fd0e9730d2c9e3a8fdcf6f9f65601032c9b", "size": "2166", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tiapp.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2552" }, { "name": "Java", "bytes": "5384" }, { "name": "JavaScript", "bytes": "316833" }, { "name": "Python", "bytes": "5251" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "f365a2b7049cf7a40534a19ce4198237", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "b20eaf2afc8e7b90f6d51cf924f29128390d17d2", "size": "174", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Caryophyllaceae/Lepigonum/Lepigonum longipes/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
namespace v8 { namespace internal { namespace { enum class ExceptionHandling { kSwallow, kThrow }; bool DoNextStepOnMainThread(Isolate* isolate, CompilerDispatcherJob* job, ExceptionHandling exception_handling) { DCHECK(ThreadId::Current().Equals(isolate->thread_id())); TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.compile"), "V8.CompilerDispatcherForgroundStep"); switch (job->status()) { case CompilerDispatcherJob::Status::kInitial: job->PrepareOnMainThread(isolate); break; case CompilerDispatcherJob::Status::kPrepared: job->Compile(false); break; case CompilerDispatcherJob::Status::kCompiled: job->FinalizeOnMainThread(isolate); break; case CompilerDispatcherJob::Status::kHasErrorsToReport: job->ReportErrorsOnMainThread(isolate); break; case CompilerDispatcherJob::Status::kFailed: case CompilerDispatcherJob::Status::kDone: UNREACHABLE(); } DCHECK_EQ(job->IsFailed(), isolate->has_pending_exception()); if (job->IsFailed() && exception_handling == ExceptionHandling::kSwallow) { isolate->clear_pending_exception(); } return job->IsFailed(); } void DoNextStepOnBackgroundThread(CompilerDispatcherJob* job) { DCHECK(job->NextStepCanRunOnAnyThread()); TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.compile"), "V8.CompilerDispatcherBackgroundStep"); switch (job->status()) { case CompilerDispatcherJob::Status::kPrepared: job->Compile(true); break; default: UNREACHABLE(); } } // Theoretically we get 50ms of idle time max, however it's unlikely that // we'll get all of it so try to be a conservative. const double kMaxIdleTimeToExpectInMs = 40; class MemoryPressureTask : public CancelableTask { public: MemoryPressureTask(Isolate* isolate, CancelableTaskManager* task_manager, CompilerDispatcher* dispatcher); ~MemoryPressureTask() override; // CancelableTask implementation. void RunInternal() override; private: CompilerDispatcher* dispatcher_; DISALLOW_COPY_AND_ASSIGN(MemoryPressureTask); }; MemoryPressureTask::MemoryPressureTask(Isolate* isolate, CancelableTaskManager* task_manager, CompilerDispatcher* dispatcher) : CancelableTask(task_manager), dispatcher_(dispatcher) {} MemoryPressureTask::~MemoryPressureTask() {} void MemoryPressureTask::RunInternal() { dispatcher_->AbortAll(BlockingBehavior::kDontBlock); } } // namespace class CompilerDispatcher::AbortTask : public CancelableTask { public: AbortTask(Isolate* isolate, CancelableTaskManager* task_manager, CompilerDispatcher* dispatcher); ~AbortTask() override; // CancelableTask implementation. void RunInternal() override; private: CompilerDispatcher* dispatcher_; DISALLOW_COPY_AND_ASSIGN(AbortTask); }; CompilerDispatcher::AbortTask::AbortTask(Isolate* isolate, CancelableTaskManager* task_manager, CompilerDispatcher* dispatcher) : CancelableTask(task_manager), dispatcher_(dispatcher) {} CompilerDispatcher::AbortTask::~AbortTask() {} void CompilerDispatcher::AbortTask::RunInternal() { dispatcher_->AbortInactiveJobs(); } class CompilerDispatcher::BackgroundTask : public CancelableTask { public: BackgroundTask(Isolate* isolate, CancelableTaskManager* task_manager, CompilerDispatcher* dispatcher); ~BackgroundTask() override; // CancelableTask implementation. void RunInternal() override; private: CompilerDispatcher* dispatcher_; DISALLOW_COPY_AND_ASSIGN(BackgroundTask); }; CompilerDispatcher::BackgroundTask::BackgroundTask( Isolate* isolate, CancelableTaskManager* task_manager, CompilerDispatcher* dispatcher) : CancelableTask(task_manager), dispatcher_(dispatcher) {} CompilerDispatcher::BackgroundTask::~BackgroundTask() {} void CompilerDispatcher::BackgroundTask::RunInternal() { dispatcher_->DoBackgroundWork(); } class CompilerDispatcher::IdleTask : public CancelableIdleTask { public: IdleTask(Isolate* isolate, CancelableTaskManager* task_manager, CompilerDispatcher* dispatcher); ~IdleTask() override; // CancelableIdleTask implementation. void RunInternal(double deadline_in_seconds) override; private: CompilerDispatcher* dispatcher_; DISALLOW_COPY_AND_ASSIGN(IdleTask); }; CompilerDispatcher::IdleTask::IdleTask(Isolate* isolate, CancelableTaskManager* task_manager, CompilerDispatcher* dispatcher) : CancelableIdleTask(task_manager), dispatcher_(dispatcher) {} CompilerDispatcher::IdleTask::~IdleTask() {} void CompilerDispatcher::IdleTask::RunInternal(double deadline_in_seconds) { dispatcher_->DoIdleWork(deadline_in_seconds); } CompilerDispatcher::CompilerDispatcher(Isolate* isolate, Platform* platform, size_t max_stack_size) : isolate_(isolate), platform_(platform), max_stack_size_(max_stack_size), trace_compiler_dispatcher_(FLAG_trace_compiler_dispatcher), tracer_(new CompilerDispatcherTracer(isolate_)), task_manager_(new CancelableTaskManager()), next_job_id_(0), shared_to_unoptimized_job_id_(isolate->heap()), memory_pressure_level_(MemoryPressureLevel::kNone), abort_(false), idle_task_scheduled_(false), num_background_tasks_(0), main_thread_blocking_on_job_(nullptr), block_for_testing_(false), semaphore_for_testing_(0) { if (trace_compiler_dispatcher_ && !IsEnabled()) { PrintF("CompilerDispatcher: dispatcher is disabled\n"); } } CompilerDispatcher::~CompilerDispatcher() { // To avoid crashing in unit tests due to unfished jobs. AbortAll(BlockingBehavior::kBlock); task_manager_->CancelAndWait(); } bool CompilerDispatcher::CanEnqueue() { if (!IsEnabled()) return false; if (memory_pressure_level_.Value() != MemoryPressureLevel::kNone) { return false; } { base::LockGuard<base::Mutex> lock(&mutex_); if (abort_) return false; } return true; } bool CompilerDispatcher::CanEnqueue(Handle<SharedFunctionInfo> function) { if (!CanEnqueue()) return false; // We only handle functions (no eval / top-level code / native) that are // attached to a script. if (!function->script()->IsScript() || function->is_toplevel() || function->native()) { return false; } return true; } CompilerDispatcher::JobId CompilerDispatcher::Enqueue( std::unique_ptr<CompilerDispatcherJob> job) { DCHECK(!job->IsFinished()); JobMap::const_iterator it = InsertJob(std::move(job)); ConsiderJobForBackgroundProcessing(it->second.get()); ScheduleIdleTaskIfNeeded(); return it->first; } CompilerDispatcher::JobId CompilerDispatcher::EnqueueAndStep( std::unique_ptr<CompilerDispatcherJob> job) { DCHECK(!job->IsFinished()); JobMap::const_iterator it = InsertJob(std::move(job)); if (trace_compiler_dispatcher_) { PrintF("CompilerDispatcher: stepping "); it->second->ShortPrintOnMainThread(); PrintF("\n"); } DoNextStepOnMainThread(isolate_, it->second.get(), ExceptionHandling::kSwallow); ConsiderJobForBackgroundProcessing(it->second.get()); RemoveIfFinished(it); ScheduleIdleTaskIfNeeded(); return it->first; } bool CompilerDispatcher::Enqueue(Handle<SharedFunctionInfo> function) { TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.compile"), "V8.CompilerDispatcherEnqueue"); if (!CanEnqueue(function)) return false; if (IsEnqueued(function)) return true; if (trace_compiler_dispatcher_) { PrintF("CompilerDispatcher: enqueuing "); function->ShortPrint(); PrintF(" for parse and compile\n"); } std::unique_ptr<CompilerDispatcherJob> job(new UnoptimizedCompileJob( isolate_, tracer_.get(), function, max_stack_size_)); Enqueue(std::move(job)); return true; } bool CompilerDispatcher::EnqueueAndStep(Handle<SharedFunctionInfo> function) { TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.compile"), "V8.CompilerDispatcherEnqueueAndStep"); if (!CanEnqueue(function)) return false; if (IsEnqueued(function)) return true; if (trace_compiler_dispatcher_) { PrintF("CompilerDispatcher: enqueuing "); function->ShortPrint(); PrintF(" for parse and compile\n"); } std::unique_ptr<CompilerDispatcherJob> job(new UnoptimizedCompileJob( isolate_, tracer_.get(), function, max_stack_size_)); EnqueueAndStep(std::move(job)); return true; } bool CompilerDispatcher::IsEnabled() const { return FLAG_compiler_dispatcher; } bool CompilerDispatcher::IsEnqueued(Handle<SharedFunctionInfo> function) const { if (jobs_.empty()) return false; return GetJobFor(function) != jobs_.end(); } void CompilerDispatcher::WaitForJobIfRunningOnBackground( CompilerDispatcherJob* job) { TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.compile"), "V8.CompilerDispatcherWaitForBackgroundJob"); RuntimeCallTimerScope runtimeTimer( isolate_, RuntimeCallCounterId::kCompileWaitForDispatcher); base::LockGuard<base::Mutex> lock(&mutex_); if (running_background_jobs_.find(job) == running_background_jobs_.end()) { pending_background_jobs_.erase(job); return; } DCHECK_NULL(main_thread_blocking_on_job_); main_thread_blocking_on_job_ = job; while (main_thread_blocking_on_job_ != nullptr) { main_thread_blocking_signal_.Wait(&mutex_); } DCHECK(pending_background_jobs_.find(job) == pending_background_jobs_.end()); DCHECK(running_background_jobs_.find(job) == running_background_jobs_.end()); } bool CompilerDispatcher::FinishNow(CompilerDispatcherJob* job) { if (trace_compiler_dispatcher_) { PrintF("CompilerDispatcher: finishing "); job->ShortPrintOnMainThread(); PrintF(" now\n"); } WaitForJobIfRunningOnBackground(job); while (!job->IsFinished()) { DoNextStepOnMainThread(isolate_, job, ExceptionHandling::kThrow); } return !job->IsFailed(); } bool CompilerDispatcher::FinishNow(Handle<SharedFunctionInfo> function) { TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.compile"), "V8.CompilerDispatcherFinishNow"); JobMap::const_iterator job = GetJobFor(function); CHECK(job != jobs_.end()); bool result = FinishNow(job->second.get()); RemoveIfFinished(job); return result; } void CompilerDispatcher::FinishAllNow() { // First finish all jobs not running in background for (auto it = jobs_.cbegin(); it != jobs_.cend();) { CompilerDispatcherJob* job = it->second.get(); bool is_running_in_background; { base::LockGuard<base::Mutex> lock(&mutex_); is_running_in_background = running_background_jobs_.find(job) != running_background_jobs_.end(); pending_background_jobs_.erase(job); } if (!is_running_in_background) { while (!job->IsFinished()) { DoNextStepOnMainThread(isolate_, job, ExceptionHandling::kThrow); } it = RemoveIfFinished(it); } else { ++it; } } // Potentially wait for jobs that were running in background for (auto it = jobs_.cbegin(); it != jobs_.cend(); it = RemoveIfFinished(it)) { FinishNow(it->second.get()); } } void CompilerDispatcher::AbortAll(BlockingBehavior blocking) { bool background_tasks_running = task_manager_->TryAbortAll() == CancelableTaskManager::kTaskRunning; if (!background_tasks_running || blocking == BlockingBehavior::kBlock) { for (auto& it : jobs_) { WaitForJobIfRunningOnBackground(it.second.get()); if (trace_compiler_dispatcher_) { PrintF("CompilerDispatcher: aborted "); it.second->ShortPrintOnMainThread(); PrintF("\n"); } it.second->ResetOnMainThread(isolate_); } jobs_.clear(); shared_to_unoptimized_job_id_.Clear(); { base::LockGuard<base::Mutex> lock(&mutex_); DCHECK(pending_background_jobs_.empty()); DCHECK(running_background_jobs_.empty()); abort_ = false; } return; } { base::LockGuard<base::Mutex> lock(&mutex_); abort_ = true; pending_background_jobs_.clear(); } AbortInactiveJobs(); // All running background jobs might already have scheduled idle tasks instead // of abort tasks. Schedule a single abort task here to make sure they get // processed as soon as possible (and not first when we have idle time). ScheduleAbortTask(); } void CompilerDispatcher::AbortInactiveJobs() { { base::LockGuard<base::Mutex> lock(&mutex_); // Since we schedule two abort tasks per async abort, we might end up // here with nothing left to do. if (!abort_) return; } for (auto it = jobs_.cbegin(); it != jobs_.cend();) { auto job = it; ++it; { base::LockGuard<base::Mutex> lock(&mutex_); if (running_background_jobs_.find(job->second.get()) != running_background_jobs_.end()) { continue; } } if (trace_compiler_dispatcher_) { PrintF("CompilerDispatcher: aborted "); job->second->ShortPrintOnMainThread(); PrintF("\n"); } it = RemoveJob(job); } if (jobs_.empty()) { base::LockGuard<base::Mutex> lock(&mutex_); if (num_background_tasks_ == 0) abort_ = false; } } void CompilerDispatcher::MemoryPressureNotification( v8::MemoryPressureLevel level, bool is_isolate_locked) { MemoryPressureLevel previous = memory_pressure_level_.Value(); memory_pressure_level_.SetValue(level); // If we're already under pressure, we haven't accepted new tasks meanwhile // and can just return. If we're no longer under pressure, we're also done. if (previous != MemoryPressureLevel::kNone || level == MemoryPressureLevel::kNone) { return; } if (trace_compiler_dispatcher_) { PrintF("CompilerDispatcher: received memory pressure notification\n"); } if (is_isolate_locked) { AbortAll(BlockingBehavior::kDontBlock); } else { { base::LockGuard<base::Mutex> lock(&mutex_); if (abort_) return; // By going into abort mode here, and clearing the // pending_background_jobs_, we at keep existing background jobs from // picking up more work before the MemoryPressureTask gets executed. abort_ = true; pending_background_jobs_.clear(); } platform_->CallOnForegroundThread( reinterpret_cast<v8::Isolate*>(isolate_), new MemoryPressureTask(isolate_, task_manager_.get(), this)); } } CompilerDispatcher::JobMap::const_iterator CompilerDispatcher::GetJobFor( Handle<SharedFunctionInfo> shared) const { JobId* job_id_ptr = shared_to_unoptimized_job_id_.Find(shared); JobMap::const_iterator job = jobs_.end(); if (job_id_ptr) { job = jobs_.find(*job_id_ptr); DCHECK(job == jobs_.end() || job->second->AsUnoptimizedCompileJob()->IsAssociatedWith(shared)); } return job; } void CompilerDispatcher::ScheduleIdleTaskFromAnyThread() { v8::Isolate* v8_isolate = reinterpret_cast<v8::Isolate*>(isolate_); if (!platform_->IdleTasksEnabled(v8_isolate)) return; { base::LockGuard<base::Mutex> lock(&mutex_); if (idle_task_scheduled_) return; idle_task_scheduled_ = true; } platform_->CallIdleOnForegroundThread( v8_isolate, new IdleTask(isolate_, task_manager_.get(), this)); } void CompilerDispatcher::ScheduleIdleTaskIfNeeded() { if (jobs_.empty()) return; ScheduleIdleTaskFromAnyThread(); } void CompilerDispatcher::ScheduleAbortTask() { v8::Isolate* v8_isolate = reinterpret_cast<v8::Isolate*>(isolate_); platform_->CallOnForegroundThread( v8_isolate, new AbortTask(isolate_, task_manager_.get(), this)); } void CompilerDispatcher::ConsiderJobForBackgroundProcessing( CompilerDispatcherJob* job) { if (!job->NextStepCanRunOnAnyThread()) return; { base::LockGuard<base::Mutex> lock(&mutex_); pending_background_jobs_.insert(job); } ScheduleMoreBackgroundTasksIfNeeded(); } void CompilerDispatcher::ScheduleMoreBackgroundTasksIfNeeded() { TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.compile"), "V8.CompilerDispatcherScheduleMoreBackgroundTasksIfNeeded"); { base::LockGuard<base::Mutex> lock(&mutex_); if (pending_background_jobs_.empty()) return; if (platform_->NumberOfAvailableBackgroundThreads() <= num_background_tasks_) { return; } ++num_background_tasks_; } platform_->CallOnBackgroundThread( new BackgroundTask(isolate_, task_manager_.get(), this), v8::Platform::kShortRunningTask); } void CompilerDispatcher::DoBackgroundWork() { for (;;) { CompilerDispatcherJob* job = nullptr; { base::LockGuard<base::Mutex> lock(&mutex_); if (!pending_background_jobs_.empty()) { auto it = pending_background_jobs_.begin(); job = *it; pending_background_jobs_.erase(it); running_background_jobs_.insert(job); } } if (job == nullptr) break; if (V8_UNLIKELY(block_for_testing_.Value())) { block_for_testing_.SetValue(false); semaphore_for_testing_.Wait(); } if (trace_compiler_dispatcher_) { PrintF("CompilerDispatcher: doing background work\n"); } DoNextStepOnBackgroundThread(job); // Unconditionally schedule an idle task, as all background steps have to be // followed by a main thread step. ScheduleIdleTaskFromAnyThread(); { base::LockGuard<base::Mutex> lock(&mutex_); running_background_jobs_.erase(job); if (main_thread_blocking_on_job_ == job) { main_thread_blocking_on_job_ = nullptr; main_thread_blocking_signal_.NotifyOne(); } } } { base::LockGuard<base::Mutex> lock(&mutex_); --num_background_tasks_; if (running_background_jobs_.empty() && abort_) { // This is the last background job that finished. The abort task // scheduled by AbortAll might already have ran, so schedule another // one to be on the safe side. ScheduleAbortTask(); } } // Don't touch |this| anymore after this point, as it might have been // deleted. } void CompilerDispatcher::DoIdleWork(double deadline_in_seconds) { bool aborted = false; { base::LockGuard<base::Mutex> lock(&mutex_); idle_task_scheduled_ = false; aborted = abort_; } if (aborted) { AbortInactiveJobs(); return; } // Number of jobs that are unlikely to make progress during any idle callback // due to their estimated duration. size_t too_long_jobs = 0; // Iterate over all available jobs & remaining time. For each job, decide // whether to 1) skip it (if it would take too long), 2) erase it (if it's // finished), or 3) make progress on it. double idle_time_in_seconds = deadline_in_seconds - platform_->MonotonicallyIncreasingTime(); if (trace_compiler_dispatcher_) { PrintF("CompilerDispatcher: received %0.1lfms of idle time\n", idle_time_in_seconds * static_cast<double>(base::Time::kMillisecondsPerSecond)); } for (auto job = jobs_.cbegin(); job != jobs_.cend() && idle_time_in_seconds > 0.0; idle_time_in_seconds = deadline_in_seconds - platform_->MonotonicallyIncreasingTime()) { // Don't work on jobs that are being worked on by background tasks. // Similarly, remove jobs we work on from the set of available background // jobs. std::unique_ptr<base::LockGuard<base::Mutex>> lock( new base::LockGuard<base::Mutex>(&mutex_)); if (running_background_jobs_.find(job->second.get()) != running_background_jobs_.end()) { ++job; continue; } auto it = pending_background_jobs_.find(job->second.get()); double estimate_in_ms = job->second->EstimateRuntimeOfNextStepInMs(); if (idle_time_in_seconds < (estimate_in_ms / static_cast<double>(base::Time::kMillisecondsPerSecond))) { // If there's not enough time left, try to estimate whether we would // have managed to finish the job in a large idle task to assess // whether we should ask for another idle callback. if (estimate_in_ms > kMaxIdleTimeToExpectInMs) ++too_long_jobs; if (it == pending_background_jobs_.end()) { lock.reset(); ConsiderJobForBackgroundProcessing(job->second.get()); } ++job; } else if (job->second->IsFinished()) { DCHECK(it == pending_background_jobs_.end()); lock.reset(); job = RemoveJob(job); continue; } else { // Do one step, and keep processing the job (as we don't advance the // iterator). if (it != pending_background_jobs_.end()) { pending_background_jobs_.erase(it); } lock.reset(); DoNextStepOnMainThread(isolate_, job->second.get(), ExceptionHandling::kSwallow); } } if (jobs_.size() > too_long_jobs) ScheduleIdleTaskIfNeeded(); } CompilerDispatcher::JobMap::const_iterator CompilerDispatcher::RemoveIfFinished( JobMap::const_iterator job) { if (!job->second->IsFinished()) { return job; } if (trace_compiler_dispatcher_) { bool result = !job->second->IsFailed(); PrintF("CompilerDispatcher: finished working on "); job->second->ShortPrintOnMainThread(); PrintF(": %s\n", result ? "success" : "failure"); tracer_->DumpStatistics(); } return RemoveJob(job); } CompilerDispatcher::JobMap::const_iterator CompilerDispatcher::InsertJob( std::unique_ptr<CompilerDispatcherJob> job) { bool added; JobMap::const_iterator it; std::tie(it, added) = jobs_.insert(std::make_pair(next_job_id_++, std::move(job))); DCHECK(added); JobId id = it->first; CompilerDispatcherJob* inserted_job = it->second.get(); // Maps unoptimized jobs' SFIs to their job id. if (inserted_job->type() == CompilerDispatcherJob::Type::kUnoptimizedCompile) { Handle<SharedFunctionInfo> shared = inserted_job->AsUnoptimizedCompileJob()->shared(); if (!shared.is_null()) { shared_to_unoptimized_job_id_.Set(shared, id); } } return it; } CompilerDispatcher::JobMap::const_iterator CompilerDispatcher::RemoveJob( CompilerDispatcher::JobMap::const_iterator it) { CompilerDispatcherJob* job = it->second.get(); job->ResetOnMainThread(isolate_); // Unmaps unoptimized jobs' SFIs to their job id. if (job->type() == CompilerDispatcherJob::Type::kUnoptimizedCompile) { Handle<SharedFunctionInfo> shared = job->AsUnoptimizedCompileJob()->shared(); if (!shared.is_null()) { JobId deleted_id = shared_to_unoptimized_job_id_.Delete(shared); USE(deleted_id); DCHECK_EQ(it->first, deleted_id); } } it = jobs_.erase(it); if (jobs_.empty()) { base::LockGuard<base::Mutex> lock(&mutex_); if (num_background_tasks_ == 0) abort_ = false; } return it; } } // namespace internal } // namespace v8
{ "content_hash": "38478bd5e3629a91e333009168c1f4b8", "timestamp": "", "source": "github", "line_count": 712, "max_line_length": 80, "avg_line_length": 32.37078651685393, "alnum_prop": 0.6747657063519611, "repo_name": "MTASZTAKI/ApertusVR", "id": "27af96c85e8a0b35d859e086e8c5b8631b8a1c5e", "size": "23673", "binary": false, "copies": "1", "ref": "refs/heads/0.9", "path": "plugins/languageAPI/jsAPI/3rdParty/nodejs/10.1.0/source/deps/v8/src/compiler-dispatcher/compiler-dispatcher.cc", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "7599" }, { "name": "C++", "bytes": "1207412" }, { "name": "CMake", "bytes": "165066" }, { "name": "CSS", "bytes": "1816" }, { "name": "GLSL", "bytes": "223507" }, { "name": "HLSL", "bytes": "141879" }, { "name": "HTML", "bytes": "34827" }, { "name": "JavaScript", "bytes": "140550" }, { "name": "Python", "bytes": "1370" } ], "symlink_target": "" }
<!--Author: Date: File: Modify2.php Purpose:Chapter 8 Exercise Modify2.html does not need to be changed. Change Modify2.php so that if the entire party (adults and children) is at least 10 there is a 15.00 discount, and if the entire party is at least 6 there is a 10.00 discount. So for example, tickets for a party of 2 adults and 2 children will cost $22.00 tickets for a party of 6 adults and 4 children will cost $42.00 tickets for a party of 4 adults and 2 children will cost $25.00 --> <html> <head> <title>Modify2</title> <link rel ="stylesheet" type="text/css" href="sample.css" > </head> <body> <h1>Modify2</h1> <?php $adultTickets = $_POST['adultTickets']; $childTickets = $_POST['childTickets']; $discount = 0.00; $totalCost = $adultTickets * 6.50 + $childTickets * 4.50 - $discount; print("<p>You ordered $adultTickets adult tickets and $childTickets children's tickets.</p>"); print("<p>Your cost is $$totalCost.</p>"); print("<p>Your discount was $$discount.</p>"); ?> </body> </html>
{ "content_hash": "defe434cf9c4ca28efb0e559bad49906", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 71, "avg_line_length": 25.634146341463413, "alnum_prop": 0.6774500475737393, "repo_name": "iswitzer/cis115", "id": "50f41fda65b72f51502016c90e9594fe3cb4562d", "size": "1051", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "coursework/Chapter08/Modify2.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "13603" }, { "name": "PHP", "bytes": "111142" } ], "symlink_target": "" }
'use strict'; var mixIn = require('mout/object/mixIn'), path = require('path'), fs = require('fs'), statusCodes = require('http').STATUS_CODES, /** * Return true if the error status represents * a client error that should not trigger a * restart. * * @param {number} status * @return {boolean} */ isClientError = function isClientError(status) { return (status >= 400 && status <= 499); }, /** * Attempt a graceful shutdown, and then time * out if the connections fail to drain in time. * * @param {object} o options * @param {object} o.server server object * @param {object} o.timeout timeout in ms * @param {function} exit - force kill function */ close = function close(o, exit) { // We need to kill the server process so // the app can repair itself. Your process // should be monitored in production and // restarted when it shuts down. // // That can be accomplished with modules // like forever, forky, etc... // // First, try a graceful shutdown: if (o.server && typeof o.server.close === 'function') { o.server.close(function () { process.exit(o.exitStatus); }); } // Just in case the server.close() callback // never fires, this will wait for a timeout // and then terminate. Users can override // this function by passing options.shutdown: exit(o); }, /** * Take an error status and return a route that * sends an error with the appropriate status * and message to an error handler via * `next(err)`. * * @param {number} status * @param {string} message * @return {function} Express route handler */ httpError = function httpError (status, message) { var err = new Error(); err.status = status; err.message = message || statusCodes[status] || 'Internal server error'; return function httpErr(req, res, next) { next(err); }; }, sendFile = function sendFile (staticFile, res) { var filePath = path.resolve(staticFile), stream = fs.createReadStream(filePath); stream.pipe(res); }, send = function send(statusCode, err, res, o) { var body = mixIn({}, { status: statusCode, message: err.message || statusCodes[statusCode] }); body = (o.serializer) ? o.serializer(body) : body; res.send(statusCode, body); }, defaults = { handlers: {}, views: {}, static: {}, timeout: 3 * 1000, exitStatus: 1, server: undefined, shutdown: undefined, serializer: undefined, framework: 'express' }, createHandler; /** * A graceful error handler for Express * applications. * * @param {object} [options] * * @param {object} [options.handlers] Custom * handlers for specific status codes. * * @param {object} [options.views] View files to * render in response to specific status * codes. Specify a default with * options.views.default. * * @param {object} [options.static] Static files * to send in response to specific status * codes. Specify a default with * options.static.default. * * @param {number} [options.timeout] Delay * between the graceful shutdown * attempt and the forced shutdown * timeout. * * @param {number} [options.exitStatus] Custom * process exit status code. * * @param {object} [options.server] The app server * object for graceful shutdowns. * * @param {function} [options.shutdown] An * alternative shutdown function if the * graceful shutdown fails. * * @param {function} serializer A function to * customize the JSON error object. * Usage: serializer(err) return errObj * * @param {function} framework Either 'express' * (default) or 'restify'. * * @return {function} errorHandler Express error * handling middleware. */ createHandler = function createHandler(options) { var o = mixIn({}, defaults, options), /** * In case of an error, wait for a timer to * elapse, and then terminate. * @param {object} options * @param {number} o.exitStatus * @param {number} o.timeout */ exit = o.shutdown || function exit(o){ // Give the app time for graceful shutdown. setTimeout(function () { process.exit(o.exitStatus); }, o.timeout); }, express = o.framework === 'express', restify = o.framework === 'restify', errorHandler; /** * Express error handler to handle any * uncaught express errors. For error logging, * see bunyan-request-logger. * * @param {object} err * @param {object} req * @param {object} res * @param {function} next */ errorHandler = function errorHandler(err, req, res, next) { var defaultView = o.views['default'], defaultStatic = o.static['default'], status = err && err.status || res && res.statusCode, handler = o.handlers[status], view = o.views[status], staticFile = o.static[status], renderDefault = function renderDefault(statusCode) { res.statusCode = statusCode; if (defaultView) { return res.render(defaultView, err); } if (defaultStatic) { return sendFile(defaultStatic, res); } if (restify) { send(statusCode, err, res, o); } if (express) { return res.format({ json: function () { send(statusCode, err, res, o); }, text: function () { res.send(statusCode); }, html: function () { res.send(statusCode); } }); } }, resumeOrClose = function resumeOrClose(status) { if (!isClientError(status)) { return close(o, exit); } }; if (!res) { return resumeOrClose(status); } // If there's a custom handler defined, // use it and return. if (typeof handler === 'function') { handler(err, req, res, next); return resumeOrClose(status); } // If there's a custom view defined, // render it. if (view) { res.render(view, err); return resumeOrClose(status); } // If there's a custom static file defined, // render it. if (staticFile) { sendFile(staticFile, res); return resumeOrClose(status); } // If the error is user generated, send // a helpful error message, and don't shut // down. // // If we shutdown on user errors, // attackers can send malformed requests // for the purpose of creating a Denial // Of Service (DOS) attack. if (isClientError(status)) { return renderDefault(status); } // For all other errors, deliver a 500 // error and shut down. renderDefault(500); close(o, exit); }; if (express) { return errorHandler; } if (restify) { return function (req, res, route, err) { return errorHandler(err, req, res); }; } }; createHandler.isClientError = isClientError; createHandler.clientError = function () { var args = [].slice.call(arguments); console.log('WARNING: .clientError() is ' + 'deprecated. Use isClientError() instead.'); return this.isClientError.apply(this, args); }; // HTTP error generating route. createHandler.httpError = httpError; module.exports = createHandler;
{ "content_hash": "18d619ea768aa845a62beaaf04550012", "timestamp": "", "source": "github", "line_count": 305, "max_line_length": 52, "avg_line_length": 25.84262295081967, "alnum_prop": 0.5683836589698046, "repo_name": "pliik/gugamarket", "id": "1c9de8cb2f4cc0b4746786958ff047329ac8a22f", "size": "8119", "binary": false, "copies": "1", "ref": "refs/heads/openshiftv3", "path": "node_modules/express-error-handler/error-handler.js", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "475" }, { "name": "CSS", "bytes": "37350" }, { "name": "HTML", "bytes": "6754" }, { "name": "JavaScript", "bytes": "433099" }, { "name": "Makefile", "bytes": "71" }, { "name": "PHP", "bytes": "32051" }, { "name": "Shell", "bytes": "1328" } ], "symlink_target": "" }
from __future__ import print_function import argparse import json import os import sys import dlrnapi_client from dlrnapi_client.rest import ApiException # Helper class to allow us to convert API response objects into JSON for output class ResponseEncoder(json.JSONEncoder): def default(self, obj): # All the API response objects have a "swagger_types" attribute if hasattr(obj, 'swagger_types'): return obj.to_dict() # Use the default encoder for anything else return json.JSONEncoder.default(self, obj) def get_last_tested_repo(api_instance, options): params = dlrnapi_client.Params() # Params | The JSON params to post params.max_age = options.max_age if options.success: params.success = str(options.success) if options.component: params.component = str(options.component) params.job_id = options.job_id params.sequential_mode = str(options.sequential) params.previous_job_id = options.previous_job_id try: api_response = api_instance.api_last_tested_repo_get(params) return api_response except ApiException as e: raise e def post_last_tested_repo(api_instance, options): params = dlrnapi_client.Params1() # Params1 | The JSON params to post params.max_age = options.max_age params.reporting_job_id = options.reporting_job_id if options.success: params.success = str(options.success) if options.component: params.component = str(options.component) params.job_id = options.job_id params.sequential_mode = str(options.sequential) params.previous_job_id = options.previous_job_id try: api_response = api_instance.api_last_tested_repo_post(params) return api_response except ApiException as e: raise e def repo_status(api_instance, options): params = dlrnapi_client.Params2() # Params2 | The JSON params to post params.commit_hash = options.commit_hash params.distro_hash = options.distro_hash if options.success: params.success = str(options.success) try: api_response = api_instance.api_repo_status_get(params) return api_response except ApiException as e: raise e def agg_status(api_instance, options): params = dlrnapi_client.AggQuery() # AggQuery | The JSON params to post params.aggregate_hash = options.agg_hash if options.success: params.success = str(options.success) try: api_response = api_instance.api_agg_status_get(params) return api_response except ApiException as e: raise e def repo_promote(api_instance, options): params = dlrnapi_client.Promotion() # Promotion | The JSON params to post params.commit_hash = options.commit_hash params.distro_hash = options.distro_hash params.promote_name = options.promote_name try: api_response = api_instance.api_promote_post(params) return api_response except ApiException as e: raise e def repo_promote_batch(api_instance, options): params = list() hash_pairs = options.hash_pairs.split(',') for pair in hash_pairs: commit_hash = pair.split('_')[0] distro_hash = pair.split('_')[1] param = dlrnapi_client.Promotion() param.commit_hash = commit_hash param.distro_hash = distro_hash param.promote_name = options.promote_name params.append(param) try: api_response = api_instance.api_promote_batch_post(params) return api_response except ApiException as e: raise e def get_promotions(api_instance, options): params = dlrnapi_client.PromotionQuery() # PromotionQuery if options.commit_hash: params.commit_hash = options.commit_hash if options.distro_hash: params.distro_hash = options.distro_hash if options.agg_hash: params.aggregate_hash = options.agg_hash if options.promote_name: params.promote_name = options.promote_name if options.offset: params.offset = options.offset if options.limit: params.limit = options.limit if options.component: params.component = options.component try: api_response = api_instance.api_promotions_get(params) return api_response except ApiException as e: raise e def report_result(api_instance, options): params = dlrnapi_client.Params3() # Params3 | The JSON params to post params.job_id = options.job_id params.commit_hash = options.commit_hash params.distro_hash = options.distro_hash params.aggregate_hash = options.agg_hash params.success = str(options.success) params.url = options.info_url params.timestamp = options.timestamp params.notes = options.notes if (params.commit_hash and not params.distro_hash) or\ (not params.commit_hash and params.distro_hash): raise Exception('Both --commit-hash and --distro-hash must be ' 'specified together') if params.aggregate_hash and (params.commit_hash or params.distro_hash): raise Exception('--agg-hash is mutually exclusive with --commit-hash ' 'and --distro-hash') if (not params.aggregate_hash and not params.commit_hash and not params.distro_hash): raise Exception('Must specify either --agg-hash or --commit-hash and ' '--distro-hash') try: api_response = api_instance.api_report_result_post(params) return api_response except ApiException as e: raise e def import_commit(api_instance, options): params = dlrnapi_client.ModelImport() # ModelImport | JSON params to post params.repo_url = options.repo_url try: api_response = api_instance.api_remote_import_post(params) return api_response except ApiException as e: raise e def get_metrics_builds(api_instance, options): # MetricRequest | JSON params to post params = dlrnapi_client.MetricsRequest() params.start_date = options.start_date params.end_date = options.end_date if options.package_name: params.package_name = options.package_name try: api_response = api_instance.api_build_metrics_get(params) return api_response except ApiException as e: raise e command_funcs = { 'repo-get': get_last_tested_repo, 'repo-use': post_last_tested_repo, 'repo-status': repo_status, 'agg-status': agg_status, 'report-result': report_result, 'repo-promote': repo_promote, 'repo-promote-batch': repo_promote_batch, 'commit-import': import_commit, 'promotion-get': get_promotions, 'build-metrics': get_metrics_builds, } def main(): parser = argparse.ArgumentParser(prog='dlrnapi') parser.add_argument('--url', required=True, help='URL to use') parser.add_argument('--username', '-u', help='username for authentication, defaults to ' '"DLRNAPI_USERNAME" environment variable if set', default=os.getenv('DLRNAPI_USERNAME', None) ) parser.add_argument('--password', '-p', help='password for authentication, defaults to ' '"DLRNAPI_PASSWORD" environment variable is set', default=os.getenv('DLRNAPI_PASSWORD', None) ) subparsers = parser.add_subparsers(dest='command', title='subcommands', description='available subcommands') # Subcommand repo-get parser_last = subparsers.add_parser('repo-get', help='Get last tested repo') parser_last.add_argument('--max-age', type=int, default=0, help='max_age') parser_last.add_argument('--success', type=str, default=None, help='Find repos with a successful/unsuccessful ' 'vote, if true or false are specified') parser_last.add_argument('--job-id', type=str, default=None, help='Name of the CI that sent the vote. If not ' 'set, no filter will be set on CI') parser_last.add_argument('--sequential-mode', dest='sequential', action='store_true', help='Use the sequential mode algorithm. In this ' 'case, return the last tested repo within ' 'that timeframe for the CI job described by ' '--previous-job-id') parser_last.set_defaults(sequential=False) parser_last.add_argument('--previous-job-id', type=str, default=None, help='If --sequential-mode is set, look for jobs' ' tested by this CI') parser_last.add_argument('--component', type=str, default=None, required=False, help='Only search for repos related to ' 'this component.') # Subcommand repo-use parser_use_last = subparsers.add_parser('repo-use', help='Get the last tested repo ' 'since a specific time ' '(optionally for a CI job), ' 'and add an "in progress" ' 'entry in the CI job table ' 'for this.') parser_use_last.add_argument('--max-age', type=int, default=0, help='max_age') parser_use_last.add_argument('--reporting-job-id', type=str, required=True, help=' Name of the CI that will add the "in ' 'progress" entry in the CI job table.') parser_use_last.add_argument('--success', type=str, default=None, help='Find repos with a successful/' 'unsuccessful vote, if true or false ' 'are specified') parser_use_last.add_argument('--job-id', type=str, default=None, help='Name of the CI that sent the vote. If ' 'not set, no filter will be set on CI') parser_use_last.add_argument('--sequential-mode', dest='sequential', action='store_true', help='Use the sequential mode algorithm. In ' 'this case, return the last tested repo ' 'within that timeframe for the CI job ' 'described by --previous-job-id') parser_use_last.set_defaults(sequential=False) parser_use_last.add_argument('--previous-job-id', type=str, default=None, help='If --sequential-mode is true, look for ' 'jobs tested by this CI') parser_use_last.add_argument('--component', type=str, default=None, required=False, help='Only search for repos related to ' 'this component.') # Subcommand repo-status parser_st = subparsers.add_parser('repo-status', help='Get all the CI reports for a ' 'specific repository.') parser_st.add_argument('--commit-hash', type=str, required=True, help='commit_hash of the repo to fetch ' 'information for.') parser_st.add_argument('--distro-hash', type=str, required=True, help='distro_hash of the repo to fetch ' 'information for.') parser_st.add_argument('--success', type=str, default=None, help='If set to a value (true/false), only return ' 'the CI reports with the specified vote. If ' 'not set, return all CI reports.') # Subcommand agg-status parser_st = subparsers.add_parser('agg-status', help='Get all the CI reports for a ' 'specific aggregated repository.') parser_st.add_argument('--agg-hash', type=str, required=True, help='hash of the aggregated repo to fetch ' 'information for.') parser_st.add_argument('--success', type=str, default=None, help='If set to a value (true/false), only return ' 'the CI reports with the specified vote. If ' 'not set, return all CI reports.') # Subcommand report-result parser_rep = subparsers.add_parser('report-result', help='Report the result of a CI job') parser_rep.add_argument('--job-id', type=str, required=True, help='Name of the CI sending the vote') parser_rep.add_argument('--commit-hash', type=str, required=False, help='commit_hash of tested repo') parser_rep.add_argument('--distro-hash', type=str, required=False, help='distro_hash of tested repo') parser_rep.add_argument('--agg-hash', type=str, required=False, help='hash of the tested aggregated repo. Note ' 'that either --commit-hash and --distro-hash or' ' --agg-hash must be specified.') parser_rep.add_argument('--info-url', type=str, required=True, help='URL where to find additional information ' 'from the CI execution') parser_rep.add_argument('--timestamp', type=str, required=True, help='Timestamp (in seconds since the epoch)') parser_rep.add_argument('--success', type=str, required=True, help='Was the CI execution successful? Set to ' 'true or false.') parser_rep.add_argument('--notes', type=str, help='Additional notes') # Subcommand promote parser_prom = subparsers.add_parser('repo-promote', help='Promote a repository') parser_prom.add_argument('--commit-hash', type=str, required=True, help='commit_hash of the repo to be promoted') parser_prom.add_argument('--distro-hash', type=str, required=True, help='distro_hash of the repo to be promoted') parser_prom.add_argument('--promote-name', type=str, required=True, help='Name to be used for the promotion') # Subcommand repo-promote-batch parser_prom = subparsers.add_parser('repo-promote-batch', help='Promote multiple repositories ' 'at the same time, as an atomic ' 'operation.') parser_prom.add_argument('--hash-pairs', type=str, required=True, help='commit_hash+distro_hash of the repos to ' 'be promoted, specified as a comma-separated' ' list of commit_distro hash pairs') parser_prom.add_argument('--promote-name', type=str, required=True, help='Name to be used for the promotion') # Subcommand promotion-get parser_promget = subparsers.add_parser('promotion-get', help='Get information about ' 'promotions') parser_promget.add_argument('--commit-hash', type=str, required=False, help='commit_hash of the repo to search ' 'promotions for. Requires --distro-hash ' 'if specified.') parser_promget.add_argument('--distro-hash', type=str, required=False, help='distro_hash of the repo to search ' 'promotions for. Requires --commit-hash ' 'if specified.') parser_promget.add_argument('--agg-hash', type=str, required=False, help='hash of the tested aggregated repo.') parser_promget.add_argument('--promote-name', type=str, required=False, help='Filter results for this promotion name.') parser_promget.add_argument('--offset', type=int, required=False, help='Show results after this offset. Each ' 'query will only return 100 entries by ' 'default.') parser_promget.add_argument('--limit', type=int, required=False, help='Limit the results to the first limit ' 'items') parser_promget.add_argument('--component', type=str, required=False, help='Only search for promotions related to ' 'this component.') # Subcommand commit-import parser_imp = subparsers.add_parser('commit-import', help='Import a commit built by another' ' instance') parser_imp.add_argument('--repo-url', type=str, required=True, help='Base repository URL for the remote repo ' 'to import') # Subcommand build-metrics parser_metrics = subparsers.add_parser( 'build-metrics', help='Fetch build metrics in a time period') parser_metrics.add_argument( '--start-date', type=str, required=True, help='Start date for the query, in YYYY-MM-DD format') parser_metrics.add_argument( '--end-date', type=str, required=True, help='End date for the query, in YYYY-MM-DD format') parser_metrics.add_argument( '--package-name', type=str, required=False, help='If specified, only fetch metrics for this package name') options, args = parser.parse_known_args(sys.argv[1:]) # create an instance of the API class api_client = dlrnapi_client.ApiClient(host=options.url) dlrnapi_client.configuration.username = options.username dlrnapi_client.configuration.password = options.password api_instance = dlrnapi_client.DefaultApi(api_client=api_client) try: api_response = command_funcs[options.command](api_instance, options) print(json.dumps(api_response, cls=ResponseEncoder, indent=2, sort_keys=True)) except ApiException as e: # Handle 404 exceptions gracefully if e.status == 404: print("ERROR: Got error 404, probably endpoint %s is not available" % options.url) return 1 else: raise except Exception as e: raise e
{ "content_hash": "cb173ecc96d318dad977d198f94a3696", "timestamp": "", "source": "github", "line_count": 436, "max_line_length": 79, "avg_line_length": 45.23853211009175, "alnum_prop": 0.5551612249036707, "repo_name": "javierpena/dlrnapi_client", "id": "8cc0e7aed4274d2ddbf41aeced81f9c4a80941d3", "size": "20270", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dlrnapi_client/shell.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "155950" } ], "symlink_target": "" }
package com.playtika.test.grafana; import com.playtika.test.common.spring.DockerPresenceBootstrapConfiguration; import com.playtika.test.common.utils.ContainerUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.MapPropertySource; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.Network; import org.testcontainers.containers.wait.strategy.HttpWaitStrategy; import org.testcontainers.containers.wait.strategy.WaitStrategy; import java.util.LinkedHashMap; import static com.playtika.test.common.utils.ContainerUtils.configureCommonsAndStart; @Slf4j @Configuration @ConditionalOnExpression("${embedded.containers.enabled:true}") @AutoConfigureAfter(DockerPresenceBootstrapConfiguration.class) @ConditionalOnProperty(name = "embedded.grafana.enabled", matchIfMissing = true) @EnableConfigurationProperties(GrafanaProperties.class) public class EmbeddedGrafanaBootstrapConfiguration { @Bean @ConditionalOnMissingBean(name = "grafanaWaitStrategy") public WaitStrategy grafanaWaitStrategy(GrafanaProperties properties) { return new HttpWaitStrategy() .forPath("/") .forPort(properties.getPort()) .forStatusCode(200); } @Bean(name = GrafanaProperties.GRAFANA_BEAN_NAME, destroyMethod = "stop") public GenericContainer grafana(ConfigurableEnvironment environment, GrafanaProperties properties, WaitStrategy grafanaWaitStrategy) { GenericContainer container = new GenericContainer(ContainerUtils.getDockerImageName(properties)) .withEnv("GF_SECURITY_ADMIN_USER", properties.getUsername()) .withEnv("GF_SECURITY_ADMIN_PASSWORD", properties.getPassword()) .withExposedPorts(properties.getPort()) .withNetwork(Network.SHARED) .withNetworkAliases(properties.getNetworkAlias()) .waitingFor(grafanaWaitStrategy); configureCommonsAndStart(container, properties, log); registerEnvironment(container, environment, properties); return container; } private void registerEnvironment(GenericContainer grafana, ConfigurableEnvironment environment, GrafanaProperties properties) { Integer mappedPort = grafana.getMappedPort(properties.port); String host = grafana.getContainerIpAddress(); LinkedHashMap<String, Object> map = new LinkedHashMap<>(); map.put("embedded.grafana.host", host); map.put("embedded.grafana.port", mappedPort); map.put("embedded.grafana.username", properties.getUsername()); map.put("embedded.grafana.password", properties.getPassword()); log.info("Started Grafana server. Connection details: {}", map); MapPropertySource propertySource = new MapPropertySource("embeddedGrafanaInfo", map); environment.getPropertySources().addFirst(propertySource); } }
{ "content_hash": "22720181db7257ce3d7328634a3b5549", "timestamp": "", "source": "github", "line_count": 80, "max_line_length": 93, "avg_line_length": 46.35, "alnum_prop": 0.7273462783171522, "repo_name": "Playtika/testcontainers-spring-boot", "id": "8346652b9590a06a113af973c0d6e6d71a84891b", "size": "3708", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "embedded-grafana/src/main/java/com/playtika/test/grafana/EmbeddedGrafanaBootstrapConfiguration.java", "mode": "33188", "license": "mit", "language": [ { "name": "HCL", "bytes": "218" }, { "name": "HTML", "bytes": "558" }, { "name": "Java", "bytes": "650066" }, { "name": "Lua", "bytes": "175" }, { "name": "Shell", "bytes": "42" } ], "symlink_target": "" }
topoleaf ======== TopoJSON and Leaflet - Replacement for Population Estimates, Census, and Other Potential Projects
{ "content_hash": "65afe428b3787d55ff3cf857e46d675b", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 97, "avg_line_length": 29.25, "alnum_prop": 0.7692307692307693, "repo_name": "rdennist/topoleaf", "id": "769cfb315387a71dd3931a95c649b5f207382cbe", "size": "117", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ namespace Larium\Security\Authentication; use Larium\Executor\Executor; use Larium\Security\Storage\StorageInterface; use Larium\Security\Encoder\PlainTextEncoder; use Larium\Security\User\UserProviderInterface; use Larium\Security\Encoder\PasswordEncoderInterface; class AuthenticationService { const AFTER_AUTHENTICATE = 'after.authenticate'; protected $userProvider; protected $storage; protected $encoder; protected $executor; /** * * @param UserProviderInterface $userProvider * @param StorageInterface $storage * @param PasswordEncoderInterface $encoder */ public function __construct( UserProviderInterface $userProvider, StorageInterface $storage, PasswordEncoderInterface $encoder = null ) { $this->userProvider = $userProvider; $this->storage = $storage; $encoder = $encoder ?: new PlainTextEncoder(); $this->encoder = $encoder; $this->executor = new Executor(); } public function authenticate($username, $password) { try { $this->user = $this->userProvider->getByUsername($username); $result = $this->encoder->validate( $password, $this->user->getCryptedPassword() ); if (true === $result) { $message = new AuthenticationMessage(); $message->setUser($this->user); $this->executor->execute(self::AFTER_AUTHENTICATE, $message); $this->storage->setUser($this->user); $this->storage->save(); } return $result; } catch (UserNotFoundException $e) { throw $e; } } /** * Gets User instance * * @access public * @return UserInterface */ public function getUser() { return $this->user; } /** * Get AuthenticateStorage * * @access public * @return StorageInterface */ public function getAuthenticateStorage() { return $this->storage; } public function isAuthenticated() { $storage_user = $this->storage->getUser(); if (null === $storage_user) { return false; } $user = $this->userProvider->getByUsername($storage_user->getUsername()); $compare = $user->compare($storage_user) && !$this->storage->hasExpired(); if ($compare) { $this->user = $user; } return $compare; } public function addListener($state, $callback) { $this->executor->addCommand($state, $callback); } }
{ "content_hash": "0caac21f338f9267e59ea4bc6b178516", "timestamp": "", "source": "github", "line_count": 118, "max_line_length": 82, "avg_line_length": 23.347457627118644, "alnum_prop": 0.5764065335753176, "repo_name": "Larium/larium_security", "id": "284475b49201a152ae480eb468d8beff919dd0f6", "size": "2755", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Larium/Security/Authentication/AuthenticationService.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "37601" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.5.0_21) on Fri Jun 22 15:32:35 EDT 2012 --> <TITLE> Serialized Form (classes) </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="Serialized Form (classes)"; } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="index.html?serialized-form.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="serialized-form.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H1> Serialized Form</H1> </CENTER> <HR SIZE="4" NOSHADE> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="center"><FONT SIZE="+2"> <B>Package</B> <B>&lt;Unnamed&gt;</B></FONT></TH> </TR> </TABLE> <P> <A NAME="ImageDisplay"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Class <A HREF="ImageDisplay.html" title="class in &lt;Unnamed&gt;">ImageDisplay</A> extends <A HREF="http://java.sun.com/j2se/1.5/docs/api/javax/swing/JPanel.html" title="class or interface in javax.swing">JPanel</A> implements Serializable</B></FONT></TH> </TR> </TABLE> <P> <A NAME="serializedForm"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Serialized Fields</B></FONT></TH> </TR> </TABLE> <H3> image</H3> <PRE> <A HREF="http://java.sun.com/j2se/1.5/docs/api/java/awt/Image.html" title="class or interface in java.awt">Image</A> <B>image</B></PRE> <DL> <DD>the image to draw <P> <DL> </DL> </DL> <HR> <H3> prefSize</H3> <PRE> <A HREF="http://java.sun.com/j2se/1.5/docs/api/java/awt/Dimension.html" title="class or interface in java.awt">Dimension</A> <B>prefSize</B></PRE> <DL> <DD>the preferred size of the display <P> <DL> </DL> </DL> <HR> <H3> currentX</H3> <PRE> int <B>currentX</B></PRE> <DL> <DD>the current x index <P> <DL> </DL> </DL> <HR> <H3> currentY</H3> <PRE> int <B>currentY</B></PRE> <DL> <DD>the current y index <P> <DL> </DL> </DL> <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="index.html?serialized-form.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="serialized-form.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
{ "content_hash": "cf8e99a39fc62a1f6e8833c15ffc0ce6", "timestamp": "", "source": "github", "line_count": 204, "max_line_length": 259, "avg_line_length": 29.220588235294116, "alnum_prop": 0.6317731924173796, "repo_name": "brimstone-/APCompSci", "id": "2a9d6337a50169a52aa7fe71d0d090efdb66f8e1", "size": "5961", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Projects/pixLab/classes/doc/serialized-form.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "6766" }, { "name": "HTML", "bytes": "567512" }, { "name": "Java", "bytes": "378958" } ], "symlink_target": "" }
<?php namespace PHPExiftool\Driver\Tag\Sigma; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class AFMode extends AbstractTag { protected $Id = 5; protected $Name = 'AFMode'; protected $FullName = 'Sigma::Main'; protected $GroupName = 'Sigma'; protected $g0 = 'MakerNotes'; protected $g1 = 'Sigma'; protected $g2 = 'Camera'; protected $Type = 'string'; protected $Writable = true; protected $Description = 'AF Mode'; protected $flag_Permanent = true; }
{ "content_hash": "84543e5b24deb5147eb8715c580832f3", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 46, "avg_line_length": 15.394736842105264, "alnum_prop": 0.652991452991453, "repo_name": "bburnichon/PHPExiftool", "id": "aef1e7cf5a11aeda74d5680bd162438c48f83c64", "size": "809", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/PHPExiftool/Driver/Tag/Sigma/AFMode.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "22076400" } ], "symlink_target": "" }
package com.strategicgains.util; import java.text.ParseException; /** * Defines an interface to convert an object to a text string and back. * * @author toddf * @since Nov 13, 2009 */ public interface TextAdapter<T> { public T parse(String value) throws ParseException; public String format(T value); }
{ "content_hash": "4579d783a309be4026973c8951f968fb", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 71, "avg_line_length": 16.736842105263158, "alnum_prop": 0.7232704402515723, "repo_name": "tfredrich/DateAdapterJ", "id": "ca05bfb0d892b3924c4f9128f79e86d61b8b24c6", "size": "926", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/java/com/strategicgains/util/TextAdapter.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "56863" } ], "symlink_target": "" }
package com.grarak.kerneladiutor.fragments.other; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.widget.AppCompatEditText; import android.text.InputType; import android.view.Gravity; import android.widget.LinearLayout; import com.grarak.kerneladiutor.MainActivity; import com.grarak.kerneladiutor.R; import com.grarak.kerneladiutor.elements.DAdapter; import com.grarak.kerneladiutor.elements.cards.CardViewItem; import com.grarak.kerneladiutor.elements.cards.DDividerCard; import com.grarak.kerneladiutor.elements.cards.PopupCardView; import com.grarak.kerneladiutor.elements.cards.SwitchCardView; import com.grarak.kerneladiutor.fragments.RecyclerViewFragment; import com.grarak.kerneladiutor.services.BootService; import com.grarak.kerneladiutor.utils.Constants; import com.grarak.kerneladiutor.utils.Utils; import com.grarak.kerneladiutor.utils.root.RootUtils; import java.util.ArrayList; import java.util.List; /** * Created by willi on 09.03.15. */ public class SettingsFragment extends RecyclerViewFragment { @Override public boolean showApplyOnBoot() { return false; } @Override public void init(Bundle savedInstanceState) { super.init(savedInstanceState); darkthemeInit(); if (!Resources.getSystem().getConfiguration().locale.getLanguage().startsWith("en") && !Utils.isTV(getActivity())) forceenglishlanguageInit(); if (Constants.VERSION_NAME.contains("beta")) betainfoInit(); applyonbootInit(); debuggingInit(); securityInit(); showSectionsInit(); } private void darkthemeInit() { SwitchCardView.DSwitchCard mDarkthemeCard = new SwitchCardView.DSwitchCard(); mDarkthemeCard.setDescription(getString(R.string.dark_theme)); mDarkthemeCard.setChecked(Utils.DARKTHEME); mDarkthemeCard.setOnDSwitchCardListener(new SwitchCardView.DSwitchCard.OnDSwitchCardListener() { @Override public void onChecked(SwitchCardView.DSwitchCard dSwitchCard, boolean checked) { Utils.saveBoolean("darktheme", checked, getActivity()); startActivity(new Intent(getActivity(), MainActivity.class)); } }); addView(mDarkthemeCard); } private void forceenglishlanguageInit() { SwitchCardView.DSwitchCard mForceEnglishLanguageCard = new SwitchCardView.DSwitchCard(); mForceEnglishLanguageCard.setDescription(getString(R.string.force_english_language)); mForceEnglishLanguageCard.setChecked(Utils.getBoolean("forceenglish", false, getActivity())); mForceEnglishLanguageCard.setOnDSwitchCardListener( new SwitchCardView.DSwitchCard.OnDSwitchCardListener() { @Override public void onChecked(SwitchCardView.DSwitchCard dSwitchCard, boolean checked) { Utils.saveBoolean("forceenglish", checked, getActivity()); if (!checked) Utils.setLocale(Resources.getSystem().getConfiguration().locale.getLanguage(), getActivity()); startActivity(new Intent(getActivity(), MainActivity.class)); } }); addView(mForceEnglishLanguageCard); } private void betainfoInit() { SwitchCardView.DSwitchCard mBetaInfoCard = new SwitchCardView.DSwitchCard(); mBetaInfoCard.setTitle(getString(R.string.beta_info)); mBetaInfoCard.setDescription(getString(R.string.beta_info_summary)); mBetaInfoCard.setChecked(Utils.getBoolean("betainfo", true, getActivity())); mBetaInfoCard.setOnDSwitchCardListener( new SwitchCardView.DSwitchCard.OnDSwitchCardListener() { @Override public void onChecked(SwitchCardView.DSwitchCard dSwitchCard, boolean checked) { Utils.saveBoolean("betainfo", checked, getActivity()); } }); addView(mBetaInfoCard); } private void applyonbootInit() { DDividerCard mApplyonBootDividerCard = new DDividerCard(); mApplyonBootDividerCard.setText(getString(R.string.apply_on_boot)); addView(mApplyonBootDividerCard); if (!Utils.isTV(getActivity())) { SwitchCardView.DSwitchCard mHideApplyOnBootCard = new SwitchCardView.DSwitchCard(); mHideApplyOnBootCard.setTitle(getString(R.string.hide_apply_on_boot)); mHideApplyOnBootCard.setDescription(getString(R.string.hide_apply_on_boot_summary)); mHideApplyOnBootCard.setChecked(Utils.getBoolean("hideapplyonboot", true, getActivity())); mHideApplyOnBootCard.setOnDSwitchCardListener(new SwitchCardView.DSwitchCard.OnDSwitchCardListener() { @Override public void onChecked(SwitchCardView.DSwitchCard dSwitchCard, boolean checked) { Utils.saveBoolean("hideapplyonboot", checked, getActivity()); } }); addView(mHideApplyOnBootCard); } final List<String> list = new ArrayList<>(); for (int i = 5; i < 421; i *= 2) list.add(i + getString(R.string.sec)); PopupCardView.DPopupCard mApplyonbootDelayCard = new PopupCardView.DPopupCard(list); mApplyonbootDelayCard.setDescription(getString(R.string.delay)); mApplyonbootDelayCard.setItem(Utils.getInt("applyonbootdelay", 5, getActivity()) + getString(R.string.sec)); mApplyonbootDelayCard.setOnDPopupCardListener(new PopupCardView.DPopupCard.OnDPopupCardListener() { @Override public void onItemSelected(PopupCardView.DPopupCard dPopupCard, int position) { Utils.saveInt("applyonbootdelay", Utils.stringToInt(list.get(position) .replace(getString(R.string.sec), "")), getActivity()); } }); addView(mApplyonbootDelayCard); SwitchCardView.DSwitchCard mApplyonbootNotificationCard = new SwitchCardView.DSwitchCard(); mApplyonbootNotificationCard.setTitle(getString(R.string.notification)); mApplyonbootNotificationCard.setDescription(getString(R.string.notification_summary)); mApplyonbootNotificationCard.setChecked(Utils.getBoolean("applyonbootnotification", true, getActivity())); mApplyonbootNotificationCard.setOnDSwitchCardListener( new SwitchCardView.DSwitchCard.OnDSwitchCardListener() { @Override public void onChecked(SwitchCardView.DSwitchCard dSwitchCard, boolean checked) { Utils.saveBoolean("applyonbootnotification", checked, getActivity()); } }); addView(mApplyonbootNotificationCard); SwitchCardView.DSwitchCard mShowToastCard = new SwitchCardView.DSwitchCard(); mShowToastCard.setDescription(getString(R.string.show_toast)); mShowToastCard.setChecked(Utils.getBoolean("applyonbootshowtoast", true, getActivity())); mShowToastCard.setOnDSwitchCardListener(new SwitchCardView.DSwitchCard.OnDSwitchCardListener() { @Override public void onChecked(SwitchCardView.DSwitchCard dSwitchCard, boolean checked) { Utils.saveBoolean("applyonbootshowtoast", checked, getActivity()); } }); addView(mShowToastCard); CardViewItem.DCardView mTestCard = new CardViewItem.DCardView(); mTestCard.setTitle(getString(R.string.test)); mTestCard.setDescription(getString(R.string.test_summary)); mTestCard.setOnDCardListener(new CardViewItem.DCardView.OnDCardListener() { @Override public void onClick(CardViewItem.DCardView dCardView) { boolean applyonbootenabled = false; for (DAdapter.DView item : Constants.ITEMS) if (item.getFragment() != null && Utils.getBoolean(item.getFragment().getClass().getSimpleName() + "onboot", false, getActivity())) { applyonbootenabled = true; break; } if (applyonbootenabled) getActivity().startService(new Intent(getActivity(), BootService.class)); else Utils.toast(getString(R.string.enable_apply_on_boot_first), getActivity()); } }); addView(mTestCard); } private void debuggingInit() { DDividerCard mDebuggingDividerCard = new DDividerCard(); mDebuggingDividerCard.setText(getString(R.string.debugging)); addView(mDebuggingDividerCard); CardViewItem.DCardView mLogcatCard = new CardViewItem.DCardView(); mLogcatCard.setTitle(getString(R.string.logcat)); mLogcatCard.setDescription(getString(R.string.logcat_summary)); mLogcatCard.setOnDCardListener(new CardViewItem.DCardView.OnDCardListener() { @Override public void onClick(CardViewItem.DCardView dCardView) { new Execute().execute("logcat -d > /sdcard/logcat.txt"); } }); addView(mLogcatCard); if (Utils.existFile("/proc/last_kmsg")) { CardViewItem.DCardView mLastKmsgCard = new CardViewItem.DCardView(); mLastKmsgCard.setTitle(getString(R.string.last_kmsg)); mLastKmsgCard.setDescription(getString(R.string.last_kmsg_summary)); mLastKmsgCard.setOnDCardListener(new CardViewItem.DCardView.OnDCardListener() { @Override public void onClick(CardViewItem.DCardView dCardView) { new Execute().execute("cat /proc/last_kmsg > /sdcard/last_kmsg.txt"); } }); addView(mLastKmsgCard); } CardViewItem.DCardView mDmesgCard = new CardViewItem.DCardView(); mDmesgCard.setTitle(getString(R.string.driver_message)); mDmesgCard.setDescription(getString(R.string.driver_message_summary)); mDmesgCard.setOnDCardListener(new CardViewItem.DCardView.OnDCardListener() { @Override public void onClick(CardViewItem.DCardView dCardView) { new Execute().execute("dmesg > /sdcard/dmesg.txt"); } }); addView(mDmesgCard); } private class Execute extends AsyncTask<String, Void, Void> { private ProgressDialog progressDialog; @Override protected void onPreExecute() { super.onPreExecute(); progressDialog = new ProgressDialog(getActivity()); progressDialog.setMessage(getString(R.string.execute)); progressDialog.setCancelable(false); progressDialog.show(); } @Override protected Void doInBackground(String... params) { RootUtils.runCommand(params[0]); return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); progressDialog.dismiss(); } } private void securityInit() { DDividerCard mSecurityDividerCard = new DDividerCard(); mSecurityDividerCard.setText(getString(R.string.security)); addView(mSecurityDividerCard); CardViewItem.DCardView mSetPasswordCard = new CardViewItem.DCardView(); mSetPasswordCard.setTitle(getString(R.string.set_password)); mSetPasswordCard.setDescription(getString(R.string.set_password_summary)); mSetPasswordCard.setOnDCardListener(new CardViewItem.DCardView.OnDCardListener() { @Override public void onClick(CardViewItem.DCardView dCardView) { editPasswordDialog(Utils.getString("password", "", getActivity())); } }); addView(mSetPasswordCard); CardViewItem.DCardView mDeletePasswordCard = new CardViewItem.DCardView(); mDeletePasswordCard.setDescription(getString(R.string.delete_password)); mDeletePasswordCard.setOnDCardListener(new CardViewItem.DCardView.OnDCardListener() { @Override public void onClick(CardViewItem.DCardView dCardView) { deletePasswordDialog(Utils.getString("password", "", getActivity())); } }); addView(mDeletePasswordCard); } private void editPasswordDialog(final String oldPass) { LinearLayout linearLayout = new LinearLayout(getActivity()); linearLayout.setOrientation(LinearLayout.VERTICAL); linearLayout.setGravity(Gravity.CENTER); linearLayout.setPadding(30, 20, 30, 20); final AppCompatEditText mOldPassword = new AppCompatEditText(getActivity()); mOldPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); mOldPassword.setHint(getString(R.string.old_password)); if (!oldPass.isEmpty()) linearLayout.addView(mOldPassword); final AppCompatEditText mNewPassword = new AppCompatEditText(getActivity()); mNewPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); mNewPassword.setHint(getString(R.string.new_password)); linearLayout.addView(mNewPassword); final AppCompatEditText mConfirmNewPassword = new AppCompatEditText(getActivity()); mConfirmNewPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); mConfirmNewPassword.setHint(getString(R.string.confirm_new_password)); linearLayout.addView(mConfirmNewPassword); new AlertDialog.Builder(getActivity()).setView(linearLayout) .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }) .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { if (!oldPass.isEmpty() && !mOldPassword.getText().toString().equals(Utils.decodeString(oldPass))) { Utils.toast(getString(R.string.old_password_wrong), getActivity()); return; } if (mNewPassword.getText().toString().isEmpty()) { Utils.toast(getString(R.string.password_empty), getActivity()); return; } if (!mNewPassword.getText().toString().equals(mConfirmNewPassword.getText().toString())) { Utils.toast(getString(R.string.password_not_match), getActivity()); return; } if (mNewPassword.getText().toString().length() > 20) { Utils.toast(getString(R.string.password_too_long), getActivity()); return; } Utils.saveString("password", Utils.encodeString(mNewPassword.getText().toString()), getActivity()); } }).show(); } private void deletePasswordDialog(final String password) { if (password.isEmpty()) { Utils.toast(getString(R.string.set_password_first), getActivity()); return; } LinearLayout linearLayout = new LinearLayout(getActivity()); linearLayout.setOrientation(LinearLayout.VERTICAL); linearLayout.setGravity(Gravity.CENTER); linearLayout.setPadding(30, 20, 30, 20); final AppCompatEditText mPassword = new AppCompatEditText(getActivity()); mPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); mPassword.setHint(getString(R.string.password)); linearLayout.addView(mPassword); new AlertDialog.Builder(getActivity()).setView(linearLayout) .setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { if (!mPassword.getText().toString().equals(Utils.decodeString(password))) { Utils.toast(getString(R.string.password_wrong), getActivity()); return; } Utils.saveString("password", "", getActivity()); } }).show(); } private void showSectionsInit() { DDividerCard mShowSectionsDividerCard = new DDividerCard(); mShowSectionsDividerCard.setText(getString(R.string.show_sections)); addView(mShowSectionsDividerCard); for (final DAdapter.DView section : Constants.ITEMS) { if (section.getFragment() != null && !section.getFragment().getClass().getSimpleName().equals(getClass().getSimpleName())) { SwitchCardView.DSwitchCard mSectionCard = new SwitchCardView.DSwitchCard(); mSectionCard.setDescription(section.getTitle()); mSectionCard.setChecked(Utils.getBoolean(section.getFragment().getClass().getSimpleName() + "visible", true, getActivity())); mSectionCard.setOnDSwitchCardListener(new SwitchCardView.DSwitchCard.OnDSwitchCardListener() { @Override public void onChecked(SwitchCardView.DSwitchCard dSwitchCard, boolean checked) { Utils.saveBoolean(section.getFragment().getClass().getSimpleName() + "visible", checked, getActivity()); ((MainActivity) getActivity()).setItems(SettingsFragment.this); } }); addView(mSectionCard); } } } }
{ "content_hash": "a6129c44bf0d608ed9a2e82421d6bb14", "timestamp": "", "source": "github", "line_count": 403, "max_line_length": 123, "avg_line_length": 45.60545905707196, "alnum_prop": 0.6423091571902715, "repo_name": "LiquidSmooth/android_packages_apps_KernelAdiutor", "id": "c7bb182b72ad0712d664c548101cc75fba5962ce", "size": "18975", "binary": false, "copies": "1", "ref": "refs/heads/lp5.1", "path": "app/src/main/java/com/grarak/kerneladiutor/fragments/other/SettingsFragment.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "934314" }, { "name": "Makefile", "bytes": "4718" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Xml; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; using Wox.Infrastructure; using Wox.Infrastructure.Http; using YAMP.Numerics; namespace Wox.Plugin.SystemPlugins.SuggestionSources { public class Baidu : AbstractSuggestionSource { Regex reg = new Regex("window.baidu.sug\\((.*)\\)"); public override List<string> GetSuggestions(string query) { var result = HttpRequest.Get("http://suggestion.baidu.com/su?json=1&wd=" + Uri.EscapeUriString(query), "GB2312"); if (string.IsNullOrEmpty(result)) return new List<string>(); Match match = reg.Match(result); if (match.Success) { JContainer json = null; try { json =JsonConvert.DeserializeObject(match.Groups[1].Value) as JContainer; } catch{} if (json != null) { var results = json["s"] as JArray; if (results != null) { return results.OfType<JValue>().Select(o => o.Value).OfType<string>().ToList(); } } } return new List<string>(); } } }
{ "content_hash": "1dc157f5c9f81fecc02d7ddf1488ade1", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 125, "avg_line_length": 29.93877551020408, "alnum_prop": 0.5528289025221541, "repo_name": "shangvven/Wox", "id": "edb81bcddd2d65f0cdf4eae342a7fdbb4aaee756", "size": "1469", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Wox.Plugin.SystemPlugins/SuggestionSources/Baidu.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "1199621" }, { "name": "PowerShell", "bytes": "761" }, { "name": "Python", "bytes": "1515969" }, { "name": "Shell", "bytes": "130" } ], "symlink_target": "" }
package com.vaslabs.police_api; /** * Created by vnicolaou on 02/11/15. */ public final class Location { private double latitude; private double longitude; private Street street; public double getLatitude() { return latitude; } public double getLongitude() { return longitude; } public Street getStreet() { return street; } }
{ "content_hash": "bbaa13d470e4018b3dc2f95c427482c8", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 36, "avg_line_length": 17.08695652173913, "alnum_prop": 0.628498727735369, "repo_name": "vaslabs/GuardianBuddy", "id": "1be5ab9f4c106ba6299bc5716c89236b198a9e3a", "size": "393", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/vaslabs/police_api/Location.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "24136" } ], "symlink_target": "" }
package com.microsoft.azure.management.network.v2020_06_01.implementation; import retrofit2.Retrofit; import com.google.common.reflect.TypeToken; import com.microsoft.azure.AzureServiceFuture; import com.microsoft.azure.CloudException; import com.microsoft.azure.ListOperationCallback; import com.microsoft.azure.management.network.v2020_06_01.VpnConnectionPacketCaptureStartParameters; import com.microsoft.azure.management.network.v2020_06_01.VpnConnectionPacketCaptureStopParameters; import com.microsoft.azure.Page; import com.microsoft.azure.PagedList; import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceFuture; import com.microsoft.rest.ServiceResponse; import com.microsoft.rest.Validator; import java.io.IOException; import java.util.List; import okhttp3.ResponseBody; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.Headers; import retrofit2.http.HTTP; import retrofit2.http.Path; import retrofit2.http.POST; import retrofit2.http.PUT; import retrofit2.http.Query; import retrofit2.http.Url; import retrofit2.Response; import rx.functions.Func1; import rx.Observable; import com.microsoft.azure.LongRunningFinalState; import com.microsoft.azure.LongRunningOperationOptions; /** * An instance of this class provides access to all the operations defined * in VpnConnections. */ public class VpnConnectionsInner { /** The Retrofit service to perform REST calls. */ private VpnConnectionsService service; /** The service client containing this operation class. */ private NetworkManagementClientImpl client; /** * Initializes an instance of VpnConnectionsInner. * * @param retrofit the Retrofit instance built from a Retrofit Builder. * @param client the instance of the service client containing this operation class. */ public VpnConnectionsInner(Retrofit retrofit, NetworkManagementClientImpl client) { this.service = retrofit.create(VpnConnectionsService.class); this.client = client; } /** * The interface defining all the services for VpnConnections to be * used by Retrofit to perform actually REST calls. */ interface VpnConnectionsService { @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2020_06_01.VpnConnections get" }) @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}") Observable<Response<ResponseBody>> get(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("gatewayName") String gatewayName, @Path("connectionName") String connectionName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2020_06_01.VpnConnections createOrUpdate" }) @PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}") Observable<Response<ResponseBody>> createOrUpdate(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("gatewayName") String gatewayName, @Path("connectionName") String connectionName, @Query("api-version") String apiVersion, @Body VpnConnectionInner vpnConnectionParameters, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2020_06_01.VpnConnections beginCreateOrUpdate" }) @PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}") Observable<Response<ResponseBody>> beginCreateOrUpdate(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("gatewayName") String gatewayName, @Path("connectionName") String connectionName, @Query("api-version") String apiVersion, @Body VpnConnectionInner vpnConnectionParameters, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2020_06_01.VpnConnections delete" }) @HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}", method = "DELETE", hasBody = true) Observable<Response<ResponseBody>> delete(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("gatewayName") String gatewayName, @Path("connectionName") String connectionName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2020_06_01.VpnConnections beginDelete" }) @HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}", method = "DELETE", hasBody = true) Observable<Response<ResponseBody>> beginDelete(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("gatewayName") String gatewayName, @Path("connectionName") String connectionName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2020_06_01.VpnConnections startPacketCapture" }) @POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{vpnConnectionName}/startpacketcapture") Observable<Response<ResponseBody>> startPacketCapture(@Path("resourceGroupName") String resourceGroupName, @Path("gatewayName") String gatewayName, @Path("vpnConnectionName") String vpnConnectionName, @Path("subscriptionId") String subscriptionId, @Body VpnConnectionPacketCaptureStartParameters parameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2020_06_01.VpnConnections beginStartPacketCapture" }) @POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{vpnConnectionName}/startpacketcapture") Observable<Response<ResponseBody>> beginStartPacketCapture(@Path("resourceGroupName") String resourceGroupName, @Path("gatewayName") String gatewayName, @Path("vpnConnectionName") String vpnConnectionName, @Path("subscriptionId") String subscriptionId, @Body VpnConnectionPacketCaptureStartParameters parameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2020_06_01.VpnConnections stopPacketCapture" }) @POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{vpnConnectionName}/stoppacketcapture") Observable<Response<ResponseBody>> stopPacketCapture(@Path("resourceGroupName") String resourceGroupName, @Path("gatewayName") String gatewayName, @Path("vpnConnectionName") String vpnConnectionName, @Path("subscriptionId") String subscriptionId, @Body VpnConnectionPacketCaptureStopParameters parameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2020_06_01.VpnConnections beginStopPacketCapture" }) @POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{vpnConnectionName}/stoppacketcapture") Observable<Response<ResponseBody>> beginStopPacketCapture(@Path("resourceGroupName") String resourceGroupName, @Path("gatewayName") String gatewayName, @Path("vpnConnectionName") String vpnConnectionName, @Path("subscriptionId") String subscriptionId, @Body VpnConnectionPacketCaptureStopParameters parameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2020_06_01.VpnConnections listByVpnGateway" }) @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections") Observable<Response<ResponseBody>> listByVpnGateway(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("gatewayName") String gatewayName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2020_06_01.VpnConnections listByVpnGatewayNext" }) @GET Observable<Response<ResponseBody>> listByVpnGatewayNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); } /** * Retrieves the details of a vpn connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the vpn connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the VpnConnectionInner object if successful. */ public VpnConnectionInner get(String resourceGroupName, String gatewayName, String connectionName) { return getWithServiceResponseAsync(resourceGroupName, gatewayName, connectionName).toBlocking().single().body(); } /** * Retrieves the details of a vpn connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the vpn connection. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<VpnConnectionInner> getAsync(String resourceGroupName, String gatewayName, String connectionName, final ServiceCallback<VpnConnectionInner> serviceCallback) { return ServiceFuture.fromResponse(getWithServiceResponseAsync(resourceGroupName, gatewayName, connectionName), serviceCallback); } /** * Retrieves the details of a vpn connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the vpn connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the VpnConnectionInner object */ public Observable<VpnConnectionInner> getAsync(String resourceGroupName, String gatewayName, String connectionName) { return getWithServiceResponseAsync(resourceGroupName, gatewayName, connectionName).map(new Func1<ServiceResponse<VpnConnectionInner>, VpnConnectionInner>() { @Override public VpnConnectionInner call(ServiceResponse<VpnConnectionInner> response) { return response.body(); } }); } /** * Retrieves the details of a vpn connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the vpn connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the VpnConnectionInner object */ public Observable<ServiceResponse<VpnConnectionInner>> getWithServiceResponseAsync(String resourceGroupName, String gatewayName, String connectionName) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (gatewayName == null) { throw new IllegalArgumentException("Parameter gatewayName is required and cannot be null."); } if (connectionName == null) { throw new IllegalArgumentException("Parameter connectionName is required and cannot be null."); } final String apiVersion = "2020-06-01"; return service.get(this.client.subscriptionId(), resourceGroupName, gatewayName, connectionName, apiVersion, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<VpnConnectionInner>>>() { @Override public Observable<ServiceResponse<VpnConnectionInner>> call(Response<ResponseBody> response) { try { ServiceResponse<VpnConnectionInner> clientResponse = getDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<VpnConnectionInner> getDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<VpnConnectionInner, CloudException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<VpnConnectionInner>() { }.getType()) .registerError(CloudException.class) .build(response); } /** * Creates a vpn connection to a scalable vpn gateway if it doesn't exist else updates the existing connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the connection. * @param vpnConnectionParameters Parameters supplied to create or Update a VPN Connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the VpnConnectionInner object if successful. */ public VpnConnectionInner createOrUpdate(String resourceGroupName, String gatewayName, String connectionName, VpnConnectionInner vpnConnectionParameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, gatewayName, connectionName, vpnConnectionParameters).toBlocking().last().body(); } /** * Creates a vpn connection to a scalable vpn gateway if it doesn't exist else updates the existing connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the connection. * @param vpnConnectionParameters Parameters supplied to create or Update a VPN Connection. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<VpnConnectionInner> createOrUpdateAsync(String resourceGroupName, String gatewayName, String connectionName, VpnConnectionInner vpnConnectionParameters, final ServiceCallback<VpnConnectionInner> serviceCallback) { return ServiceFuture.fromResponse(createOrUpdateWithServiceResponseAsync(resourceGroupName, gatewayName, connectionName, vpnConnectionParameters), serviceCallback); } /** * Creates a vpn connection to a scalable vpn gateway if it doesn't exist else updates the existing connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the connection. * @param vpnConnectionParameters Parameters supplied to create or Update a VPN Connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ public Observable<VpnConnectionInner> createOrUpdateAsync(String resourceGroupName, String gatewayName, String connectionName, VpnConnectionInner vpnConnectionParameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, gatewayName, connectionName, vpnConnectionParameters).map(new Func1<ServiceResponse<VpnConnectionInner>, VpnConnectionInner>() { @Override public VpnConnectionInner call(ServiceResponse<VpnConnectionInner> response) { return response.body(); } }); } /** * Creates a vpn connection to a scalable vpn gateway if it doesn't exist else updates the existing connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the connection. * @param vpnConnectionParameters Parameters supplied to create or Update a VPN Connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ public Observable<ServiceResponse<VpnConnectionInner>> createOrUpdateWithServiceResponseAsync(String resourceGroupName, String gatewayName, String connectionName, VpnConnectionInner vpnConnectionParameters) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (gatewayName == null) { throw new IllegalArgumentException("Parameter gatewayName is required and cannot be null."); } if (connectionName == null) { throw new IllegalArgumentException("Parameter connectionName is required and cannot be null."); } if (vpnConnectionParameters == null) { throw new IllegalArgumentException("Parameter vpnConnectionParameters is required and cannot be null."); } Validator.validate(vpnConnectionParameters); final String apiVersion = "2020-06-01"; Observable<Response<ResponseBody>> observable = service.createOrUpdate(this.client.subscriptionId(), resourceGroupName, gatewayName, connectionName, apiVersion, vpnConnectionParameters, this.client.acceptLanguage(), this.client.userAgent()); return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken<VpnConnectionInner>() { }.getType()); } /** * Creates a vpn connection to a scalable vpn gateway if it doesn't exist else updates the existing connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the connection. * @param vpnConnectionParameters Parameters supplied to create or Update a VPN Connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the VpnConnectionInner object if successful. */ public VpnConnectionInner beginCreateOrUpdate(String resourceGroupName, String gatewayName, String connectionName, VpnConnectionInner vpnConnectionParameters) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, gatewayName, connectionName, vpnConnectionParameters).toBlocking().single().body(); } /** * Creates a vpn connection to a scalable vpn gateway if it doesn't exist else updates the existing connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the connection. * @param vpnConnectionParameters Parameters supplied to create or Update a VPN Connection. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<VpnConnectionInner> beginCreateOrUpdateAsync(String resourceGroupName, String gatewayName, String connectionName, VpnConnectionInner vpnConnectionParameters, final ServiceCallback<VpnConnectionInner> serviceCallback) { return ServiceFuture.fromResponse(beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, gatewayName, connectionName, vpnConnectionParameters), serviceCallback); } /** * Creates a vpn connection to a scalable vpn gateway if it doesn't exist else updates the existing connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the connection. * @param vpnConnectionParameters Parameters supplied to create or Update a VPN Connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the VpnConnectionInner object */ public Observable<VpnConnectionInner> beginCreateOrUpdateAsync(String resourceGroupName, String gatewayName, String connectionName, VpnConnectionInner vpnConnectionParameters) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, gatewayName, connectionName, vpnConnectionParameters).map(new Func1<ServiceResponse<VpnConnectionInner>, VpnConnectionInner>() { @Override public VpnConnectionInner call(ServiceResponse<VpnConnectionInner> response) { return response.body(); } }); } /** * Creates a vpn connection to a scalable vpn gateway if it doesn't exist else updates the existing connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the connection. * @param vpnConnectionParameters Parameters supplied to create or Update a VPN Connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the VpnConnectionInner object */ public Observable<ServiceResponse<VpnConnectionInner>> beginCreateOrUpdateWithServiceResponseAsync(String resourceGroupName, String gatewayName, String connectionName, VpnConnectionInner vpnConnectionParameters) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (gatewayName == null) { throw new IllegalArgumentException("Parameter gatewayName is required and cannot be null."); } if (connectionName == null) { throw new IllegalArgumentException("Parameter connectionName is required and cannot be null."); } if (vpnConnectionParameters == null) { throw new IllegalArgumentException("Parameter vpnConnectionParameters is required and cannot be null."); } Validator.validate(vpnConnectionParameters); final String apiVersion = "2020-06-01"; return service.beginCreateOrUpdate(this.client.subscriptionId(), resourceGroupName, gatewayName, connectionName, apiVersion, vpnConnectionParameters, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<VpnConnectionInner>>>() { @Override public Observable<ServiceResponse<VpnConnectionInner>> call(Response<ResponseBody> response) { try { ServiceResponse<VpnConnectionInner> clientResponse = beginCreateOrUpdateDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<VpnConnectionInner> beginCreateOrUpdateDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<VpnConnectionInner, CloudException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<VpnConnectionInner>() { }.getType()) .register(201, new TypeToken<VpnConnectionInner>() { }.getType()) .registerError(CloudException.class) .build(response); } /** * Deletes a vpn connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent */ public void delete(String resourceGroupName, String gatewayName, String connectionName) { deleteWithServiceResponseAsync(resourceGroupName, gatewayName, connectionName).toBlocking().last().body(); } /** * Deletes a vpn connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the connection. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<Void> deleteAsync(String resourceGroupName, String gatewayName, String connectionName, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromResponse(deleteWithServiceResponseAsync(resourceGroupName, gatewayName, connectionName), serviceCallback); } /** * Deletes a vpn connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ public Observable<Void> deleteAsync(String resourceGroupName, String gatewayName, String connectionName) { return deleteWithServiceResponseAsync(resourceGroupName, gatewayName, connectionName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); } /** * Deletes a vpn connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ public Observable<ServiceResponse<Void>> deleteWithServiceResponseAsync(String resourceGroupName, String gatewayName, String connectionName) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (gatewayName == null) { throw new IllegalArgumentException("Parameter gatewayName is required and cannot be null."); } if (connectionName == null) { throw new IllegalArgumentException("Parameter connectionName is required and cannot be null."); } final String apiVersion = "2020-06-01"; Observable<Response<ResponseBody>> observable = service.delete(this.client.subscriptionId(), resourceGroupName, gatewayName, connectionName, apiVersion, this.client.acceptLanguage(), this.client.userAgent()); return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken<Void>() { }.getType()); } /** * Deletes a vpn connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent */ public void beginDelete(String resourceGroupName, String gatewayName, String connectionName) { beginDeleteWithServiceResponseAsync(resourceGroupName, gatewayName, connectionName).toBlocking().single().body(); } /** * Deletes a vpn connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the connection. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<Void> beginDeleteAsync(String resourceGroupName, String gatewayName, String connectionName, final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromResponse(beginDeleteWithServiceResponseAsync(resourceGroupName, gatewayName, connectionName), serviceCallback); } /** * Deletes a vpn connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceResponse} object if successful. */ public Observable<Void> beginDeleteAsync(String resourceGroupName, String gatewayName, String connectionName) { return beginDeleteWithServiceResponseAsync(resourceGroupName, gatewayName, connectionName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); } /** * Deletes a vpn connection. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param connectionName The name of the connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceResponse} object if successful. */ public Observable<ServiceResponse<Void>> beginDeleteWithServiceResponseAsync(String resourceGroupName, String gatewayName, String connectionName) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (gatewayName == null) { throw new IllegalArgumentException("Parameter gatewayName is required and cannot be null."); } if (connectionName == null) { throw new IllegalArgumentException("Parameter connectionName is required and cannot be null."); } final String apiVersion = "2020-06-01"; return service.beginDelete(this.client.subscriptionId(), resourceGroupName, gatewayName, connectionName, apiVersion, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() { @Override public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) { try { ServiceResponse<Void> clientResponse = beginDeleteDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<Void> beginDeleteDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<Void, CloudException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<Void>() { }.getType()) .register(202, new TypeToken<Void>() { }.getType()) .register(204, new TypeToken<Void>() { }.getType()) .registerError(CloudException.class) .build(response); } /** * Starts packet capture on Vpn connection in the specified resource group. * * @param resourceGroupName The name of the resource group. * @param gatewayName The name of the gateway. * @param vpnConnectionName The name of the vpn connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the String object if successful. */ public String startPacketCapture(String resourceGroupName, String gatewayName, String vpnConnectionName) { return startPacketCaptureWithServiceResponseAsync(resourceGroupName, gatewayName, vpnConnectionName).toBlocking().last().body(); } /** * Starts packet capture on Vpn connection in the specified resource group. * * @param resourceGroupName The name of the resource group. * @param gatewayName The name of the gateway. * @param vpnConnectionName The name of the vpn connection. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<String> startPacketCaptureAsync(String resourceGroupName, String gatewayName, String vpnConnectionName, final ServiceCallback<String> serviceCallback) { return ServiceFuture.fromResponse(startPacketCaptureWithServiceResponseAsync(resourceGroupName, gatewayName, vpnConnectionName), serviceCallback); } /** * Starts packet capture on Vpn connection in the specified resource group. * * @param resourceGroupName The name of the resource group. * @param gatewayName The name of the gateway. * @param vpnConnectionName The name of the vpn connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ public Observable<String> startPacketCaptureAsync(String resourceGroupName, String gatewayName, String vpnConnectionName) { return startPacketCaptureWithServiceResponseAsync(resourceGroupName, gatewayName, vpnConnectionName).map(new Func1<ServiceResponse<String>, String>() { @Override public String call(ServiceResponse<String> response) { return response.body(); } }); } /** * Starts packet capture on Vpn connection in the specified resource group. * * @param resourceGroupName The name of the resource group. * @param gatewayName The name of the gateway. * @param vpnConnectionName The name of the vpn connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ public Observable<ServiceResponse<String>> startPacketCaptureWithServiceResponseAsync(String resourceGroupName, String gatewayName, String vpnConnectionName) { if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (gatewayName == null) { throw new IllegalArgumentException("Parameter gatewayName is required and cannot be null."); } if (vpnConnectionName == null) { throw new IllegalArgumentException("Parameter vpnConnectionName is required and cannot be null."); } if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } final String apiVersion = "2020-06-01"; final VpnConnectionPacketCaptureStartParameters parameters = null; Observable<Response<ResponseBody>> observable = service.startPacketCapture(resourceGroupName, gatewayName, vpnConnectionName, this.client.subscriptionId(), parameters, apiVersion, this.client.acceptLanguage(), this.client.userAgent()); return client.getAzureClient().getPostOrDeleteResultAsync(observable, new LongRunningOperationOptions().withFinalStateVia(LongRunningFinalState.LOCATION), new TypeToken<String>() { }.getType()); } /** * Starts packet capture on Vpn connection in the specified resource group. * * @param resourceGroupName The name of the resource group. * @param gatewayName The name of the gateway. * @param vpnConnectionName The name of the vpn connection. * @param parameters Vpn Connection packet capture parameters supplied to start packet capture on gateway connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the String object if successful. */ public String startPacketCapture(String resourceGroupName, String gatewayName, String vpnConnectionName, VpnConnectionPacketCaptureStartParameters parameters) { return startPacketCaptureWithServiceResponseAsync(resourceGroupName, gatewayName, vpnConnectionName, parameters).toBlocking().last().body(); } /** * Starts packet capture on Vpn connection in the specified resource group. * * @param resourceGroupName The name of the resource group. * @param gatewayName The name of the gateway. * @param vpnConnectionName The name of the vpn connection. * @param parameters Vpn Connection packet capture parameters supplied to start packet capture on gateway connection. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<String> startPacketCaptureAsync(String resourceGroupName, String gatewayName, String vpnConnectionName, VpnConnectionPacketCaptureStartParameters parameters, final ServiceCallback<String> serviceCallback) { return ServiceFuture.fromResponse(startPacketCaptureWithServiceResponseAsync(resourceGroupName, gatewayName, vpnConnectionName, parameters), serviceCallback); } /** * Starts packet capture on Vpn connection in the specified resource group. * * @param resourceGroupName The name of the resource group. * @param gatewayName The name of the gateway. * @param vpnConnectionName The name of the vpn connection. * @param parameters Vpn Connection packet capture parameters supplied to start packet capture on gateway connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ public Observable<String> startPacketCaptureAsync(String resourceGroupName, String gatewayName, String vpnConnectionName, VpnConnectionPacketCaptureStartParameters parameters) { return startPacketCaptureWithServiceResponseAsync(resourceGroupName, gatewayName, vpnConnectionName, parameters).map(new Func1<ServiceResponse<String>, String>() { @Override public String call(ServiceResponse<String> response) { return response.body(); } }); } /** * Starts packet capture on Vpn connection in the specified resource group. * * @param resourceGroupName The name of the resource group. * @param gatewayName The name of the gateway. * @param vpnConnectionName The name of the vpn connection. * @param parameters Vpn Connection packet capture parameters supplied to start packet capture on gateway connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ public Observable<ServiceResponse<String>> startPacketCaptureWithServiceResponseAsync(String resourceGroupName, String gatewayName, String vpnConnectionName, VpnConnectionPacketCaptureStartParameters parameters) { if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (gatewayName == null) { throw new IllegalArgumentException("Parameter gatewayName is required and cannot be null."); } if (vpnConnectionName == null) { throw new IllegalArgumentException("Parameter vpnConnectionName is required and cannot be null."); } if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } Validator.validate(parameters); final String apiVersion = "2020-06-01"; Observable<Response<ResponseBody>> observable = service.startPacketCapture(resourceGroupName, gatewayName, vpnConnectionName, this.client.subscriptionId(), parameters, apiVersion, this.client.acceptLanguage(), this.client.userAgent()); return client.getAzureClient().getPostOrDeleteResultAsync(observable, new LongRunningOperationOptions().withFinalStateVia(LongRunningFinalState.LOCATION), new TypeToken<String>() { }.getType()); } /** * Starts packet capture on Vpn connection in the specified resource group. * * @param resourceGroupName The name of the resource group. * @param gatewayName The name of the gateway. * @param vpnConnectionName The name of the vpn connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the String object if successful. */ public String beginStartPacketCapture(String resourceGroupName, String gatewayName, String vpnConnectionName) { return beginStartPacketCaptureWithServiceResponseAsync(resourceGroupName, gatewayName, vpnConnectionName).toBlocking().single().body(); } /** * Starts packet capture on Vpn connection in the specified resource group. * * @param resourceGroupName The name of the resource group. * @param gatewayName The name of the gateway. * @param vpnConnectionName The name of the vpn connection. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<String> beginStartPacketCaptureAsync(String resourceGroupName, String gatewayName, String vpnConnectionName, final ServiceCallback<String> serviceCallback) { return ServiceFuture.fromResponse(beginStartPacketCaptureWithServiceResponseAsync(resourceGroupName, gatewayName, vpnConnectionName), serviceCallback); } /** * Starts packet capture on Vpn connection in the specified resource group. * * @param resourceGroupName The name of the resource group. * @param gatewayName The name of the gateway. * @param vpnConnectionName The name of the vpn connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the String object */ public Observable<String> beginStartPacketCaptureAsync(String resourceGroupName, String gatewayName, String vpnConnectionName) { return beginStartPacketCaptureWithServiceResponseAsync(resourceGroupName, gatewayName, vpnConnectionName).map(new Func1<ServiceResponse<String>, String>() { @Override public String call(ServiceResponse<String> response) { return response.body(); } }); } /** * Starts packet capture on Vpn connection in the specified resource group. * * @param resourceGroupName The name of the resource group. * @param gatewayName The name of the gateway. * @param vpnConnectionName The name of the vpn connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the String object */ public Observable<ServiceResponse<String>> beginStartPacketCaptureWithServiceResponseAsync(String resourceGroupName, String gatewayName, String vpnConnectionName) { if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (gatewayName == null) { throw new IllegalArgumentException("Parameter gatewayName is required and cannot be null."); } if (vpnConnectionName == null) { throw new IllegalArgumentException("Parameter vpnConnectionName is required and cannot be null."); } if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } final String apiVersion = "2020-06-01"; final VpnConnectionPacketCaptureStartParameters parameters = null; return service.beginStartPacketCapture(resourceGroupName, gatewayName, vpnConnectionName, this.client.subscriptionId(), parameters, apiVersion, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<String>>>() { @Override public Observable<ServiceResponse<String>> call(Response<ResponseBody> response) { try { ServiceResponse<String> clientResponse = beginStartPacketCaptureDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } /** * Starts packet capture on Vpn connection in the specified resource group. * * @param resourceGroupName The name of the resource group. * @param gatewayName The name of the gateway. * @param vpnConnectionName The name of the vpn connection. * @param parameters Vpn Connection packet capture parameters supplied to start packet capture on gateway connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the String object if successful. */ public String beginStartPacketCapture(String resourceGroupName, String gatewayName, String vpnConnectionName, VpnConnectionPacketCaptureStartParameters parameters) { return beginStartPacketCaptureWithServiceResponseAsync(resourceGroupName, gatewayName, vpnConnectionName, parameters).toBlocking().single().body(); } /** * Starts packet capture on Vpn connection in the specified resource group. * * @param resourceGroupName The name of the resource group. * @param gatewayName The name of the gateway. * @param vpnConnectionName The name of the vpn connection. * @param parameters Vpn Connection packet capture parameters supplied to start packet capture on gateway connection. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<String> beginStartPacketCaptureAsync(String resourceGroupName, String gatewayName, String vpnConnectionName, VpnConnectionPacketCaptureStartParameters parameters, final ServiceCallback<String> serviceCallback) { return ServiceFuture.fromResponse(beginStartPacketCaptureWithServiceResponseAsync(resourceGroupName, gatewayName, vpnConnectionName, parameters), serviceCallback); } /** * Starts packet capture on Vpn connection in the specified resource group. * * @param resourceGroupName The name of the resource group. * @param gatewayName The name of the gateway. * @param vpnConnectionName The name of the vpn connection. * @param parameters Vpn Connection packet capture parameters supplied to start packet capture on gateway connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the String object */ public Observable<String> beginStartPacketCaptureAsync(String resourceGroupName, String gatewayName, String vpnConnectionName, VpnConnectionPacketCaptureStartParameters parameters) { return beginStartPacketCaptureWithServiceResponseAsync(resourceGroupName, gatewayName, vpnConnectionName, parameters).map(new Func1<ServiceResponse<String>, String>() { @Override public String call(ServiceResponse<String> response) { return response.body(); } }); } /** * Starts packet capture on Vpn connection in the specified resource group. * * @param resourceGroupName The name of the resource group. * @param gatewayName The name of the gateway. * @param vpnConnectionName The name of the vpn connection. * @param parameters Vpn Connection packet capture parameters supplied to start packet capture on gateway connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the String object */ public Observable<ServiceResponse<String>> beginStartPacketCaptureWithServiceResponseAsync(String resourceGroupName, String gatewayName, String vpnConnectionName, VpnConnectionPacketCaptureStartParameters parameters) { if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (gatewayName == null) { throw new IllegalArgumentException("Parameter gatewayName is required and cannot be null."); } if (vpnConnectionName == null) { throw new IllegalArgumentException("Parameter vpnConnectionName is required and cannot be null."); } if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } Validator.validate(parameters); final String apiVersion = "2020-06-01"; return service.beginStartPacketCapture(resourceGroupName, gatewayName, vpnConnectionName, this.client.subscriptionId(), parameters, apiVersion, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<String>>>() { @Override public Observable<ServiceResponse<String>> call(Response<ResponseBody> response) { try { ServiceResponse<String> clientResponse = beginStartPacketCaptureDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<String> beginStartPacketCaptureDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<String, CloudException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<String>() { }.getType()) .register(202, new TypeToken<Void>() { }.getType()) .registerError(CloudException.class) .build(response); } /** * Stops packet capture on Vpn connection in the specified resource group. * * @param resourceGroupName The name of the resource group. * @param gatewayName The name of the gateway. * @param vpnConnectionName The name of the vpn connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the String object if successful. */ public String stopPacketCapture(String resourceGroupName, String gatewayName, String vpnConnectionName) { return stopPacketCaptureWithServiceResponseAsync(resourceGroupName, gatewayName, vpnConnectionName).toBlocking().last().body(); } /** * Stops packet capture on Vpn connection in the specified resource group. * * @param resourceGroupName The name of the resource group. * @param gatewayName The name of the gateway. * @param vpnConnectionName The name of the vpn connection. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<String> stopPacketCaptureAsync(String resourceGroupName, String gatewayName, String vpnConnectionName, final ServiceCallback<String> serviceCallback) { return ServiceFuture.fromResponse(stopPacketCaptureWithServiceResponseAsync(resourceGroupName, gatewayName, vpnConnectionName), serviceCallback); } /** * Stops packet capture on Vpn connection in the specified resource group. * * @param resourceGroupName The name of the resource group. * @param gatewayName The name of the gateway. * @param vpnConnectionName The name of the vpn connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ public Observable<String> stopPacketCaptureAsync(String resourceGroupName, String gatewayName, String vpnConnectionName) { return stopPacketCaptureWithServiceResponseAsync(resourceGroupName, gatewayName, vpnConnectionName).map(new Func1<ServiceResponse<String>, String>() { @Override public String call(ServiceResponse<String> response) { return response.body(); } }); } /** * Stops packet capture on Vpn connection in the specified resource group. * * @param resourceGroupName The name of the resource group. * @param gatewayName The name of the gateway. * @param vpnConnectionName The name of the vpn connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ public Observable<ServiceResponse<String>> stopPacketCaptureWithServiceResponseAsync(String resourceGroupName, String gatewayName, String vpnConnectionName) { if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (gatewayName == null) { throw new IllegalArgumentException("Parameter gatewayName is required and cannot be null."); } if (vpnConnectionName == null) { throw new IllegalArgumentException("Parameter vpnConnectionName is required and cannot be null."); } if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } final String apiVersion = "2020-06-01"; final VpnConnectionPacketCaptureStopParameters parameters = null; Observable<Response<ResponseBody>> observable = service.stopPacketCapture(resourceGroupName, gatewayName, vpnConnectionName, this.client.subscriptionId(), parameters, apiVersion, this.client.acceptLanguage(), this.client.userAgent()); return client.getAzureClient().getPostOrDeleteResultAsync(observable, new LongRunningOperationOptions().withFinalStateVia(LongRunningFinalState.LOCATION), new TypeToken<String>() { }.getType()); } /** * Stops packet capture on Vpn connection in the specified resource group. * * @param resourceGroupName The name of the resource group. * @param gatewayName The name of the gateway. * @param vpnConnectionName The name of the vpn connection. * @param parameters Vpn Connection packet capture parameters supplied to stop packet capture on gateway connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the String object if successful. */ public String stopPacketCapture(String resourceGroupName, String gatewayName, String vpnConnectionName, VpnConnectionPacketCaptureStopParameters parameters) { return stopPacketCaptureWithServiceResponseAsync(resourceGroupName, gatewayName, vpnConnectionName, parameters).toBlocking().last().body(); } /** * Stops packet capture on Vpn connection in the specified resource group. * * @param resourceGroupName The name of the resource group. * @param gatewayName The name of the gateway. * @param vpnConnectionName The name of the vpn connection. * @param parameters Vpn Connection packet capture parameters supplied to stop packet capture on gateway connection. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<String> stopPacketCaptureAsync(String resourceGroupName, String gatewayName, String vpnConnectionName, VpnConnectionPacketCaptureStopParameters parameters, final ServiceCallback<String> serviceCallback) { return ServiceFuture.fromResponse(stopPacketCaptureWithServiceResponseAsync(resourceGroupName, gatewayName, vpnConnectionName, parameters), serviceCallback); } /** * Stops packet capture on Vpn connection in the specified resource group. * * @param resourceGroupName The name of the resource group. * @param gatewayName The name of the gateway. * @param vpnConnectionName The name of the vpn connection. * @param parameters Vpn Connection packet capture parameters supplied to stop packet capture on gateway connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ public Observable<String> stopPacketCaptureAsync(String resourceGroupName, String gatewayName, String vpnConnectionName, VpnConnectionPacketCaptureStopParameters parameters) { return stopPacketCaptureWithServiceResponseAsync(resourceGroupName, gatewayName, vpnConnectionName, parameters).map(new Func1<ServiceResponse<String>, String>() { @Override public String call(ServiceResponse<String> response) { return response.body(); } }); } /** * Stops packet capture on Vpn connection in the specified resource group. * * @param resourceGroupName The name of the resource group. * @param gatewayName The name of the gateway. * @param vpnConnectionName The name of the vpn connection. * @param parameters Vpn Connection packet capture parameters supplied to stop packet capture on gateway connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable for the request */ public Observable<ServiceResponse<String>> stopPacketCaptureWithServiceResponseAsync(String resourceGroupName, String gatewayName, String vpnConnectionName, VpnConnectionPacketCaptureStopParameters parameters) { if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (gatewayName == null) { throw new IllegalArgumentException("Parameter gatewayName is required and cannot be null."); } if (vpnConnectionName == null) { throw new IllegalArgumentException("Parameter vpnConnectionName is required and cannot be null."); } if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } Validator.validate(parameters); final String apiVersion = "2020-06-01"; Observable<Response<ResponseBody>> observable = service.stopPacketCapture(resourceGroupName, gatewayName, vpnConnectionName, this.client.subscriptionId(), parameters, apiVersion, this.client.acceptLanguage(), this.client.userAgent()); return client.getAzureClient().getPostOrDeleteResultAsync(observable, new LongRunningOperationOptions().withFinalStateVia(LongRunningFinalState.LOCATION), new TypeToken<String>() { }.getType()); } /** * Stops packet capture on Vpn connection in the specified resource group. * * @param resourceGroupName The name of the resource group. * @param gatewayName The name of the gateway. * @param vpnConnectionName The name of the vpn connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the String object if successful. */ public String beginStopPacketCapture(String resourceGroupName, String gatewayName, String vpnConnectionName) { return beginStopPacketCaptureWithServiceResponseAsync(resourceGroupName, gatewayName, vpnConnectionName).toBlocking().single().body(); } /** * Stops packet capture on Vpn connection in the specified resource group. * * @param resourceGroupName The name of the resource group. * @param gatewayName The name of the gateway. * @param vpnConnectionName The name of the vpn connection. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<String> beginStopPacketCaptureAsync(String resourceGroupName, String gatewayName, String vpnConnectionName, final ServiceCallback<String> serviceCallback) { return ServiceFuture.fromResponse(beginStopPacketCaptureWithServiceResponseAsync(resourceGroupName, gatewayName, vpnConnectionName), serviceCallback); } /** * Stops packet capture on Vpn connection in the specified resource group. * * @param resourceGroupName The name of the resource group. * @param gatewayName The name of the gateway. * @param vpnConnectionName The name of the vpn connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the String object */ public Observable<String> beginStopPacketCaptureAsync(String resourceGroupName, String gatewayName, String vpnConnectionName) { return beginStopPacketCaptureWithServiceResponseAsync(resourceGroupName, gatewayName, vpnConnectionName).map(new Func1<ServiceResponse<String>, String>() { @Override public String call(ServiceResponse<String> response) { return response.body(); } }); } /** * Stops packet capture on Vpn connection in the specified resource group. * * @param resourceGroupName The name of the resource group. * @param gatewayName The name of the gateway. * @param vpnConnectionName The name of the vpn connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the String object */ public Observable<ServiceResponse<String>> beginStopPacketCaptureWithServiceResponseAsync(String resourceGroupName, String gatewayName, String vpnConnectionName) { if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (gatewayName == null) { throw new IllegalArgumentException("Parameter gatewayName is required and cannot be null."); } if (vpnConnectionName == null) { throw new IllegalArgumentException("Parameter vpnConnectionName is required and cannot be null."); } if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } final String apiVersion = "2020-06-01"; final VpnConnectionPacketCaptureStopParameters parameters = null; return service.beginStopPacketCapture(resourceGroupName, gatewayName, vpnConnectionName, this.client.subscriptionId(), parameters, apiVersion, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<String>>>() { @Override public Observable<ServiceResponse<String>> call(Response<ResponseBody> response) { try { ServiceResponse<String> clientResponse = beginStopPacketCaptureDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } /** * Stops packet capture on Vpn connection in the specified resource group. * * @param resourceGroupName The name of the resource group. * @param gatewayName The name of the gateway. * @param vpnConnectionName The name of the vpn connection. * @param parameters Vpn Connection packet capture parameters supplied to stop packet capture on gateway connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the String object if successful. */ public String beginStopPacketCapture(String resourceGroupName, String gatewayName, String vpnConnectionName, VpnConnectionPacketCaptureStopParameters parameters) { return beginStopPacketCaptureWithServiceResponseAsync(resourceGroupName, gatewayName, vpnConnectionName, parameters).toBlocking().single().body(); } /** * Stops packet capture on Vpn connection in the specified resource group. * * @param resourceGroupName The name of the resource group. * @param gatewayName The name of the gateway. * @param vpnConnectionName The name of the vpn connection. * @param parameters Vpn Connection packet capture parameters supplied to stop packet capture on gateway connection. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<String> beginStopPacketCaptureAsync(String resourceGroupName, String gatewayName, String vpnConnectionName, VpnConnectionPacketCaptureStopParameters parameters, final ServiceCallback<String> serviceCallback) { return ServiceFuture.fromResponse(beginStopPacketCaptureWithServiceResponseAsync(resourceGroupName, gatewayName, vpnConnectionName, parameters), serviceCallback); } /** * Stops packet capture on Vpn connection in the specified resource group. * * @param resourceGroupName The name of the resource group. * @param gatewayName The name of the gateway. * @param vpnConnectionName The name of the vpn connection. * @param parameters Vpn Connection packet capture parameters supplied to stop packet capture on gateway connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the String object */ public Observable<String> beginStopPacketCaptureAsync(String resourceGroupName, String gatewayName, String vpnConnectionName, VpnConnectionPacketCaptureStopParameters parameters) { return beginStopPacketCaptureWithServiceResponseAsync(resourceGroupName, gatewayName, vpnConnectionName, parameters).map(new Func1<ServiceResponse<String>, String>() { @Override public String call(ServiceResponse<String> response) { return response.body(); } }); } /** * Stops packet capture on Vpn connection in the specified resource group. * * @param resourceGroupName The name of the resource group. * @param gatewayName The name of the gateway. * @param vpnConnectionName The name of the vpn connection. * @param parameters Vpn Connection packet capture parameters supplied to stop packet capture on gateway connection. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the String object */ public Observable<ServiceResponse<String>> beginStopPacketCaptureWithServiceResponseAsync(String resourceGroupName, String gatewayName, String vpnConnectionName, VpnConnectionPacketCaptureStopParameters parameters) { if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (gatewayName == null) { throw new IllegalArgumentException("Parameter gatewayName is required and cannot be null."); } if (vpnConnectionName == null) { throw new IllegalArgumentException("Parameter vpnConnectionName is required and cannot be null."); } if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } Validator.validate(parameters); final String apiVersion = "2020-06-01"; return service.beginStopPacketCapture(resourceGroupName, gatewayName, vpnConnectionName, this.client.subscriptionId(), parameters, apiVersion, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<String>>>() { @Override public Observable<ServiceResponse<String>> call(Response<ResponseBody> response) { try { ServiceResponse<String> clientResponse = beginStopPacketCaptureDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<String> beginStopPacketCaptureDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<String, CloudException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<String>() { }.getType()) .register(202, new TypeToken<Void>() { }.getType()) .registerError(CloudException.class) .build(response); } /** * Retrieves all vpn connections for a particular virtual wan vpn gateway. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the PagedList&lt;VpnConnectionInner&gt; object if successful. */ public PagedList<VpnConnectionInner> listByVpnGateway(final String resourceGroupName, final String gatewayName) { ServiceResponse<Page<VpnConnectionInner>> response = listByVpnGatewaySinglePageAsync(resourceGroupName, gatewayName).toBlocking().single(); return new PagedList<VpnConnectionInner>(response.body()) { @Override public Page<VpnConnectionInner> nextPage(String nextPageLink) { return listByVpnGatewayNextSinglePageAsync(nextPageLink).toBlocking().single().body(); } }; } /** * Retrieves all vpn connections for a particular virtual wan vpn gateway. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<List<VpnConnectionInner>> listByVpnGatewayAsync(final String resourceGroupName, final String gatewayName, final ListOperationCallback<VpnConnectionInner> serviceCallback) { return AzureServiceFuture.fromPageResponse( listByVpnGatewaySinglePageAsync(resourceGroupName, gatewayName), new Func1<String, Observable<ServiceResponse<Page<VpnConnectionInner>>>>() { @Override public Observable<ServiceResponse<Page<VpnConnectionInner>>> call(String nextPageLink) { return listByVpnGatewayNextSinglePageAsync(nextPageLink); } }, serviceCallback); } /** * Retrieves all vpn connections for a particular virtual wan vpn gateway. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;VpnConnectionInner&gt; object */ public Observable<Page<VpnConnectionInner>> listByVpnGatewayAsync(final String resourceGroupName, final String gatewayName) { return listByVpnGatewayWithServiceResponseAsync(resourceGroupName, gatewayName) .map(new Func1<ServiceResponse<Page<VpnConnectionInner>>, Page<VpnConnectionInner>>() { @Override public Page<VpnConnectionInner> call(ServiceResponse<Page<VpnConnectionInner>> response) { return response.body(); } }); } /** * Retrieves all vpn connections for a particular virtual wan vpn gateway. * * @param resourceGroupName The resource group name of the VpnGateway. * @param gatewayName The name of the gateway. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;VpnConnectionInner&gt; object */ public Observable<ServiceResponse<Page<VpnConnectionInner>>> listByVpnGatewayWithServiceResponseAsync(final String resourceGroupName, final String gatewayName) { return listByVpnGatewaySinglePageAsync(resourceGroupName, gatewayName) .concatMap(new Func1<ServiceResponse<Page<VpnConnectionInner>>, Observable<ServiceResponse<Page<VpnConnectionInner>>>>() { @Override public Observable<ServiceResponse<Page<VpnConnectionInner>>> call(ServiceResponse<Page<VpnConnectionInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listByVpnGatewayNextWithServiceResponseAsync(nextPageLink)); } }); } /** * Retrieves all vpn connections for a particular virtual wan vpn gateway. * ServiceResponse<PageImpl<VpnConnectionInner>> * @param resourceGroupName The resource group name of the VpnGateway. ServiceResponse<PageImpl<VpnConnectionInner>> * @param gatewayName The name of the gateway. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the PagedList&lt;VpnConnectionInner&gt; object wrapped in {@link ServiceResponse} if successful. */ public Observable<ServiceResponse<Page<VpnConnectionInner>>> listByVpnGatewaySinglePageAsync(final String resourceGroupName, final String gatewayName) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (gatewayName == null) { throw new IllegalArgumentException("Parameter gatewayName is required and cannot be null."); } final String apiVersion = "2020-06-01"; return service.listByVpnGateway(this.client.subscriptionId(), resourceGroupName, gatewayName, apiVersion, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<VpnConnectionInner>>>>() { @Override public Observable<ServiceResponse<Page<VpnConnectionInner>>> call(Response<ResponseBody> response) { try { ServiceResponse<PageImpl<VpnConnectionInner>> result = listByVpnGatewayDelegate(response); return Observable.just(new ServiceResponse<Page<VpnConnectionInner>>(result.body(), result.response())); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<PageImpl<VpnConnectionInner>> listByVpnGatewayDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<PageImpl<VpnConnectionInner>, CloudException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<PageImpl<VpnConnectionInner>>() { }.getType()) .registerError(CloudException.class) .build(response); } /** * Retrieves all vpn connections for a particular virtual wan vpn gateway. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @throws CloudException thrown if the request is rejected by server * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent * @return the PagedList&lt;VpnConnectionInner&gt; object if successful. */ public PagedList<VpnConnectionInner> listByVpnGatewayNext(final String nextPageLink) { ServiceResponse<Page<VpnConnectionInner>> response = listByVpnGatewayNextSinglePageAsync(nextPageLink).toBlocking().single(); return new PagedList<VpnConnectionInner>(response.body()) { @Override public Page<VpnConnectionInner> nextPage(String nextPageLink) { return listByVpnGatewayNextSinglePageAsync(nextPageLink).toBlocking().single().body(); } }; } /** * Retrieves all vpn connections for a particular virtual wan vpn gateway. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @param serviceFuture the ServiceFuture object tracking the Retrofit calls * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */ public ServiceFuture<List<VpnConnectionInner>> listByVpnGatewayNextAsync(final String nextPageLink, final ServiceFuture<List<VpnConnectionInner>> serviceFuture, final ListOperationCallback<VpnConnectionInner> serviceCallback) { return AzureServiceFuture.fromPageResponse( listByVpnGatewayNextSinglePageAsync(nextPageLink), new Func1<String, Observable<ServiceResponse<Page<VpnConnectionInner>>>>() { @Override public Observable<ServiceResponse<Page<VpnConnectionInner>>> call(String nextPageLink) { return listByVpnGatewayNextSinglePageAsync(nextPageLink); } }, serviceCallback); } /** * Retrieves all vpn connections for a particular virtual wan vpn gateway. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;VpnConnectionInner&gt; object */ public Observable<Page<VpnConnectionInner>> listByVpnGatewayNextAsync(final String nextPageLink) { return listByVpnGatewayNextWithServiceResponseAsync(nextPageLink) .map(new Func1<ServiceResponse<Page<VpnConnectionInner>>, Page<VpnConnectionInner>>() { @Override public Page<VpnConnectionInner> call(ServiceResponse<Page<VpnConnectionInner>> response) { return response.body(); } }); } /** * Retrieves all vpn connections for a particular virtual wan vpn gateway. * * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the observable to the PagedList&lt;VpnConnectionInner&gt; object */ public Observable<ServiceResponse<Page<VpnConnectionInner>>> listByVpnGatewayNextWithServiceResponseAsync(final String nextPageLink) { return listByVpnGatewayNextSinglePageAsync(nextPageLink) .concatMap(new Func1<ServiceResponse<Page<VpnConnectionInner>>, Observable<ServiceResponse<Page<VpnConnectionInner>>>>() { @Override public Observable<ServiceResponse<Page<VpnConnectionInner>>> call(ServiceResponse<Page<VpnConnectionInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listByVpnGatewayNextWithServiceResponseAsync(nextPageLink)); } }); } /** * Retrieves all vpn connections for a particular virtual wan vpn gateway. * ServiceResponse<PageImpl<VpnConnectionInner>> * @param nextPageLink The NextLink from the previous successful call to List operation. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the PagedList&lt;VpnConnectionInner&gt; object wrapped in {@link ServiceResponse} if successful. */ public Observable<ServiceResponse<Page<VpnConnectionInner>>> listByVpnGatewayNextSinglePageAsync(final String nextPageLink) { if (nextPageLink == null) { throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); } String nextUrl = String.format("%s", nextPageLink); return service.listByVpnGatewayNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<VpnConnectionInner>>>>() { @Override public Observable<ServiceResponse<Page<VpnConnectionInner>>> call(Response<ResponseBody> response) { try { ServiceResponse<PageImpl<VpnConnectionInner>> result = listByVpnGatewayNextDelegate(response); return Observable.just(new ServiceResponse<Page<VpnConnectionInner>>(result.body(), result.response())); } catch (Throwable t) { return Observable.error(t); } } }); } private ServiceResponse<PageImpl<VpnConnectionInner>> listByVpnGatewayNextDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException { return this.client.restClient().responseBuilderFactory().<PageImpl<VpnConnectionInner>, CloudException>newInstance(this.client.serializerAdapter()) .register(200, new TypeToken<PageImpl<VpnConnectionInner>>() { }.getType()) .registerError(CloudException.class) .build(response); } }
{ "content_hash": "30cf9bdb0bf2ab0f4c836330db1dc4ac", "timestamp": "", "source": "github", "line_count": 1449, "max_line_length": 452, "avg_line_length": 61.70531400966183, "alnum_prop": 0.7221370972251736, "repo_name": "selvasingh/azure-sdk-for-java", "id": "0b84b8bdb70d014d35555287d616a91da7664ef3", "size": "89641", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sdk/network/mgmt-v2020_06_01/src/main/java/com/microsoft/azure/management/network/v2020_06_01/implementation/VpnConnectionsInner.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "29891970" }, { "name": "JavaScript", "bytes": "6198" }, { "name": "PowerShell", "bytes": "160" }, { "name": "Shell", "bytes": "609" } ], "symlink_target": "" }
{% extends "base.html" %} {% block title %}Crunch.io - Account Information{% endblock %} {% block pagetitle %}Account Information for {{user.username}}{% endblock %} {% block javascript %} {% endblock %} {% block content %} {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <h3>General Information</h3> <div class="colgroup"> <div class="column width2 first"> <p class="label-box">Username</p> </div> <div class="column width4"> <p class="data-box">{{user.username}}</p> </div> <div class="column width2 first"> <p class="label-box">Name</p> </div> <div class="column width4"> <p class="data-box">{{user.first_name}}&nbsp;{{user.last_name}}</p> </div> <div class="column width2 first"> <p class="label-box">Email</p> </div> <div class="column width4"> <p class="data-box">{{user.email}}</p> </div> </div> <div class="clear">&nbsp;</div> <h3>AWS Information</h3> <div class="colgroup"> <div class="column width2 first"> <p class="label-box">AWS User ID</p> </div> <div class="column width4"> <p class="data-box">{{user.get_profile.awscredential.aws_user_id}}</p> </div> <div class="column width2 first"> <p class="label-box">AWS Email</p> </div> <div class="column width4"> <p class="data-box">{{user.get_profile.awscredential.aws_email}}</p> </div> <div class="column width2 first"> <p class="label-box">AWS Key ID</p> </div> <div class="column width4"> <p class="data-box">{{user.get_profile.awscredential.aws_key_id}}</p> </div> <div class="column width2 first"> <p class="label-box">AWS Secret Key</p> </div> <div class="column width4"> <p class="data-box"> &middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot; </p> </div> </div> <div class="clear">&nbsp;</div> <a href="/cluster/account/password" class="btn">Change Password</a> <a href="#" class="btn">Edit Account</a> <div class="clear">&nbsp;</div> {% endblock %}
{ "content_hash": "69f437de8f7b2453e0deadad37af2609", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 324, "avg_line_length": 33.76470588235294, "alnum_prop": 0.6206445993031359, "repo_name": "godber/crunch.io-dashboard", "id": "0997734c53754e22270a88b5b17c16c1e15185c6", "size": "2296", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cluster/templates/account.html", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "167812" } ], "symlink_target": "" }
import { CommonTranslations } from './definitions'; export const commonTranslationsIT: CommonTranslations = { plzChooseValue: 'Fai una scelta', newChanges: 'nuove modifiche!', changesNotSaved: 'Modifiche non salvate', changesSaved: 'Modifiche salvate', changesWillBeLost: 'I cambiamenti andranno persi.', areYouSure: 'Sei sicuro di voler continuare?', whatDoYouWantToDo: 'Che cosa voi fare', loading: 'Caricamento', loadingFiles: 'Caricare i file', someWentWrong: 'Qualcosa è andato storto', accept: 'Accettare', cancel: 'Cancellare', delete: 'Cancellare', reset: 'resettare', restart: 'Riavviare', save: 'Salva', doNotSave: 'Non salvare', edit: 'Modifica', duplicate: 'Duplicato', close: 'Chiudere', add: 'Aggiungere', filter: 'Filtro', empty: 'Vuoto', forceDelete: 'Forzare la cancellazione', seeChanges: 'Vedere le modifiche', buildingWorld: 'Il mondo è in costruzione!', features: 'Caratteristiche', language: 'Lingua', deepSearch: 'Ricerca profonda', addVariable: 'Aggiungere una nuova variabile', role: 'Ruolo utente', header: { hide: 'Nascondi intestazione', show: 'Montare la intestazione', restartGame: 'Riavviare il gioco (applicato ad ogni scenarista)', restartRealGame: 'ATTENZIONE, state per riavviare un gioco vero e proprio. Tutte le squadre saranno azzerate.', resetLayout: 'Ripristinare il layout', notifications: 'Notifiche', teams: 'Squadre', addExtraTestPlayer: 'Aggiungi un test giocatore', }, noContent: 'Nessun contenuto', noSelectedTab: 'Nessun tab selezionato', serverDown: 'Riconnessione...', serverOutaded: 'La sua versione di Wegas non è aggiornata, aggiorna il suo browser.', somethingIsUndefined: name => `${name} è indefinito`, authorizations: { authorize: 'Autorizza', refuse: 'Rifiuta', authorizationsText: 'Autorizzazioni', authorizationNeeded: 'Autorizzazione necessaria', authorizationRefused: "Il componente non può essere visualizzato perché l'autorizzazione è stata rifiutata.", resetAllAuthorizations: 'Reimposta tutte le autorizzazioni', authorizations: { allowExternalUrl: { label: "Consentire l'accesso a URL esterni", description: "L'utente accetta di rendere disponibile il proprio indirizzo IP ad altri siti web in modo che Wegas possa ottenere risorse esterne (font, immagini, mappe, ecc.).", }, }, }, qrCode: { notAuthorizedToUseCamera : "L'accesso alla telecamera è proibito", tabSetting: 'Controllare se la telecamera è stata bloccata (icona della telecamera nella barra degli indirizzi).', iOSSettingsHint: (navigator: string) => `Controllare le configurazioni dell'iPad/iPhone (Configurazioni / ${navigator})`, androidSettingsHint: (navigator: string) => `Controllare le impostazioni del proprio smartphone/tablet (Impostazioni / Applicazioni / ${ navigator } / Autorizzazioni / Fotocamera` }, };
{ "content_hash": "7f9df54e26533299863501af97caa35e", "timestamp": "", "source": "github", "line_count": 75, "max_line_length": 174, "avg_line_length": 39.57333333333333, "alnum_prop": 0.7159703504043127, "repo_name": "Heigvd/Wegas", "id": "74e97d36f4212801b6d518fd06792756801463cd", "size": "2977", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "wegas-app/src/main/node/wegas-react/src/i18n/common/common-it.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "754253" }, { "name": "HTML", "bytes": "117319" }, { "name": "Java", "bytes": "3575584" }, { "name": "JavaScript", "bytes": "8760248" }, { "name": "Less", "bytes": "6224" }, { "name": "Shell", "bytes": "7009" }, { "name": "TypeScript", "bytes": "2999617" } ], "symlink_target": "" }
<?php /* vim: set expandtab sw=4 ts=4 sts=4: */ /** * set of functions for structure section in pma * * @package PhpMyAdmin */ if (!defined('PHPMYADMIN')) { exit; } /** * Get the HTML links for action links * Actions are, Browse, Search, Browse table label, empty table * * @param array $current_table current table * @param boolean $table_is_view Is table view or not * @param string $tbl_url_query table url query * @param array $titles titles and icons for action links * @param string $truename table name * @param boolean $db_is_information_schema is database information schema or not * @param string $url_query url query * * @return array ($browse_table, $search_table, $browse_table_label, $empty_table, * $tracking_icon) */ function PMA_getHtmlForActionLinks($current_table, $table_is_view, $tbl_url_query, $titles, $truename, $db_is_information_schema, $url_query ) { $empty_table = ''; if ($current_table['TABLE_ROWS'] > 0 || $table_is_view) { $may_have_rows = true; } else { $may_have_rows = false; } $browse_table = '<a href="sql.php?' . $tbl_url_query . '&amp;pos=0">'; if ($may_have_rows) { $browse_table .= $titles['Browse']; } else { $browse_table .= $titles['NoBrowse']; } $browse_table .= '</a>'; $search_table = '<a href="tbl_select.php?' . $tbl_url_query . '">'; if ($may_have_rows) { $search_table .= $titles['Search']; } else { $search_table .= $titles['NoSearch']; } $search_table .= '</a>'; $browse_table_label = '<a href="sql.php?' . $tbl_url_query . '&amp;pos=0">' . $truename . '</a>'; if (!$db_is_information_schema) { $empty_table = '<a class="truncate_table_anchor ajax"'; $empty_table .= ' href="sql.php?' . $tbl_url_query . '&amp;sql_query='; $empty_table .= urlencode( 'TRUNCATE ' . PMA_Util::backquote($current_table['TABLE_NAME']) ); $empty_table .= '&amp;message_to_show=' . urlencode( sprintf( __('Table %s has been emptied'), htmlspecialchars($current_table['TABLE_NAME']) ) ) . '">'; if ($may_have_rows) { $empty_table .= $titles['Empty']; } else { $empty_table .= $titles['NoEmpty']; } $empty_table .= '</a>'; // truncating views doesn't work if ($table_is_view) { $empty_table = '&nbsp;'; } } $tracking_icon = ''; if (PMA_Tracker::isActive()) { if (PMA_Tracker::isTracked($GLOBALS["db"], $truename)) { $tracking_icon = '<a href="tbl_tracking.php?' . $url_query . '&amp;table=' . $truename . '">' . PMA_Util::getImage( 'eye.png', __('Tracking is active.') ) . '</a>'; } elseif (PMA_Tracker::getVersion($GLOBALS["db"], $truename) > 0) { $tracking_icon = '<a href="tbl_tracking.php?' . $url_query . '&amp;table=' . $truename . '">' . PMA_Util::getImage( 'eye_grey.png', __('Tracking is not active.') ) . '</a>'; } } return array($browse_table, $search_table, $browse_table_label, $empty_table, $tracking_icon ); } /** * Get table drop query and drop message * * @param boolean $table_is_view Is table view or not * @param string $current_table current table * * @return array ($drop_query, $drop_message) */ function PMA_getTableDropQueryAndMessage($table_is_view, $current_table) { $drop_query = 'DROP ' . (($table_is_view || $current_table['ENGINE'] == null) ? 'VIEW' : 'TABLE') . ' ' . PMA_Util::backquote( $current_table['TABLE_NAME'] ); $drop_message = sprintf( (($table_is_view || $current_table['ENGINE'] == null) ? __('View %s has been dropped') : __('Table %s has been dropped')), str_replace( ' ', '&nbsp;', htmlspecialchars($current_table['TABLE_NAME']) ) ); return array($drop_query, $drop_message); } /** * Get HTML body for table summery * * @param integer $num_tables number of tables * @param boolean $server_slave_status server slave state * @param boolean $db_is_information_schema whether database is information * schema or not * @param integer $sum_entries sum entries * @param string $db_collation collation of given db * @param boolean $is_show_stats whether stats is show or not * @param double $sum_size sum size * @param double $overhead_size overhead size * @param string $create_time_all create time * @param string $update_time_all update time * @param string $check_time_all check time * @param integer $sum_row_count_pre sum row count pre * * @return string $html_output */ function PMA_getHtmlBodyForTableSummary($num_tables, $server_slave_status, $db_is_information_schema, $sum_entries, $db_collation, $is_show_stats, $sum_size, $overhead_size, $create_time_all, $update_time_all, $check_time_all, $sum_row_count_pre ) { if ($is_show_stats) { list($sum_formatted, $unit) = PMA_Util::formatByteDown( $sum_size, 3, 1 ); list($overhead_formatted, $overhead_unit) = PMA_Util::formatByteDown($overhead_size, 3, 1); } $html_output = '<tbody id="tbl_summary_row">' . '<tr><th></th>'; $html_output .= '<th class="tbl_num nowrap">'; $html_output .= sprintf( _ngettext('%s table', '%s tables', $num_tables), PMA_Util::formatNumber($num_tables, 0) ); $html_output .= '</th>'; if ($server_slave_status) { $html_output .= '<th>' . __('Replication') . '</th>' . "\n"; } $html_output .= '<th colspan="'. ($db_is_information_schema ? 3 : 6) . '">' . __('Sum') . '</th>'; $html_output .= '<th class="value tbl_rows">' . $sum_row_count_pre . PMA_Util::formatNumber($sum_entries, 0) . '</th>'; if (!($GLOBALS['cfg']['PropertiesNumColumns'] > 1)) { $default_engine = PMA_DBI_fetch_value( 'SHOW VARIABLES LIKE \'storage_engine\';', 0, 1 ); $html_output .= '<th class="center">' . "\n" . '<dfn title="' . sprintf( __('%s is the default storage engine on this MySQL server.'), $default_engine ) . '">' .$default_engine . '</dfn></th>' . "\n"; // we got a case where $db_collation was empty $html_output .= '<th>' . "\n"; if (! empty($db_collation)) { $html_output .= '<dfn title="' . PMA_getCollationDescr($db_collation) . ' (' . __('Default') . ')">' . $db_collation . '</dfn>'; } $html_output .= '</th>'; } if ($is_show_stats) { $html_output .= '<th class="value tbl_size">' . $sum_formatted . ' ' . $unit . '</th>'; $html_output .= '<th class="value tbl_overhead">' . $overhead_formatted . ' ' . $overhead_unit . '</th>'; } if ($GLOBALS['cfg']['ShowDbStructureCreation']) { $html_output .= '<th class="value tbl_creation">' . "\n" . ' ' . ($create_time_all ? PMA_Util::localisedDate(strtotime($create_time_all)) : '-' ) . '</th>'; } if ($GLOBALS['cfg']['ShowDbStructureLastUpdate']) { $html_output .= '<th class="value tbl_last_update">' . "\n" . ' ' . ($update_time_all ? PMA_Util::localisedDate(strtotime($update_time_all)) : '-' ) . '</th>'; } if ($GLOBALS['cfg']['ShowDbStructureLastCheck']) { $html_output .= '<th class="value tbl_last_check">' . "\n" . ' ' . ($check_time_all ? PMA_Util::localisedDate(strtotime($check_time_all)) : '-' ) . '</th>'; } $html_output .= '</tr>' . '</tbody>'; return $html_output; } /** * Get HTML for "check all" check box with "with selected" dropdown * * @param string $pmaThemeImage pma theme image url * @param string $text_dir url for text directory * @param string $overhead_check overhead check * @param boolean $db_is_information_schema whether database is information * schema or not * @param string $hidden_fields hidden fields * * @return string $html_output */ function PMA_getHtmlForCheckAllTables($pmaThemeImage, $text_dir, $overhead_check, $db_is_information_schema, $hidden_fields ) { $html_output = '<div class="clearfloat">'; $html_output .= '<img class="selectallarrow" ' . 'src="' .$pmaThemeImage .'arrow_'.$text_dir.'.png' . '"' . 'width="38" height="22" alt="' . __('With selected:') . '" />'; $html_output .= '<input type="checkbox" id="checkall" ' . 'title="' . __('Check All') .'" />'; $html_output .= '<label for="checkall">' .__('Check All') . '</label>'; if ($overhead_check != '') { $html_output .= PMA_getHtmlForCheckTablesHavingOverheadlink( $overhead_check ); } $html_output .= '<select name="submit_mult" class="autosubmit" ' . 'style="margin: 0 3em 0 3em;">'; $html_output .= '<option value="' . __('With selected:') . '" selected="selected">' . __('With selected:') . '</option>' . "\n"; $html_output .= '<option value="export" >' . __('Export') . '</option>' . "\n"; $html_output .= '<option value="print" >' . __('Print view') . '</option>' . "\n"; if (!$db_is_information_schema && !$GLOBALS['cfg']['DisableMultiTableMaintenance'] ) { $html_output .= '<option value="empty_tbl" >' . __('Empty') . '</option>' . "\n"; $html_output .= '<option value="drop_tbl" >' . __('Drop') . '</option>' . "\n"; $html_output .= '<option value="check_tbl" >' . __('Check table') . '</option>' . "\n"; if (!PMA_DRIZZLE) { $html_output .= '<option value="optimize_tbl" >' . __('Optimize table') . '</option>' . "\n"; $html_output .= '<option value="repair_tbl" >' . __('Repair table') . '</option>' . "\n"; } $html_output .= '<option value="analyze_tbl" >' . __('Analyze table') . '</option>' . "\n"; $html_output .= '<option value="add_prefix_tbl" >' . __('Add prefix to table') . '</option>' . "\n"; $html_output .= '<option value="replace_prefix_tbl" >' . __('Replace table prefix') . '</option>' . "\n"; $html_output .= '<option value="copy_tbl_change_prefix" >' . __('Copy table with prefix') . '</option>' . "\n"; } $html_output .= '</select>' . implode("\n", $hidden_fields) . "\n"; $html_output .= '</div>'; return $html_output; } /** * Get HTML code for "Check tables having overhead" link * * @param string $overhead_check overhead check * * @return string $html_output */ function PMA_getHtmlForCheckTablesHavingOverheadlink($overhead_check) { return ' / ' . '<a href="#" onclick="unMarkAllRows(\'tablesForm\');' . $overhead_check . 'return false;">' . __('Check tables having overhead') . '</a>'; } /** * Get HTML links for "Print view" options * * @param string $url_query url query * * @return string $html_output */ function PMA_getHtmlForTablePrintViewLink($url_query) { return '<p>' . '<a href="db_printview.php?' . $url_query . '" target="print_view">' . PMA_Util::getIcon( 'b_print.png', __('Print view'), true ) . '</a>'; } /** * Get HTML links "Data Dictionary" options * * @param string $url_query url query * * @return string $html_output */ function PMA_getHtmlForDataDictionaryLink($url_query) { return '<a href="db_datadict.php?' . $url_query . '" target="print_view">' . PMA_Util::getIcon( 'b_tblanalyse.png', __('Data Dictionary'), true ) . '</a>' . '</p>'; } /** * Get Time for Create time, update time and check time * * @param array $current_table current table * @param string $time_label Create_time, Update_time, Check_time * @param integer $time_all time * * @return array ($time, $time_all) */ function PMA_getTimeForCreateUpdateCheck($current_table, $time_label, $time_all) { $showtable = PMA_Table::sGetStatusInfo( $GLOBALS['db'], $current_table['TABLE_NAME'], null, true ); $time = isset($showtable[$time_label]) ? $showtable[$time_label] : false; // show oldest creation date in summary row if ($time && (!$time_all || $time < $time_all)) { $time_all = $time; } return array($time, $time_all); } /** * Get HTML for each table row of the database structure table, * And this function returns $odd_row param also * * @param integer $curr current entry * @param boolean $odd_row whether row is odd or not * @param boolean $table_is_view whether table is view or not * @param array $current_table current table * @param string $browse_table_label browse table label action link * @param string $tracking_icon tracking icon * @param boolean $server_slave_status server slave state * @param string $browse_table browse table action link * @param string $tbl_url_query table url query * @param string $search_table search table action link * @param boolean $db_is_information_schema whether db is information schema or not * @param array $titles titles array * @param string $empty_table empty table action link * @param string $drop_query table dropt query * @param string $drop_message table drop message * @param string $collation collation * @param string $formatted_size formatted size * @param string $unit unit * @param string $overhead overhead * @param string $create_time create time * @param string $update_time last update time * @param string $check_time last check time * @param boolean $is_show_stats whether stats is show or not * @param boolean $ignored ignored * @param boolean $do do * @param intger $colspan_for_structure colspan for structure * * @return array $html_output, $odd_row */ function PMA_getHtmlForStructureTableRow( $curr, $odd_row, $table_is_view, $current_table, $browse_table_label, $tracking_icon,$server_slave_status, $browse_table, $tbl_url_query, $search_table, $db_is_information_schema,$titles, $empty_table, $drop_query, $drop_message, $collation, $formatted_size, $unit, $overhead, $create_time, $update_time, $check_time,$is_show_stats, $ignored, $do, $colspan_for_structure ) { $html_output = '<tr class="' . ($odd_row ? 'odd' : 'even'); $odd_row = ! $odd_row; $html_output .= ($table_is_view ? ' is_view' : '') .'" id="row_tbl_' . $curr . '">'; $html_output .= '<td class="center">' . '<input type="checkbox" name="selected_tbl[]" class="checkall" ' . 'value="' . htmlspecialchars($current_table['TABLE_NAME']) . '" ' . 'id="checkbox_tbl_' . $curr .'" /></td>'; $html_output .= '<th>' . $browse_table_label . (! empty($tracking_icon) ? $tracking_icon : '') . '</th>'; if ($server_slave_status) { $html_output .= '<td class="center">' . ($ignored ? PMA_Util::getImage('s_cancel.png', 'NOT REPLICATED') : '') . ($do ? PMA_Util::getImage('s_success.png', 'REPLICATED') : '') . '</td>'; } $html_output .= '<td class="center">' . $browse_table . '</td>'; $html_output .= '<td class="center">' . '<a href="tbl_structure.php?' . $tbl_url_query . '">' . $titles['Structure'] . '</a></td>'; $html_output .= '<td class="center">' . $search_table . '</td>'; if (! $db_is_information_schema) { $html_output .= PMA_getHtmlForInsertEmptyDropActionLinks( $tbl_url_query, $table_is_view, $titles, $empty_table, $current_table, $drop_query, $drop_message ); } // end if (! $db_is_information_schema) // there is a null value in the ENGINE // - when the table needs to be repaired, or // - when it's a view // so ensure that we'll display "in use" below for a table // that needs to be repaired if (isset($current_table['TABLE_ROWS']) && ($current_table['ENGINE'] != null || $table_is_view) ) { $html_output .= PMA_getHtmlForNotNullEngineViewTable( $table_is_view, $current_table, $collation, $is_show_stats, $tbl_url_query, $formatted_size, $unit, $overhead, $create_time, $update_time, $check_time ); } elseif ($table_is_view) { $html_output .= PMA_getHtmlForViewTable($is_show_stats); } else { $html_output .= PMA_getHtmlForRepairtable( $colspan_for_structure, $db_is_information_schema ); } // end if (isset($current_table['TABLE_ROWS'])) else $html_output .= '</tr>'; return array($html_output, $odd_row); } /** * Get HTML for Insert/Empty/Drop action links * * @param string $tbl_url_query table url query * @param boolean $table_is_view whether table is view or not * @param array $titles titles array * @param string $empty_table HTML link for empty table * @param array $current_table current table * @param string $drop_query query for drop table * @param string $drop_message table drop message * * @return string $html_output */ function PMA_getHtmlForInsertEmptyDropActionLinks($tbl_url_query, $table_is_view, $titles, $empty_table, $current_table, $drop_query, $drop_message ) { $html_output = '<td class="insert_table center">' . '<a href="tbl_change.php?' . $tbl_url_query . '">' . $titles['Insert'] . '</a></td>'; $html_output .= '<td class="center">' . $empty_table . '</td>'; $html_output .= '<td class="center">'; $html_output .= '<a '; $html_output .= 'class="ajax drop_table_anchor'; if ($table_is_view || $current_table['ENGINE'] == null) { // this class is used in db_structure.js to display the // correct confirmation message $html_output .= ' view'; } $html_output .= '"'; $html_output .= 'href="sql.php?' . $tbl_url_query . '&amp;reload=1&amp;purge=1&amp;sql_query=' . urlencode($drop_query) . '&amp;message_to_show=' . urlencode($drop_message) . '" >' . $titles['Drop'] . '</a></td>'; return $html_output; } /** * Get HTML for show stats * * @param string $tbl_url_query tabel url query * @param string $formatted_size formatted size * @param string $unit unit * @param string $overhead overhead * * @return string $html_output */ function PMA_getHtmlForShowStats($tbl_url_query, $formatted_size, $unit, $overhead ) { $html_output = '<td class="value tbl_size"><a' . 'href="tbl_structure.php?' . $tbl_url_query . '#showusage" >' . '<span>' . $formatted_size . '</span> ' . '<span class="unit">' . $unit . '</span>' . '</a></td>'; $html_output .= '<td class="value tbl_overhead">' . $overhead . '</td>'; return $html_output; } /** * Get HTML to show database structure creation, last update and last checkx time * * @param string $create_time create time * @param string $update_time last update time * @param string $check_time last check time * * @return string $html_output */ function PMA_getHtmlForStructureTimes($create_time, $update_time, $check_time) { $html_output = ''; if ($GLOBALS['cfg']['ShowDbStructureCreation']) { $html_output .= '<td class="value tbl_creation">' . ($create_time ? PMA_Util::localisedDate(strtotime($create_time)) : '-' ) . '</td>'; } // end if if ($GLOBALS['cfg']['ShowDbStructureLastUpdate']) { $html_output .= '<td class="value tbl_last_update">' . ($update_time ? PMA_Util::localisedDate(strtotime($update_time)) : '-' ) . '</td>'; } // end if if ($GLOBALS['cfg']['ShowDbStructureLastCheck']) { $html_output .= '<td class="value tbl_last_check">' . ($check_time ? PMA_Util::localisedDate(strtotime($check_time)) : '-' ) . '</td>'; } return $html_output; } /** * Get HTML for ENGINE value not null or view tables that are not empty tables * * @param boolean $table_is_view whether table is view * @param array $current_table current table * @param string $collation collation * @param boolean $is_show_stats whether atats show or not * @param string $tbl_url_query table url query * @param string $formatted_size formatted size * @param string $unit unit * @param string $overhead overhead * @param string $create_time create time * @param string $update_time update time * @param string $check_time check time * * @return string $html_output */ function PMA_getHtmlForNotNullEngineViewTable($table_is_view, $current_table, $collation, $is_show_stats, $tbl_url_query, $formatted_size, $unit, $overhead, $create_time, $update_time, $check_time ) { $html_output = ''; $row_count_pre = ''; $show_superscript = ''; if ($table_is_view) { // Drizzle views use FunctionEngine, and the only place where they are // available are I_S and D_D schemas, where we do exact counting if ($current_table['TABLE_ROWS'] >= $GLOBALS['cfg']['MaxExactCountViews'] && $current_table['ENGINE'] != 'FunctionEngine' ) { $row_count_pre = '~'; $sum_row_count_pre = '~'; $show_superscript = PMA_Util::showHint( PMA_sanitize( sprintf( __('This view has at least this number of rows. Please refer to %sdocumentation%s.'), '[doc@cfg_MaxExactCountViews]', '[/doc]' ) ) ); } } elseif ($current_table['ENGINE'] == 'InnoDB' && (! $current_table['COUNTED']) ) { // InnoDB table: we did not get an accurate row count $row_count_pre = '~'; $sum_row_count_pre = '~'; $show_superscript = ''; } $html_output .= '<td class="value tbl_rows">' . $row_count_pre . PMA_Util::formatNumber( $current_table['TABLE_ROWS'], 0 ) . $show_superscript . '</td>'; if (!($GLOBALS['cfg']['PropertiesNumColumns'] > 1)) { $html_output .= '<td class="nowrap">' . ($table_is_view ? __('View') : $current_table['ENGINE']) . '</td>'; if (strlen($collation)) { $html_output .= '<td class="nowrap">' . $collation . '</td>'; } } if ($is_show_stats) { $html_output .= PMA_getHtmlForShowStats( $tbl_url_query, $formatted_size, $unit, $overhead ); } $html_output .= PMA_getHtmlForStructureTimes( $create_time, $update_time, $check_time ); return $html_output; } /** * Get HTML snippet view table * * @param type $is_show_stats whether stats show or not * * @return string $html_output */ function PMA_getHtmlForViewTable($is_show_stats) { $html_output = '<td class="value">-</td>' . '<td>' . __('View') . '</td>' . '<td>---</td>'; if ($is_show_stats) { $html_output .= '<td class="value">-</td>' . '<td class="value">-</td>'; } return $html_output; } /** * display "in use" below for a table that needs to be repaired * * @param integer $colspan_for_structure colspan for structure * @param boolean $db_is_information_schema whether db is information schema or not * * @return string HTML snippet */ function PMA_getHtmlForRepairtable( $colspan_for_structure, $db_is_information_schema ) { return '<td colspan="' . ($colspan_for_structure - ($db_is_information_schema ? 5 : 8)) . '"' . 'class="center">' . __('in use') . '</td>'; } /** * display table header (<table><thead>...</thead><tbody>) * * @param boolean $db_is_information_schema whether db is information schema or not * @param boolean $replication whether to sho replication status * * @return html data */ function PMA_TableHeader($db_is_information_schema = false, $replication = false) { $cnt = 0; // Let's count the columns... if ($db_is_information_schema) { $action_colspan = 3; } else { $action_colspan = 6; } $html_output = '<table class="data">' . "\n" .'<thead>' . "\n" .'<tr><th></th>' . "\n" .'<th>' . PMA_sortableTableHeader(__('Table'), 'table') . '</th>' . "\n"; if ($replication) { $html_output .= '<th>' . "\n" .' ' . __('Replication') . "\n" .'</th>'; } $html_output .= '<th colspan="' . $action_colspan . '">' . "\n" .' ' . __('Action') . "\n" .'</th>' // larger values are more interesting so default sort order is DESC .'<th>' . PMA_sortableTableHeader(__('Rows'), 'records', 'DESC') . PMA_Util::showHint( PMA_sanitize( __('May be approximate. See [doc@faq3-11]FAQ 3.11[/doc]') ) ) . "\n" .'</th>' . "\n"; if (!($GLOBALS['cfg']['PropertiesNumColumns'] > 1)) { $html_output .= '<th>' . PMA_sortableTableHeader(__('Type'), 'type') . '</th>' . "\n"; $cnt++; $html_output .= '<th>' . PMA_sortableTableHeader(__('Collation'), 'collation') . '</th>' . "\n"; $cnt++; } if ($GLOBALS['is_show_stats']) { // larger values are more interesting so default sort order is DESC $html_output .= '<th>' . PMA_sortableTableHeader(__('Size'), 'size', 'DESC') . '</th>' . "\n" // larger values are more interesting so default sort order is DESC . '<th>' . PMA_sortableTableHeader(__('Overhead'), 'overhead', 'DESC') . '</th>' . "\n"; $cnt += 2; } if ($GLOBALS['cfg']['ShowDbStructureCreation']) { // larger values are more interesting so default sort order is DESC $html_output .= '<th>' . PMA_sortableTableHeader(__('Creation'), 'creation', 'DESC') . '</th>' . "\n"; $cnt += 2; } if ($GLOBALS['cfg']['ShowDbStructureLastUpdate']) { // larger values are more interesting so default sort order is DESC $html_output .= '<th>' . PMA_sortableTableHeader(__('Last update'), 'last_update', 'DESC') . '</th>' . "\n"; $cnt += 2; } if ($GLOBALS['cfg']['ShowDbStructureLastCheck']) { // larger values are more interesting so default sort order is DESC $html_output .= '<th>' . PMA_sortableTableHeader(__('Last check'), 'last_check', 'DESC') . '</th>' . "\n"; $cnt += 2; } $html_output .= '</tr>' . "\n"; $html_output .= '</thead>' . "\n"; $html_output .= '<tbody>' . "\n"; $GLOBALS['colspan_for_structure'] = $cnt + $action_colspan + 3; return $html_output; } /** * Creates a clickable column header for table information * * @param string $title title to use for the link * @param string $sort corresponds to sortable data name mapped in * libraries/db_info.inc.php * @param string $initial_sort_order initial sort order * * @return string link to be displayed in the table header */ function PMA_sortableTableHeader($title, $sort, $initial_sort_order = 'ASC') { // Set some defaults $requested_sort = 'table'; $requested_sort_order = $future_sort_order = $initial_sort_order; // If the user requested a sort if (isset($_REQUEST['sort'])) { $requested_sort = $_REQUEST['sort']; if (isset($_REQUEST['sort_order'])) { $requested_sort_order = $_REQUEST['sort_order']; } } $order_img = ''; $order_link_params = array(); $order_link_params['title'] = __('Sort'); // If this column was requested to be sorted. if ($requested_sort == $sort) { if ($requested_sort_order == 'ASC') { $future_sort_order = 'DESC'; // current sort order is ASC $order_img = ' ' . PMA_Util::getImage( 's_asc.png', __('Ascending'), array('class' => 'sort_arrow', 'title' => '') ); $order_img .= ' ' . PMA_Util::getImage( 's_desc.png', __('Descending'), array('class' => 'sort_arrow hide', 'title' => '') ); // but on mouse over, show the reverse order (DESC) $order_link_params['onmouseover'] = "$('.sort_arrow').toggle();"; // on mouse out, show current sort order (ASC) $order_link_params['onmouseout'] = "$('.sort_arrow').toggle();"; } else { $future_sort_order = 'ASC'; // current sort order is DESC $order_img = ' ' . PMA_Util::getImage( 's_asc.png', __('Ascending'), array('class' => 'sort_arrow hide', 'title' => '') ); $order_img .= ' ' . PMA_Util::getImage( 's_desc.png', __('Descending'), array('class' => 'sort_arrow', 'title' => '') ); // but on mouse over, show the reverse order (ASC) $order_link_params['onmouseover'] = "$('.sort_arrow').toggle();"; // on mouse out, show current sort order (DESC) $order_link_params['onmouseout'] = "$('.sort_arrow').toggle();"; } } $_url_params = array( 'db' => $_REQUEST['db'], ); $url = 'db_structure.php'.PMA_generate_common_url($_url_params); // We set the position back to 0 every time they sort. $url .= "&amp;pos=0&amp;sort=$sort&amp;sort_order=$future_sort_order"; return PMA_Util::linkOrButton( $url, $title . $order_img, $order_link_params ); } /** * Get the alias ant truname * * @param string $tooltip_aliasname tooltip alias name * @param array $current_table current table * @param string $tooltip_truename tooltip true name * * @return array ($alias, $truename) */ function PMA_getAliasAndTrueName($tooltip_aliasname, $current_table, $tooltip_truename ) { $alias = (! empty($tooltip_aliasname) && isset($tooltip_aliasname[$current_table['TABLE_NAME']]) ) ? str_replace( ' ', '&nbsp;', htmlspecialchars($tooltip_truename[$current_table['TABLE_NAME']]) ) : str_replace( ' ', '&nbsp;', htmlspecialchars($current_table['TABLE_NAME']) ); $truename = (! empty($tooltip_truename) && isset($tooltip_truename[$current_table['TABLE_NAME']]) ) ? str_replace( ' ', '&nbsp;', htmlspecialchars($tooltip_truename[$current_table['TABLE_NAME']]) ) : str_replace( ' ', '&nbsp;', htmlspecialchars($current_table['TABLE_NAME']) ); return array($alias, $truename); } /** * Get the server slave state * * @param boolean $server_slave_status server slave state * @param string $truename true name * * @return array ($do, $ignored) */ function PMA_getServerSlaveStatus($server_slave_status, $truename) { $ignored = false; $do = false; include_once 'libraries/replication.inc.php'; if ($server_slave_status) { if ((strlen(array_search($truename, $server_slave_Do_Table)) > 0) || (strlen(array_search($GLOBALS['db'], $server_slave_Do_DB)) > 0) || (count($server_slave_Do_DB) == 1 && count($server_slave_Ignore_DB) == 1) ) { $do = true; } foreach ($server_slave_Wild_Do_Table as $db_table) { $table_part = PMA_extract_db_or_table($db_table, 'table'); if (($GLOBALS['db'] == PMA_extract_db_or_table($db_table, 'db')) && (preg_match("@^" . substr($table_part, 0, strlen($table_part) - 1) . "@", $truename)) ) { $do = true; } } if ((strlen(array_search($truename, $server_slave_Ignore_Table)) > 0) || (strlen(array_search($GLOBALS['db'], $server_slave_Ignore_DB)) > 0) ) { $ignored = true; } foreach ($server_slave_Wild_Ignore_Table as $db_table) { $table_part = PMA_extract_db_or_table($db_table, 'table'); if (($db == PMA_extract_db_or_table($db_table)) && (preg_match("@^" . substr($table_part, 0, strlen($table_part) - 1) . "@", $truename)) ) { $ignored = true; } } } return array($do, $ignored); } /** * Get the value set for ENGINE table, * $current_table, $formatted_size, $unit, $formatted_overhead, * $overhead_unit, $overhead_size, $table_is_view * * @param array $current_table current table * @param boolean $db_is_information_schema whether db is information schema or not * @param boolean $is_show_stats whether stats show or not * @param boolean $table_is_view whether table is view or not * @param double $sum_size totle table size * @param double $overhead_size overhead size * * @return array */ function PMA_getStuffForEngineTypeTable($current_table, $db_is_information_schema, $is_show_stats, $table_is_view, $sum_size, $overhead_size ) { $formatted_size = '-'; $unit = ''; $formatted_overhead = ''; $overhead_unit = ''; switch ( $current_table['ENGINE']) { // MyISAM, ISAM or Heap table: Row count, data size and index size // are accurate; data size is accurate for ARCHIVE case 'MyISAM' : case 'ISAM' : case 'HEAP' : case 'MEMORY' : case 'ARCHIVE' : case 'Aria' : case 'Maria' : list($current_table, $formatted_size, $unit, $formatted_overhead, $overhead_unit, $overhead_size, $sum_size) = PMA_getValuesForAriaTable( $db_is_information_schema, $current_table, $is_show_stats, $sum_size, $overhead_size, $formatted_size, $unit, $formatted_overhead, $overhead_unit ); break; case 'InnoDB' : case 'PBMS' : // InnoDB table: Row count is not accurate but data and index sizes are. // PBMS table in Drizzle: TABLE_ROWS is taken from table cache, // so it may be unavailable list($current_table, $formatted_size, $unit, $sum_size) = PMA_getValuesForPbmsTable($current_table, $is_show_stats, $sum_size); //$display_rows = ' - '; break; // Mysql 5.0.x (and lower) uses MRG_MyISAM // and MySQL 5.1.x (and higher) uses MRG_MYISAM // Both are aliases for MERGE case 'MRG_MyISAM' : case 'MRG_MYISAM' : case 'MERGE' : case 'BerkeleyDB' : // Merge or BerkleyDB table: Only row count is accurate. if ($is_show_stats) { $formatted_size = ' - '; $unit = ''; } break; // for a view, the ENGINE is sometimes reported as null, // or on some servers it's reported as "SYSTEM VIEW" case null : case 'SYSTEM VIEW' : case 'FunctionEngine' : // if table is broken, Engine is reported as null, so one more test if ($current_table['TABLE_TYPE'] == 'VIEW') { // countRecords() takes care of $cfg['MaxExactCountViews'] $current_table['TABLE_ROWS'] = PMA_Table::countRecords( $GLOBALS['db'], $current_table['TABLE_NAME'], $force_exact = true, $is_view = true ); $table_is_view = true; } break; default : // Unknown table type. if ($is_show_stats) { $formatted_size = __('unknown'); $unit = ''; } } // end switch return array($current_table, $formatted_size, $unit, $formatted_overhead, $overhead_unit, $overhead_size, $table_is_view, $sum_size ); } /** * Get values for ARIA/MARIA tables * $current_table, $formatted_size, $unit, $formatted_overhead, * $overhead_unit, $overhead_size * * @param boolean $db_is_information_schema whether db is information schema or not * @param array $current_table current table * @param boolean $is_show_stats whether stats show or not * @param double $sum_size sum size * @param double $overhead_size overhead size * * @return array */ function PMA_getValuesForAriaTable($db_is_information_schema, $current_table, $is_show_stats, $sum_size, $overhead_size, $formatted_size, $unit, $formatted_overhead, $overhead_unit ) { if ($db_is_information_schema) { $current_table['Rows'] = PMA_Table::countRecords( $GLOBALS['db'], $current_table['Name'] ); } if ($is_show_stats) { $tblsize = doubleval($current_table['Data_length']) + doubleval($current_table['Index_length']); $sum_size += $tblsize; list($formatted_size, $unit) = PMA_Util::formatByteDown( $tblsize, 3, ($tblsize > 0) ? 1 : 0 ); if (isset($current_table['Data_free']) && $current_table['Data_free'] > 0) { list($formatted_overhead, $overhead_unit) = PMA_Util::formatByteDown( $current_table['Data_free'], 3, (($current_table['Data_free'] > 0) ? 1 : 0) ); $overhead_size += $current_table['Data_free']; } } return array($current_table, $formatted_size, $unit, $formatted_overhead, $overhead_unit, $overhead_size, $sum_size ); } /** * Get valuse for PBMS table * $current_table, $formatted_size, $unit, $sum_size * * @param array $current_table current table * @param boolean $is_show_stats whether stats show or not * @param double $sum_size sum size * * @return array */ function PMA_getValuesForPbmsTable($current_table, $is_show_stats, $sum_size) { if (($current_table['ENGINE'] == 'InnoDB' && $current_table['TABLE_ROWS'] < $GLOBALS['cfg']['MaxExactCount']) || !isset($current_table['TABLE_ROWS']) ) { $current_table['COUNTED'] = true; $current_table['TABLE_ROWS'] = PMA_Table::countRecords( $GLOBALS['db'], $current_table['TABLE_NAME'], $force_exact = true, $is_view = false ); } else { $current_table['COUNTED'] = false; } // Drizzle doesn't provide data and index length, check for null if ($is_show_stats && $current_table['Data_length'] !== null) { $tblsize = $current_table['Data_length'] + $current_table['Index_length']; $sum_size += $tblsize; list($formatted_size, $unit) = PMA_Util::formatByteDown( $tblsize, 3, (($tblsize > 0) ? 1 : 0) ); } return array($current_table, $formatted_size, $unit, $sum_size); } /** * table structure */ /** * Get the HTML snippet for structure table table header * * @param type $db_is_information_schema whether db is information schema or not * @param type $tbl_is_view whether table is view or nt * * @return string $html_output */ function PMA_getHtmlForTableStructureHeader( $db_is_information_schema, $tbl_is_view ) { $html_output = '<thead>'; $html_output .= '<tr>'; $html_output .= '<th></th>' . '<th>#</th>' . '<th>' . __('Name') . '</th>' . '<th>' . __('Type'). '</th>' . '<th>' . __('Collation') . '</th>' . '<th>' . __('Attributes') . '</th>' . '<th>' . __('Null') . '</th>' . '<th>' . __('Default') . '</th>' . '<th>' . __('Extra') . '</th>'; if ($db_is_information_schema || $tbl_is_view) { $html_output .= '<th>' . __('View') . '</th>'; } else { /* see tbl_structure.js, function moreOptsMenuResize() */ $colspan = 9; if (PMA_DRIZZLE) { $colspan -= 2; } if (in_array( $GLOBALS['cfg']['ActionLinksMode'], array('icons', 'both') ) ) { $colspan--; } $html_output .= '<th colspan="' . $colspan . '" ' . 'class="action">' . __('Action') . '</th>'; } $html_output .= '</tr>' . '</thead>'; return $html_output; } /** * Get HTML for structure table's rows and return $odd_row parameter also * For "Action" Column, this function contains only HTML code for "Change" * and "Drop" * * @param array $row current row * @param string $rownum row number * @param string $displayed_field_name displayed field name * @param string $type_nowrap type nowrap * @param array $extracted_columnspec associative array containing type, * spec_in_brackets and possibly * enum_set_values (another array) * @param string $type_mime mime type * @param string $field_charset field charset * @param string $attribute attribute (BINARY, UNSIGNED, * UNSIGNED ZEROFILL, * on update CURRENT_TIMESTAMP) * @param boolean $tbl_is_view whether tables is view or not * @param boolean $db_is_information_schema whether db is information schema or not * @param string $url_query url query * @param string $field_encoded field encoded * @param array $titles tittles array * @param string $table table * * @return array ($html_output, $odd_row) */ function PMA_getHtmlTableStructureRow($row, $rownum, $displayed_field_name, $type_nowrap, $extracted_columnspec, $type_mime, $field_charset, $attribute, $tbl_is_view, $db_is_information_schema, $url_query, $field_encoded, $titles, $table ) { $html_output = '<td class="center">' . '<input type="checkbox" class="checkall" name="selected_fld[]" ' . 'value="' . htmlspecialchars($row['Field']) . '" ' . 'id="checkbox_row_' . $rownum . '"/>' . '</td>'; $html_output .= '<td class="right">' . $rownum . '</td>'; $html_output .= '<th class="nowrap">' . '<label for="checkbox_row_' . $rownum . '">' . $displayed_field_name . '</label>' . '</th>'; $html_output .= '<td' . $type_nowrap . '>' .'<bdo dir="ltr" lang="en">' . $extracted_columnspec['displayed_type'] . $type_mime . '</bdo></td>'; $html_output .= '<td>' . (empty($field_charset) ? '' : '<dfn title="' . PMA_getCollationDescr($field_charset) . '">' . $field_charset . '</dfn>' ) . '</td>'; $html_output .= '<td class="column_attribute nowrap">' . $attribute . '</td>'; $html_output .= '<td>' . (($row['Null'] == 'YES') ? __('Yes') : __('No')) . ' </td>'; $html_output .= '<td class="nowrap">'; if (isset($row['Default'])) { if ($extracted_columnspec['type'] == 'bit') { // here, $row['Default'] contains something like b'010' $html_output .= PMA_Util::convertBitDefaultValue($row['Default']); } else { $html_output .= $row['Default']; } } else { $html_output .= '<i>' . _pgettext('None for default', 'None') . '</i>'; } $html_output .= '</td>'; $html_output .= '<td class="nowrap">' . strtoupper($row['Extra']) . '</td>'; $html_output .= PMA_getHtmlForDropColumn( $tbl_is_view, $db_is_information_schema, $url_query, $field_encoded, $titles, $table, $row ); return $html_output; } /** * Get HTML code for "Drop" Action link * * @param boolean $tbl_is_view whether tables is view or not * @param boolean $db_is_information_schema whether db is information schema or not * @param string $url_query url query * @param string $field_encoded field encoded * @param array $titles tittles array * @param string $table table * @param array $row current row * * @return string $html_output */ function PMA_getHtmlForDropColumn($tbl_is_view, $db_is_information_schema, $url_query, $field_encoded, $titles, $table, $row ) { $html_output = ''; if (! $tbl_is_view && ! $db_is_information_schema) { $html_output .= '<td class="edit center">' . '<a class="change_column_anchor ajax"' . ' href="tbl_structure.php?' . $url_query . '&amp;field=' . $field_encoded . '&amp;change_column=1">' . $titles['Change'] . '</a>' . '</td>'; $html_output .= '<td class="drop center">' . '<a class="drop_column_anchor ajax"' . ' href="sql.php?' . $url_query . '&amp;sql_query=' . urlencode( 'ALTER TABLE ' . PMA_Util::backquote($table) . ' DROP ' . PMA_Util::backquote($row['Field']) . ';' ) . '&amp;dropped_column=' . urlencode($row['Field']) . '&amp;message_to_show=' . urlencode( sprintf( __('Column %s has been dropped'), htmlspecialchars($row['Field']) ) ) . '" >' . $titles['Drop'] . '</a>' . '</td>'; } return $html_output; } /** * Get HTML for "check all" check box with "with selected" actions in table * structure * * @param string $pmaThemeImage pma theme image url * @param string $text_dir test directory * @param boolean $tbl_is_view whether table is view or not * @param boolean $db_is_information_schema whether db is information schema or not * @param string $tbl_storage_engine table storage engine * * @return string $html_output */ function PMA_getHtmlForCheckAllTableColumn($pmaThemeImage, $text_dir, $tbl_is_view, $db_is_information_schema, $tbl_storage_engine ) { $html_output = '<img class="selectallarrow" ' . 'src="' . $pmaThemeImage . 'arrow_' . $text_dir . '.png' . '"' . 'width="38" height="22" alt="' . __('With selected:') . '" />'; $html_output .= '<input type="checkbox" id="checkall" ' . 'title="' . __('Check All') . '" />' . '<label for="checkall">' . __('Check All') . '</label>'; $html_output .= '<i style="margin-left: 2em">' . __('With selected:') . '</i>'; $html_output .= PMA_Util::getButtonOrImage( 'submit_mult', 'mult_submit', 'submit_mult_browse', __('Browse'), 'b_browse.png', 'browse' ); if (! $tbl_is_view && ! $db_is_information_schema) { $html_output .= PMA_Util::getButtonOrImage( 'submit_mult', 'mult_submit change_columns_anchor ajax', 'submit_mult_change', __('Change'), 'b_edit.png', 'change' ); $html_output .= PMA_Util::getButtonOrImage( 'submit_mult', 'mult_submit', 'submit_mult_drop', __('Drop'), 'b_drop.png', 'drop' ); if ('ARCHIVE' != $tbl_storage_engine) { $html_output .= PMA_Util::getButtonOrImage( 'submit_mult', 'mult_submit', 'submit_mult_primary', __('Primary'), 'b_primary.png', 'primary' ); $html_output .= PMA_Util::getButtonOrImage( 'submit_mult', 'mult_submit', 'submit_mult_unique', __('Unique'), 'b_unique.png', 'unique' ); $html_output .= PMA_Util::getButtonOrImage( 'submit_mult', 'mult_submit', 'submit_mult_index', __('Index'), 'b_index.png', 'index' ); } if (! empty($tbl_storage_engine) && $tbl_storage_engine == 'MYISAM') { $html_output .= PMA_Util::getButtonOrImage( 'submit_mult', 'mult_submit', 'submit_mult_spatial', __('Spatial'), 'b_spatial.png', 'spatial' ); } if (! empty($tbl_storage_engine) && ($tbl_storage_engine == 'MYISAM' || $tbl_storage_engine == 'ARIA' || $tbl_storage_engine == 'MARIA') ) { $html_output .= PMA_Util::getButtonOrImage( 'submit_mult', 'mult_submit', 'submit_mult_fulltext', __('Fulltext'), 'b_ftext.png', 'ftext' ); } } return $html_output; } /** * Get HTML for move columns dialog * * @return string $html_output */ function PMA_getHtmlDivForMoveColumnsDialog() { $html_output = '<div id="move_columns_dialog" ' . 'title="' . __('Move columns') . '" style="display: none">'; $html_output .= '<p>' . __('Move the columns by dragging them up and down.') . '</p>'; $html_output .= '<form action="tbl_structure.php">' . '<div>' . PMA_generate_common_hidden_inputs($GLOBALS['db'], $GLOBALS['table']) . '<ul></ul>' . '</div>' . '</form>' . '</div>'; return $html_output; } /** * Get HTML for edit views' * * @param string $url_params URL parameters * * @return string $html_output */ function PMA_getHtmlForEditView($url_params) { $create_view = PMA_DBI_get_definition( $GLOBALS['db'], 'VIEW', $GLOBALS['table'] ); $create_view = preg_replace('@^CREATE@', 'ALTER', $create_view); $html_output = PMA_Util::linkOrButton( 'tbl_sql.php' . PMA_generate_common_url( $url_params + array( 'sql_query' => $create_view, 'show_query' => '1', ) ), PMA_Util::getIcon('b_edit.png', __('Edit view'), true) ); return $html_output; } /** * Get HTML links for 'Print view', 'Relation view', 'Propose table structure', * 'Track table' and 'Move columns' * * @param string $url_query url query * @param boolean $tbl_is_view whether table is view or not * @param boolean $db_is_information_schema whether db is information schema or not * @param string $tbl_storage_engine table storage engine * @param array $cfgRelation current relation parameters * * @return string $html_output */ function PMA_getHtmlForOptionalActionLinks($url_query, $tbl_is_view, $db_is_information_schema, $tbl_storage_engine, $cfgRelation ) { $html_output = '<a href="tbl_printview.php?' . $url_query . '" target="print_view">' . PMA_Util::getIcon('b_print.png', __('Print view'), true) . '</a>'; if (! $tbl_is_view && ! $db_is_information_schema) { // if internal relations are available, or foreign keys are supported // ($tbl_storage_engine comes from libraries/tbl_info.inc.php if ($cfgRelation['relwork'] || PMA_Util::isForeignKeySupported($tbl_storage_engine) ) { $html_output .= '<a href="tbl_relation.php?' . $url_query . '">' . PMA_Util::getIcon( 'b_relations.png', __('Relation view'), true ) . '</a>'; } if (!PMA_DRIZZLE) { $html_output .= '<a href="sql.php?' . $url_query . '&amp;session_max_rows=all&amp;sql_query=' . urlencode( 'SELECT * FROM ' . PMA_Util::backquote($GLOBALS['table']) . ' PROCEDURE ANALYSE()' ) . '">' . PMA_Util::getIcon( 'b_tblanalyse.png', __('Propose table structure'), true ) . '</a>'; $html_output .= PMA_Util::showMySQLDocu( 'Extending_MySQL', 'procedure_analyse' ) . "\n"; } if (PMA_Tracker::isActive()) { $html_output .= '<a href="tbl_tracking.php?' . $url_query . '">' . PMA_Util::getIcon('eye.png', __('Track table'), true) . '</a>'; } $html_output .= '<a href="#" id="move_columns_anchor">' . PMA_Util::getIcon('b_move.png', __('Move columns'), true) . '</a>'; } return $html_output; } /** * Get HTML snippet for "Add column" feature in structure table * * @param array $columns_list column list array * * @return string $html_output */ function PMA_getHtmlForAddColumn($columns_list) { $html_output = '<form method="post" action="tbl_addfield.php" ' . 'id="addColumns" name="addColumns" ' . 'onsubmit="return checkFormElementInRange(' . 'this, \'num_fields\', \'' . str_replace( '\'', '\\\'', __('You have to add at least one column.') ) . '\', 1)' . '">'; $html_output .= PMA_generate_common_hidden_inputs( $GLOBALS['db'], $GLOBALS['table'] ); if (in_array( $GLOBALS['cfg']['ActionLinksMode'], array('icons', 'both') ) ) { $html_output .=PMA_Util::getImage( 'b_insrow.png', __('Add column') ); } $num_fields = '<input type="text" name="num_fields" size="2" ' . 'maxlength="2" value="1" onfocus="this.select()" />'; $html_output .= sprintf(__('Add %s column(s)'), $num_fields); // I tried displaying the drop-down inside the label but with Firefox // the drop-down was blinking $column_selector = '<select name="after_field" ' . 'onclick="this.form.field_where[2].checked=true" ' . 'onchange="this.form.field_where[2].checked=true">'; foreach ($columns_list as $one_column_name) { $column_selector .= '<option ' . 'value="' . htmlspecialchars($one_column_name) . '">' . htmlspecialchars($one_column_name) . '</option>'; } $column_selector .= '</select>'; $choices = array( 'last' => __('At End of Table'), 'first' => __('At Beginning of Table'), 'after' => sprintf(__('After %s'), '') ); $html_output .= PMA_Util::getRadioFields( 'field_where', $choices, 'last', false ); $html_output .= $column_selector; $html_output .= '<input type="submit" value="' . __('Go') . '" />' . '</form>'; return $html_output; } /** * Get HTML snippet for table rows in the Information ->Space usage table * * @param boolean $odd_row whether current row is odd or even * @param string $name type of usage * @param string $value value of usage * @param string $unit unit * * @return string $html_output */ function PMA_getHtmlForSpaceUsageTableRow($odd_row, $name, $value, $unit) { $html_output = '<tr class="' . (($odd_row = !$odd_row) ? 'odd' : 'even') . '">'; $html_output .= '<th class="name">' . $name . '</th>'; $html_output .= '<td class="value">' . $value . '</td>'; $html_output .= '<td class="unit">' . $unit . '</td>'; $html_output .= '</tr>'; return $html_output; } /** * Get HTML for Optimize link if overhead in Information fieldset * * @param type $url_query URL query * * @return string $html_output */ function PMA_getHtmlForOptimizeLink($url_query) { $html_output = '<tr class="tblFooters">'; $html_output .= '<td colspan="3" class="center">'; $html_output .= '<a href="sql.php?' . $url_query . '&pos=0&amp;sql_query=' . urlencode( 'OPTIMIZE TABLE ' . PMA_Util::backquote($GLOBALS['table']) ) . '">' . PMA_Util::getIcon('b_tbloptimize.png', __('Optimize table')) . '</a>'; $html_output .= '</td>'; $html_output .= '</tr>'; return $html_output; } /** * Get HTML for 'Row statistics' table row * * @param type $odd_row whether current row is odd or even * @param type $name statement name * @param type $value value * * @return string $html_output */ function PMA_getHtmlForRowStatsTableRow($odd_row, $name, $value) { $html_output = '<tr class="' . (($odd_row = !$odd_row) ? 'odd' : 'even') . '">'; $html_output .= '<th class="name">' . $name . '</th>'; $html_output .= '<td class="value">' . $value . '</td>'; $html_output .= '</tr>'; return $html_output; } /** * Get HTML snippet for display Row statistics table * * @param array $showtable show table array * @param string $tbl_collation table collation * @param boolean $is_innodb whether table is innob or not * @param boolean $mergetable Checks if current table is a merge table * @param integer $avg_size average size * @param string $avg_unit average unit * * @return string $html_output */ function getHtmlForRowStatsTable($showtable, $tbl_collation, $is_innodb, $mergetable, $avg_size, $avg_unit ) { $odd_row = false; $html_output = '<table id="tablerowstats" class="data">'; $html_output .= '<caption class="tblHeaders">' . __('Row statistics') . '</caption>'; $html_output .= '<tbody>'; if (isset($showtable['Row_format'])) { if ($showtable['Row_format'] == 'Fixed') { $value = __('static'); } elseif ($showtable['Row_format'] == 'Dynamic') { $value = __('dynamic'); } else { $value = $showtable['Row_format']; } $html_output .= PMA_getHtmlForRowStatsTableRow( $odd_row, __('Format'), $value ); $odd_row = !$odd_row; } if (! empty($showtable['Create_options'])) { if ($showtable['Create_options'] == 'partitioned') { $value = __('partitioned'); } else { $value = $showtable['Create_options']; } $html_output .= PMA_getHtmlForRowStatsTableRow( $odd_row, __('Options'), $value ); $odd_row = !$odd_row; } if (!empty($tbl_collation)) { $value = '<dfn title="' . PMA_getCollationDescr($tbl_collation) . '">' . $tbl_collation . '</dfn>'; $html_output .= PMA_getHtmlForRowStatsTableRow( $odd_row, __('Collation'), $value ); $odd_row = !$odd_row; } if (!$is_innodb && isset($showtable['Rows'])) { $html_output .= PMA_getHtmlForRowStatsTableRow( $odd_row, __('Rows'), PMA_Util::formatNumber($showtable['Rows'], 0) ); $odd_row = !$odd_row; } if (!$is_innodb && isset($showtable['Avg_row_length']) && $showtable['Avg_row_length'] > 0 ) { list($avg_row_length_value, $avg_row_length_unit) = PMA_Util::formatByteDown( $showtable['Avg_row_length'], 6, 1 ); $html_output .= PMA_getHtmlForRowStatsTableRow( $odd_row, __('Row length'), ($avg_row_length_value . ' ' . $avg_row_length_unit) ); unset($avg_row_length_value, $avg_row_length_unit); $odd_row = !$odd_row; } if (!$is_innodb && isset($showtable['Data_length']) && $showtable['Rows'] > 0 && $mergetable == false ) { $html_output .= PMA_getHtmlForRowStatsTableRow( $odd_row, __('Row size'), ($avg_size . ' ' . $avg_unit) ); $odd_row = !$odd_row; } if (isset($showtable['Auto_increment'])) { $html_output .= PMA_getHtmlForRowStatsTableRow( $odd_row, __('Next autoindex'), PMA_Util::formatNumber($showtable['Auto_increment'], 0) ); $odd_row = !$odd_row; } if (isset($showtable['Create_time'])) { $html_output .= PMA_getHtmlForRowStatsTableRow( $odd_row, __('Creation'), PMA_Util::localisedDate(strtotime($showtable['Create_time'])) ); $odd_row = !$odd_row; } if (isset($showtable['Update_time'])) { $html_output .= PMA_getHtmlForRowStatsTableRow( $odd_row, __('Last update'), PMA_Util::localisedDate(strtotime($showtable['Update_time'])) ); $odd_row = !$odd_row; } if (isset($showtable['Check_time'])) { $html_output .= PMA_getHtmlForRowStatsTableRow( $odd_row, __('Last check'), PMA_Util::localisedDate(strtotime($showtable['Check_time'])) ); } $html_output .= '</tbody>' . '</table>' . '</fieldset>' . '</div>'; return $html_output; } /** * Get HTML snippet for action row in structure table, * This function returns common HTML <td> for Primary, Unique, Index, * Spatial actions * * @param array $type column type * @param array $tbl_storage_engine table storage engine * @param string $class class attribute for <td> * @param boolean $hasField has field * @param boolean $hasLinkClass has <a> the class attribute * @param string $url_query url query * @param boolean $primary primary if set, false otherwise * @param string $syntax Sql syntax * @param string $message message to show * @param string $action action * @param array $titles titles array * @param array $row current row * @param boolean $isPrimary is primary action * * @return array $html_output, $action_enabled */ function PMA_getHtmlForActionRowInStructureTable($type, $tbl_storage_engine, $class, $hasField, $hasLinkClass, $url_query, $primary, $syntax, $message, $action, $titles, $row, $isPrimary ) { $html_output = '<li class="'. $class .'">'; if ($type == 'text' || $type == 'blob' || 'ARCHIVE' == $tbl_storage_engine || $hasField ) { $html_output .= $titles['No' . $action]; $action_enabled = false; } else { $html_output .= '<a rel="samepage" ' . ($hasLinkClass ? 'class="ajax add_primary_key_anchor" ' : '') . 'href="sql.php?' . $url_query . '&amp;sql_query=' . urlencode( 'ALTER TABLE ' . PMA_Util::backquote($GLOBALS['table']) . ($isPrimary ? ($primary ? ' DROP PRIMARY KEY,' : '') : '') . ' ' . $syntax . '(' . PMA_Util::backquote($row['Field']) . ');' ) . '&amp;message_to_show=' . urlencode( sprintf( $message, htmlspecialchars($row['Field']) ) ) . '" >' . $titles[$action] . '</a>'; $action_enabled = true; } $html_output .= '</li>'; return array($html_output, $action_enabled); } /** * Get HTML for fulltext action, * and this function returns $fulltext_enabled boolean value also * * @param string $tbl_storage_engine table storage engine * @param string $type column type * @param string $url_query url query * @param array $row current row * @param array $titles titles array * * @return type array $html_output, $fulltext_enabled */ function PMA_getHtmlForFullTextAction($tbl_storage_engine, $type, $url_query, $row, $titles ) { $html_output = '<li class="fulltext nowrap">'; if (! empty($tbl_storage_engine) && ($tbl_storage_engine == 'MYISAM' || $tbl_storage_engine == 'ARIA' || $tbl_storage_engine == 'MARIA' || ($tbl_storage_engine == 'INNODB' && PMA_MYSQL_INT_VERSION >= 50604)) && (strpos(' ' . $type, 'text') || strpos(' ' . $type, 'char')) ) { $html_output .= '<a rel="samepage" href="sql.php?' . $url_query . '&amp;sql_query=' . urlencode( 'ALTER TABLE ' . PMA_Util::backquote($GLOBALS['table']) . ' ADD FULLTEXT(' . PMA_Util::backquote($row['Field']) . ');' ) . '&amp;message_to_show=' . urlencode( sprintf( __('An index has been added on %s'), htmlspecialchars($row['Field']) ) ) . '">'; $html_output .= $titles['IdxFulltext'] . '</a>'; $fulltext_enabled = true; } else { $html_output .= $titles['NoIdxFulltext']; $fulltext_enabled = false; } $html_output .= '</li>'; return array($html_output, $fulltext_enabled); } /** * Get HTML snippet for "Distinc Value" action * * @param string $url_query url query * @param array $row current row * @param array $titles titles array * * @return string $html_output */ function PMA_getHtmlForDistinctValueAction($url_query, $row, $titles) { $html_output = '<li class="browse nowrap">'; $html_output .= '<a href="sql.php?' . $url_query . '&amp;sql_query=' . urlencode( 'SELECT COUNT(*) AS ' . PMA_Util::backquote(__('Rows')) . ', ' . PMA_Util::backquote($row['Field']) . ' FROM ' . PMA_Util::backquote($GLOBALS['table']) . ' GROUP BY ' . PMA_Util::backquote($row['Field']) . ' ORDER BY ' . PMA_Util::backquote($row['Field']) ) . '">' . $titles['DistinctValues'] . '</a>'; $html_output .= '</li>'; return $html_output; } /** * Get HTML snippet for Actions in table structure * * @param string $type column type * @param string $tbl_storage_engine table storage engine * @param boolean $primary primary if set, false otherwise * @param string $field_name column name * @param string $url_query url query * @param array $titles titles array * @param array $row current row * @param string $rownum row number * @param array $hidden_titles hidden titles * @param array $columns_with_unique_index columns with unique index * * @return string $html_output; */ function PMA_getHtmlForActionsInTableStructure($type, $tbl_storage_engine, $primary, $field_name, $url_query, $titles, $row, $rownum, $hidden_titles, $columns_with_unique_index ) { $html_output = '<td><ul class="table-structure-actions resizable-menu">'; list($primary, $primary_enabled) = PMA_getHtmlForActionRowInStructureTable( $type, $tbl_storage_engine, 'primary nowrap', ($primary && $primary->hasColumn($field_name)), true, $url_query, $primary, 'ADD PRIMARY KEY', __('A primary key has been added on %s'), 'Primary', $titles, $row, true ); $html_output .= $primary; list($unique, $unique_enabled) = PMA_getHtmlForActionRowInStructureTable( $type, $tbl_storage_engine, 'unique nowrap', isset($columns_with_unique_index[$field_name]), false, $url_query, $primary, 'ADD UNIQUE', __('An index has been added on %s'), 'Unique', $titles, $row, false ); $html_output .= $unique; list($index, $index_enabled) = PMA_getHtmlForActionRowInStructureTable( $type, $tbl_storage_engine, 'index nowrap', false, false, $url_query, $primary, 'ADD INDEX', __('An index has been added on %s'), 'Index', $titles, $row, false ); $html_output .= $index; if (!PMA_DRIZZLE) { $spatial_types = array( 'geometry', 'point', 'linestring', 'polygon', 'multipoint', 'multilinestring', 'multipolygon', 'geomtrycollection' ); list($spatial, $spatial_enabled) = PMA_getHtmlForActionRowInStructureTable( $type, $tbl_storage_engine, 'spatial nowrap', (! in_array($type, $spatial_types) || 'MYISAM' != $tbl_storage_engine ), false, $url_query, $primary, 'ADD SPATIAL', __('An index has been added on %s'), 'Spatial', $titles, $row, false ); $html_output .= $spatial; // FULLTEXT is possible on TEXT, CHAR and VARCHAR list ($fulltext, $fulltext_enabled) = PMA_getHtmlForFullTextAction( $tbl_storage_engine, $type, $url_query, $row, $titles ); $html_output .= $fulltext; } $html_output .= PMA_getHtmlForDistinctValueAction($url_query, $row, $titles); $html_output .= '</ul></td>'; return $html_output; } /** * Get hidden action titles (image and string) * * @return array $hidden_titles */ function PMA_getHiddenTitlesArray() { $hidden_titles = array(); $hidden_titles['DistinctValues'] = PMA_Util::getIcon( 'b_browse.png', __('Distinct values'), true ); $hidden_titles['Primary'] = PMA_Util::getIcon( 'b_primary.png', __('Add primary key'), true ); $hidden_titles['NoPrimary'] = PMA_Util::getIcon( 'bd_primary.png', __('Add primary key'), true ); $hidden_titles['Index'] = PMA_Util::getIcon( 'b_index.png', __('Add index'), true ); $hidden_titles['NoIndex'] = PMA_Util::getIcon( 'bd_index.png', __('Add index'), true ); $hidden_titles['Unique'] = PMA_Util::getIcon( 'b_unique.png', __('Add unique index'), true ); $hidden_titles['NoUnique'] = PMA_Util::getIcon( 'bd_unique.png', __('Add unique index'), true ); $hidden_titles['Spatial'] = PMA_Util::getIcon( 'b_spatial.png', __('Add SPATIAL index'), true ); $hidden_titles['NoSpatial'] = PMA_Util::getIcon( 'bd_spatial.png', __('Add SPATIAL index'), true ); $hidden_titles['IdxFulltext'] = PMA_Util::getIcon( 'b_ftext.png', __('Add FULLTEXT index'), true ); $hidden_titles['NoIdxFulltext'] = PMA_Util::getIcon( 'bd_ftext.png', __('Add FULLTEXT index'), true ); return $hidden_titles; } /** * Get action titles (image or string array * * @return array $titles */ function PMA_getActionTitlesArray() { $titles = array(); $titles['Change'] = PMA_Util::getIcon('b_edit.png', __('Change')); $titles['Drop'] = PMA_Util::getIcon('b_drop.png', __('Drop')); $titles['NoDrop'] = PMA_Util::getIcon('b_drop.png', __('Drop')); $titles['Primary'] = PMA_Util::getIcon('b_primary.png', __('Primary')); $titles['Index'] = PMA_Util::getIcon('b_index.png', __('Index')); $titles['Unique'] = PMA_Util::getIcon('b_unique.png', __('Unique')); $titles['Spatial'] = PMA_Util::getIcon('b_spatial.png', __('Spatial')); $titles['IdxFulltext'] = PMA_Util::getIcon('b_ftext.png', __('Fulltext')); $titles['NoPrimary'] = PMA_Util::getIcon('bd_primary.png', __('Primary')); $titles['NoIndex'] = PMA_Util::getIcon('bd_index.png', __('Index')); $titles['NoUnique'] = PMA_Util::getIcon('bd_unique.png', __('Unique')); $titles['NoSpatial'] = PMA_Util::getIcon('bd_spatial.png', __('Spatial')); $titles['NoIdxFulltext'] = PMA_Util::getIcon('bd_ftext.png', __('Fulltext')); $titles['DistinctValues'] = PMA_Util::getIcon('b_browse.png', __('Distinct values')); return $titles; } /** * Get HTML snippet for display table statistics * * @param array $showtable full table status info * @param integer $table_info_num_rows table info number of rows * @param boolean $tbl_is_view whether table is view or not * @param boolean $db_is_information_schema whether db is information schema or not * @param string $tbl_storage_engine table storage engine * @param string $url_query url query * @param string $tbl_collation table collation * * @return string $html_output */ function PMA_getHtmlForDisplayTableStats($showtable, $table_info_num_rows, $tbl_is_view, $db_is_information_schema, $tbl_storage_engine, $url_query, $tbl_collation ) { $html_output = '<div id="tablestatistics">'; if (empty($showtable)) { $showtable = PMA_Table::sGetStatusInfo( $GLOBALS['db'], $GLOBALS['table'], null, true ); } $nonisam = false; $is_innodb = (isset($showtable['Type']) && $showtable['Type'] == 'InnoDB'); if (isset($showtable['Type']) && ! preg_match('@ISAM|HEAP@i', $showtable['Type']) ) { $nonisam = true; } // Gets some sizes $mergetable = PMA_Table::isMerge($GLOBALS['db'], $GLOBALS['table']); // this is to display for example 261.2 MiB instead of 268k KiB $max_digits = 3; $decimals = 1; list($data_size, $data_unit) = PMA_Util::formatByteDown( $showtable['Data_length'], $max_digits, $decimals ); if ($mergetable == false) { list($index_size, $index_unit) = PMA_Util::formatByteDown( $showtable['Index_length'], $max_digits, $decimals ); } // InnoDB returns a huge value in Data_free, do not use it if (! $is_innodb && isset($showtable['Data_free']) && $showtable['Data_free'] > 0 ) { list($free_size, $free_unit) = PMA_Util::formatByteDown( $showtable['Data_free'], $max_digits, $decimals ); list($effect_size, $effect_unit) = PMA_Util::formatByteDown( $showtable['Data_length'] + $showtable['Index_length'] - $showtable['Data_free'], $max_digits, $decimals ); } else { list($effect_size, $effect_unit) = PMA_Util::formatByteDown( $showtable['Data_length'] + $showtable['Index_length'], $max_digits, $decimals ); } list($tot_size, $tot_unit) = PMA_Util::formatByteDown( $showtable['Data_length'] + $showtable['Index_length'], $max_digits, $decimals ); if ($table_info_num_rows > 0) { list($avg_size, $avg_unit) = PMA_Util::formatByteDown( ($showtable['Data_length'] + $showtable['Index_length']) / $showtable['Rows'], 6, 1 ); } // Displays them $odd_row = false; $html_output .= '<fieldset>' . '<legend>' . __('Information') . '</legend>' . '<a id="showusage"></a>'; if (! $tbl_is_view && ! $db_is_information_schema) { $html_output .= '<table id="tablespaceusage" class="data">' . '<caption class="tblHeaders">' . __('Space usage') . '</caption>' . '<tbody>'; $html_output .= PMA_getHtmlForSpaceUsageTableRow( $odd_row, __('Data'), $data_size, $data_unit ); $odd_row = !$odd_row; if (isset($index_size)) { $html_output .= PMA_getHtmlForSpaceUsageTableRow( $odd_row, __('Index'), $index_size, $index_unit ); $odd_row = !$odd_row; } if (isset($free_size)) { $html_output .= PMA_getHtmlForSpaceUsageTableRow( $odd_row, __('Overhead'), $free_size, $free_unit ); $html_output .= PMA_getHtmlForSpaceUsageTableRow( $odd_row, __('Effective'), $effect_size, $effect_unit ); $odd_row = !$odd_row; } if (isset($tot_size) && $mergetable == false) { $html_output .= PMA_getHtmlForSpaceUsageTableRow( $odd_row, __('Total'), $tot_size, $tot_unit ); $odd_row = !$odd_row; } // Optimize link if overhead if (isset($free_size) && !PMA_DRIZZLE && ($tbl_storage_engine == 'MYISAM' || $tbl_storage_engine == 'ARIA' || $tbl_storage_engine == 'MARIA' || $tbl_storage_engine == 'BDB') ) { $html_output .= PMA_getHtmlForOptimizeLink($url_query); } $html_output .= '</tbody>' . '</table>'; } $html_output .= getHtmlForRowStatsTable( $showtable, $tbl_collation, $is_innodb, $mergetable, (isset ($avg_size) ? $avg_size : ''), (isset ($avg_unit) ? $avg_unit : '') ); return $html_output; } /** * Displays HTML for changing one or more columns * * @param string $db database name * @param string $table table name * @param array $selected the selected columns * @param string $action target script to call * * @return boolean $regenerate true if error occurred * */ function PMA_displayHtmlForColumnChange($db, $table, $selected, $action) { // $selected comes from multi_submits.inc.php if (empty($selected)) { $selected[] = $_REQUEST['field']; $selected_cnt = 1; } else { // from a multiple submit $selected_cnt = count($selected); } /** * @todo optimize in case of multiple fields to modify */ for ($i = 0; $i < $selected_cnt; $i++) { $fields_meta[] = PMA_DBI_get_columns($db, $table, $selected[$i], true); } $num_fields = count($fields_meta); // set these globals because tbl_columns_definition_form.inc.php // verifies them // @todo: refactor tbl_columns_definition_form.inc.php so that it uses // function params $GLOBALS['action'] = 'tbl_structure.php'; $GLOBALS['num_fields'] = $num_fields; // Get more complete field information. // For now, this is done to obtain MySQL 4.1.2+ new TIMESTAMP options // and to know when there is an empty DEFAULT value. // Later, if the analyser returns more information, it // could be executed to replace the info given by SHOW FULL COLUMNS FROM. /** * @todo put this code into a require() * or maybe make it part of PMA_DBI_get_columns(); */ // We also need this to correctly learn if a TIMESTAMP is NOT NULL, since // SHOW FULL COLUMNS says NULL and SHOW CREATE TABLE says NOT NULL (tested // in MySQL 4.0.25). $show_create_table = PMA_DBI_fetch_value( 'SHOW CREATE TABLE ' . PMA_Util::backquote($db) . '.' . PMA_Util::backquote($table), 0, 1 ); $analyzed_sql = PMA_SQP_analyze(PMA_SQP_parse($show_create_table)); unset($show_create_table); /** * Form for changing properties. */ include 'libraries/tbl_columns_definition_form.inc.php'; } /** * Update the table's structure based on $_REQUEST * * @param string $db database name * @param string $table table name * * @return boolean $regenerate true if error occurred * */ function PMA_updateColumns($db, $table) { $err_url = 'tbl_structure.php?' . PMA_generate_common_url($db, $table); $regenerate = false; $field_cnt = count($_REQUEST['field_name']); $key_fields = array(); $changes = array(); for ($i = 0; $i < $field_cnt; $i++) { $changes[] = 'CHANGE ' . PMA_Table::generateAlter( isset($_REQUEST['field_orig'][$i]) ? $_REQUEST['field_orig'][$i] : '', $_REQUEST['field_name'][$i], $_REQUEST['field_type'][$i], $_REQUEST['field_length'][$i], $_REQUEST['field_attribute'][$i], isset($_REQUEST['field_collation'][$i]) ? $_REQUEST['field_collation'][$i] : '', isset($_REQUEST['field_null'][$i]) ? $_REQUEST['field_null'][$i] : 'NOT NULL', $_REQUEST['field_default_type'][$i], $_REQUEST['field_default_value'][$i], isset($_REQUEST['field_extra'][$i]) ? $_REQUEST['field_extra'][$i] : false, isset($_REQUEST['field_comments'][$i]) ? $_REQUEST['field_comments'][$i] : '', $key_fields, $i, isset($_REQUEST['field_move_to'][$i]) ? $_REQUEST['field_move_to'][$i] : '' ); } // end for // Builds the primary keys statements and updates the table $key_query = ''; /** * this is a little bit more complex * * @todo if someone selects A_I when altering a column we need to check: * - no other column with A_I * - the column has an index, if not create one * if (count($key_fields)) { $fields = array(); foreach ($key_fields as $each_field) { if (isset($_REQUEST['field_name'][$each_field]) && strlen($_REQUEST['field_name'][$each_field])) { $fields[] = PMA_Util::backquote($_REQUEST['field_name'][$each_field]); } } // end for $key_query = ', ADD KEY (' . implode(', ', $fields) . ') '; } */ // To allow replication, we first select the db to use and then run queries // on this db. if (! PMA_DBI_select_db($db)) { PMA_Util::mysqlDie( PMA_DBI_getError(), 'USE ' . PMA_Util::backquote($db) . ';', '', $err_url ); } $sql_query = 'ALTER TABLE ' . PMA_Util::backquote($table) . ' '; $sql_query .= implode(', ', $changes) . $key_query; $sql_query .= ';'; $result = PMA_DBI_try_query($sql_query); $response = PMA_Response::getInstance(); if ($result !== false) { $message = PMA_Message::success( __('Table %1$s has been altered successfully') ); $message->addParam($table); /** * If comments were sent, enable relation stuff */ include_once 'libraries/transformations.lib.php'; // update field names in relation if (isset($_REQUEST['field_orig']) && is_array($_REQUEST['field_orig'])) { foreach ($_REQUEST['field_orig'] as $fieldindex => $fieldcontent) { if ($_REQUEST['field_name'][$fieldindex] != $fieldcontent) { PMA_REL_renameField( $db, $table, $fieldcontent, $_REQUEST['field_name'][$fieldindex] ); } } } // update mime types if (isset($_REQUEST['field_mimetype']) && is_array($_REQUEST['field_mimetype']) && $GLOBALS['cfg']['BrowseMIME'] ) { foreach ($_REQUEST['field_mimetype'] as $fieldindex => $mimetype) { if (isset($_REQUEST['field_name'][$fieldindex]) && strlen($_REQUEST['field_name'][$fieldindex]) ) { PMA_setMIME( $db, $table, $_REQUEST['field_name'][$fieldindex], $mimetype, $_REQUEST['field_transformation'][$fieldindex], $_REQUEST['field_transformation_options'][$fieldindex] ); } } } $response->addHTML( PMA_Util::getMessage($message, $sql_query, 'success') ); } else { // An error happened while inserting/updating a table definition $response->isSuccess(false); $response->addJSON('message', PMA_Message::rawError(__('Query error') . ':<br />'.PMA_DBI_getError()) ); $regenerate = true; } return $regenerate; } /** * Moves columns in the table's structure based on $_REQUEST * * @param string $db database name * @param string $table table name */ function PMA_moveColumns($db, $table) { PMA_DBI_select_db($db); /* * load the definitions for all columns */ $columns = PMA_DBI_get_columns_full($db, $table); $column_names = array_keys($columns); $changes = array(); $we_dont_change_keys = array(); // move columns from first to last for ($i = 0, $l = count($_REQUEST['move_columns']); $i < $l; $i++) { $column = $_REQUEST['move_columns'][$i]; // is this column already correctly placed? if ($column_names[$i] == $column) { continue; } // it is not, let's move it to index $i $data = $columns[$column]; $extracted_columnspec = PMA_Util::extractColumnSpec($data['Type']); if (isset($data['Extra']) && $data['Extra'] == 'on update CURRENT_TIMESTAMP') { $extracted_columnspec['attribute'] = $data['Extra']; unset($data['Extra']); } $current_timestamp = false; if (($data['Type'] == 'timestamp' || $data['Type'] == 'datetime') && $data['Default'] == 'CURRENT_TIMESTAMP' ) { $current_timestamp = true; } $default_type = $data['Null'] === 'YES' && $data['Default'] === null ? 'NULL' : ($current_timestamp ? 'CURRENT_TIMESTAMP' : ($data['Default'] === null ? 'NONE' : 'USER_DEFINED')); $changes[] = 'CHANGE ' . PMA_Table::generateAlter( $column, $column, strtoupper($extracted_columnspec['type']), $extracted_columnspec['spec_in_brackets'], $extracted_columnspec['attribute'], isset($data['Collation']) ? $data['Collation'] : '', $data['Null'] === 'YES' ? 'NULL' : 'NOT NULL', $default_type, $current_timestamp ? '' : $data['Default'], isset($data['Extra']) && $data['Extra'] !== '' ? $data['Extra'] : false, isset($data['Comments']) && $data['Comments'] !== '' ? $data['Comments'] : false, $we_dont_change_keys, $i, $i === 0 ? '-first' : $column_names[$i - 1] ); // update current column_names array, first delete old position for ($j = 0, $ll = count($column_names); $j < $ll; $j++) { if ($column_names[$j] == $column) { unset($column_names[$j]); } } // insert moved column array_splice($column_names, $i, 0, $column); } $response = PMA_Response::getInstance(); if (empty($changes)) { // should never happen $response->isSuccess(false); exit; } $move_query = 'ALTER TABLE ' . PMA_Util::backquote($table) . ' '; $move_query .= implode(', ', $changes); // move columns $result = PMA_DBI_try_query($move_query); $tmp_error = PMA_DBI_getError(); if ($tmp_error) { $response->isSuccess(false); $response->addJSON('message', PMA_Message::error($tmp_error)); } else { $message = PMA_Message::success( __('The columns have been moved successfully.') ); $response->addJSON('message', $message); $response->addJSON('columns', $column_names); } exit; } ?>
{ "content_hash": "0e2c947df67171b91ec27e0baaa03697", "timestamp": "", "source": "github", "line_count": 2523, "max_line_length": 110, "avg_line_length": 35.16924296472453, "alnum_prop": 0.5263151963215075, "repo_name": "exhibia/exhibia", "id": "2d9fab94a2eddf33709e307d026dba6852768f04", "size": "88732", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "phpmyadmin/libraries/structure.lib.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "9307" }, { "name": "JavaScript", "bytes": "126410" }, { "name": "PHP", "bytes": "2449281" }, { "name": "Shell", "bytes": "2611" } ], "symlink_target": "" }