text
stringlengths
2
1.04M
meta
dict
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Internal.Text; using Internal.TypeSystem; using Debug = System.Diagnostics.Debug; namespace ILCompiler.DependencyAnalysis { /// <summary> /// Represents an unboxing stub that supports calling instance methods on boxed valuetypes. /// </summary> public partial class UnboxingStubNode : AssemblyStubNode, IMethodNode, IExportableSymbolNode { private MethodDesc _target; public MethodDesc Method { get { return _target; } } public bool IsExported(NodeFactory factory) => factory.CompilationModuleGroup.ExportsMethod(Method); public UnboxingStubNode(MethodDesc target) { Debug.Assert(target.GetCanonMethodTarget(CanonicalFormKind.Specific) == target); Debug.Assert(target.OwningType.IsValueType); _target = target; } public override void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { sb.Append("unbox_").Append(nameMangler.GetMangledMethodName(_target)); } public static string GetMangledName(NameMangler nameMangler, MethodDesc method) { return "unbox_" + nameMangler.GetMangledMethodName(method); } public override bool IsShareable => true; protected override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler); } }
{ "content_hash": "bb853cb5d0443b9f3d54147168f592ff", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 108, "avg_line_length": 32.96, "alnum_prop": 0.6705097087378641, "repo_name": "yizhang82/corert", "id": "e63087f885e1354aab3beab24e4c60cbb2b6b8f9", "size": "1650", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "src/ILCompiler.Compiler/src/Compiler/DependencyAnalysis/UnboxingStubNode.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "845310" }, { "name": "Batchfile", "bytes": "60223" }, { "name": "C", "bytes": "663925" }, { "name": "C#", "bytes": "20003372" }, { "name": "C++", "bytes": "4333358" }, { "name": "CMake", "bytes": "56167" }, { "name": "Groovy", "bytes": "4569" }, { "name": "Objective-C", "bytes": "14753" }, { "name": "PAWN", "bytes": "849" }, { "name": "PowerShell", "bytes": "2992" }, { "name": "Shell", "bytes": "106793" } ], "symlink_target": "" }
#include "string_copy.h" #include "csnan.h" #include <cstring> using namespace v8; namespace node_libxl { StringCopy::StringCopy(String::Utf8Value& utf8Value) { str = new char[strlen(*utf8Value) + 1]; strcpy(str, *utf8Value); } StringCopy::StringCopy(Local<Value> value) { String::Utf8Value utf8Value(v8::Isolate::GetCurrent(), value); str = new char[strlen(*utf8Value) + 1]; strcpy(str, *utf8Value); } StringCopy::~StringCopy() { delete[] str; } char* StringCopy::operator*() { return str; } }
{ "content_hash": "c729c38577c831c55c46e83177d6b9fe", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 66, "avg_line_length": 15.342857142857143, "alnum_prop": 0.659217877094972, "repo_name": "DirtyHairy/node-libxl", "id": "34d906441ec29b0a4f7a91d48a64ba266eed4059", "size": "1714", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/string_copy.cc", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "2691" }, { "name": "C++", "bytes": "187770" }, { "name": "JavaScript", "bytes": "74577" }, { "name": "Python", "bytes": "6093" } ], "symlink_target": "" }
<?php //---------------------------------------------------------------------- // Copyright (c) 2011-2015 Raytheon BBN Technologies // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and/or hardware specification (the "Work") to // deal in the Work without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Work, and to permit persons to whom the Work // is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Work. // // THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS // IN THE WORK. //---------------------------------------------------------------------- ?> <?php require_once("user.php"); require_once("cert_utils.php"); require_once("rq_client.php"); require_once("settings.php"); require_once("user-preferences.php"); ?> <?php function js_delete_ssh_key() { /* * * A javascript function to confirm the delete. */ echo <<< END <script type="text/javascript" src="tools-user.js"></script> <script type="text/javascript"> function deleteSshKey(dest){ var r=confirm("Are you sure you want to delete this ssh key?"); if (r==true) { window.location = dest; } } </script> END; } ?> <script src='cards.js'></script> <div class='nav2'> <ul class='tabs'> <li><a class='tab' data-tabindex=1 href='#accountsummary'>Account Summary</a></li> <li><a class='tab' data-tabindex=2 href='#ssh'>SSH Keys</a></li> <li><a class='tab' data-tabindex=3 href='#ssl'>SSL</a></li> <li><a class='tab' data-tabindex=4 href='#omni'>Configure <code>omni</code></a></li> <li><a class='tab' data-tabindex=5 href='#rspecs' title="Resource Specifications">RSpecs</a></li> <li><a class='tab' data-tabindex=6 href='#tools'>Manage Accounts</a></li> <li><a class='tab' data-tabindex=7 href='#outstandingrequests'>Outstanding Requests</a></li> <li><a class='tab' data-tabindex=8 href='#preferences'>Preferences</a></li> </ul> </div> <?php // BEGIN the tabContent class // this makes a fixed height box with scrolling for overflow echo "<div class='tabContent'>"; ?> <?php /*---------------------------------------------------------------------- * SSH key management *---------------------------------------------------------------------- */ // BEGIN SSH tab echo "<div class='card' id='ssh'>"; print "<h2>SSH Keys</h2>\n"; $keys = $user->sshKeys(); $disable_ssh_keys = ""; if ($in_lockdown_mode) $disable_ssh_keys = "disabled"; if (count($keys) == 0) { // No ssh keys are present. print "<p>No SSH keys have been uploaded. "; print "SSH keys are required to log in to reserved compute resources. You have two options:</p>\n"; $generate_btn = "<button $disable_ssh_keys onClick=\"window.location='generatesshkey.php'\"> generate and download an SSH keypair</button>"; print '<ol type="i">'; print "<li>$generate_btn"; print "The private key (but not the passphrase that protects it) might be shared with other GENI entities. If you choose this option do not reuse this key pair outside of GENI, or</li>\n"; print "<li><button $disable_ssh_keys onClick=\"window.location='uploadsshkey.php'\"> upload an SSH public key</button>, if you have one you want to use. If you only choose this option then some GENI tools might not work properly</p>\n"; print "</ol>\n"; print "<p>If you're not sure what to do, choose $generate_btn</p>\n"; } else { $download_pkey_url = relative_url('downloadsshkey.php?'); $download_putty_url = relative_url('downloadputtykey.php?'); $download_public_key_url = relative_url('downloadsshpublickey.php?'); $edit_sshkey_url = relative_url('sshkeyedit.php?'); $delete_sshkey_url = relative_url('deletesshkey.php?'); js_delete_ssh_key(); // javascript for delete key confirmation print "\n<div class='tablecontainer'><table>\n"; print "<tr><th>Name</th><th>Description</th><th>Public Key</th><th>Private Key</th>" . "<th>PuTTY</th>" . "<th>Edit</th><th>Delete</th></tr>\n"; foreach ($keys as $key) { // generate key's fingerprint $fingerprint_key = NULL; $fingerprint_key = $key['public_key']; // write key to temp file $fingerprint_key_filename = tempnam(sys_get_temp_dir(), 'fingerprint'); $fingerprint_key_file = fopen($fingerprint_key_filename, "w"); fwrite($fingerprint_key_file, $fingerprint_key); fclose($fingerprint_key_file); // get fingerprint $cmd_array = array('/usr/bin/ssh-keygen', '-lf', $fingerprint_key_filename, ); $command = implode(" ", $cmd_array); $result = exec($command, $output, $status); $fingerprint_array = explode(' ', $result); $fingerprint = $fingerprint_array[1]; // store fingerprint unlink($fingerprint_key_filename); $args['id'] = $key['id']; $query = http_build_query($args); if (is_null($key['private_key'])) { $pkey_cell = 'N/A'; $putty_cell = "N/A"; } else { $pkey_cell = ("<button onClick=\"window.location='" . $download_pkey_url . $query . "'\">Download Private Key</button>"); $putty_cell = ("<button onClick=\"window.location='" . $download_putty_url . $query . "'\">Download PuTTY Key</button>"); } $public_key_download_cell = ("<button $disable_ssh_keys onClick=\"window.location='" . $download_public_key_url . $query . "'\">Download Public Key</button>"); $edit_cell = ("<button $disable_ssh_keys onClick=\"window.location='" . $edit_sshkey_url . $query . "'\">Edit</button>"); $delete_cell = ("<button $disable_ssh_keys onClick=\"deleteSshKey('" . $delete_sshkey_url . $query . "')\">Delete</button>"); print "<tr>" . "<td>" . htmlentities($key['filename']) . "<br><small>" . $fingerprint . "</small>" . "</td>" . "<td>" . htmlentities($key['description']) . "</td>" . '<td>' . $public_key_download_cell . '</td>' . '<td>' . $pkey_cell . '</td>' . '<td>' . $putty_cell . '</td>' . '<td>' . $edit_cell . '</td>' . '<td>' . $delete_cell . '</td>' . "</tr>\n"; } print "</table></div>\n"; print "<p>On Linux and Mac systems and for most Windows SSH clients (not PuTTY), do:"; print "<ul class='instructions'>"; print "<li>Download your private key.</li>"; print "<li>On Windows, just point your SSH client (not PuTTY) to the downloaded private key.</li>"; print "<li>On Linux and Mac, open a terminal.</li>"; print "<ul class='instructions'>"; print "<li>Store your key under ~/.ssh/ :"; print "<ul class='instructions'>"; print "<li>If the directory does not exist, create it:</li>"; print "<pre>mkdir ~/.ssh</pre>"; print "<li>Move the key to ~/.ssh/ :</li>"; print "<pre>mv ~/Downloads/id_geni_ssh_rsa ~/.ssh/</pre>"; print "<li>Change the file permissions:"; print "<pre>chmod 0600 ~/.ssh/id_geni_ssh_rsa</pre>"; print "</ul>"; print "<li>Your SSH command will be something like:</li>"; print "<pre>ssh -i ~/.ssh/id_geni_ssh_rsa [username]@[hostname] -p [port]</pre>"; print "</ul>"; print "</ul>"; print "<p>"; print "<p>For PuTTY users:"; print "<ul class='instructions'>"; print "<li>Download PuTTY key."; print "<li>In PuTTY, create a new session that uses the 'username', 'hostname' and 'port' for the resources you have reserved.</li>"; print "<li>Under the authentication menu, point the key field to the downloaded PuTTY key file.</li>"; print "</ul>"; /* print "<p><b>Note</b>: You will need your SSH private key on your local machine. </p>\n<p>If you generated your SSH keypair on this portal and have not already done so, be sure to:</p> <ol> <li>Download your SSH key.</li> <li>After you download your key, be sure to set local permissions on that file appropriately. On Linux and Mac, do <pre>chmod 0600 [path-to-SSH-private-key]</pre></li> <li>When you invoke SSH to log in to reserved resources, you will need to remember the path to that file.</li> <li>Your SSH command will be something like: <pre>ssh -i path-to-SSH-key-you-downloaded [username]@[hostname]</pre>\n"; print "</ol>\n"; */ print "<p><button $disable_ssh_keys onClick=\"window.location='uploadsshkey.php'\">Upload another SSH public key</button></p>\n"; } // END SSH tab echo "</div>"; /*---------------------------------------------------------------------- * SSL Cert *---------------------------------------------------------------------- */ // BEGIN SSL tab echo "<div class='card' id='ssl'>"; print "<h2>SSL Certificate</h2>\n"; print "<p>"; if (! isset($ma_url)) { $ma_url = get_first_service_of_type(SR_SERVICE_TYPE::MEMBER_AUTHORITY); if (! isset($ma_url) || is_null($ma_url) || $ma_url == '') { error_log("Found no MA in SR!'"); } } $result = ma_lookup_certificate($ma_url, $user, $user->account_id); $expiration_key = 'expiration'; $has_certificate = False; $has_key = False; $expired = False; $expiration = NULL; if (! is_null($result)) { $has_certificate = True; $has_key = array_key_exists(MA_ARGUMENT::PRIVATE_KEY, $result); if (array_key_exists($expiration_key, $result)) { $expiration = $result[$expiration_key]; $now = new DateTime('now', new DateTimeZone("UTC")); $expired = ($expiration < $now); } } $kmcert_url = "kmcert.php?close=1"; $button1_label = 'Create an SSL certificate'; if (! $has_certificate) { /* No certificate, so show the create button. */ print "<button onClick=\"window.open('$kmcert_url')\">"; print $button1_label; print "</button>"; print "</p>"; } else if ($expired) { /* Have an expired certificate, just renew it. */ print 'Your SSL certificate has expired. Please'; print ' <a href="kmcert.php?close=1&renew=1" target="_blank">'; print 'renew your SSL certificate</a> now'; print '</p>'; } else { /* Have a current certificate */ if ($has_key) { $button1_label = 'Download your SSL certificate and key'; } else if ($has_certificate) { $button1_label = 'Download your SSL certificate'; } print "<button onClick=\"window.open('$kmcert_url')\">"; print $button1_label; print "</button>"; print "</p>"; // Display a renew link print '<p>'; if ($expiration) { print 'Your SSL certificate expires on '; print dateUIFormat($expiration); print '.'; } print ' You can <a href="kmcert.php?close=1&renew=1" target="_blank">'; print 'renew your SSL certificate</a> at any time.'; print '</p>'; } // END SSL tab echo "</div>"; // BEGIN outstand requests tab echo "<div class='card' id='outstandingrequests'>"; print "<h2>Outstanding Requests</h2>"; // Show outstanding requests BY this user if (! isset($sa_url)) { $sa_url = get_first_service_of_type(SR_SERVICE_TYPE::SLICE_AUTHORITY); if (! isset($sa_url) || is_null($sa_url) || $sa_url == '') { error_log("Found no SA in SR!'"); } } if (! isset($ma_url)) { $ma_url = get_first_service_of_type(SR_SERVICE_TYPE::MEMBER_AUTHORITY); if (! isset($ma_url) || is_null($ma_url) || $ma_url == '') { error_log("Found no MA in SR!'"); } } // This next block of code pretends to handle requests to join a slice, but we don't do that // It also claims to handle profile modification requests. But those are handled separately. // FIXME: Show outstanding project lead requests. See code in tools-admin.php $preqs = get_requests_by_user($sa_url, $user, $user->account_id, CS_CONTEXT_TYPE::PROJECT, null, RQ_REQUEST_STATUS::PENDING); //$sreqs = get_requests_by_user($sa_url, $user, $user->account_id, CS_CONTEXT_TYPE::SLICE, null, RQ_REQUEST_STATUS::PENDING); //$reqs = array_merge($preqs, $sreqs); $reqs = $preqs; if (isset($reqs) && count($reqs) > 0) { print "Found " . count($reqs) . " outstanding request(s) by you:<br/>\n"; print "<div class='tablecontainer'><table>\n"; // Could add the lead and purpose? print "<tr><th>Request Type</th><th>Project</th><th>Request Created</th><th>Request Reason</th><th>Cancel Request?</th></tr>\n"; $REQ_TYPE_NAMES = array(); $REQ_TYPE_NAMES[] = 'Join'; $REQ_TYPE_NAMES[] = 'Update Attributes'; foreach ($reqs as $request) { $name = ""; //error_log(print_r($request, true)); $typestr = $REQ_TYPE_NAMES[$request[RQ_REQUEST_TABLE_FIELDNAME::REQUEST_TYPE]] . " " . $CS_CONTEXT_TYPE_NAME[$request[RQ_REQUEST_TABLE_FIELDNAME::CONTEXT_TYPE]]; if ($request[RQ_REQUEST_TABLE_FIELDNAME::CONTEXT_TYPE] == CS_CONTEXT_TYPE::PROJECT) { //error_log("looking up project " . $request[RQ_REQUEST_TABLE_FIELDNAME::CONTEXT_ID]); $project = lookup_project($sa_url, $user, $request[RQ_REQUEST_TABLE_FIELDNAME::CONTEXT_ID]); $name = $project[PA_PROJECT_TABLE_FIELDNAME::PROJECT_NAME]; $cancel_url="cancel-join-project.php?request_id=" . $request[RQ_REQUEST_TABLE_FIELDNAME::ID]; // } elseif ($request[RQ_REQUEST_TABLE_FIELDNAME::CONTEXT_TYPE] == CS_CONTEXT_TYPE::SLICE) { // $slice = lookup_slice($sa_url, $request[RQ_REQUEST_TABLE_FIELDNAME::CONTEXT_ID]); // $name = $slice[SA_SLICE_TABLE_FIELDNAME::SLICE_NAME]; // $cancel_url="cancel-join-slice.php?request_id=" . $request[RQ_REQUEST_TABLE_FIELDNAME::ID]; // } else { // $name = ""; // $cancel_url="cancel-account-mod.php?request_id=" . $request[RQ_REQUEST_TABLE_FIELDNAME::ID]; } $cancel_button = "<button style=\"\" onClick=\"window.location='" . $cancel_url . "'\"><b>Cancel Request</b></button>"; $reason = $request[RQ_REQUEST_TABLE_FIELDNAME::REQUEST_TEXT]; $req_date_db = $request[RQ_REQUEST_TABLE_FIELDNAME::CREATION_TIMESTAMP]; $req_date = dateUIFormat($req_date_db); print "<tr><td>$typestr</td><td>$name</td><td>$req_date</td><td>$reason</td><td>$cancel_button</td></tr>\n"; } print "</table></div>\n"; print "<br/>\n"; } else { print "<p><i>No outstanding requests to join projects.</i></p>\n"; } // END outstanding requests tab echo "</div>"; // BEGIN account summary tab echo "<div class='card' id='accountsummary'>"; $disable_account_details = ""; if($in_lockdown_mode) { $disable_account_details = "disabled"; } /* Determine OpenID URL */ $protocol = "http"; if (array_key_exists('HTTPS', $_SERVER)) { $protocol = "https"; } $host = $_SERVER['SERVER_NAME']; $openid_url = ("$protocol://$host/server/server.php/idpage?user=" . $user->username); print "<h2>Account Summary</h2>\n"; // Show username, email, affiliation, IdP, urn, prettyName, maybe project count and slice count // Put this in a nice table print "<div class='tablecontainer'><table>\n"; print "<tr><th>Name</th><td>" . $user->prettyName() . "</td></tr>\n"; print "<tr><th>Email</th><td>" . $user->email() . "</td></tr>\n"; print "<tr><th>GENI Username</th><td>" . $user->username . "</td></tr>\n"; print "<tr><th>GENI OpenID URL</th><td>" . $openid_url . "</td></tr>\n"; print "<tr><th>GENI URN</th><td>" . $user->urn() . "</td></tr>\n"; print "<tr><th>Affiliation</th><td>" . $user->affiliation . "</td></tr>\n"; if ($user->phone() != "") print "<tr><th>Telephone Number</th><td>" . $user->phone() . "</td></tr>\n"; // FIXME: Project count? Slice count? // FIXME: Other attributes? // FIXME: Permissions print "</table></div>\n"; print "<p><button $disable_account_details onClick=\"window.location='modify.php'\">Modify user supplied account details </button> (e.g. to become a Project Lead).</p>"; $sfcred = $user->speaksForCred(); if ($sfcred) { $sf_expires = $sfcred->expires(); ?> <p>Portal authorization expires: <?php echo $sf_expires; ?><br/> <a onclick='deauthorizePortal()'>Deauthorize the portal</a> </p> <?php } else if ($user->isAllowed(CS_ACTION::ADMINISTER_MEMBERS, CS_CONTEXT_TYPE::MEMBER, null)) { /* If user is an operator... show the authorize link. */ /* This is really just for debugging/development at this time. */ ?> <p><a href='speaks-for.php'>Authorize the portal</a></p> <?php } // END account summary tab echo "</div>"; //print "<h1>My Stuff</h1>\n"; // BEGIN rspecs tab echo "<div class='card' id='rspecs'>"; /*---------------------------------------------------------------------- * RSpecs *---------------------------------------------------------------------- */ if (!$in_lockdown_mode) { include("tool-rspecs.php"); } // END rspecs tab echo "</div>"; ?> <?php /*---------------------------------------------------------------------- * SSL Cert management *---------------------------------------------------------------------- */ // BEGIN omni tab echo "<div class='card' id='omni'>"; // Does the user have an outside certificate? $result = ma_lookup_certificate($ma_url, $user, $user->account_id); $has_certificate = ! is_null($result); // FIXME: hardcoded paths $create_url = "https://" . $_SERVER['SERVER_NAME'] . "/secure/kmcert.php?close=1"; $download_url = "https://" . $_SERVER['SERVER_NAME'] . "/secure/kmcert.php?close=1"; ?> <h2>Configure <code>omni</code></h2> <p><a href='http://trac.gpolab.bbn.com/gcf/wiki/Omni'><code>omni</code></a> is a command line tool intended for experienced users. </p> <h3>Option 1: Automatic <code>omni</code> configuration</h3> <p>To automatically configure <code>omni</code>, use the <a href='http://trac.gpolab.bbn.com/gcf/wiki/OmniConfigure/Automatic'><code>omni-configure</code></a> script distributed with <code>omni</code> as described below.</p> <ol> <li> In order to use <code>omni</code> you will need to generate an SSL certificate. <br/> <?php if (!$has_certificate): ?> <button onClick="window.open('<?php print $create_url?>')">Generate an SSL certificate</button>. <?php else: ?> <b>Good! You have already generated an SSL certificate.</b> <?php endif; ?> </li> <li>Download your customized <code>omni</code> configuration data and save it in the default location (<code>~/Downloads/omni.bundle</code>):<br/> <button onClick="window.location='omni-bundle.php'">Download your omni data</button> </li> <li>Run the following command in a terminal to generate a configuration file for omni (<code>omni_config</code>): <pre>omni-configure</pre></li> <li>Test your setup by running the following command in a terminal: <pre>omni -a gpo-ig getversion</pre> The output should look similar to this <a href='http://trac.gpolab.bbn.com/gcf/attachment/wiki/OmniConfigure/Automatic/getversion.out'>example output</a>. </li> </ol> <table id='tip'> <tr> <td rowspan=3><img id='tipimg' src="/images/Symbols-Tips-icon-clear.png" width="75" height="75" alt="Tip"></td> <td><b>Tip</b> Make sure you are running <b>omni 2.8.1</b> or newer.</td> </tr> <tr><td>To determine the version of an existing <code>omni</code> installation, run: <pre>omni --version</pre> </td></tr> <tr><td>If necessary, <a href="http://trac.gpolab.bbn.com/gcf/wiki#GettingStarted" target='_blank'>download</a> and <a href="http://trac.gpolab.bbn.com/gcf/wiki/QuickStart" target='_blank'>install</a> the latest version of <code>omni</code>.</td></tr> </table> <p>Complete <a href='http://trac.gpolab.bbn.com/gcf/wiki/OmniConfigure/Automatic'><code>omni-configure</code> instructions</a> are available.</p> <h3>Option 2: Manual <code>omni</code> configuration</h3> <p><a href='tool-omniconfig.php'>Download and customize a template <code>omni</code> configuration file</a>.</p> <?php // END omni tab echo "</div>"; ?> <!-- <table> <tr><th>Tool</th><th>Description</th><th>Configuration File</th></tr> <tr> <td><a href='http://trac.gpolab.bbn.com/gcf/wiki'>Omni</a></td> <td>command line resource allocation tool</td> <td><a href='tool-omniconfig.php'>Get omni_config</a></td> </tr> <tr> <td>omni_configure</td> <td>omni configuration tool</td> <td><a href='omni-bundle.php'>Get omni-bundle.zip</a></td> </tr> </table> --> <?php // BEGIN tools tab echo "<div class='card' id='tools'>"; $disable_authorize_tools = ""; if($in_lockdown_mode) { $disable_authorize_tools = "disabled"; } /* Only show the tools authorization page if we're not in full * speaks-for mode. */ print '<h2>Manage accounts</h2>'; if (!$speaks_for_enabled) { print "<p><button $disable_authorize_tools onClick=\"window.location='kmhome.php'\">Authorize or De-authorize tools</button> to act on your behalf.</p>"; } $irodsdisabled="disabled"; if (! isset($disable_irods) or $user->hasAttribute('enable_irods')) { $irodsdisabled = ""; } print "<a class='button' href='irods.php' $irodsdisabled>Manage iRODS Account</a><br><br>\n"; print "<a class='button' href='savi.php'>Create SAVI Account</a><br><br>\n"; print "<a class='button' href='wimax-enable.php'>Manage Wireless Account</a>\n"; // END tools tab echo "</div>"; // END the tabContent class echo "</div>"; ?> <script type="text/javascript"> $(document).ready(function(){ $(".preferenceselect").change(function(){ $("#saveprefs").prop("disabled", false); }); }); function save_preferences(user_urn) { params = { user_urn: user_urn, <?php foreach($possible_prefs as $pref_name => $pref_values) { echo "$pref_name: $('#default_{$pref_name}').val(), \n"; } ?> }; $.post("do-update-user-preferences", params, function(data){ $("#preferencesuccess").html(data); $("#saveprefs").prop("disabled", true); }); } </script> <?php echo "<div class='card' id='preferences'>"; echo "<h2>Portal preferences</h2>"; $preference_descriptions = array( "homepage_view" => "Default homepage style (for slices and projects)", "slice_view" => "Default tab for slice page" ); foreach($possible_prefs as $pref_name => $pref_values) { print $preference_descriptions[$pref_name]; print "<select id='default_{$pref_name}' class='preferenceselect'>"; foreach ($pref_values as $pref_value) { $user_value = get_preference($user->urn(), $pref_name); $selected = $pref_value == $user_value ? "selected" : ""; print "<option value='$pref_value' $selected>$pref_value</option>"; } print "</select><br>"; } echo "<button disabled onclick='save_preferences(\"{$user->urn()}\")' id='saveprefs' style='margin-right: 20px;'>Save preferences</button>"; echo "<span id='preferencesuccess'></span>"; echo "</div>"; ?>
{ "content_hash": "bc6a83b15920dd5a9182adc8176fde8c", "timestamp": "", "source": "github", "line_count": 588, "max_line_length": 259, "avg_line_length": 39.39115646258504, "alnum_prop": 0.6129436145410586, "repo_name": "charliemeyer/geni-portal", "id": "209deb9815ac8af73afa97dc4c965278ffb5de2c", "size": "23162", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "lib/php/tools-user.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "961" }, { "name": "Batchfile", "bytes": "181" }, { "name": "CSS", "bytes": "89826" }, { "name": "HTML", "bytes": "44473" }, { "name": "JavaScript", "bytes": "262028" }, { "name": "Makefile", "bytes": "1688" }, { "name": "PHP", "bytes": "2130894" }, { "name": "Python", "bytes": "122744" }, { "name": "SQLPL", "bytes": "399" }, { "name": "Shell", "bytes": "25131" } ], "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>ConnectionPendingException - Android SDK | Android Developers</title> <!-- STYLESHEETS --> <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:regular,medium,thin,italic,mediumitalic,bold" title="roboto"> <link href="../../../../assets/css/default.css" 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 devsite = false; </script> <script src="../../../../assets/js/docs.js" type="text/javascript"></script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-5831155-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); })(); </script> </head> <body class="gc-documentation develop" itemscope itemtype="http://schema.org/Article"> <div id="doc-api-level" class="1" style="display:none"></div> <a name="top"></a> <a name="top"></a> <!-- Header --> <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" 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/index.html" zh-tw-lang="發佈" zh-cn-lang="分发" ru-lang="Распространение" ko-lang="배포" ja-lang="配布" es-lang="Distribuir" >Distribute</a></li> </ul> <!-- New Search --> <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/">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> <div class="bottom"></div> </div> <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> </div> <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> <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> <!-- /New Search> <!-- Expanded quicknav --> <div id="quicknav" class="col-9"> <ul> <li class="design"> <ul> <li><a href="../../../../design/index.html">Get Started</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/components/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="../../../../tools/index.html" zh-tw-lang="相關工具" zh-cn-lang="工具" ru-lang="Инструменты" ko-lang="도구" ja-lang="ツール" es-lang="Herramientas" >Tools</a> <ul><li><a href="../../../../sdk/index.html">Get the SDK</a></li></ul> </li> <li><a href="../../../../google/index.html">Google Services</a> </li> </ul> </li> <li class="distribute last"> <ul> <li><a href="../../../../distribute/index.html">Google Play</a></li> <li><a href="../../../../distribute/googleplay/publish/index.html">Publishing</a></li> <li><a href="../../../../distribute/googleplay/promote/index.html">Promoting</a></li> <li><a href="../../../../distribute/googleplay/quality/index.html">App Quality</a></li> <li><a href="../../../../distribute/googleplay/spotlight/index.html">Spotlight</a></li> <li><a href="../../../../distribute/open.html">Open Distribution</a></li> </ul> </li> </ul> </div> <!-- /Expanded quicknav --> </div> </div> <!-- /Header --> <div id="searchResults" class="wrap" style="display:none;"> <h2 id="searchTitle">Results</h2> <div id="leftSearchControl" class="search-control">Loading...</div> </div> <!-- 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/components/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="../../../../tools/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 --> <div class="wrap clearfix" id="body-content"> <div class="col-4" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement"> <div id="devdoc-nav"> <a class="totop" href="#top" data-g-event="left-nav-top">to top</a> <div id="api-nav-header"> <div id="api-level-toggle"> <label for="apiLevelCheckbox" class="disabled">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 = [ '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19' ]; 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-1"> <a href="../../../../reference/android/package-summary.html">android</a></li> <li class="api apilevel-4"> <a href="../../../../reference/android/accessibilityservice/package-summary.html">android.accessibilityservice</a></li> <li class="api apilevel-5"> <a href="../../../../reference/android/accounts/package-summary.html">android.accounts</a></li> <li class="api apilevel-11"> <a href="../../../../reference/android/animation/package-summary.html">android.animation</a></li> <li class="api apilevel-1"> <a href="../../../../reference/android/app/package-summary.html">android.app</a></li> <li class="api apilevel-8"> <a href="../../../../reference/android/app/admin/package-summary.html">android.app.admin</a></li> <li class="api apilevel-8"> <a href="../../../../reference/android/app/backup/package-summary.html">android.app.backup</a></li> <li class="api apilevel-3"> <a href="../../../../reference/android/appwidget/package-summary.html">android.appwidget</a></li> <li class="api apilevel-5"> <a href="../../../../reference/android/bluetooth/package-summary.html">android.bluetooth</a></li> <li class="api apilevel-1"> <a href="../../../../reference/android/content/package-summary.html">android.content</a></li> <li class="api apilevel-1"> <a href="../../../../reference/android/content/pm/package-summary.html">android.content.pm</a></li> <li class="api apilevel-1"> <a href="../../../../reference/android/content/res/package-summary.html">android.content.res</a></li> <li class="api apilevel-1"> <a href="../../../../reference/android/database/package-summary.html">android.database</a></li> <li class="api apilevel-1"> <a href="../../../../reference/android/database/sqlite/package-summary.html">android.database.sqlite</a></li> <li class="api apilevel-11"> <a href="../../../../reference/android/drm/package-summary.html">android.drm</a></li> <li class="api apilevel-4"> <a href="../../../../reference/android/gesture/package-summary.html">android.gesture</a></li> <li class="api apilevel-1"> <a href="../../../../reference/android/graphics/package-summary.html">android.graphics</a></li> <li class="api apilevel-1"> <a href="../../../../reference/android/graphics/drawable/package-summary.html">android.graphics.drawable</a></li> <li class="api apilevel-1"> <a href="../../../../reference/android/graphics/drawable/shapes/package-summary.html">android.graphics.drawable.shapes</a></li> <li class="api apilevel-19"> <a href="../../../../reference/android/graphics/pdf/package-summary.html">android.graphics.pdf</a></li> <li class="api apilevel-1"> <a href="../../../../reference/android/hardware/package-summary.html">android.hardware</a></li> <li class="api apilevel-17"> <a href="../../../../reference/android/hardware/display/package-summary.html">android.hardware.display</a></li> <li class="api apilevel-16"> <a href="../../../../reference/android/hardware/input/package-summary.html">android.hardware.input</a></li> <li class="api apilevel-18"> <a href="../../../../reference/android/hardware/location/package-summary.html">android.hardware.location</a></li> <li class="api apilevel-12"> <a href="../../../../reference/android/hardware/usb/package-summary.html">android.hardware.usb</a></li> <li class="api apilevel-3"> <a href="../../../../reference/android/inputmethodservice/package-summary.html">android.inputmethodservice</a></li> <li class="api apilevel-1"> <a href="../../../../reference/android/location/package-summary.html">android.location</a></li> <li class="api apilevel-1"> <a href="../../../../reference/android/media/package-summary.html">android.media</a></li> <li class="api apilevel-9"> <a href="../../../../reference/android/media/audiofx/package-summary.html">android.media.audiofx</a></li> <li class="api apilevel-14"> <a href="../../../../reference/android/media/effect/package-summary.html">android.media.effect</a></li> <li class="api apilevel-12"> <a href="../../../../reference/android/mtp/package-summary.html">android.mtp</a></li> <li class="api apilevel-1"> <a href="../../../../reference/android/net/package-summary.html">android.net</a></li> <li class="api apilevel-1"> <a href="../../../../reference/android/net/http/package-summary.html">android.net.http</a></li> <li class="api apilevel-16"> <a href="../../../../reference/android/net/nsd/package-summary.html">android.net.nsd</a></li> <li class="api apilevel-12"> <a href="../../../../reference/android/net/rtp/package-summary.html">android.net.rtp</a></li> <li class="api apilevel-9"> <a href="../../../../reference/android/net/sip/package-summary.html">android.net.sip</a></li> <li class="api apilevel-1"> <a href="../../../../reference/android/net/wifi/package-summary.html">android.net.wifi</a></li> <li class="api apilevel-14"> <a href="../../../../reference/android/net/wifi/p2p/package-summary.html">android.net.wifi.p2p</a></li> <li class="api apilevel-16"> <a href="../../../../reference/android/net/wifi/p2p/nsd/package-summary.html">android.net.wifi.p2p.nsd</a></li> <li class="api apilevel-9"> <a href="../../../../reference/android/nfc/package-summary.html">android.nfc</a></li> <li class="api apilevel-19"> <a href="../../../../reference/android/nfc/cardemulation/package-summary.html">android.nfc.cardemulation</a></li> <li class="api apilevel-10"> <a href="../../../../reference/android/nfc/tech/package-summary.html">android.nfc.tech</a></li> <li class="api apilevel-1"> <a href="../../../../reference/android/opengl/package-summary.html">android.opengl</a></li> <li class="api apilevel-1"> <a href="../../../../reference/android/os/package-summary.html">android.os</a></li> <li class="api apilevel-9"> <a href="../../../../reference/android/os/storage/package-summary.html">android.os.storage</a></li> <li class="api apilevel-1"> <a href="../../../../reference/android/preference/package-summary.html">android.preference</a></li> <li class="api apilevel-19"> <a href="../../../../reference/android/print/package-summary.html">android.print</a></li> <li class="api apilevel-19"> <a href="../../../../reference/android/print/pdf/package-summary.html">android.print.pdf</a></li> <li class="api apilevel-19"> <a href="../../../../reference/android/printservice/package-summary.html">android.printservice</a></li> <li class="api apilevel-1"> <a href="../../../../reference/android/provider/package-summary.html">android.provider</a></li> <li class="api apilevel-11"> <a href="../../../../reference/android/renderscript/package-summary.html">android.renderscript</a></li> <li class="api apilevel-1"> <a href="../../../../reference/android/sax/package-summary.html">android.sax</a></li> <li class="api apilevel-14"> <a href="../../../../reference/android/security/package-summary.html">android.security</a></li> <li class="api apilevel-17"> <a href="../../../../reference/android/service/dreams/package-summary.html">android.service.dreams</a></li> <li class="api apilevel-18"> <a href="../../../../reference/android/service/notification/package-summary.html">android.service.notification</a></li> <li class="api apilevel-14"> <a href="../../../../reference/android/service/textservice/package-summary.html">android.service.textservice</a></li> <li class="api apilevel-7"> <a href="../../../../reference/android/service/wallpaper/package-summary.html">android.service.wallpaper</a></li> <li class="api apilevel-3"> <a href="../../../../reference/android/speech/package-summary.html">android.speech</a></li> <li class="api apilevel-4"> <a href="../../../../reference/android/speech/tts/package-summary.html">android.speech.tts</a></li> <li class="api apilevel-"> <a href="../../../../reference/android/support/v13/app/package-summary.html">android.support.v13.app</a></li> <li class="api apilevel-"> <a href="../../../../reference/android/support/v4/accessibilityservice/package-summary.html">android.support.v4.accessibilityservice</a></li> <li class="api apilevel-"> <a href="../../../../reference/android/support/v4/app/package-summary.html">android.support.v4.app</a></li> <li class="api apilevel-"> <a href="../../../../reference/android/support/v4/content/package-summary.html">android.support.v4.content</a></li> <li class="api apilevel-"> <a href="../../../../reference/android/support/v4/content/pm/package-summary.html">android.support.v4.content.pm</a></li> <li class="api apilevel-"> <a href="../../../../reference/android/support/v4/database/package-summary.html">android.support.v4.database</a></li> <li class="api apilevel-"> <a href="../../../../reference/android/support/v4/graphics/drawable/package-summary.html">android.support.v4.graphics.drawable</a></li> <li class="api apilevel-"> <a href="../../../../reference/android/support/v4/hardware/display/package-summary.html">android.support.v4.hardware.display</a></li> <li class="api apilevel-"> <a href="../../../../reference/android/support/v4/media/package-summary.html">android.support.v4.media</a></li> <li class="api apilevel-"> <a href="../../../../reference/android/support/v4/net/package-summary.html">android.support.v4.net</a></li> <li class="api apilevel-"> <a href="../../../../reference/android/support/v4/os/package-summary.html">android.support.v4.os</a></li> <li class="api apilevel-"> <a href="../../../../reference/android/support/v4/print/package-summary.html">android.support.v4.print</a></li> <li class="api apilevel-"> <a href="../../../../reference/android/support/v4/text/package-summary.html">android.support.v4.text</a></li> <li class="api apilevel-"> <a href="../../../../reference/android/support/v4/util/package-summary.html">android.support.v4.util</a></li> <li class="api apilevel-"> <a href="../../../../reference/android/support/v4/view/package-summary.html">android.support.v4.view</a></li> <li class="api apilevel-"> <a href="../../../../reference/android/support/v4/view/accessibility/package-summary.html">android.support.v4.view.accessibility</a></li> <li class="api apilevel-"> <a href="../../../../reference/android/support/v4/widget/package-summary.html">android.support.v4.widget</a></li> <li class="api apilevel-"> <a href="../../../../reference/android/support/v7/app/package-summary.html">android.support.v7.app</a></li> <li class="api apilevel-"> <a href="../../../../reference/android/support/v7/appcompat/package-summary.html">android.support.v7.appcompat</a></li> <li class="api apilevel-"> <a href="../../../../reference/android/support/v7/gridlayout/package-summary.html">android.support.v7.gridlayout</a></li> <li class="api apilevel-"> <a href="../../../../reference/android/support/v7/media/package-summary.html">android.support.v7.media</a></li> <li class="api apilevel-"> <a href="../../../../reference/android/support/v7/mediarouter/package-summary.html">android.support.v7.mediarouter</a></li> <li class="api apilevel-"> <a href="../../../../reference/android/support/v7/view/package-summary.html">android.support.v7.view</a></li> <li class="api apilevel-"> <a href="../../../../reference/android/support/v7/widget/package-summary.html">android.support.v7.widget</a></li> <li class="api apilevel-"> <a href="../../../../reference/android/support/v8/renderscript/package-summary.html">android.support.v8.renderscript</a></li> <li class="api apilevel-1"> <a href="../../../../reference/android/telephony/package-summary.html">android.telephony</a></li> <li class="api apilevel-5"> <a href="../../../../reference/android/telephony/cdma/package-summary.html">android.telephony.cdma</a></li> <li class="api apilevel-1"> <a href="../../../../reference/android/telephony/gsm/package-summary.html">android.telephony.gsm</a></li> <li class="api apilevel-1"> <a href="../../../../reference/android/test/package-summary.html">android.test</a></li> <li class="api apilevel-1"> <a href="../../../../reference/android/test/mock/package-summary.html">android.test.mock</a></li> <li class="api apilevel-1"> <a href="../../../../reference/android/test/suitebuilder/package-summary.html">android.test.suitebuilder</a></li> <li class="api apilevel-1"> <a href="../../../../reference/android/text/package-summary.html">android.text</a></li> <li class="api apilevel-3"> <a href="../../../../reference/android/text/format/package-summary.html">android.text.format</a></li> <li class="api apilevel-1"> <a href="../../../../reference/android/text/method/package-summary.html">android.text.method</a></li> <li class="api apilevel-1"> <a href="../../../../reference/android/text/style/package-summary.html">android.text.style</a></li> <li class="api apilevel-1"> <a href="../../../../reference/android/text/util/package-summary.html">android.text.util</a></li> <li class="api apilevel-19"> <a href="../../../../reference/android/transition/package-summary.html">android.transition</a></li> <li class="api apilevel-1"> <a href="../../../../reference/android/util/package-summary.html">android.util</a></li> <li class="api apilevel-1"> <a href="../../../../reference/android/view/package-summary.html">android.view</a></li> <li class="api apilevel-4"> <a href="../../../../reference/android/view/accessibility/package-summary.html">android.view.accessibility</a></li> <li class="api apilevel-1"> <a href="../../../../reference/android/view/animation/package-summary.html">android.view.animation</a></li> <li class="api apilevel-3"> <a href="../../../../reference/android/view/inputmethod/package-summary.html">android.view.inputmethod</a></li> <li class="api apilevel-14"> <a href="../../../../reference/android/view/textservice/package-summary.html">android.view.textservice</a></li> <li class="api apilevel-1"> <a href="../../../../reference/android/webkit/package-summary.html">android.webkit</a></li> <li class="api apilevel-1"> <a href="../../../../reference/android/widget/package-summary.html">android.widget</a></li> <li class="api apilevel-1"> <a href="../../../../reference/dalvik/bytecode/package-summary.html">dalvik.bytecode</a></li> <li class="api apilevel-1"> <a href="../../../../reference/dalvik/system/package-summary.html">dalvik.system</a></li> <li class="api apilevel-1"> <a href="../../../../reference/java/awt/font/package-summary.html">java.awt.font</a></li> <li class="api apilevel-3"> <a href="../../../../reference/java/beans/package-summary.html">java.beans</a></li> <li class="api apilevel-1"> <a href="../../../../reference/java/io/package-summary.html">java.io</a></li> <li class="api apilevel-1"> <a href="../../../../reference/java/lang/package-summary.html">java.lang</a></li> <li class="api apilevel-1"> <a href="../../../../reference/java/lang/annotation/package-summary.html">java.lang.annotation</a></li> <li class="api apilevel-1"> <a href="../../../../reference/java/lang/ref/package-summary.html">java.lang.ref</a></li> <li class="api apilevel-1"> <a href="../../../../reference/java/lang/reflect/package-summary.html">java.lang.reflect</a></li> <li class="api apilevel-1"> <a href="../../../../reference/java/math/package-summary.html">java.math</a></li> <li class="api apilevel-1"> <a href="../../../../reference/java/net/package-summary.html">java.net</a></li> <li class="api apilevel-1"> <a href="../../../../reference/java/nio/package-summary.html">java.nio</a></li> <li class="selected api apilevel-1"> <a href="../../../../reference/java/nio/channels/package-summary.html">java.nio.channels</a></li> <li class="api apilevel-1"> <a href="../../../../reference/java/nio/channels/spi/package-summary.html">java.nio.channels.spi</a></li> <li class="api apilevel-1"> <a href="../../../../reference/java/nio/charset/package-summary.html">java.nio.charset</a></li> <li class="api apilevel-1"> <a href="../../../../reference/java/nio/charset/spi/package-summary.html">java.nio.charset.spi</a></li> <li class="api apilevel-1"> <a href="../../../../reference/java/security/package-summary.html">java.security</a></li> <li class="api apilevel-1"> <a href="../../../../reference/java/security/acl/package-summary.html">java.security.acl</a></li> <li class="api apilevel-1"> <a href="../../../../reference/java/security/cert/package-summary.html">java.security.cert</a></li> <li class="api apilevel-1"> <a href="../../../../reference/java/security/interfaces/package-summary.html">java.security.interfaces</a></li> <li class="api apilevel-1"> <a href="../../../../reference/java/security/spec/package-summary.html">java.security.spec</a></li> <li class="api apilevel-1"> <a href="../../../../reference/java/sql/package-summary.html">java.sql</a></li> <li class="api apilevel-1"> <a href="../../../../reference/java/text/package-summary.html">java.text</a></li> <li class="api apilevel-1"> <a href="../../../../reference/java/util/package-summary.html">java.util</a></li> <li class="api apilevel-1"> <a href="../../../../reference/java/util/concurrent/package-summary.html">java.util.concurrent</a></li> <li class="api apilevel-1"> <a href="../../../../reference/java/util/concurrent/atomic/package-summary.html">java.util.concurrent.atomic</a></li> <li class="api apilevel-1"> <a href="../../../../reference/java/util/concurrent/locks/package-summary.html">java.util.concurrent.locks</a></li> <li class="api apilevel-1"> <a href="../../../../reference/java/util/jar/package-summary.html">java.util.jar</a></li> <li class="api apilevel-1"> <a href="../../../../reference/java/util/logging/package-summary.html">java.util.logging</a></li> <li class="api apilevel-1"> <a href="../../../../reference/java/util/prefs/package-summary.html">java.util.prefs</a></li> <li class="api apilevel-1"> <a href="../../../../reference/java/util/regex/package-summary.html">java.util.regex</a></li> <li class="api apilevel-1"> <a href="../../../../reference/java/util/zip/package-summary.html">java.util.zip</a></li> <li class="api apilevel-1"> <a href="../../../../reference/javax/crypto/package-summary.html">javax.crypto</a></li> <li class="api apilevel-1"> <a href="../../../../reference/javax/crypto/interfaces/package-summary.html">javax.crypto.interfaces</a></li> <li class="api apilevel-1"> <a href="../../../../reference/javax/crypto/spec/package-summary.html">javax.crypto.spec</a></li> <li class="api apilevel-1"> <a href="../../../../reference/javax/microedition/khronos/egl/package-summary.html">javax.microedition.khronos.egl</a></li> <li class="api apilevel-1"> <a href="../../../../reference/javax/microedition/khronos/opengles/package-summary.html">javax.microedition.khronos.opengles</a></li> <li class="api apilevel-1"> <a href="../../../../reference/javax/net/package-summary.html">javax.net</a></li> <li class="api apilevel-1"> <a href="../../../../reference/javax/net/ssl/package-summary.html">javax.net.ssl</a></li> <li class="api apilevel-1"> <a href="../../../../reference/javax/security/auth/package-summary.html">javax.security.auth</a></li> <li class="api apilevel-1"> <a href="../../../../reference/javax/security/auth/callback/package-summary.html">javax.security.auth.callback</a></li> <li class="api apilevel-1"> <a href="../../../../reference/javax/security/auth/login/package-summary.html">javax.security.auth.login</a></li> <li class="api apilevel-1"> <a href="../../../../reference/javax/security/auth/x500/package-summary.html">javax.security.auth.x500</a></li> <li class="api apilevel-1"> <a href="../../../../reference/javax/security/cert/package-summary.html">javax.security.cert</a></li> <li class="api apilevel-1"> <a href="../../../../reference/javax/sql/package-summary.html">javax.sql</a></li> <li class="api apilevel-1"> <a href="../../../../reference/javax/xml/package-summary.html">javax.xml</a></li> <li class="api apilevel-8"> <a href="../../../../reference/javax/xml/datatype/package-summary.html">javax.xml.datatype</a></li> <li class="api apilevel-8"> <a href="../../../../reference/javax/xml/namespace/package-summary.html">javax.xml.namespace</a></li> <li class="api apilevel-1"> <a href="../../../../reference/javax/xml/parsers/package-summary.html">javax.xml.parsers</a></li> <li class="api apilevel-8"> <a href="../../../../reference/javax/xml/transform/package-summary.html">javax.xml.transform</a></li> <li class="api apilevel-8"> <a href="../../../../reference/javax/xml/transform/dom/package-summary.html">javax.xml.transform.dom</a></li> <li class="api apilevel-8"> <a href="../../../../reference/javax/xml/transform/sax/package-summary.html">javax.xml.transform.sax</a></li> <li class="api apilevel-8"> <a href="../../../../reference/javax/xml/transform/stream/package-summary.html">javax.xml.transform.stream</a></li> <li class="api apilevel-8"> <a href="../../../../reference/javax/xml/validation/package-summary.html">javax.xml.validation</a></li> <li class="api apilevel-8"> <a href="../../../../reference/javax/xml/xpath/package-summary.html">javax.xml.xpath</a></li> <li class="api apilevel-1"> <a href="../../../../reference/junit/framework/package-summary.html">junit.framework</a></li> <li class="api apilevel-1"> <a href="../../../../reference/junit/runner/package-summary.html">junit.runner</a></li> <li class="api apilevel-1"> <a href="../../../../reference/org/apache/http/package-summary.html">org.apache.http</a></li> <li class="api apilevel-1"> <a href="../../../../reference/org/apache/http/auth/package-summary.html">org.apache.http.auth</a></li> <li class="api apilevel-1"> <a href="../../../../reference/org/apache/http/auth/params/package-summary.html">org.apache.http.auth.params</a></li> <li class="api apilevel-1"> <a href="../../../../reference/org/apache/http/client/package-summary.html">org.apache.http.client</a></li> <li class="api apilevel-1"> <a href="../../../../reference/org/apache/http/client/entity/package-summary.html">org.apache.http.client.entity</a></li> <li class="api apilevel-1"> <a href="../../../../reference/org/apache/http/client/methods/package-summary.html">org.apache.http.client.methods</a></li> <li class="api apilevel-1"> <a href="../../../../reference/org/apache/http/client/params/package-summary.html">org.apache.http.client.params</a></li> <li class="api apilevel-1"> <a href="../../../../reference/org/apache/http/client/protocol/package-summary.html">org.apache.http.client.protocol</a></li> <li class="api apilevel-1"> <a href="../../../../reference/org/apache/http/client/utils/package-summary.html">org.apache.http.client.utils</a></li> <li class="api apilevel-1"> <a href="../../../../reference/org/apache/http/conn/package-summary.html">org.apache.http.conn</a></li> <li class="api apilevel-1"> <a href="../../../../reference/org/apache/http/conn/params/package-summary.html">org.apache.http.conn.params</a></li> <li class="api apilevel-1"> <a href="../../../../reference/org/apache/http/conn/routing/package-summary.html">org.apache.http.conn.routing</a></li> <li class="api apilevel-1"> <a href="../../../../reference/org/apache/http/conn/scheme/package-summary.html">org.apache.http.conn.scheme</a></li> <li class="api apilevel-1"> <a href="../../../../reference/org/apache/http/conn/ssl/package-summary.html">org.apache.http.conn.ssl</a></li> <li class="api apilevel-1"> <a href="../../../../reference/org/apache/http/conn/util/package-summary.html">org.apache.http.conn.util</a></li> <li class="api apilevel-1"> <a href="../../../../reference/org/apache/http/cookie/package-summary.html">org.apache.http.cookie</a></li> <li class="api apilevel-1"> <a href="../../../../reference/org/apache/http/cookie/params/package-summary.html">org.apache.http.cookie.params</a></li> <li class="api apilevel-1"> <a href="../../../../reference/org/apache/http/entity/package-summary.html">org.apache.http.entity</a></li> <li class="api apilevel-1"> <a href="../../../../reference/org/apache/http/impl/package-summary.html">org.apache.http.impl</a></li> <li class="api apilevel-1"> <a href="../../../../reference/org/apache/http/impl/auth/package-summary.html">org.apache.http.impl.auth</a></li> <li class="api apilevel-1"> <a href="../../../../reference/org/apache/http/impl/client/package-summary.html">org.apache.http.impl.client</a></li> <li class="api apilevel-1"> <a href="../../../../reference/org/apache/http/impl/conn/package-summary.html">org.apache.http.impl.conn</a></li> <li class="api apilevel-1"> <a href="../../../../reference/org/apache/http/impl/conn/tsccm/package-summary.html">org.apache.http.impl.conn.tsccm</a></li> <li class="api apilevel-1"> <a href="../../../../reference/org/apache/http/impl/cookie/package-summary.html">org.apache.http.impl.cookie</a></li> <li class="api apilevel-1"> <a href="../../../../reference/org/apache/http/impl/entity/package-summary.html">org.apache.http.impl.entity</a></li> <li class="api apilevel-1"> <a href="../../../../reference/org/apache/http/impl/io/package-summary.html">org.apache.http.impl.io</a></li> <li class="api apilevel-1"> <a href="../../../../reference/org/apache/http/io/package-summary.html">org.apache.http.io</a></li> <li class="api apilevel-1"> <a href="../../../../reference/org/apache/http/message/package-summary.html">org.apache.http.message</a></li> <li class="api apilevel-1"> <a href="../../../../reference/org/apache/http/params/package-summary.html">org.apache.http.params</a></li> <li class="api apilevel-1"> <a href="../../../../reference/org/apache/http/protocol/package-summary.html">org.apache.http.protocol</a></li> <li class="api apilevel-1"> <a href="../../../../reference/org/apache/http/util/package-summary.html">org.apache.http.util</a></li> <li class="api apilevel-1"> <a href="../../../../reference/org/json/package-summary.html">org.json</a></li> <li class="api apilevel-1"> <a href="../../../../reference/org/w3c/dom/package-summary.html">org.w3c.dom</a></li> <li class="api apilevel-8"> <a href="../../../../reference/org/w3c/dom/ls/package-summary.html">org.w3c.dom.ls</a></li> <li class="api apilevel-1"> <a href="../../../../reference/org/xml/sax/package-summary.html">org.xml.sax</a></li> <li class="api apilevel-1"> <a href="../../../../reference/org/xml/sax/ext/package-summary.html">org.xml.sax.ext</a></li> <li class="api apilevel-1"> <a href="../../../../reference/org/xml/sax/helpers/package-summary.html">org.xml.sax.helpers</a></li> <li class="api apilevel-1"> <a href="../../../../reference/org/xmlpull/v1/package-summary.html">org.xmlpull.v1</a></li> <li class="api apilevel-1"> <a href="../../../../reference/org/xmlpull/v1/sax2/package-summary.html">org.xmlpull.v1.sax2</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-1"><a href="../../../../reference/java/nio/channels/ByteChannel.html">ByteChannel</a></li> <li class="api apilevel-1"><a href="../../../../reference/java/nio/channels/Channel.html">Channel</a></li> <li class="api apilevel-1"><a href="../../../../reference/java/nio/channels/GatheringByteChannel.html">GatheringByteChannel</a></li> <li class="api apilevel-1"><a href="../../../../reference/java/nio/channels/InterruptibleChannel.html">InterruptibleChannel</a></li> <li class="api apilevel-1"><a href="../../../../reference/java/nio/channels/ReadableByteChannel.html">ReadableByteChannel</a></li> <li class="api apilevel-1"><a href="../../../../reference/java/nio/channels/ScatteringByteChannel.html">ScatteringByteChannel</a></li> <li class="api apilevel-1"><a href="../../../../reference/java/nio/channels/WritableByteChannel.html">WritableByteChannel</a></li> </ul> </li> <li><h2>Classes</h2> <ul> <li class="api apilevel-1"><a href="../../../../reference/java/nio/channels/Channels.html">Channels</a></li> <li class="api apilevel-1"><a href="../../../../reference/java/nio/channels/DatagramChannel.html">DatagramChannel</a></li> <li class="api apilevel-1"><a href="../../../../reference/java/nio/channels/FileChannel.html">FileChannel</a></li> <li class="api apilevel-1"><a href="../../../../reference/java/nio/channels/FileChannel.MapMode.html">FileChannel.MapMode</a></li> <li class="api apilevel-1"><a href="../../../../reference/java/nio/channels/FileLock.html">FileLock</a></li> <li class="api apilevel-1"><a href="../../../../reference/java/nio/channels/Pipe.html">Pipe</a></li> <li class="api apilevel-1"><a href="../../../../reference/java/nio/channels/Pipe.SinkChannel.html">Pipe.SinkChannel</a></li> <li class="api apilevel-1"><a href="../../../../reference/java/nio/channels/Pipe.SourceChannel.html">Pipe.SourceChannel</a></li> <li class="api apilevel-1"><a href="../../../../reference/java/nio/channels/SelectableChannel.html">SelectableChannel</a></li> <li class="api apilevel-1"><a href="../../../../reference/java/nio/channels/SelectionKey.html">SelectionKey</a></li> <li class="api apilevel-1"><a href="../../../../reference/java/nio/channels/Selector.html">Selector</a></li> <li class="api apilevel-1"><a href="../../../../reference/java/nio/channels/ServerSocketChannel.html">ServerSocketChannel</a></li> <li class="api apilevel-1"><a href="../../../../reference/java/nio/channels/SocketChannel.html">SocketChannel</a></li> </ul> </li> <li><h2>Exceptions</h2> <ul> <li class="api apilevel-1"><a href="../../../../reference/java/nio/channels/AlreadyConnectedException.html">AlreadyConnectedException</a></li> <li class="api apilevel-1"><a href="../../../../reference/java/nio/channels/AsynchronousCloseException.html">AsynchronousCloseException</a></li> <li class="api apilevel-1"><a href="../../../../reference/java/nio/channels/CancelledKeyException.html">CancelledKeyException</a></li> <li class="api apilevel-1"><a href="../../../../reference/java/nio/channels/ClosedByInterruptException.html">ClosedByInterruptException</a></li> <li class="api apilevel-1"><a href="../../../../reference/java/nio/channels/ClosedChannelException.html">ClosedChannelException</a></li> <li class="api apilevel-1"><a href="../../../../reference/java/nio/channels/ClosedSelectorException.html">ClosedSelectorException</a></li> <li class="selected api apilevel-1"><a href="../../../../reference/java/nio/channels/ConnectionPendingException.html">ConnectionPendingException</a></li> <li class="api apilevel-1"><a href="../../../../reference/java/nio/channels/FileLockInterruptionException.html">FileLockInterruptionException</a></li> <li class="api apilevel-1"><a href="../../../../reference/java/nio/channels/IllegalBlockingModeException.html">IllegalBlockingModeException</a></li> <li class="api apilevel-1"><a href="../../../../reference/java/nio/channels/IllegalSelectorException.html">IllegalSelectorException</a></li> <li class="api apilevel-1"><a href="../../../../reference/java/nio/channels/NoConnectionPendingException.html">NoConnectionPendingException</a></li> <li class="api apilevel-1"><a href="../../../../reference/java/nio/channels/NonReadableChannelException.html">NonReadableChannelException</a></li> <li class="api apilevel-1"><a href="../../../../reference/java/nio/channels/NonWritableChannelException.html">NonWritableChannelException</a></li> <li class="api apilevel-1"><a href="../../../../reference/java/nio/channels/NotYetBoundException.html">NotYetBoundException</a></li> <li class="api apilevel-1"><a href="../../../../reference/java/nio/channels/NotYetConnectedException.html">NotYetConnectedException</a></li> <li class="api apilevel-1"><a href="../../../../reference/java/nio/channels/OverlappingFileLockException.html">OverlappingFileLockException</a></li> <li class="api apilevel-1"><a href="../../../../reference/java/nio/channels/UnresolvedAddressException.html">UnresolvedAddressException</a></li> <li class="api apilevel-1"><a href="../../../../reference/java/nio/channels/UnsupportedAddressTypeException.html">UnsupportedAddressTypeException</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="sum-details-links"> Summary: <a href="#pubctors">Ctors</a> &#124; <a href="#inhmethods">Inherited Methods</a> &#124; <a href="#" onclick="return toggleAllClassInherited()" id="toggleAllClassInherited">[Expand All]</a> </div><!-- end sum-details-links --> <div class="api-level"> Added in <a href="../../../../guide/topics/manifest/uses-sdk-element.html#ApiLevels">API level 1</a> </div> </div><!-- end api-info-block --> <!-- ======== START OF CLASS DATA ======== --> <div id="jd-header"> public class <h1 itemprop="name">ConnectionPendingException</h1> extends <a href="../../../../reference/java/lang/IllegalStateException.html">IllegalStateException</a><br/> </div><!-- end header --> <div id="naMessage"></div> <div id="jd-content" class="api apilevel-1"> <table class="jd-inheritance-table"> <tr> <td colspan="6" class="jd-inheritance-class-cell"><a href="../../../../reference/java/lang/Object.html">java.lang.Object</a></td> </tr> <tr> <td class="jd-inheritance-space">&nbsp;&nbsp;&nbsp;&#x21b3;</td> <td colspan="5" class="jd-inheritance-class-cell"><a href="../../../../reference/java/lang/Throwable.html">java.lang.Throwable</a></td> </tr> <tr> <td class="jd-inheritance-space">&nbsp;</td> <td class="jd-inheritance-space">&nbsp;&nbsp;&nbsp;&#x21b3;</td> <td colspan="4" class="jd-inheritance-class-cell"><a href="../../../../reference/java/lang/Exception.html">java.lang.Exception</a></td> </tr> <tr> <td class="jd-inheritance-space">&nbsp;</td> <td class="jd-inheritance-space">&nbsp;</td> <td class="jd-inheritance-space">&nbsp;&nbsp;&nbsp;&#x21b3;</td> <td colspan="3" class="jd-inheritance-class-cell"><a href="../../../../reference/java/lang/RuntimeException.html">java.lang.RuntimeException</a></td> </tr> <tr> <td class="jd-inheritance-space">&nbsp;</td> <td class="jd-inheritance-space">&nbsp;</td> <td class="jd-inheritance-space">&nbsp;</td> <td class="jd-inheritance-space">&nbsp;&nbsp;&nbsp;&#x21b3;</td> <td colspan="2" class="jd-inheritance-class-cell"><a href="../../../../reference/java/lang/IllegalStateException.html">java.lang.IllegalStateException</a></td> </tr> <tr> <td class="jd-inheritance-space">&nbsp;</td> <td class="jd-inheritance-space">&nbsp;</td> <td class="jd-inheritance-space">&nbsp;</td> <td class="jd-inheritance-space">&nbsp;</td> <td class="jd-inheritance-space">&nbsp;&nbsp;&nbsp;&#x21b3;</td> <td colspan="1" class="jd-inheritance-class-cell">java.nio.channels.ConnectionPendingException</td> </tr> </table> <div class="jd-descr"> <h2>Class Overview</h2> <p itemprop="articleBody">A <code>ConnectionPendingException</code> is thrown when an attempt is made to connect a <code><a href="../../../../reference/java/nio/channels/SocketChannel.html">SocketChannel</a></code> that has a non-blocking connection already underway. </p> </div><!-- jd-descr --> <div class="jd-descr"> <h2>Summary</h2> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <table id="pubctors" class="jd-sumtable"><tr><th colspan="12">Public Constructors</th></tr> <tr class="alt-color api apilevel-1" > <td class="jd-typecol"><nobr> </nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../../reference/java/nio/channels/ConnectionPendingException.html#ConnectionPendingException()">ConnectionPendingException</a></span>()</nobr> <div class="jd-descrdiv">Constructs a <code>ConnectionPendingException</code>.</div> </td></tr> </table> <!-- ========== METHOD SUMMARY =========== --> <table id="inhmethods" class="jd-sumtable"><tr><th> <a href="#" class="toggle-all" onclick="return toggleAllInherited(this, null)">[Expand]</a> <div style="clear:left;">Inherited Methods</div></th></tr> <tr class="api apilevel-" > <td colspan="12"> <a href="#" onclick="return toggleInherited(this, null)" id="inherited-methods-java.lang.Throwable" class="jd-expando-trigger closed" ><img id="inherited-methods-java.lang.Throwable-trigger" src="../../../../assets/images/triangle-closed.png" class="jd-expando-trigger-img" /></a> From class <a href="../../../../reference/java/lang/Throwable.html">java.lang.Throwable</a> <div id="inherited-methods-java.lang.Throwable"> <div id="inherited-methods-java.lang.Throwable-list" class="jd-inheritedlinks"> </div> <div id="inherited-methods-java.lang.Throwable-summary" style="display: none;"> <table class="jd-sumtable-expando"> <tr class="alt-color api apilevel-19" > <td class="jd-typecol"><nobr> final void</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../../reference/java/lang/Throwable.html#addSuppressed(java.lang.Throwable)">addSuppressed</a></span>(<a href="../../../../reference/java/lang/Throwable.html">Throwable</a> throwable)</nobr> <div class="jd-descrdiv">Adds <code>throwable</code> to the list of throwables suppressed by this.</div> </td></tr> <tr class=" api apilevel-1" > <td class="jd-typecol"><nobr> <a href="../../../../reference/java/lang/Throwable.html">Throwable</a></nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../../reference/java/lang/Throwable.html#fillInStackTrace()">fillInStackTrace</a></span>()</nobr> <div class="jd-descrdiv">Records the stack trace from the point where this method has been called to this <code>Throwable</code>.</div> </td></tr> <tr class="alt-color api apilevel-1" > <td class="jd-typecol"><nobr> <a href="../../../../reference/java/lang/Throwable.html">Throwable</a></nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../../reference/java/lang/Throwable.html#getCause()">getCause</a></span>()</nobr> <div class="jd-descrdiv">Returns the cause of this <code>Throwable</code>, or <code>null</code> if there is no cause.</div> </td></tr> <tr class=" api apilevel-1" > <td class="jd-typecol"><nobr> <a href="../../../../reference/java/lang/String.html">String</a></nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../../reference/java/lang/Throwable.html#getLocalizedMessage()">getLocalizedMessage</a></span>()</nobr> <div class="jd-descrdiv">Returns the detail message which was provided when this <code>Throwable</code> was created.</div> </td></tr> <tr class="alt-color api apilevel-1" > <td class="jd-typecol"><nobr> <a href="../../../../reference/java/lang/String.html">String</a></nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../../reference/java/lang/Throwable.html#getMessage()">getMessage</a></span>()</nobr> <div class="jd-descrdiv">Returns the detail message which was provided when this <code>Throwable</code> was created.</div> </td></tr> <tr class=" api apilevel-1" > <td class="jd-typecol"><nobr> <a href="../../../../reference/java/lang/StackTraceElement.html">StackTraceElement[]</a></nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../../reference/java/lang/Throwable.html#getStackTrace()">getStackTrace</a></span>()</nobr> <div class="jd-descrdiv">Returns a clone of the array of stack trace elements of this <code>Throwable</code>.</div> </td></tr> <tr class="alt-color api apilevel-19" > <td class="jd-typecol"><nobr> final <a href="../../../../reference/java/lang/Throwable.html">Throwable[]</a></nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../../reference/java/lang/Throwable.html#getSuppressed()">getSuppressed</a></span>()</nobr> <div class="jd-descrdiv">Returns the throwables suppressed by this.</div> </td></tr> <tr class=" api apilevel-1" > <td class="jd-typecol"><nobr> <a href="../../../../reference/java/lang/Throwable.html">Throwable</a></nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../../reference/java/lang/Throwable.html#initCause(java.lang.Throwable)">initCause</a></span>(<a href="../../../../reference/java/lang/Throwable.html">Throwable</a> throwable)</nobr> <div class="jd-descrdiv">Initializes the cause of this <code>Throwable</code>.</div> </td></tr> <tr class="alt-color api apilevel-1" > <td class="jd-typecol"><nobr> void</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../../reference/java/lang/Throwable.html#printStackTrace(java.io.PrintStream)">printStackTrace</a></span>(<a href="../../../../reference/java/io/PrintStream.html">PrintStream</a> err)</nobr> <div class="jd-descrdiv">Writes a printable representation of this <code>Throwable</code>'s stack trace to the given print stream.</div> </td></tr> <tr class=" api apilevel-1" > <td class="jd-typecol"><nobr> void</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../../reference/java/lang/Throwable.html#printStackTrace(java.io.PrintWriter)">printStackTrace</a></span>(<a href="../../../../reference/java/io/PrintWriter.html">PrintWriter</a> err)</nobr> <div class="jd-descrdiv">Writes a printable representation of this <code>Throwable</code>'s stack trace to the specified print writer.</div> </td></tr> <tr class="alt-color api apilevel-1" > <td class="jd-typecol"><nobr> void</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../../reference/java/lang/Throwable.html#printStackTrace()">printStackTrace</a></span>()</nobr> <div class="jd-descrdiv">Writes a printable representation of this <code>Throwable</code>'s stack trace to the <code>System.err</code> stream.</div> </td></tr> <tr class=" api apilevel-1" > <td class="jd-typecol"><nobr> void</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../../reference/java/lang/Throwable.html#setStackTrace(java.lang.StackTraceElement[])">setStackTrace</a></span>(<a href="../../../../reference/java/lang/StackTraceElement.html">StackTraceElement[]</a> trace)</nobr> <div class="jd-descrdiv">Sets the array of stack trace elements.</div> </td></tr> <tr class="alt-color api apilevel-1" > <td class="jd-typecol"><nobr> <a href="../../../../reference/java/lang/String.html">String</a></nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../../reference/java/lang/Throwable.html#toString()">toString</a></span>()</nobr> <div class="jd-descrdiv">Returns a string containing a concise, human-readable description of this object.</div> </td></tr> </table> </div> </div> </td></tr> <tr class="api apilevel-" > <td colspan="12"> <a href="#" onclick="return toggleInherited(this, null)" id="inherited-methods-java.lang.Object" class="jd-expando-trigger closed" ><img id="inherited-methods-java.lang.Object-trigger" src="../../../../assets/images/triangle-closed.png" class="jd-expando-trigger-img" /></a> From class <a href="../../../../reference/java/lang/Object.html">java.lang.Object</a> <div id="inherited-methods-java.lang.Object"> <div id="inherited-methods-java.lang.Object-list" class="jd-inheritedlinks"> </div> <div id="inherited-methods-java.lang.Object-summary" style="display: none;"> <table class="jd-sumtable-expando"> <tr class="alt-color api apilevel-1" > <td class="jd-typecol"><nobr> <a href="../../../../reference/java/lang/Object.html">Object</a></nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../../reference/java/lang/Object.html#clone()">clone</a></span>()</nobr> <div class="jd-descrdiv">Creates and returns a copy of this <code>Object</code>.</div> </td></tr> <tr class=" api apilevel-1" > <td class="jd-typecol"><nobr> boolean</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../../reference/java/lang/Object.html#equals(java.lang.Object)">equals</a></span>(<a href="../../../../reference/java/lang/Object.html">Object</a> o)</nobr> <div class="jd-descrdiv">Compares this instance with the specified object and indicates if they are equal.</div> </td></tr> <tr class="alt-color api apilevel-1" > <td class="jd-typecol"><nobr> void</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../../reference/java/lang/Object.html#finalize()">finalize</a></span>()</nobr> <div class="jd-descrdiv">Invoked when the garbage collector has detected that this instance is no longer reachable.</div> </td></tr> <tr class=" api apilevel-1" > <td class="jd-typecol"><nobr> final <a href="../../../../reference/java/lang/Class.html">Class</a>&lt;?&gt;</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../../reference/java/lang/Object.html#getClass()">getClass</a></span>()</nobr> <div class="jd-descrdiv">Returns the unique instance of <code><a href="../../../../reference/java/lang/Class.html">Class</a></code> that represents this object's class.</div> </td></tr> <tr class="alt-color api apilevel-1" > <td class="jd-typecol"><nobr> int</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../../reference/java/lang/Object.html#hashCode()">hashCode</a></span>()</nobr> <div class="jd-descrdiv">Returns an integer hash code for this object.</div> </td></tr> <tr class=" api apilevel-1" > <td class="jd-typecol"><nobr> final void</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../../reference/java/lang/Object.html#notify()">notify</a></span>()</nobr> <div class="jd-descrdiv">Causes a thread which is waiting on this object's monitor (by means of calling one of the <code>wait()</code> methods) to be woken up.</div> </td></tr> <tr class="alt-color api apilevel-1" > <td class="jd-typecol"><nobr> final void</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../../reference/java/lang/Object.html#notifyAll()">notifyAll</a></span>()</nobr> <div class="jd-descrdiv">Causes all threads which are waiting on this object's monitor (by means of calling one of the <code>wait()</code> methods) to be woken up.</div> </td></tr> <tr class=" api apilevel-1" > <td class="jd-typecol"><nobr> <a href="../../../../reference/java/lang/String.html">String</a></nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../../reference/java/lang/Object.html#toString()">toString</a></span>()</nobr> <div class="jd-descrdiv">Returns a string containing a concise, human-readable description of this object.</div> </td></tr> <tr class="alt-color api apilevel-1" > <td class="jd-typecol"><nobr> final void</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../../reference/java/lang/Object.html#wait()">wait</a></span>()</nobr> <div class="jd-descrdiv">Causes the calling thread to wait until another thread calls the <code>notify()</code> or <code>notifyAll()</code> method of this object.</div> </td></tr> <tr class=" api apilevel-1" > <td class="jd-typecol"><nobr> final void</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../../reference/java/lang/Object.html#wait(long, int)">wait</a></span>(long millis, int nanos)</nobr> <div class="jd-descrdiv">Causes the calling thread to wait until another thread calls the <code>notify()</code> or <code>notifyAll()</code> method of this object or until the specified timeout expires.</div> </td></tr> <tr class="alt-color api apilevel-1" > <td class="jd-typecol"><nobr> final void</nobr> </td> <td class="jd-linkcol" width="100%"><nobr> <span class="sympad"><a href="../../../../reference/java/lang/Object.html#wait(long)">wait</a></span>(long millis)</nobr> <div class="jd-descrdiv">Causes the calling thread to wait until another thread calls the <code>notify()</code> or <code>notifyAll()</code> method of this object or until the specified timeout expires.</div> </td></tr> </table> </div> </div> </td></tr> </table> </div><!-- jd-descr (summary) --> <!-- Details --> <!-- XML Attributes --> <!-- Enum Values --> <!-- Constants --> <!-- Fields --> <!-- Public ctors --> <!-- ========= CONSTRUCTOR DETAIL ======== --> <h2>Public Constructors</h2> <A NAME="ConnectionPendingException()"></A> <div class="jd-details api apilevel-1"> <h4 class="jd-details-title"> <span class="normal"> public </span> <span class="sympad">ConnectionPendingException</span> <span class="normal">()</span> </h4> <div class="api-level"> <div> Added in <a href="../../../../guide/topics/manifest/uses-sdk-element.html#ApiLevels">API level 1</a></div> </div> <div class="jd-details-descr"> <div class="jd-tagdata jd-tagdescr"><p>Constructs a <code>ConnectionPendingException</code>. </p></div> </div> </div> <!-- ========= CONSTRUCTOR DETAIL ======== --> <!-- Protected ctors --> <!-- ========= METHOD DETAIL ======== --> <!-- Public methdos --> <!-- ========= METHOD DETAIL ======== --> <!-- ========= END OF CLASS DATA ========= --> <A NAME="navbar_top"></A> <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 4.4&nbsp;r1 &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> <!-- jd-content --> </div><!-- end doc-content --> </div> <!-- end body-content --> </body> </html>
{ "content_hash": "7911f7f0b1dbf2c6678c1d449aeefecb", "timestamp": "", "source": "github", "line_count": 1842, "max_line_length": 258, "avg_line_length": 37.84419109663409, "alnum_prop": 0.5680184768107418, "repo_name": "terrytowne/android-developer-cn", "id": "bf8481941a811b37082ad5264e2a6f6635341b63", "size": "70085", "binary": false, "copies": "2", "ref": "refs/heads/4.4.zh_cn", "path": "reference/java/nio/channels/ConnectionPendingException.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "225261" }, { "name": "JavaScript", "bytes": "218708" } ], "symlink_target": "" }
`Setting<T>` is the base class for all global setting `ScriptableObject`. All the `ScriptableObject` will be stored in a single folder that can be configured for each project. `PathSetting` is the `ScriptableObject` that contains the path of the folder that all other setting objects will be stored in. The `PathSetting` object itself is hardcoded to be stored in the root of `Assets/Resources` folder. ### FileSystemHelper This is a helper with useful functions to deal with file system ### ReflectionHelper This is a helper with useful functions to deal with reflection ### Consolation This is a `MonoBehaviour` which can be attached to any scene object. It will allow opening a custom console log using backtick ``` in PC and shaking in mobile. It is suggested to wrap it in a Singleton in your game, which will read configuration parameters from your game settings, instead of making it a prefab and set the prefab parameters. ### MeshSaver This is an Editor script which will allow you to save any mesh using the context menu of the `MeshFilter` component. ### MeshVisualizerWindow Visualize Mesh in Scene view ### SceneViewWindow A simple Editor window to quickly switch between build scenes ### PlayerPrefsEditor A simple Editor window to delete PlayerPrefs ### AssetReferencerFinder Quickly find references to an asset
{ "content_hash": "d0475b04afae1aa4d236e7f956c11508", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 342, "avg_line_length": 49.48148148148148, "alnum_prop": 0.7919161676646707, "repo_name": "minhhh/UBootstrap.Core", "id": "ca29cd709e0c60c6569017d837712e32243092e9", "size": "1365", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs.md", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "85866" }, { "name": "JavaScript", "bytes": "990" } ], "symlink_target": "" }
<?php namespace Page; use Behat\Mink\Session; use Behat\Mink\Element\NodeElement; use SensioLabs\Behat\PageObjectExtension\PageObject\Exception\ElementNotFoundException; /** * PageObject for a single notification */ class Notification extends OwncloudPage { /** * * @var NodeElement */ private $notificationElement; private $buttonByTextXpath = "//button[text()='%s']"; private $notificationLinkXpath = "//a[@class='notification-link']"; /** * sets the NodeElement for the current notification * a little bit like __construct() but as we access this "sub-page-object" * from an other Page Object by $this->getPage("Notification") * there is no real __construct() that can take arguments * * @param \Behat\Mink\Element\NodeElement $notificationElement * * @return void */ public function setElement(NodeElement $notificationElement) { $this->notificationElement = $notificationElement; } /** * * @param Session $session * @param int $timeout_msec * * @return void * @throws ElementNotFoundException * */ public function followLink( Session $session, $timeout_msec = STANDARD_UI_WAIT_TIMEOUT_MILLISEC ) { $link = $this->notificationElement->find( "xpath", $this->notificationLinkXpath ); $this->assertElementNotNull( $link, __METHOD__ . " could not find notification link with xpath $this->notificationLinkXpath" ); $destination = $link->getAttribute('href'); $link->click(); $currentTime = \microtime(true); $end = $currentTime + ($timeout_msec / 1000); while ($currentTime <= $end) { if ($destination === $session->getCurrentUrl()) { break; } $currentTime = \microtime(true); } } /** * * @param string $reaction * @param Session $session * * @return void */ public function react($reaction, Session $session) { $buttonXpath = \sprintf($this->buttonByTextXpath, $reaction); $button = $this->notificationElement->find( "xpath", $buttonXpath ); $this->assertElementNotNull( $button, __METHOD__ . " xpath $buttonXpath could not find button with the given text" ); $button->click(); $this->waitForAjaxCallsToStartAndFinish($session); } }
{ "content_hash": "257ca9d0c900ab966310914cbbbed0c0", "timestamp": "", "source": "github", "line_count": 90, "max_line_length": 87, "avg_line_length": 24.27777777777778, "alnum_prop": 0.6823798627002289, "repo_name": "phil-davis/core", "id": "f903e9bdc24261257718cccabf55a38b1c9a2e8c", "size": "2976", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/acceptance/features/lib/Notification.php", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "262" }, { "name": "Makefile", "bytes": "473" }, { "name": "Shell", "bytes": "8644" } ], "symlink_target": "" }
/* $Id: APISanityIT.java 1493838 2013-06-17 16:31:02Z piergiorgio $ */ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.manifoldcf.alfresco_tests; import java.io.IOException; import java.rmi.RemoteException; import org.alfresco.webservice.content.ContentServiceSoapBindingStub; import org.alfresco.webservice.repository.QueryResult; import org.alfresco.webservice.repository.RepositoryFault; import org.alfresco.webservice.repository.RepositoryServiceSoapBindingStub; import org.alfresco.webservice.repository.UpdateResult; import org.alfresco.webservice.types.CML; import org.alfresco.webservice.types.CMLCreate; import org.alfresco.webservice.types.CMLDelete; import org.alfresco.webservice.types.ContentFormat; import org.alfresco.webservice.types.NamedValue; import org.alfresco.webservice.types.ParentReference; import org.alfresco.webservice.types.Predicate; import org.alfresco.webservice.types.Query; import org.alfresco.webservice.types.Reference; import org.alfresco.webservice.types.ResultSetRow; import org.alfresco.webservice.types.Store; import org.alfresco.webservice.util.AuthenticationUtils; import org.alfresco.webservice.util.Constants; import org.alfresco.webservice.util.Utils; import org.alfresco.webservice.util.WebServiceFactory; import org.apache.commons.lang.StringUtils; import org.apache.manifoldcf.core.interfaces.Configuration; import org.apache.manifoldcf.core.interfaces.ConfigurationNode; import org.apache.manifoldcf.core.interfaces.ManifoldCFException; import org.apache.manifoldcf.crawler.connectors.alfresco.AlfrescoConfig; import org.apache.manifoldcf.crawler.system.ManifoldCF; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * @author Piergiorgio Lucidi */ public class APISanityIT extends BaseDerby { private static final String REPLACER = "?"; private static final String ALFRESCO_TEST_QUERY_CHANGE_DOC = "PATH:\"/app:company_home/cm:testdata/*\" AND TYPE:\"cm:content\" AND @cm\\:name:\""+REPLACER+"\""; private static final String ALFRESCO_TEST_QUERY = "PATH:\"/app:company_home/cm:testdata\""; private static final String ALFRESCO_USERNAME = "admin"; private static final String ALFRESCO_PASSWORD = "admin"; private static final String ALFRESCO_PROTOCOL = "http"; private static final String ALFRESCO_SERVER = "localhost"; private static final String ALFRESCO_PORT = "9090"; private static final String ALFRESCO_PATH = "/alfresco/api"; private static final int SOCKET_TIMEOUT = 120000; private static final String ALFRESCO_ENDPOINT_TEST_SERVER = ALFRESCO_PROTOCOL+"://"+ALFRESCO_SERVER+":"+ALFRESCO_PORT+ALFRESCO_PATH; private static final Store STORE = new Store(Constants.WORKSPACE_STORE, "SpacesStore"); public Reference getTestFolder() throws RepositoryFault, RemoteException{ WebServiceFactory.setTimeoutMilliseconds(SOCKET_TIMEOUT); WebServiceFactory.setEndpointAddress(ALFRESCO_ENDPOINT_TEST_SERVER); AuthenticationUtils.startSession(ALFRESCO_USERNAME, ALFRESCO_PASSWORD); Reference reference = new Reference(); try{ RepositoryServiceSoapBindingStub repositoryService = WebServiceFactory.getRepositoryService(); Query query = new Query(Constants.QUERY_LANG_LUCENE, ALFRESCO_TEST_QUERY); QueryResult queryResult = repositoryService.query(STORE, query, false); ResultSetRow row = queryResult.getResultSet().getRows(0); reference.setStore(STORE); reference.setUuid(row.getNode().getId()); return reference; } finally { AuthenticationUtils.endSession(); } } public void createNewDocument(Reference folder, String name) throws IOException{ ParentReference folderReference = new ParentReference(STORE, folder.getUuid(), null, Constants.ASSOC_CONTAINS, null); folderReference.setChildName("{"+Constants.NAMESPACE_CONTENT_MODEL +"}"+ name); NamedValue[] contentProps = new NamedValue[1]; contentProps[0] = Utils.createNamedValue(Constants.PROP_NAME, name); CMLCreate create = new CMLCreate("1", folderReference, null, null, null, Constants.TYPE_CONTENT, contentProps); CML cml = new CML(); cml.setCreate(new CMLCreate[] {create}); WebServiceFactory.setEndpointAddress(ALFRESCO_ENDPOINT_TEST_SERVER); AuthenticationUtils.startSession(ALFRESCO_USERNAME, ALFRESCO_PASSWORD); try{ UpdateResult[] result = WebServiceFactory.getRepositoryService().update(cml); //format ContentFormat contentFormat = new ContentFormat(); contentFormat.setEncoding("UTF-8"); contentFormat.setMimetype("text/plain"); //the content String content = "Alfresco Testdata "+name; //the new node Reference reference = result[0].getDestination(); //write the content in the new node ContentServiceSoapBindingStub contentService = WebServiceFactory.getContentService(); contentService.write(reference, Constants.PROP_CONTENT, content.getBytes(), contentFormat); } finally{ AuthenticationUtils.endSession(); } } /** * change the document content with the new one provided as an argument * @param session * @param name * @param newContent * @throws RemoteException * @throws RepositoryFault */ public void changeDocument(String name, String newContent) throws RepositoryFault, RemoteException{ String luceneQuery = StringUtils.replace(ALFRESCO_TEST_QUERY_CHANGE_DOC, REPLACER, name); WebServiceFactory.setTimeoutMilliseconds(SOCKET_TIMEOUT); WebServiceFactory.setEndpointAddress(ALFRESCO_ENDPOINT_TEST_SERVER); AuthenticationUtils.startSession(ALFRESCO_USERNAME, ALFRESCO_PASSWORD); try{ RepositoryServiceSoapBindingStub repositoryService = WebServiceFactory.getRepositoryService(); Query query = new Query(Constants.QUERY_LANG_LUCENE, luceneQuery); QueryResult queryResult = repositoryService.query(STORE, query, false); ResultSetRow row = queryResult.getResultSet().getRows(0); Reference reference = new Reference(); reference.setStore(STORE); reference.setUuid(row.getNode().getId()); ContentFormat contentFormat = new ContentFormat(); contentFormat.setEncoding("UTF-8"); contentFormat.setMimetype("text/plain"); ContentServiceSoapBindingStub contentService = WebServiceFactory.getContentService(); contentService.write(reference, Constants.PROP_CONTENT, newContent.getBytes(), contentFormat); } finally { AuthenticationUtils.endSession(); } } public void removeDocument(String name) throws RepositoryFault, RemoteException{ String luceneQuery = StringUtils.replace(ALFRESCO_TEST_QUERY_CHANGE_DOC, REPLACER, name); WebServiceFactory.setTimeoutMilliseconds(SOCKET_TIMEOUT); WebServiceFactory.setEndpointAddress(ALFRESCO_ENDPOINT_TEST_SERVER); AuthenticationUtils.startSession(ALFRESCO_USERNAME, ALFRESCO_PASSWORD); try{ RepositoryServiceSoapBindingStub repositoryService = WebServiceFactory.getRepositoryService(); Query query = new Query(Constants.QUERY_LANG_LUCENE, luceneQuery); QueryResult queryResult = repositoryService.query(STORE, query, false); ResultSetRow row = queryResult.getResultSet().getRows(0); Reference reference = new Reference(); reference.setStore(STORE); reference.setUuid(row.getNode().getId()); Predicate predicate = new Predicate(); predicate.setStore(STORE); predicate.setNodes(new Reference[]{reference}); CMLDelete cmlDelete = new CMLDelete(); cmlDelete.setWhere(predicate); CML cml = new CML(); cml.setDelete(new CMLDelete[]{cmlDelete}); repositoryService.update(cml); } finally { AuthenticationUtils.endSession(); } } @Before public void createTestArea() throws Exception { removeTestArea(); try { AuthenticationUtils.startSession(ALFRESCO_USERNAME, ALFRESCO_PASSWORD); UpdateResult[] result = null; ParentReference companyHomeParent = new ParentReference(STORE, null, "/app:company_home", Constants.ASSOC_CONTAINS, null); String name = "testdata"; companyHomeParent.setChildName("{"+Constants.NAMESPACE_CONTENT_MODEL +"}" + name); NamedValue[] contentProps = new NamedValue[1]; contentProps[0] = Utils.createNamedValue(Constants.PROP_NAME, name); CMLCreate create = new CMLCreate("1", companyHomeParent, null, null, null, Constants.TYPE_FOLDER, contentProps); CML cml = new CML(); cml.setCreate(new CMLCreate[] {create}); try{ result = WebServiceFactory.getRepositoryService().update(cml); } finally { AuthenticationUtils.endSession(); } Reference testData = result[0].getDestination(); createNewDocument(testData, "testdata1.txt"); createNewDocument(testData, "testdata2.txt"); } catch (Exception e) { e.printStackTrace(); throw e; } } @After public void removeTestArea() throws Exception { WebServiceFactory.setEndpointAddress(ALFRESCO_ENDPOINT_TEST_SERVER); AuthenticationUtils.startSession(ALFRESCO_USERNAME, ALFRESCO_PASSWORD); QueryResult queryResultTestArea = null; try { RepositoryServiceSoapBindingStub repositoryService = WebServiceFactory.getRepositoryService(); Query query = new Query(Constants.QUERY_LANG_LUCENE, ALFRESCO_TEST_QUERY); queryResultTestArea = repositoryService.query(STORE, query, false); if(queryResultTestArea.getResultSet().getTotalRowCount()>0){ ResultSetRow row = queryResultTestArea.getResultSet().getRows(0); Reference reference = new Reference(); reference.setStore(STORE); reference.setUuid(row.getNode().getId()); Predicate predicate = new Predicate(); predicate.setStore(STORE); predicate.setNodes(new Reference[]{reference}); CMLDelete cmlDelete = new CMLDelete(); cmlDelete.setWhere(predicate); CML cml = new CML(); cml.setDelete(new CMLDelete[]{cmlDelete}); repositoryService.update(cml); } } finally { AuthenticationUtils.endSession(); } } @Test public void sanityCheck() throws Exception { try { int i; // Create a basic file system connection, and save it. ConfigurationNode connectionObject; ConfigurationNode child; Configuration requestObject; Configuration result; connectionObject = new ConfigurationNode("repositoryconnection"); child = new ConfigurationNode("name"); child.setValue("Alfresco Connection"); connectionObject.addChild(connectionObject.getChildCount(),child); child = new ConfigurationNode("class_name"); child.setValue("org.apache.manifoldcf.crawler.connectors.alfresco.AlfrescoRepositoryConnector"); connectionObject.addChild(connectionObject.getChildCount(),child); child = new ConfigurationNode("description"); child.setValue("An Alfresco Repository Connection"); connectionObject.addChild(connectionObject.getChildCount(),child); child = new ConfigurationNode("max_connections"); child.setValue("10"); connectionObject.addChild(connectionObject.getChildCount(),child); child = new ConfigurationNode("configuration"); //Alfresco Repository Connector parameters //username ConfigurationNode alfrescoUsernameNode = new ConfigurationNode("_PARAMETER_"); alfrescoUsernameNode.setAttribute("name", AlfrescoConfig.USERNAME_PARAM); alfrescoUsernameNode.setValue(ALFRESCO_USERNAME); child.addChild(child.getChildCount(), alfrescoUsernameNode); //password ConfigurationNode alfrescoPasswordNode = new ConfigurationNode("_PARAMETER_"); alfrescoPasswordNode.setAttribute("name", AlfrescoConfig.PASSWORD_PARAM); alfrescoPasswordNode.setValue(ALFRESCO_PASSWORD); child.addChild(child.getChildCount(), alfrescoPasswordNode); //protocol ConfigurationNode alfrescoProtocolNode = new ConfigurationNode("_PARAMETER_"); alfrescoProtocolNode.setAttribute("name", AlfrescoConfig.PROTOCOL_PARAM); alfrescoProtocolNode.setValue(ALFRESCO_PROTOCOL); child.addChild(child.getChildCount(), alfrescoProtocolNode); //server ConfigurationNode alfrescoServerNode = new ConfigurationNode("_PARAMETER_"); alfrescoServerNode.setAttribute("name", AlfrescoConfig.SERVER_PARAM); alfrescoServerNode.setValue(ALFRESCO_SERVER); child.addChild(child.getChildCount(), alfrescoServerNode); //port ConfigurationNode alfrescoPortNode = new ConfigurationNode("_PARAMETER_"); alfrescoPortNode.setAttribute("name", AlfrescoConfig.PORT_PARAM); alfrescoPortNode.setValue(ALFRESCO_PORT); child.addChild(child.getChildCount(), alfrescoPortNode); //path ConfigurationNode alfrescoPathNode = new ConfigurationNode("_PARAMETER_"); alfrescoPathNode.setAttribute("name", AlfrescoConfig.PATH_PARAM); alfrescoPathNode.setValue(ALFRESCO_PATH); child.addChild(child.getChildCount(), alfrescoPathNode); //socketTimeout ConfigurationNode socketTimeoutNode = new ConfigurationNode("_PARAMETER_"); socketTimeoutNode.setAttribute("name", AlfrescoConfig.SOCKET_TIMEOUT_PARAM); socketTimeoutNode.setValue(String.valueOf(SOCKET_TIMEOUT)); child.addChild(child.getChildCount(), socketTimeoutNode); connectionObject.addChild(connectionObject.getChildCount(),child); requestObject = new Configuration(); requestObject.addChild(0,connectionObject); result = performAPIPutOperationViaNodes("repositoryconnections/Alfresco%20Connection",201,requestObject); i = 0; while (i < result.getChildCount()) { ConfigurationNode resultNode = result.findChild(i++); if (resultNode.getType().equals("error")) throw new Exception(resultNode.getValue()); } // Create a basic null output connection, and save it. connectionObject = new ConfigurationNode("outputconnection"); child = new ConfigurationNode("name"); child.setValue("Null Connection"); connectionObject.addChild(connectionObject.getChildCount(),child); child = new ConfigurationNode("class_name"); child.setValue("org.apache.manifoldcf.agents.output.nullconnector.NullConnector"); connectionObject.addChild(connectionObject.getChildCount(),child); child = new ConfigurationNode("description"); child.setValue("Null Connection"); connectionObject.addChild(connectionObject.getChildCount(),child); child = new ConfigurationNode("max_connections"); child.setValue("100"); connectionObject.addChild(connectionObject.getChildCount(),child); requestObject = new Configuration(); requestObject.addChild(0,connectionObject); result = performAPIPutOperationViaNodes("outputconnections/Null%20Connection",201,requestObject); i = 0; while (i < result.getChildCount()) { ConfigurationNode resultNode = result.findChild(i++); if (resultNode.getType().equals("error")) throw new Exception(resultNode.getValue()); } // Create a job. ConfigurationNode jobObject = new ConfigurationNode("job"); child = new ConfigurationNode("description"); child.setValue("Test Job"); jobObject.addChild(jobObject.getChildCount(),child); child = new ConfigurationNode("repository_connection"); child.setValue("Alfresco Connection"); jobObject.addChild(jobObject.getChildCount(),child); child = new ConfigurationNode("output_connection"); child.setValue("Null Connection"); jobObject.addChild(jobObject.getChildCount(),child); child = new ConfigurationNode("run_mode"); child.setValue("scan once"); jobObject.addChild(jobObject.getChildCount(),child); child = new ConfigurationNode("start_mode"); child.setValue("manual"); jobObject.addChild(jobObject.getChildCount(),child); child = new ConfigurationNode("hopcount_mode"); child.setValue("accurate"); jobObject.addChild(jobObject.getChildCount(),child); child = new ConfigurationNode("document_specification"); //Job configuration ConfigurationNode sn = new ConfigurationNode("startpoint"); sn.setAttribute("luceneQuery",ALFRESCO_TEST_QUERY); child.addChild(child.getChildCount(),sn); jobObject.addChild(jobObject.getChildCount(),child); requestObject = new Configuration(); requestObject.addChild(0,jobObject); result = performAPIPostOperationViaNodes("jobs",201,requestObject); String jobIDString = null; i = 0; while (i < result.getChildCount()) { ConfigurationNode resultNode = result.findChild(i++); if (resultNode.getType().equals("error")) throw new Exception(resultNode.getValue()); else if (resultNode.getType().equals("job_id")) jobIDString = resultNode.getValue(); } if (jobIDString == null) throw new Exception("Missing job_id from return!"); // Now, start the job, and wait until it completes. startJob(jobIDString); waitJobInactive(jobIDString, 360000L); // Check to be sure we actually processed the right number of documents. // The test data area has 3 documents and one directory, and we have to count the root directory too. long count; count = getJobDocumentsProcessed(jobIDString); if (count != 3) throw new ManifoldCFException("Wrong number of documents processed - expected 3, saw "+new Long(count).toString()); // Add a file and recrawl Reference testFolder = getTestFolder(); createNewDocument(testFolder, "testdata3.txt"); createNewDocument(testFolder, "testdata4.txt"); // Now, start the job, and wait until it completes. startJob(jobIDString); waitJobInactive(jobIDString, 360000L); // The test data area has 4 documents and one directory, and we have to count the root directory too. count = getJobDocumentsProcessed(jobIDString); if (count != 5) throw new ManifoldCFException("Wrong number of documents processed after add - expected 5, saw "+new Long(count).toString()); // Change a document, and recrawl changeDocument("testdata1*","MODIFIED - Alfresco Testdata - MODIFIED"); // Now, start the job, and wait until it completes. startJob(jobIDString); waitJobInactive(jobIDString, 360000L); // The test data area has 4 documents and one directory, and we have to count the root directory too. count = getJobDocumentsProcessed(jobIDString); if (count != 5) throw new ManifoldCFException("Wrong number of documents processed after change - expected 5, saw "+new Long(count).toString()); // We also need to make sure the new document was indexed. Have to think about how to do this though. // MHL // Delete a file, and recrawl removeDocument("testdata2*"); // Now, start the job, and wait until it completes. startJob(jobIDString); waitJobInactive(jobIDString, 360000L); // Check to be sure we actually processed the right number of documents. // The test data area has 3 documents and one directory, and we have to count the root directory too. count = getJobDocumentsProcessed(jobIDString); if (count != 4) throw new ManifoldCFException("Wrong number of documents processed after delete - expected 4, saw "+new Long(count).toString()); // Now, delete the job. deleteJob(jobIDString); waitJobDeleted(jobIDString, 360000L); // Cleanup is automatic by the base class, so we can feel free to leave jobs and connections lying around. } catch (Exception e) { e.printStackTrace(); throw e; } } protected void startJob(String jobIDString) throws Exception { Configuration requestObject = new Configuration(); Configuration result = performAPIPutOperationViaNodes("start/"+jobIDString,201,requestObject); int i = 0; while (i < result.getChildCount()) { ConfigurationNode resultNode = result.findChild(i++); if (resultNode.getType().equals("error")) throw new Exception(resultNode.getValue()); } } protected void deleteJob(String jobIDString) throws Exception { Configuration result = performAPIDeleteOperationViaNodes("jobs/"+jobIDString,200); int i = 0; while (i < result.getChildCount()) { ConfigurationNode resultNode = result.findChild(i++); if (resultNode.getType().equals("error")) throw new Exception(resultNode.getValue()); } } protected String getJobStatus(String jobIDString) throws Exception { Configuration result = performAPIGetOperationViaNodes("jobstatuses/"+jobIDString,200); String status = null; int i = 0; while (i < result.getChildCount()) { ConfigurationNode resultNode = result.findChild(i++); if (resultNode.getType().equals("error")) throw new Exception(resultNode.getValue()); else if (resultNode.getType().equals("jobstatus")) { int j = 0; while (j < resultNode.getChildCount()) { ConfigurationNode childNode = resultNode.findChild(j++); if (childNode.getType().equals("status")) status = childNode.getValue(); } } } return status; } protected long getJobDocumentsProcessed(String jobIDString) throws Exception { Configuration result = performAPIGetOperationViaNodes("jobstatuses/"+jobIDString,200); String documentsProcessed = null; int i = 0; while (i < result.getChildCount()) { ConfigurationNode resultNode = result.findChild(i++); if (resultNode.getType().equals("error")) throw new Exception(resultNode.getValue()); else if (resultNode.getType().equals("jobstatus")) { int j = 0; while (j < resultNode.getChildCount()) { ConfigurationNode childNode = resultNode.findChild(j++); if (childNode.getType().equals("documents_processed")) documentsProcessed = childNode.getValue(); } } } if (documentsProcessed == null) throw new Exception("Expected a documents_processed field, didn't find it"); return new Long(documentsProcessed).longValue(); } protected void waitJobInactive(String jobIDString, long maxTime) throws Exception { long startTime = System.currentTimeMillis(); while (System.currentTimeMillis() < startTime + maxTime) { String status = getJobStatus(jobIDString); if (status == null) throw new Exception("No such job: '"+jobIDString+"'"); if (status.equals("not yet run")) throw new Exception("Job was never started."); if (status.equals("done")) return; if (status.equals("error")) throw new Exception("Job reports error."); ManifoldCF.sleep(1000L); continue; } throw new ManifoldCFException("ManifoldCF did not terminate in the allotted time of "+new Long(maxTime).toString()+" milliseconds"); } protected void waitJobDeleted(String jobIDString, long maxTime) throws Exception { long startTime = System.currentTimeMillis(); while (System.currentTimeMillis() < startTime + maxTime) { String status = getJobStatus(jobIDString); if (status == null) return; ManifoldCF.sleep(1000L); } throw new ManifoldCFException("ManifoldCF did not delete in the allotted time of "+new Long(maxTime).toString()+" milliseconds"); } }
{ "content_hash": "1e42797fac231dc108cc6612a500f7dc", "timestamp": "", "source": "github", "line_count": 662, "max_line_length": 162, "avg_line_length": 37.94259818731118, "alnum_prop": 0.6951190381399793, "repo_name": "Zamrath/Sample", "id": "c6c074c11c3009743a29a959bc0be72ddbd5eccb", "size": "25118", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tests/alfresco/src/test/java/org/apache/manifoldcf/alfresco_tests/APISanityIT.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "28618" }, { "name": "Java", "bytes": "4943532" }, { "name": "JavaScript", "bytes": "17630" }, { "name": "Python", "bytes": "154355" }, { "name": "Shell", "bytes": "44004" }, { "name": "XSLT", "bytes": "190340" } ], "symlink_target": "" }
package com.facebook.buck.jvm.java.intellij; import static com.facebook.buck.jvm.java.intellij.SerializableAndroidAar.createSerializableAndroidAar; import static com.facebook.buck.jvm.java.intellij.SerializableIntellijSettings.createSerializableIntellijSettings; import static com.facebook.buck.rules.BuildableProperties.Kind.ANDROID; import static com.facebook.buck.rules.BuildableProperties.Kind.LIBRARY; import static com.facebook.buck.rules.BuildableProperties.Kind.PACKAGING; import com.facebook.buck.android.AndroidBinary; import com.facebook.buck.android.AndroidLibrary; import com.facebook.buck.android.AndroidLibraryGraphEnhancer; import com.facebook.buck.android.AndroidPackageableCollection; import com.facebook.buck.android.AndroidPrebuiltAar; import com.facebook.buck.android.AndroidPrebuiltAarCollection; import com.facebook.buck.android.AndroidResource; import com.facebook.buck.android.DummyRDotJava; import com.facebook.buck.android.NdkLibrary; import com.facebook.buck.cxx.CxxLibrary; import com.facebook.buck.graph.AbstractBreadthFirstTraversal; import com.facebook.buck.io.ProjectFilesystem; import com.facebook.buck.jvm.core.JavaPackageFinder; import com.facebook.buck.jvm.java.JavaBinary; import com.facebook.buck.jvm.java.JavaLibrary; import com.facebook.buck.jvm.java.PrebuiltJar; import com.facebook.buck.log.Logger; import com.facebook.buck.model.BuildFileTree; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.rules.ActionGraph; import com.facebook.buck.rules.BuildRule; import com.facebook.buck.rules.ExportDependencies; import com.facebook.buck.rules.ProjectConfig; import com.facebook.buck.rules.SourcePathResolver; import com.facebook.buck.rules.SourceRoot; import com.facebook.buck.shell.ShellStep; import com.facebook.buck.step.ExecutionContext; import com.facebook.buck.util.Ansi; import com.facebook.buck.util.BuckConstant; import com.facebook.buck.util.Console; import com.facebook.buck.util.KeystoreProperties; import com.facebook.buck.util.ProcessExecutor; import com.facebook.buck.util.ProcessExecutorParams; import com.facebook.buck.util.Verbosity; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Functions; import com.google.common.base.Joiner; import com.google.common.base.MoreObjects; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Splitter; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintStream; import java.io.Writer; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import javax.annotation.Nullable; /** * Utility to map the build files in a project built with Buck into a collection of metadata files * so that the project can be built with IntelliJ. This uses a number of heuristics specific to our * repository at Facebook that does not make this a generally applicable solution. Hopefully over * time, the Facebook-specific logic will be removed. */ public class Project { /** * Directory in buck-out which holds temporary files. This should be explicitly excluded * from the IntelliJ project because it causes IntelliJ to try and index temporary files * that buck creates whilst a build it taking place. */ public static final Path TMP_PATH = BuckConstant.BUCK_OUTPUT_PATH.resolve("tmp"); /** * This directory is analogous to the gen/ directory that IntelliJ would produce when building an * Android module. It contains files such as R.java, BuildConfig.java, and Manifest.java. * <p> * By default, IntelliJ generates its gen/ directories in our source tree, which would likely * mess with the user's use of {@code glob(['**&#x2f;*.java'])}. For this reason, we encourage * users to target */ public static final String ANDROID_GEN_DIR = BuckConstant.BUCK_OUTPUT_DIRECTORY + "/android"; public static final Path ANDROID_GEN_PATH = BuckConstant.BUCK_OUTPUT_PATH.resolve("android"); public static final String ANDROID_APK_DIR = BuckConstant.BUCK_OUTPUT_DIRECTORY + "/gen"; private static final Logger LOG = Logger.get(Project.class); /** * Path to the intellij.py script that is used to transform the JSON written by this file. */ private static final String PATH_TO_INTELLIJ_PY = System.getProperty( "buck.path_to_intellij_py", // Fall back on this value when running Buck from an IDE. new File("src/com/facebook/buck/command/intellij.py").getAbsolutePath()); private final SourcePathResolver resolver; private final ImmutableSortedSet<ProjectConfig> rules; private final ActionGraph actionGraph; private final BuildFileTree buildFileTree; private final ImmutableMap<Path, String> basePathToAliasMap; private final JavaPackageFinder javaPackageFinder; private final ExecutionContext executionContext; private final ProjectFilesystem projectFilesystem; private final Optional<String> pathToDefaultAndroidManifest; private final IntellijConfig intellijConfig; private final Optional<String> pathToPostProcessScript; private final Set<BuildRule> libraryJars; private final AndroidPrebuiltAarCollection androidAars; private final String pythonInterpreter; private final ObjectMapper objectMapper; private final boolean turnOffAutoSourceGeneration; public Project( SourcePathResolver resolver, ImmutableSortedSet<ProjectConfig> rules, ActionGraph actionGraph, Map<Path, String> basePathToAliasMap, JavaPackageFinder javaPackageFinder, ExecutionContext executionContext, BuildFileTree buildFileTree, ProjectFilesystem projectFilesystem, Optional<String> pathToDefaultAndroidManifest, IntellijConfig intellijConfig, Optional<String> pathToPostProcessScript, String pythonInterpreter, ObjectMapper objectMapper, boolean turnOffAutoSourceGeneration) { this.resolver = resolver; this.rules = rules; this.actionGraph = actionGraph; this.buildFileTree = buildFileTree; this.basePathToAliasMap = ImmutableMap.copyOf(basePathToAliasMap); this.javaPackageFinder = javaPackageFinder; this.executionContext = executionContext; this.projectFilesystem = projectFilesystem; this.pathToDefaultAndroidManifest = pathToDefaultAndroidManifest; this.intellijConfig = intellijConfig; this.pathToPostProcessScript = pathToPostProcessScript; this.libraryJars = Sets.newHashSet(); this.androidAars = new AndroidPrebuiltAarCollection(); this.pythonInterpreter = pythonInterpreter; this.objectMapper = objectMapper; this.turnOffAutoSourceGeneration = turnOffAutoSourceGeneration; } public int createIntellijProject( File jsonTempFile, ProcessExecutor processExecutor, boolean generateMinimalProject, PrintStream stdOut, PrintStream stdErr) throws IOException, InterruptedException { List<SerializableModule> modules = createModulesForProjectConfigs(); writeJsonConfig(jsonTempFile, modules); List<String> modifiedFiles = Lists.newArrayList(); // Process the JSON config to generate the .xml and .iml files for IntelliJ. ExitCodeAndOutput result = processJsonConfig(jsonTempFile, generateMinimalProject); if (result.exitCode != 0) { Logger.get(Project.class).error(result.stdErr); return result.exitCode; } else { // intellij.py writes the list of modified files to stdout, so parse stdout and add the // resulting file paths to the modifiedFiles list. Iterable<String> paths = Splitter.on('\n').trimResults().omitEmptyStrings().split( result.stdOut); Iterables.addAll(modifiedFiles, paths); } // Write out the .idea/compiler.xml file (the .idea/ directory is guaranteed to exist). CompilerXml compilerXml = new CompilerXml(modules); final String pathToCompilerXml = ".idea/compiler.xml"; File compilerXmlFile = projectFilesystem.getFileForRelativePath(pathToCompilerXml); if (compilerXml.write(compilerXmlFile)) { modifiedFiles.add(pathToCompilerXml); } // If the user specified a post-processing script, then run it. if (pathToPostProcessScript.isPresent()) { String pathToScript = pathToPostProcessScript.get(); ProcessExecutorParams params = ProcessExecutorParams.builder() .setCommand(ImmutableList.of(pathToScript)) .build(); ProcessExecutor.Result postProcessResult = processExecutor.launchAndExecute(params); int postProcessExitCode = postProcessResult.getExitCode(); if (postProcessExitCode != 0) { return postProcessExitCode; } } if (executionContext.getConsole().getVerbosity().shouldPrintOutput()) { SortedSet<String> modifiedFilesInSortedForder = Sets.newTreeSet(modifiedFiles); stdOut.printf("MODIFIED FILES:\n%s\n", Joiner.on('\n').join(modifiedFilesInSortedForder)); } else { // If any files have been modified by `buck project`, then inform the user. if (!modifiedFiles.isEmpty()) { stdOut.printf("Modified %d IntelliJ project files.\n", modifiedFiles.size()); } else { stdOut.println("No IntelliJ project files modified."); } } // Blit stderr from intellij.py to parent stderr. stdErr.print(result.stdErr); return 0; } @VisibleForTesting Map<String, SerializableModule> buildNameToModuleMap(List<SerializableModule> modules) { Map<String, SerializableModule> nameToModule = Maps.newHashMap(); for (SerializableModule module : modules) { nameToModule.put(module.name, module); } return nameToModule; } @VisibleForTesting static String createPathToProjectDotPropertiesFileFor(SerializableModule module) { return module.getModuleDirectoryPath().resolve("project.properties").toString(); } @VisibleForTesting ActionGraph getActionGraph() { return actionGraph; } /** * This is used exclusively for testing and will only be populated after the modules are created. */ @VisibleForTesting ImmutableSet<BuildRule> getLibraryJars() { return ImmutableSet.copyOf(libraryJars); } @VisibleForTesting List<SerializableModule> createModulesForProjectConfigs() throws IOException { List<SerializableModule> modules = Lists.newArrayList(); // Convert the project_config() targets into modules and find the union of all jars passed to // no_dx. ImmutableSet.Builder<Path> noDxJarsBuilder = ImmutableSet.builder(); for (ProjectConfig projectConfig : rules) { BuildRule srcRule = projectConfig.getSrcRule(); if (srcRule instanceof AndroidBinary) { AndroidBinary androidBinary = (AndroidBinary) srcRule; AndroidPackageableCollection packageableCollection = androidBinary.getAndroidPackageableCollection(); ImmutableList<Path> dxAbsolutePaths = resolver.getAllAbsolutePaths(packageableCollection.getNoDxClasspathEntries()); noDxJarsBuilder.addAll(FluentIterable.from(dxAbsolutePaths) .transform(projectFilesystem.getRelativizer())); } final Optional<Path> rJava; if (srcRule instanceof AndroidLibrary) { AndroidLibrary androidLibrary = (AndroidLibrary) srcRule; BuildTarget dummyRDotJavaTarget = AndroidLibraryGraphEnhancer.getDummyRDotJavaTarget( androidLibrary.getBuildTarget()); Path src = DummyRDotJava.getRDotJavaSrcFolder(dummyRDotJavaTarget); rJava = Optional.of(src); } else if (srcRule instanceof AndroidResource) { AndroidResource androidResource = (AndroidResource) srcRule; BuildTarget dummyRDotJavaTarget = AndroidLibraryGraphEnhancer.getDummyRDotJavaTarget( androidResource.getBuildTarget()); Path src = DummyRDotJava.getRDotJavaSrcFolder(dummyRDotJavaTarget); rJava = Optional.of(src); } else { rJava = Optional.absent(); } SerializableModule module = createModuleForProjectConfig(projectConfig, rJava); modules.add(module); } ImmutableSet<Path> noDxJars = noDxJarsBuilder.build(); // Update module dependencies to apply scope="PROVIDED", where appropriate. markNoDxJarsAsProvided(projectFilesystem, modules, noDxJars, resolver); return modules; } @SuppressWarnings("PMD.LooseCoupling") private SerializableModule createModuleForProjectConfig( ProjectConfig projectConfig, Optional<Path> rJava) throws IOException { BuildRule projectRule = Preconditions.checkNotNull(projectConfig.getProjectRule()); Preconditions.checkState( projectRule instanceof AndroidBinary || projectRule instanceof AndroidLibrary || projectRule instanceof AndroidResource || projectRule instanceof JavaBinary || projectRule instanceof JavaLibrary || projectRule instanceof CxxLibrary || projectRule instanceof NdkLibrary, "project_config() does not know how to process a src_target of type %s (%s).", projectRule.getType(), projectRule.getBuildTarget()); LinkedHashSet<SerializableDependentModule> dependencies = Sets.newLinkedHashSet(); final BuildTarget target = projectConfig.getBuildTarget(); SerializableModule module = new SerializableModule(projectRule, target); module.name = getIntellijNameForRule(projectRule); module.isIntelliJPlugin = projectConfig.getIsIntelliJPlugin(); Path relativePath = projectConfig.getBuildTarget().getBasePath(); module.pathToImlFile = relativePath.resolve(String.format("%s.iml", module.name)); // List the module source as the first dependency. boolean includeSourceFolder = true; // Do the tests before the sources so they appear earlier in the classpath. When tests are run, // their classpath entries may be deliberately shadowing production classpath entries. // tests folder boolean hasSourceFoldersForTestRule = addSourceFolders( module, projectConfig.getTestRule(), projectConfig.getTestsSourceRoots(), true /* isTestSource */); addResourceFolders( module, projectConfig.getTestRule(), projectConfig.getTestsResourceRoots(), true /* isTestSource */); // test dependencies BuildRule testRule = projectConfig.getTestRule(); if (testRule != null) { walkRuleAndAdd( testRule, true /* isForTests */, dependencies, projectConfig.getSrcRule()); } // src folder boolean hasSourceFoldersForSrcRule = addSourceFolders( module, projectConfig.getSrcRule(), projectConfig.getSourceRoots(), false /* isTestSource */); addResourceFolders( module, projectConfig.getSrcRule(), projectConfig.getResourceRoots(), false /* isTestSource */); addRootExcludes(module, projectConfig.getSrcRule(), projectFilesystem); // At least one of src or tests should contribute a source folder unless this is an // non-library Android project with no source roots specified. if (!hasSourceFoldersForTestRule && !hasSourceFoldersForSrcRule) { includeSourceFolder = false; } // IntelliJ expects all Android projects to have a gen/ folder, even if there is no src/ // directory specified. boolean isAndroidRule = projectRule.getProperties().is(ANDROID); if (isAndroidRule) { boolean hasSourceFolders = !module.sourceFolders.isEmpty(); module.sourceFolders.add(SerializableModule.SourceFolder.GEN); if (!hasSourceFolders) { includeSourceFolder = true; } } // src dependencies // Note that isForTests is false even if projectRule is the project_config's test_target. walkRuleAndAdd( projectRule, false /* isForTests */, dependencies, projectConfig.getSrcRule()); Path basePath = projectConfig.getBuildTarget().getBasePath(); // Specify another path for intellij to generate gen/ for each android module, // so that it will not disturb our glob() rules. // To specify the location of gen, Intellij requires the relative path from // the base path of current build target. module.moduleGenPath = generateRelativeGenPath(basePath); if (turnOffAutoSourceGeneration && rJava.isPresent()) { module.moduleRJavaPath = basePath.relativize(Paths.get("")).resolve(rJava.get()); } SerializableDependentModule jdkDependency; if (isAndroidRule) { // android details if (projectRule instanceof NdkLibrary) { NdkLibrary ndkLibrary = (NdkLibrary) projectRule; module.isAndroidLibraryProject = true; module.keystorePath = null; module.nativeLibs = relativePath.relativize(ndkLibrary.getLibraryPath()); } else if (projectRule instanceof AndroidLibrary) { module.isAndroidLibraryProject = true; module.keystorePath = null; module.resFolder = intellijConfig.getAndroidResources().orNull(); module.assetFolder = intellijConfig.getAndroidAssets().orNull(); } else if (projectRule instanceof AndroidResource) { AndroidResource androidResource = (AndroidResource) projectRule; module.resFolder = createRelativeResourcesPath( Optional.fromNullable(androidResource.getRes()) .transform(resolver.getAbsolutePathFunction()) .transform(projectFilesystem.getRelativizer()) .orNull(), target); module.isAndroidLibraryProject = true; module.keystorePath = null; } else if (projectRule instanceof AndroidBinary) { AndroidBinary androidBinary = (AndroidBinary) projectRule; module.resFolder = intellijConfig.getAndroidResources().orNull(); module.assetFolder = intellijConfig.getAndroidAssets().orNull(); module.isAndroidLibraryProject = false; module.binaryPath = generateRelativeAPKPath( projectRule.getBuildTarget().getShortName(), basePath); KeystoreProperties keystoreProperties = KeystoreProperties.createFromPropertiesFile( resolver.getAbsolutePath(androidBinary.getKeystore().getPathToStore()), resolver.getAbsolutePath(androidBinary.getKeystore().getPathToPropertiesFile()), projectFilesystem); // getKeystore() returns an absolute path, but an IntelliJ module // expects the path to the keystore to be relative to the module root. // First, grab the aboslute path to the project config. BuildTarget projectTarget = projectConfig.getBuildTarget(); Path modulePath = projectTarget.getCellPath().resolve(projectTarget.getBasePath()); // Now relativize to the keystore path, which is absolute too. module.keystorePath = modulePath.relativize(keystoreProperties.getKeystore()); } else { module.isAndroidLibraryProject = true; module.keystorePath = null; } module.hasAndroidFacet = true; module.proguardConfigPath = null; module.androidManifest = resolveAndroidManifestRelativePath(basePath); // List this last so that classes from modules can shadow classes in the JDK. jdkDependency = SerializableDependentModule.newInheritedJdk(); } else { module.hasAndroidFacet = false; if (module.isIntelliJPlugin()) { jdkDependency = SerializableDependentModule.newIntelliJPluginJdk(); } else { if (projectConfig.getJdkName() == null || projectConfig.getJdkType() == null) { jdkDependency = SerializableDependentModule.newInheritedJdk(); } else { jdkDependency = SerializableDependentModule.newStandardJdk( projectConfig.getJdkName(), projectConfig.getJdkType()); } } } // Assign the dependencies. module.setModuleDependencies( createDependenciesInOrder(includeSourceFolder, dependencies, jdkDependency)); // Annotation processing generates sources for IntelliJ to consume, but does so outside // the module directory to avoid messing up globbing. JavaLibrary javaLibrary = null; if (projectRule instanceof JavaLibrary) { javaLibrary = (JavaLibrary) projectRule; } if (javaLibrary != null) { Optional<Path> processingParams = javaLibrary.getGeneratedSourcePath(); if (processingParams.isPresent()) { module.annotationGenPath = basePath.relativize(processingParams.get()); module.annotationGenIsForTest = !hasSourceFoldersForSrcRule; } } return module; } @Nullable private Path resolveAndroidManifestRelativePath(Path basePath) { Path fallbackManifestPath = resolveAndroidManifestFileRelativePath(basePath); Path manifestPath = intellijConfig.getAndroidManifest().orNull(); if (manifestPath != null) { Path path = basePath.resolve(manifestPath); return projectFilesystem.exists(path) ? manifestPath : fallbackManifestPath; } return fallbackManifestPath; } @Nullable private Path resolveAndroidManifestFileRelativePath(Path basePath) { // If there is a default AndroidManifest.xml specified in .buckconfig, use it if // AndroidManifest.xml is not present in the root of the [Android] IntelliJ module. if (pathToDefaultAndroidManifest.isPresent()) { Path androidManifest = basePath.resolve("AndroidManifest.xml"); if (!projectFilesystem.exists(androidManifest)) { String manifestPath = this.pathToDefaultAndroidManifest.get(); String rootPrefix = "//"; Preconditions.checkState( manifestPath.startsWith(rootPrefix), "Currently, we expect this option to start with '%s', " + "indicating that it is relative to the root of the repository.", rootPrefix); manifestPath = manifestPath.substring(rootPrefix.length()); return basePath.relativize(Paths.get(manifestPath)); } } return null; } @SuppressWarnings("PMD.LooseCoupling") private List<SerializableDependentModule> createDependenciesInOrder( boolean includeSourceFolder, LinkedHashSet<SerializableDependentModule> dependencies, SerializableDependentModule jdkDependency) { List<SerializableDependentModule> dependenciesInOrder = Lists.newArrayList(); // If the source folder module is present, add it to the front of the list. if (includeSourceFolder) { dependenciesInOrder.add(SerializableDependentModule.newSourceFolder()); } // List the libraries before the non-libraries. List<SerializableDependentModule> nonLibraries = Lists.newArrayList(); for (SerializableDependentModule dep : dependencies) { if (dep.isLibrary()) { dependenciesInOrder.add(dep); } else { nonLibraries.add(dep); } } dependenciesInOrder.addAll(nonLibraries); // Add the JDK last. dependenciesInOrder.add(jdkDependency); return dependenciesInOrder; } /** * Paths.computeRelativePath(basePathWithSlash, "") generates the relative path * from base path of current build target to the root of the project. * * Paths.computeRelativePath("", basePathWithSlash) generates the relative path * from the root of the project to base path of current build target. * * For example, for the build target in $PROJECT_DIR$/android_res/com/facebook/gifts/, * Intellij will generate $PROJECT_DIR$/buck-out/android/android_res/com/facebook/gifts/gen * * @return the relative path of gen from the base path of current module. */ static Path generateRelativeGenPath(Path basePathOfModule) { return basePathOfModule .relativize(Paths.get("")) .resolve(ANDROID_GEN_DIR) .resolve(Paths.get("").relativize(basePathOfModule)) .resolve("gen"); } static Path generateRelativeAPKPath(String targetName, Path basePathOfModule) { return basePathOfModule .relativize(Paths.get("")).resolve(ANDROID_APK_DIR) .resolve(Paths.get("").relativize(basePathOfModule)) .resolve(targetName + ".apk"); } private boolean addSourceFolders( SerializableModule module, @Nullable BuildRule buildRule, @Nullable ImmutableList<SourceRoot> sourceRoots, boolean isTestSource) { if (buildRule == null || sourceRoots == null) { return false; } if (buildRule.getProperties().is(PACKAGING) && sourceRoots.isEmpty()) { return false; } if (sourceRoots.isEmpty()) { // When there is a src_target, but no src_roots were specified, then the current directory is // treated as the SourceRoot. This is the common case when a project contains one folder of // Java source code with a build file for each Java package. For example, if the project's // only source folder were named "java/" and a build file in java/com/example/base/ contained // the an extremely simple set of build rules: // // java_library( // name = 'base', // srcs = glob(['*.java']), // } // // project_config( // src_target = ':base', // ) // // then the corresponding .iml file (in the same directory) should contain: // // <content url="file://$MODULE_DIR$"> // <sourceFolder url="file://$MODULE_DIR$" // isTestSource="false" // packagePrefix="com.example.base" /> // <sourceFolder url="file://$MODULE_DIR$/gen" isTestSource="false" /> // // <!-- It will have an <excludeFolder> for every "subpackage" of com.example.base. --> // <excludeFolder url="file://$MODULE_DIR$/util" /> // </content> // // Note to prevent the <excludeFolder> elements from being included, the project_config() // rule should be: // // project_config( // src_target = ':base', // src_root_includes_subdirectories = True, // ) // // Because developers who organize their code this way will have many build files, the default // values of project_config() assume this approach to help minimize the tedium in writing all // of those project_config() rules. String url = "file://$MODULE_DIR$"; String packagePrefix = javaPackageFinder.findJavaPackage( Preconditions.checkNotNull(module.pathToImlFile)); SerializableModule.SourceFolder sourceFolder = new SerializableModule.SourceFolder(url, isTestSource, packagePrefix); module.sourceFolders.add(sourceFolder); } else { for (SourceRoot sourceRoot : sourceRoots) { SerializableModule.SourceFolder sourceFolder = new SerializableModule.SourceFolder( String.format("file://$MODULE_DIR$/%s", sourceRoot.getName()), isTestSource); module.sourceFolders.add(sourceFolder); } } // Include <excludeFolder> elements, as appropriate. for (Path relativePath : this.buildFileTree.getChildPaths(buildRule.getBuildTarget())) { String excludeFolderUrl = "file://$MODULE_DIR$/" + relativePath; SerializableModule.SourceFolder excludeFolder = new SerializableModule.SourceFolder( excludeFolderUrl, /* isTestSource */ false); module.excludeFolders.add(excludeFolder); } return true; } private void addResourceFolders( SerializableModule module, @Nullable BuildRule buildRule, @Nullable ImmutableList<SourceRoot> resourceRoots, boolean isTestSource) { if (buildRule == null || resourceRoots == null) { return; } for (SourceRoot resourceRoot : resourceRoots) { SerializableModule.SourceFolder resourceFolder = new SerializableModule.SourceFolder( String.format("file://$MODULE_DIR$/%s", resourceRoot.getName()), isTestSource, true, null); module.sourceFolders.add(resourceFolder); } } @VisibleForTesting static void addRootExcludes( SerializableModule module, @Nullable BuildRule buildRule, ProjectFilesystem projectFilesystem) { // If in the root of the project, specify ignored paths. if (buildRule != null && buildRule.getBuildTarget().getBasePathWithSlash().isEmpty()) { for (Path path : projectFilesystem.getIgnorePaths()) { // It turns out that ignoring all of buck-out causes problems in IntelliJ: it forces an // extra "modules" folder to appear at the top of the navigation pane that competes with the // ordinary file tree, making navigation a real pain. The hypothesis is that this is because // there are files in buck-out/gen and buck-out/android that IntelliJ freaks out about if it // cannot find them. Therefore, if "buck-out" is listed in the default list of paths to // ignore (which makes sense for other parts of Buck, such as Watchman), then we will ignore // only the appropriate subfolders of buck-out instead. if (BuckConstant.BUCK_OUTPUT_PATH.equals(path)) { addRootExclude(module, BuckConstant.SCRATCH_PATH); addRootExclude(module, BuckConstant.LOG_PATH); addRootExclude(module, TMP_PATH); } else { addRootExclude(module, path); } } module.isRootModule = true; } } private static void addRootExclude(SerializableModule module, Path path) { module.excludeFolders.add( new SerializableModule.SourceFolder( String.format("file://$MODULE_DIR$/%s", path), /* isTestSource */ false)); } /** * Modifies the {@code scope} of a library dependency to {@code "PROVIDED"}, where appropriate. * <p> * If an {@code android_binary()} rule uses the {@code no_dx} argument, then the jars in the * libraries that should not be dex'ed must be included with {@code scope="PROVIDED"} in * IntelliJ. * <p> * The problem is that if a library is included by two android_binary rules that each need it in a * different way (i.e., for one it should be {@code scope="COMPILE"} and another it should be * {@code scope="PROVIDED"}), then it must be tagged as {@code scope="PROVIDED"} in all * dependent modules and then added as {@code scope="COMPILE"} in the .iml file that corresponds * to the android_binary that <em>does not</em> list the library in its {@code no_dx} list. */ @VisibleForTesting static void markNoDxJarsAsProvided( ProjectFilesystem projectFilesystem, List<SerializableModule> modules, Set<Path> noDxJars, SourcePathResolver resolver) { Map<String, Path> intelliJLibraryNameToJarPath = Maps.newHashMap(); for (Path jarPath : noDxJars) { String libraryName = getIntellijNameForBinaryJar(jarPath); intelliJLibraryNameToJarPath.put(libraryName, jarPath); } for (SerializableModule module : modules) { // For an android_binary() rule, create a set of paths to JAR files (or directories) that // must be dex'ed. If a JAR file that is in the no_dx list for some android_binary rule, but // is in this set for this android_binary rule, then it should be scope="COMPILE" rather than // scope="PROVIDED". Set<Path> classpathEntriesToDex; if (module.srcRule instanceof AndroidBinary) { AndroidBinary androidBinary = (AndroidBinary) module.srcRule; AndroidPackageableCollection packageableCollection = androidBinary.getAndroidPackageableCollection(); classpathEntriesToDex = new HashSet<>( Sets.intersection( noDxJars, FluentIterable.from(packageableCollection.getClasspathEntriesToDex()) .transform(resolver.getAbsolutePathFunction()) .transform(projectFilesystem.getRelativizer()) .toSet())); } else { classpathEntriesToDex = ImmutableSet.of(); } // Inspect all of the library dependencies. If the corresponding JAR file is in the set of // noDxJars, then either change its scope to "COMPILE" or "PROVIDED", as appropriate. for (SerializableDependentModule dependentModule : Preconditions.checkNotNull(module.getDependencies())) { if (!dependentModule.isLibrary()) { continue; } // This is the IntelliJ name for the library that corresponds to the PrebuiltJarRule. String libraryName = dependentModule.getLibraryName(); Path jarPath = intelliJLibraryNameToJarPath.get(libraryName); if (jarPath != null) { if (classpathEntriesToDex.contains(jarPath)) { dependentModule.scope = null; classpathEntriesToDex.remove(jarPath); } else { dependentModule.scope = "PROVIDED"; } } } // Make sure that every classpath entry that is also in noDxJars is added with scope="COMPILE" // if it has not already been added to the module. for (Path entry : classpathEntriesToDex) { String libraryName = getIntellijNameForBinaryJar(entry); SerializableDependentModule dependency = SerializableDependentModule.newLibrary( null, libraryName); Preconditions.checkNotNull(module.getDependencies()).add(dependency); } } } /** * Walks the dependencies of a build rule and adds the appropriate DependentModules to the * specified dependencies collection. All library dependencies will be added before any module * dependencies. See {@code ProjectTest#testThatJarsAreListedBeforeModules()} for details on why * this behavior is important. */ @SuppressWarnings("PMD.LooseCoupling") private void walkRuleAndAdd( final BuildRule rule, final boolean isForTests, final LinkedHashSet<SerializableDependentModule> dependencies, @Nullable final BuildRule srcTarget) { final Path basePathForRule = rule.getBuildTarget().getBasePath(); new AbstractBreadthFirstTraversal<BuildRule>(rule.getDeps()) { private final LinkedHashSet<SerializableDependentModule> librariesToAdd = Sets.newLinkedHashSet(); private final LinkedHashSet<SerializableDependentModule> modulesToAdd = Sets.newLinkedHashSet(); @Override public ImmutableSet<BuildRule> visit(BuildRule dep) { ImmutableSet<BuildRule> depsToVisit; if (rule.getProperties().is(PACKAGING) || dep instanceof AndroidResource || dep == rule) { depsToVisit = dep.getDeps(); } else if (dep.getProperties().is(LIBRARY) && dep instanceof ExportDependencies) { depsToVisit = ((ExportDependencies) dep).getExportedDeps(); } else { depsToVisit = ImmutableSet.of(); } // Special Case: If we are traversing the test_target and we encounter a library rule in the // same package that is not the src_target, then we should traverse the deps. Consider the // following build file: // // android_library( // name = 'lib', // srcs = glob(['*.java'], excludes = ['*Test.java']), // deps = [ // # LOTS OF DEPS // ], // ) // // java_test( // name = 'test', // srcs = glob(['*Test.java']), // deps = [ // ':lib', // # MOAR DEPS // ], // ) // // project_config( // test_target = ':test', // ) // // Note that the only source folder for this IntelliJ module is the current directory. Thus, // the current directory should be treated as a source folder with test sources, but it // should contain the union of :lib and :test's deps as dependent modules. if (isForTests && depsToVisit.isEmpty() && dep.getBuildTarget().getBasePath().equals(basePathForRule) && !dep.equals(srcTarget)) { depsToVisit = dep.getDeps(); } SerializableDependentModule dependentModule; if (androidAars.contains(dep)) { AndroidPrebuiltAar aar = androidAars.getParentAar(dep); dependentModule = SerializableDependentModule.newLibrary( aar.getBuildTarget(), getIntellijNameForAar(aar)); } else if (dep instanceof PrebuiltJar) { libraryJars.add(dep); String libraryName = getIntellijNameForRule(dep); dependentModule = SerializableDependentModule.newLibrary( dep.getBuildTarget(), libraryName); } else if (dep instanceof AndroidPrebuiltAar) { androidAars.add((AndroidPrebuiltAar) dep); String libraryName = getIntellijNameForAar(dep); dependentModule = SerializableDependentModule.newLibrary( dep.getBuildTarget(), libraryName); } else if ( (dep instanceof CxxLibrary) || (dep instanceof NdkLibrary) || (dep instanceof JavaLibrary) || (dep instanceof AndroidResource)) { String moduleName = getIntellijNameForRule(dep); dependentModule = SerializableDependentModule.newModule(dep.getBuildTarget(), moduleName); } else { return depsToVisit; } if (librariesToAdd.contains(dependentModule) || modulesToAdd.contains(dependentModule)) { return depsToVisit; } if (isForTests) { dependentModule.scope = "TEST"; } else { // If the dependentModule has already been added in the "TEST" scope, then it should be // removed and then re-added using the current (compile) scope. String currentScope = dependentModule.scope; dependentModule.scope = "TEST"; if (dependencies.contains(dependentModule)) { dependencies.remove(dependentModule); } dependentModule.scope = currentScope; } // Slate the module for addition to the dependencies collection. Modules are added to // dependencies collection once the traversal is complete in the onComplete() method. if (dependentModule.isLibrary()) { librariesToAdd.add(dependentModule); } else { modulesToAdd.add(dependentModule); } return depsToVisit; } @Override protected void onComplete() { dependencies.addAll(librariesToAdd); dependencies.addAll(modulesToAdd); } }.start(); } /** * Maps a BuildRule to the name of the equivalent IntelliJ library or module. */ private String getIntellijNameForRule(BuildRule rule) { return getIntellijNameForRule(rule, basePathToAliasMap); } /** * @param rule whose corresponding IntelliJ module name will be returned * @param basePathToAliasMap may be null if rule is a {@link PrebuiltJar} */ private String getIntellijNameForRule( BuildRule rule, @Nullable Map<Path, String> basePathToAliasMap) { // Get basis for the library/module name. String name; if (rule instanceof PrebuiltJar) { PrebuiltJar prebuiltJar = (PrebuiltJar) rule; Path absolutePath = resolver.getAbsolutePath(prebuiltJar.getBinaryJar()); String binaryJar = projectFilesystem.getRootPath().relativize(absolutePath).toString(); return getIntellijNameForBinaryJar(binaryJar); } else { Path basePath = rule.getBuildTarget().getBasePath(); if (basePathToAliasMap != null && basePathToAliasMap.containsKey(basePath)) { name = Preconditions.checkNotNull(basePathToAliasMap.get(basePath)); } else { name = rule.getBuildTarget().getBasePath().toString(); name = name.replace('/', '_'); // Must add a prefix to ensure that name is non-empty. name = "module_" + name; } // Normalize name. return normalizeIntelliJName(name); } } private static String getIntellijNameForBinaryJar(Path binaryJar) { return getIntellijNameForBinaryJar(binaryJar.toString()); } private static String getIntellijNameForBinaryJar(String binaryJar) { String name = binaryJar.replace('/', '_'); return normalizeIntelliJName(name); } private static String normalizeIntelliJName(String name) { return name.replace('.', '_').replace('-', '_').replace(':', '_'); } /** * @param pathRelativeToProjectRoot if {@code null}, then this method returns {@code null} */ @Nullable private static Path createRelativeResourcesPath( @Nullable Path pathRelativeToProjectRoot, BuildTarget target) { if (pathRelativeToProjectRoot == null) { return null; } Path directoryPath = target.getBasePath(); if (pathRelativeToProjectRoot.startsWith(directoryPath)) { return directoryPath.relativize(pathRelativeToProjectRoot); } else { LOG.warn("Target %s is using generated resources, which are not supported", target.getFullyQualifiedName()); // What could possibly go wrong... return Paths.get("res"); } } private void writeJsonConfig( File jsonTempFile, List<SerializableModule> modules) throws IOException { List<SerializablePrebuiltJarRule> libraries = Lists.newArrayListWithCapacity( libraryJars.size()); for (BuildRule libraryJar : libraryJars) { Preconditions.checkState(libraryJar instanceof PrebuiltJar); String name = getIntellijNameForRule(libraryJar, null /* basePathToAliasMap */); PrebuiltJar prebuiltJar = (PrebuiltJar) libraryJar; Path binaryJarAbsolutePath = resolver.getAbsolutePath(prebuiltJar.getBinaryJar()); String binaryJar = projectFilesystem.getRelativizer().apply(binaryJarAbsolutePath).toString(); String sourceJar = prebuiltJar.getSourceJar() .transform(resolver.getAbsolutePathFunction()) .transform(projectFilesystem.getRelativizer()) .transform(Functions.toStringFunction()) .orNull(); String javadocUrl = prebuiltJar.getJavadocUrl().orNull(); libraries.add(new SerializablePrebuiltJarRule(name, binaryJar, sourceJar, javadocUrl)); } List<SerializableAndroidAar> aars = Lists.newArrayListWithCapacity(androidAars.size()); for (BuildRule aar : androidAars) { Preconditions.checkState(aar instanceof AndroidPrebuiltAar); AndroidPrebuiltAar preBuiltAar = (AndroidPrebuiltAar) aar; String name = getIntellijNameForAar(preBuiltAar); aars.add(createSerializableAndroidAar(name, preBuiltAar)); } writeJsonConfig(jsonTempFile, modules, libraries, aars); } private void writeJsonConfig( File jsonTempFile, List<SerializableModule> modules, List<SerializablePrebuiltJarRule> libraries, List<SerializableAndroidAar> aars) throws IOException { Map<String, Object> config = ImmutableMap.of( "modules", modules, "libraries", libraries, "aars", aars, "java", createSerializableIntellijSettings(intellijConfig)); // Write out the JSON config to be consumed by the Python. try (Writer writer = new FileWriter(jsonTempFile)) { if (executionContext.getVerbosity().shouldPrintOutput()) { ObjectWriter objectWriter = objectMapper.writerWithDefaultPrettyPrinter(); objectWriter.writeValue(writer, config); } else { objectMapper.writeValue(writer, config); } } } private String getIntellijNameForAar(BuildRule aar) { return getIntellijNameForBinaryJar(aar.getFullyQualifiedName()).replaceAll(":", "_"); } private ExitCodeAndOutput processJsonConfig(File jsonTempFile, boolean generateMinimalProject) throws IOException, InterruptedException { ImmutableList.Builder<String> argsBuilder = ImmutableList.<String>builder() .add(pythonInterpreter) .add(PATH_TO_INTELLIJ_PY) .add(jsonTempFile.getAbsolutePath()); if (generateMinimalProject) { argsBuilder.add("--generate_minimum_project"); } if (turnOffAutoSourceGeneration) { argsBuilder.add("--disable_android_auto_generation_setting"); } final ImmutableList<String> args = argsBuilder.build(); ShellStep command = new ShellStep(projectFilesystem.getRootPath()) { @Override public String getShortName() { return "python"; } @Override protected ImmutableList<String> getShellCommandInternal( ExecutionContext context) { return args; } }; Console console = executionContext.getConsole(); Console childConsole = new Console( Verbosity.SILENT, console.getStdOut(), console.getStdErr(), Ansi.withoutTty()); int exitCode; try (ExecutionContext childContext = ExecutionContext.builder() .setExecutionContext(executionContext) .setConsole(childConsole) .build()) { exitCode = command.execute(childContext); } return new ExitCodeAndOutput(exitCode, command.getStdout(), command.getStderr()); } private static class ExitCodeAndOutput { private final int exitCode; private final String stdOut; private final String stdErr; ExitCodeAndOutput(int exitCode, String stdOut, String stdErr) { this.exitCode = exitCode; this.stdOut = stdOut; this.stdErr = stdErr; } } @JsonInclude(Include.NON_NULL) @VisibleForTesting static class SerializablePrebuiltJarRule { @JsonProperty private final String name; @JsonProperty private final String binaryJar; @Nullable @JsonProperty private final String sourceJar; @Nullable @JsonProperty private final String javadocUrl; private SerializablePrebuiltJarRule( String name, String binaryJar, @Nullable String sourceJar, @Nullable String javadocUrl) { this.name = name; this.binaryJar = binaryJar; this.sourceJar = sourceJar; this.javadocUrl = javadocUrl; } @Override public String toString() { return MoreObjects.toStringHelper(SerializablePrebuiltJarRule.class) .add("name", name) .add("binaryJar", binaryJar) .add("sourceJar", sourceJar) .add("javadocUrl", javadocUrl) .toString(); } } }
{ "content_hash": "53c79f9b930f0d75323bec5aa6ced2f9", "timestamp": "", "source": "github", "line_count": 1162, "max_line_length": 114, "avg_line_length": 40.66006884681583, "alnum_prop": 0.6972506190869262, "repo_name": "liuyang-li/buck", "id": "d0ab53b4bb27170c5e02c518a7dc7ff74bbed820", "size": "47852", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/facebook/buck/jvm/java/intellij/Project.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "87" }, { "name": "Batchfile", "bytes": "683" }, { "name": "C", "bytes": "246045" }, { "name": "C#", "bytes": "237" }, { "name": "C++", "bytes": "4689" }, { "name": "CSS", "bytes": "54863" }, { "name": "D", "bytes": "1017" }, { "name": "Go", "bytes": "13683" }, { "name": "Groff", "bytes": "440" }, { "name": "Groovy", "bytes": "2297" }, { "name": "HTML", "bytes": "5023" }, { "name": "IDL", "bytes": "128" }, { "name": "Java", "bytes": "12000000" }, { "name": "JavaScript", "bytes": "931213" }, { "name": "Lex", "bytes": "2442" }, { "name": "Makefile", "bytes": "1791" }, { "name": "Matlab", "bytes": "47" }, { "name": "OCaml", "bytes": "2956" }, { "name": "Objective-C", "bytes": "108013" }, { "name": "Objective-C++", "bytes": "34" }, { "name": "PowerShell", "bytes": "244" }, { "name": "Python", "bytes": "488758" }, { "name": "Rust", "bytes": "938" }, { "name": "Shell", "bytes": "34363" }, { "name": "Smalltalk", "bytes": "897" }, { "name": "Thrift", "bytes": "120" }, { "name": "Yacc", "bytes": "323" } ], "symlink_target": "" }
package com.wthfeng.learn.pattern.singleton; /** * 饿汉模式变种 * 都是在类被加载时创建的对象,由jvm保证其线程安全 * 缺点:如果这个类被多次加载的话也会造成多次实例化,即该方法类不能被加载多次 */ public class SimpleSingleton { private static SimpleSingleton simpleSingleton; private SimpleSingleton() { } static { simpleSingleton = new SimpleSingleton(); } public SimpleSingleton getInstance() { return simpleSingleton; } }
{ "content_hash": "549917f3493d95add21e730bea065297", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 51, "avg_line_length": 17.869565217391305, "alnum_prop": 0.6958637469586375, "repo_name": "wangtonghe/learn-sample", "id": "4d52da660547bfe7adf7c6aa271dd1f0da071be7", "size": "541", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/wthfeng/learn/pattern/singleton/SimpleSingleton.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "319790" } ], "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.4.2_11) on Mon Jul 12 21:36:56 CEST 2010 --> <TITLE> org.apache.fop.render.pdf (Apache FOP 1.0 API) </TITLE> <META NAME="keywords" CONTENT="org.apache.fop.render.pdf package"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="org.apache.fop.render.pdf (Apache FOP 1.0 API)"; } </SCRIPT> </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=3 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="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</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> fop 1.0</EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../org/apache/fop/render/pcl/extensions/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../../../org/apache/fop/render/print/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.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> <H2> Package org.apache.fop.render.pdf </H2> PDF Renderer <P> <B>See:</B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<A HREF="#package_description"><B>Description</B></A> <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=2><FONT SIZE="+2"> <B>Interface Summary</B></FONT></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/fop/render/pdf/PDFConfigurationConstants.html" title="interface in org.apache.fop.render.pdf">PDFConfigurationConstants</A></B></TD> <TD>Constants used for configuring PDF output.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/fop/render/pdf/PDFEventProducer.html" title="interface in org.apache.fop.render.pdf">PDFEventProducer</A></B></TD> <TD>Event producer interface for events generated by the PDF renderer.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/fop/render/pdf/PDFImageHandler.html" title="interface in org.apache.fop.render.pdf">PDFImageHandler</A></B></TD> <TD>This interface is used for handling all sorts of image type for PDF output.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/fop/render/pdf/PDFRendererContextConstants.html" title="interface in org.apache.fop.render.pdf">PDFRendererContextConstants</A></B></TD> <TD>Defines a number of standard constants (keys) for use by the RendererContext class.</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=2><FONT SIZE="+2"> <B>Class Summary</B></FONT></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/fop/render/pdf/AbstractImageAdapter.html" title="class in org.apache.fop.render.pdf">AbstractImageAdapter</A></B></TD> <TD>Abstract PDFImage implementation for the PDF renderer.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/fop/render/pdf/CTMHelper.html" title="class in org.apache.fop.render.pdf">CTMHelper</A></B></TD> <TD>CTMHelper converts FOP transformation matrices to those suitable for use by the PDFRenderer.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/fop/render/pdf/ImageRawCCITTFaxAdapter.html" title="class in org.apache.fop.render.pdf">ImageRawCCITTFaxAdapter</A></B></TD> <TD>PDFImage implementation for the PDF renderer which handles raw CCITT fax images.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/fop/render/pdf/ImageRawJPEGAdapter.html" title="class in org.apache.fop.render.pdf">ImageRawJPEGAdapter</A></B></TD> <TD>PDFImage implementation for the PDF renderer which handles raw JPEG images.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/fop/render/pdf/ImageRenderedAdapter.html" title="class in org.apache.fop.render.pdf">ImageRenderedAdapter</A></B></TD> <TD>PDFImage implementation for the PDF renderer which handles RenderedImages.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/fop/render/pdf/PDFBorderPainter.html" title="class in org.apache.fop.render.pdf">PDFBorderPainter</A></B></TD> <TD>PDF-specific implementation of the <A HREF="../../../../../org/apache/fop/render/intermediate/BorderPainter.html" title="class in org.apache.fop.render.intermediate"><CODE>BorderPainter</CODE></A>.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/fop/render/pdf/PDFContentGenerator.html" title="class in org.apache.fop.render.pdf">PDFContentGenerator</A></B></TD> <TD>Generator class encapsulating all object references and state necessary to generate a PDF content stream.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/fop/render/pdf/PDFDocumentHandler.html" title="class in org.apache.fop.render.pdf">PDFDocumentHandler</A></B></TD> <TD><A HREF="../../../../../org/apache/fop/render/intermediate/IFDocumentHandler.html" title="interface in org.apache.fop.render.intermediate"><CODE>IFDocumentHandler</CODE></A> implementation that produces PDF.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/fop/render/pdf/PDFDocumentHandlerMaker.html" title="class in org.apache.fop.render.pdf">PDFDocumentHandlerMaker</A></B></TD> <TD>Intermediate format document handler factory for PDF output.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/fop/render/pdf/PDFDocumentNavigationHandler.html" title="class in org.apache.fop.render.pdf">PDFDocumentNavigationHandler</A></B></TD> <TD>Implementation of the <A HREF="../../../../../org/apache/fop/render/intermediate/IFDocumentNavigationHandler.html" title="interface in org.apache.fop.render.intermediate"><CODE>IFDocumentNavigationHandler</CODE></A> interface for PDF output.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/fop/render/pdf/PDFEventProducer.Provider.html" title="class in org.apache.fop.render.pdf">PDFEventProducer.Provider</A></B></TD> <TD>Provider class for the event producer.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/fop/render/pdf/PDFGraphics2DAdapter.html" title="class in org.apache.fop.render.pdf">PDFGraphics2DAdapter</A></B></TD> <TD>Graphics2DAdapter implementation for PDF.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/fop/render/pdf/PDFImageHandlerGraphics2D.html" title="class in org.apache.fop.render.pdf">PDFImageHandlerGraphics2D</A></B></TD> <TD>PDFImageHandler implementation which handles Graphics2D images.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/fop/render/pdf/PDFImageHandlerRawCCITTFax.html" title="class in org.apache.fop.render.pdf">PDFImageHandlerRawCCITTFax</A></B></TD> <TD>Image handler implementation which handles CCITT encoded images (CCITT fax group 3/4) for PDF output.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/fop/render/pdf/PDFImageHandlerRawJPEG.html" title="class in org.apache.fop.render.pdf">PDFImageHandlerRawJPEG</A></B></TD> <TD>Image handler implementation which handles raw JPEG images for PDF output.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/fop/render/pdf/PDFImageHandlerRegistry.html" title="class in org.apache.fop.render.pdf">PDFImageHandlerRegistry</A></B></TD> <TD>This class holds references to various image handlers used by the PDF renderer.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/fop/render/pdf/PDFImageHandlerRenderedImage.html" title="class in org.apache.fop.render.pdf">PDFImageHandlerRenderedImage</A></B></TD> <TD>Image handler implementation which handles RenderedImage instances for PDF output.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/fop/render/pdf/PDFImageHandlerSVG.html" title="class in org.apache.fop.render.pdf">PDFImageHandlerSVG</A></B></TD> <TD>Image Handler implementation which handles SVG images.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/fop/render/pdf/PDFImageHandlerXML.html" title="class in org.apache.fop.render.pdf">PDFImageHandlerXML</A></B></TD> <TD>PDFImageHandler implementation which handles XML-based images.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/fop/render/pdf/PDFPainter.html" title="class in org.apache.fop.render.pdf">PDFPainter</A></B></TD> <TD>IFPainter implementation that produces PDF.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/fop/render/pdf/PDFRenderer.html" title="class in org.apache.fop.render.pdf">PDFRenderer</A></B></TD> <TD>Renderer that renders areas to PDF.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/fop/render/pdf/PDFRendererConfigurator.html" title="class in org.apache.fop.render.pdf">PDFRendererConfigurator</A></B></TD> <TD>PDF renderer configurator.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/fop/render/pdf/PDFRendererMaker.html" title="class in org.apache.fop.render.pdf">PDFRendererMaker</A></B></TD> <TD>RendererMaker for the PDF Renderer.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/fop/render/pdf/PDFRenderingContext.html" title="class in org.apache.fop.render.pdf">PDFRenderingContext</A></B></TD> <TD>Rendering context for PDF production.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/fop/render/pdf/PDFSVGHandler.html" title="class in org.apache.fop.render.pdf">PDFSVGHandler</A></B></TD> <TD>PDF XML handler for SVG (uses Apache Batik).</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../org/apache/fop/render/pdf/PDFSVGHandler.PDFInfo.html" title="class in org.apache.fop.render.pdf">PDFSVGHandler.PDFInfo</A></B></TD> <TD>PDF information structure for drawing the XML document.</TD> </TR> </TABLE> &nbsp; <P> <A NAME="package_description"><!-- --></A><H2> Package org.apache.fop.render.pdf Description </H2> <P> <P>PDF Renderer</P> <P> <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=3 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="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</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> fop 1.0</EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../org/apache/fop/render/pcl/extensions/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../../../org/apache/fop/render/print/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.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> Copyright 1999-2010 The Apache Software Foundation. All Rights Reserved. </BODY> </HTML>
{ "content_hash": "c2d022d54a6da0700e077c3633d1c3c6", "timestamp": "", "source": "github", "line_count": 292, "max_line_length": 250, "avg_line_length": 54.24315068493151, "alnum_prop": 0.6688553570301156, "repo_name": "kezhong/XML", "id": "3a096a9ce882e701041385a93c9f877dadc7f4bf", "size": "15839", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "javadocs/org/apache/fop/render/pdf/package-summary.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "28133" }, { "name": "PHP", "bytes": "1069" }, { "name": "Shell", "bytes": "7531" } ], "symlink_target": "" }
package oauthorize.grants import oauthorize.utils._ import oauthorize.model._ import oauthorize.service._ import oauth2.spec.Req._ import oauth2.spec.AccessTokenErrors._ import oauth2.spec._ import oauth2.spec.model._ import scala.concurrent.Future import scala.concurrent.ExecutionContext class RefreshTokenEndpoint( val config: Oauth2Config, val store: Oauth2Store, val hasher: ClientSecretHasher, val tokens: TokenGenerator) { def processRefreshTokenRequest( req: OauthRequest, clientAuth: Option[ClientAuthentication])(implicit ctx: ExecutionContext): Future[Either[Err, AccessTokenResponse]] = { clientAuth match { case None => error(unauthorized_client, "unauthorized client", StatusCodes.Unauthorized) case Some(basicAuth) => store.getClient(basicAuth.clientId) flatMap { case None => error(invalid_client, "unregistered client", StatusCodes.Unauthorized) case Some(client) if (!hasher.secretMatches(basicAuth.clientSecret, client.secretInfo)) => error(invalid_client, "bad credentials", StatusCodes.Unauthorized) case Some(client) => { (req.param(grant_type), req.param(refresh_token)) match { case (Some(grantType), Some(refreshToken)) => { val atRequest = RefreshTokenRequest(grantType, refreshToken) doProcess(atRequest, client) } case _ => error(invalid_request, s"mandatory: $grant_type, $refresh_token") } } } } } private def doProcess( refreshTokenRequest: RefreshTokenRequest, oauthClient: Oauth2Client)(implicit ctx: ExecutionContext): Future[Either[Err, AccessTokenResponse]] = { import oauth2.spec.AccessTokenErrors._ refreshTokenRequest.getError(oauthClient) match { case Some(error) => Future.successful(Left(error)) case None => store.getRefreshToken(refreshTokenRequest.refreshToken) flatMap { case None => error(invalid_grant, "invalid refresh token") case Some(refreshToken) if (refreshToken.isExpired) => error(invalid_grant, "refresh token expired") case Some(refreshToken) => { val accessToken = tokens.generateAccessToken(oauthClient, refreshToken.tokenScope, refreshToken.userId) store.storeTokens(AccessAndRefreshTokens(accessToken, None), oauthClient) map { stored => val response = AccessTokenResponse( stored.accessToken.value, stored.refreshToken.map(_.value), TokenType.bearer, stored.accessToken.validity, refreshToken.tokenScope.mkString(ScopeSeparator)) Right(response) } } } } } }
{ "content_hash": "ad85d8c34dc52eb4cf38f48cb26ba974", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 165, "avg_line_length": 41.15384615384615, "alnum_prop": 0.6930841121495327, "repo_name": "adaptorel/oauthorize", "id": "f3713157b51dc4bb13b207a55672e363c5fcbe5c", "size": "2675", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "oauthorize-core/src/main/scala/grants/RefreshTokenEndpoint.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Scala", "bytes": "128324" } ], "symlink_target": "" }
using HFEA.Connector.Contracts.UserFeedback; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HFEA.Connector.Contracts.Clients { public interface IPortalUserFeedbackClient { List<ExperienceSubmissionQuestion> GetExperienceSubmissionData(); } }
{ "content_hash": "72d0d8feb00a063432c4fab9092e69c6", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 73, "avg_line_length": 24.5, "alnum_prop": 0.7900874635568513, "repo_name": "hfea/Website-Public", "id": "5d88f12bd8554348ba66c32883aae444157eb1a6", "size": "345", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Source/HFEA.API.Connector/Source/HFEA.Connector.Contracts/Clients/IPortalUserFeedbackClient.cs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C#", "bytes": "1279661" } ], "symlink_target": "" }
# JS / Algo ## Regular Expressions *Pre-requisites: lesson 8* *ECV Digital - 7/01/2016* This course is just a sumup in slides of this [very interesting course](http://eloquentjavascript.net/09_regexp.html) <!-- .element: target="_blank" --> --- ## Creating RegExp In javascript, you can write a regexp in two different manner: ```javascript var regex1 = new RegExp("abc"); // No delimiter var regex2 = /abc/; // Only accepted delimiter ``` -- ## Testing for matches You can test a string to check if it contains a match of the pattern in the expression. ```javascript console.log(/abc/.test("abcde")); // → true console.log(/abc/.test("abxde")); // → false ``` If abc occurs anywhere in the string we are testing against (not just at the start), test will return true. -- ## Matching a set of characters In a regular expression, putting a set of characters between square brackets makes that part of the expression match any of the characters between the brackets. ```javascript console.log(/[0123456789]/.test("in 1992")); // → true console.log(/[0-9]/.test("in 1992")); // → true // a dash (-) between two characters can be used to indicate a range of characters ``` > You can see `[]` as a `OR` statement You can also use [metacharacter](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp) in brackets -- ## Choice patterns More globally, The pipe character (|) denotes a choice between multiple patterns ```javascript var animalCount = /(pig|cow|stuff)s?/; console.log(animalCount.test("pigs")); // → true console.log(animalCount.test("cow")); // → true console.log(animalCount.test("chickens")); // → false ``` -- ## Matching a set of characters Using a caret (^) character after the opening bracket invert invert the set ```javascript var notBinary = /[^01]/; // D'ont match 1 nor 2 console.log(notBinary.test("1100100010100110")); // → false console.log(notBinary.test("1100100010200110")); // → true ``` --- ## Matches One can use the exec (execute) method which will return null if no match was found and return an object with information about the match otherwise. ```javascript var match = /\d+/.exec("one two 100"); console.log(match); // → ["100", index: 8, input: "one two 100"] console.log(match.index); // → 8, position of the first successful match // You also have a match method directly on strings console.log("one two 100".match(/\d+/)); // → ["100"] ``` -- ## Groups When the regular expression contains subexpressions grouped with parentheses, the text that matched those groups will also show up in the array. ```javascript var quotedText = /'([^']*)'/; console.log(quotedText.exec("she said 'hello'")); // → ["'hello'", "hello", index: 9, input: "she said 'hello'"] ``` When a group does not end up being matched at all its position in the output array will hold undefined ``` javascript console.log(/bad(ly)?/.exec("bad")); // → ["bad", undefined, index: 0, input: "bad"] ``` -- ## Groups When a group is matched multiple times, only the last match ends up in the array. ```javascript console.log(/(\d)+/.exec("123")); // → ["123", "3", index: 0, input: "123"] ``` --- ## The replace method String values have a replace method, which can be used to replace part of the string with another string. ```javascript console.log("papa".replace("p", "m")); // → mapa //You can also use RegExp console.log("Borobudur".replace(/[ou]/, "a")); // → Barobudur console.log("Borobudur".replace(/[ou]/g, "a")); // → Barabadar ``` -- ## The replace method The real power of using regular expressions with replace comes from the fact that we can refer back to matched groups ```javascript //This is a one-liner to invert firstname and lastname console.log( "Hopper, Grace\nMcCarthy, John\nRitchie, Dennis" .replace(/([\w ]+), ([\w ]+)/g, "$2 $1")); // → Grace Hopper // John McCarthy // Dennis Ritchie ``` The $1 and $2 in the replacement string refer to the parenthesized groups in the pattern. -- ## The replace method It is also possible to pass a function, rather than a string, as the second argument to replace. ```javascript var s = "the cia and fbi"; console.log(s.replace(/\b(fbi|cia)\b/g, function(str) { return str.toUpperCase(); })); // → the CIA and FBI ``` You can go pretty crazy: ```javascript var s = "1 lemon, 2 cabbages, and 101 eggs"; function minusOne(match, amount, unit) { amount = Number(amount) - 1; if (amount == 1) // only one left, remove the 's' unit = unit.slice(0, unit.length - 1); else if (amount == 0) amount = "no"; return amount + " " + unit; } console.log(s.replace(/(\d+) (\w+)/g, minusOne)); // → no lemon, 1 cabbage, and 100 eggs ``` --- ## Greed The main idea iwith RegExp is that they-re greedy in the sens that nay metachracter will try to match as mush as it can ```javascript function stripComments(code) { return code.replace(/\/\/.*|\/\*[^]*\*\//g, ""); } console.log(stripComments("1 + /* 2 */3")); // → 1 + 3 console.log(stripComments("x = 10;// ten!")); // → x = 10 console.log(stripComments("1 /* a */+/* b */ 1")); // → 1 1 // * is too greedy, the last example is a fail ``` Adding a `?` make greedy metacharcters non-greedy ```javascript function stripComments(code) { return code.replace(/\/\/.*|\/\*[^]*?\*\//g, ""); } console.log(stripComments("1 /* a */+/* b */ 1")); // → 1 + 1 ``` -- ## The lastIndex property Regular expression objects have properties. - `source`: it contains the string that expression was created from. - `lastIndex`: it controls, in some limited circumstances, where the next match will start. - The regular expression must have the global (g) option enabled - the match must happen through the exec method ```javascript var pattern = /y/g; // Notice the g global flag var match = pattern.exec("xyzzy"); console.log(match.index); // → 1 console.log(pattern.lastIndex); // → 2 pattern.exec("g") console.log(pattern.lastIndex); // → 0 ``` -- ##Looping over matches A common pattern is to scan through all occurrences of a pattern in a string, in a way that gives us access to the match object in the loop body, by using lastIndex and exec. ```javascript var input = "A string with 3 numbers in it... 42 and 88."; var number = /\b(\d+)\b/g; var match; while (match = number.exec(input)) console.log("Found", match[1], "at", match.index); // → Found 3 at 14 // Found 42 at 33 // Found 88 at 40 ``` --- ## International characters JavaScript handles badly non latin characters: For example, a “word character” is only one of **the 26 characters in the Latin alphabet (uppercase or lowercase)** and **the underscore character** --- # Exercices Train yourself on the exercice files you can find in the exercices directory Be bold, and do some [regex golf](http://regex.alf.nu/)
{ "content_hash": "ea6cccb1e54636e536e349e436a666f2", "timestamp": "", "source": "github", "line_count": 219, "max_line_length": 174, "avg_line_length": 31.013698630136986, "alnum_prop": 0.6793286219081273, "repo_name": "morgangiraud/ecvd-js", "id": "07fb6712090b80ff2d3b02d03b3d26e5f51c9fd3", "size": "6854", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lesson09/prez/course.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "387842" }, { "name": "HTML", "bytes": "123708" }, { "name": "JavaScript", "bytes": "1128067" }, { "name": "Shell", "bytes": "1299" } ], "symlink_target": "" }
package e2e import ( "fmt" "sort" "time" "github.com/GoogleCloudPlatform/kubernetes/pkg/api" "github.com/GoogleCloudPlatform/kubernetes/pkg/client" "github.com/GoogleCloudPlatform/kubernetes/pkg/util" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Services", func() { var c *client.Client BeforeEach(func() { var err error c, err = loadClient() Expect(err).NotTo(HaveOccurred()) }) It("should provide DNS for the cluster", func() { if testContext.provider == "vagrant" { By("Skipping test which is broken for vagrant (See https://github.com/GoogleCloudPlatform/kubernetes/issues/3580)") return } podClient := c.Pods(api.NamespaceDefault) //TODO: Wait for skyDNS // All the names we need to be able to resolve. namesToResolve := []string{ "kubernetes-ro", "kubernetes-ro.default", "kubernetes-ro.default.kubernetes.local", "google.com", } probeCmd := "for i in `seq 1 600`; do " for _, name := range namesToResolve { probeCmd += fmt.Sprintf("wget -O /dev/null %s && echo OK > /results/%s;", name, name) } probeCmd += "sleep 1; done" // Run a pod which probes DNS and exposes the results by HTTP. By("creating a pod to probe DNS") pod := &api.Pod{ TypeMeta: api.TypeMeta{ Kind: "Pod", APIVersion: "v1beta1", }, ObjectMeta: api.ObjectMeta{ Name: "dns-test-" + string(util.NewUUID()), }, Spec: api.PodSpec{ Volumes: []api.Volume{ { Name: "results", VolumeSource: api.VolumeSource{ EmptyDir: &api.EmptyDirVolumeSource{}, }, }, }, Containers: []api.Container{ { Name: "webserver", Image: "kubernetes/test-webserver", VolumeMounts: []api.VolumeMount{ { Name: "results", MountPath: "/results", }, }, }, { Name: "pinger", Image: "busybox", Command: []string{"sh", "-c", probeCmd}, VolumeMounts: []api.VolumeMount{ { Name: "results", MountPath: "/results", }, }, }, }, }, } By("submitting the pod to kuberenetes") defer func() { By("deleting the pod") defer GinkgoRecover() podClient.Delete(pod.Name) }() if _, err := podClient.Create(pod); err != nil { Failf("Failed to create %s pod: %v", pod.Name, err) } expectNoError(waitForPodRunning(c, pod.Name)) By("retrieving the pod") pod, err := podClient.Get(pod.Name) if err != nil { Failf("Failed to get pod %s: %v", pod.Name, err) } // Try to find results for each expected name. By("looking for the results for each expected name") var failed []string for try := 1; try < 100; try++ { failed = []string{} for _, name := range namesToResolve { _, err := c.Get(). Prefix("proxy"). Resource("pods"). Namespace("default"). Name(pod.Name). Suffix("results", name). Do().Raw() if err != nil { failed = append(failed, name) fmt.Printf("Lookup using %s for %s failed: %v\n", pod.Name, name, err) } } if len(failed) == 0 { break } fmt.Printf("lookups using %s failed for: %v\n", pod.Name, failed) time.Sleep(10 * time.Second) } Expect(len(failed)).To(Equal(0)) // TODO: probe from the host, too. fmt.Printf("DNS probes using %s succeeded\n", pod.Name) }) It("should provide RW and RO services", func() { svc := api.ServiceList{} err := c.Get(). Namespace("default"). AbsPath("/api/v1beta1/proxy/services/kubernetes-ro/api/v1beta1/services"). Do(). Into(&svc) if err != nil { Failf("unexpected error listing services using ro service: %v", err) } var foundRW, foundRO bool for i := range svc.Items { if svc.Items[i].Name == "kubernetes" { foundRW = true } if svc.Items[i].Name == "kubernetes-ro" { foundRO = true } } Expect(foundRW).To(Equal(true)) Expect(foundRO).To(Equal(true)) }) It("should serve a basic endpoint from pods", func(done Done) { serviceName := "endpoint-test2" ns := api.NamespaceDefault labels := map[string]string{ "foo": "bar", "baz": "blah", } defer func() { err := c.Services(ns).Delete(serviceName) Expect(err).NotTo(HaveOccurred()) }() service := &api.Service{ ObjectMeta: api.ObjectMeta{ Name: serviceName, }, Spec: api.ServiceSpec{ Port: 80, Selector: labels, ContainerPort: util.NewIntOrStringFromInt(80), }, } _, err := c.Services(ns).Create(service) Expect(err).NotTo(HaveOccurred()) expectedPort := 80 validateEndpointsOrFail(c, ns, serviceName, expectedPort, []string{}) var names []string defer func() { for _, name := range names { err := c.Pods(ns).Delete(name) Expect(err).NotTo(HaveOccurred()) } }() name1 := "test1" addEndpointPodOrFail(c, ns, name1, labels) names = append(names, name1) validateEndpointsOrFail(c, ns, serviceName, expectedPort, names) name2 := "test2" addEndpointPodOrFail(c, ns, name2, labels) names = append(names, name2) validateEndpointsOrFail(c, ns, serviceName, expectedPort, names) err = c.Pods(ns).Delete(name1) Expect(err).NotTo(HaveOccurred()) names = []string{name2} validateEndpointsOrFail(c, ns, serviceName, expectedPort, names) err = c.Pods(ns).Delete(name2) Expect(err).NotTo(HaveOccurred()) names = []string{} validateEndpointsOrFail(c, ns, serviceName, expectedPort, names) // We deferred Gingko pieces that may Fail, we aren't done. defer func() { close(done) }() }, 240.0) It("should correctly serve identically named services in different namespaces on different external IP addresses", func(done Done) { serviceNames := []string{"services-namespace-test0"} // Could add more here, but then it takes longer. namespaces := []string{"namespace0", "namespace1"} // As above. labels := map[string]string{ "key0": "value0", "key1": "value1", } service := &api.Service{ ObjectMeta: api.ObjectMeta{}, Spec: api.ServiceSpec{ Port: 80, Selector: labels, ContainerPort: util.NewIntOrStringFromInt(80), CreateExternalLoadBalancer: true, }, } publicIPs := []string{} // We defer Gingko pieces that may Fail, so clean up at the end. defer func() { close(done) }() for _, namespace := range namespaces { for _, serviceName := range serviceNames { service.ObjectMeta.Name = serviceName service.ObjectMeta.Namespace = namespace By("creating service " + serviceName + " in namespace " + namespace) result, err := c.Services(namespace).Create(service) Expect(err).NotTo(HaveOccurred()) defer func(namespace, serviceName string) { // clean up when we're done By("deleting service " + serviceName + " in namespace " + namespace) err := c.Services(namespace).Delete(serviceName) Expect(err).NotTo(HaveOccurred()) }(namespace, serviceName) publicIPs = append(publicIPs, result.Spec.PublicIPs...) // Save 'em to check uniqueness } } validateUniqueOrFail(publicIPs) }, 240.0) }) func validateUniqueOrFail(s []string) { By(fmt.Sprintf("validating unique: %v", s)) sort.Strings(s) var prev string for i, elem := range s { if i > 0 && elem == prev { Fail("duplicate found: " + elem) } prev = elem } } func validateIPsOrFail(c *client.Client, ns string, expectedPort int, expectedEndpoints []string, endpoints *api.Endpoints) { ips := util.StringSet{} for _, ep := range endpoints.Endpoints { if ep.Port != expectedPort { Failf("invalid port, expected %d, got %d", expectedPort, ep.Port) } ips.Insert(ep.IP) } for _, name := range expectedEndpoints { pod, err := c.Pods(ns).Get(name) if err != nil { Failf("failed to get pod %s, that's pretty weird. validation failed: %s", name, err) } if !ips.Has(pod.Status.PodIP) { Failf("ip validation failed, expected: %v, saw: %v", ips, pod.Status.PodIP) } By(fmt.Sprintf("")) } By(fmt.Sprintf("successfully validated IPs %v against expected endpoints %v port %d on namespace %s", ips, expectedEndpoints, expectedPort, ns)) } func validateEndpointsOrFail(c *client.Client, ns, serviceName string, expectedPort int, expectedEndpoints []string) { for { endpoints, err := c.Endpoints(ns).Get(serviceName) if err == nil { if len(endpoints.Endpoints) == len(expectedEndpoints) { validateIPsOrFail(c, ns, expectedPort, expectedEndpoints, endpoints) return } else { By(fmt.Sprintf("Unexpected number of endpoints: found %v, expected %v (ignoring for 1 second)", endpoints.Endpoints, expectedEndpoints)) } } else { By(fmt.Sprintf("Failed to get endpoints: %v (ignoring for 1 second)", err)) } time.Sleep(time.Second) } By(fmt.Sprintf("successfully validated endpoints %v port %d on service %s/%s", expectedEndpoints, expectedPort, ns, serviceName)) } func addEndpointPodOrFail(c *client.Client, ns, name string, labels map[string]string) { By(fmt.Sprintf("Adding pod %v in namespace %v", name, ns)) pod := &api.Pod{ ObjectMeta: api.ObjectMeta{ Name: name, Labels: labels, }, Spec: api.PodSpec{ Containers: []api.Container{ { Name: "test", Image: "kubernetes/pause", Ports: []api.ContainerPort{{ContainerPort: 80}}, }, }, }, } _, err := c.Pods(ns).Create(pod) Expect(err).NotTo(HaveOccurred()) }
{ "content_hash": "4e3263c1d3923b89ce356c1c17b4b0f6", "timestamp": "", "source": "github", "line_count": 346, "max_line_length": 145, "avg_line_length": 27.196531791907514, "alnum_prop": 0.6363443145589798, "repo_name": "nvoron23/kubernetes", "id": "af003e51376aedc72087fc740f9264dbfd3916de", "size": "9988", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/e2e/service.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "94162" }, { "name": "CSS", "bytes": "4137" }, { "name": "Go", "bytes": "6185193" }, { "name": "HTML", "bytes": "9497" }, { "name": "Java", "bytes": "3258" }, { "name": "JavaScript", "bytes": "15405" }, { "name": "Makefile", "bytes": "5479" }, { "name": "Nginx", "bytes": "1013" }, { "name": "PHP", "bytes": "736" }, { "name": "Python", "bytes": "8416" }, { "name": "Ruby", "bytes": "2778" }, { "name": "Scheme", "bytes": "1112" }, { "name": "Shell", "bytes": "537999" } ], "symlink_target": "" }
.class Lcom/android/server/LockSettingsStorage$DatabaseHelper; .super Landroid/database/sqlite/SQLiteOpenHelper; .source "LockSettingsStorage.java" # annotations .annotation system Ldalvik/annotation/EnclosingClass; value = Lcom/android/server/LockSettingsStorage; .end annotation .annotation system Ldalvik/annotation/InnerClass; accessFlags = 0x0 name = "DatabaseHelper" .end annotation # static fields .field private static final DATABASE_NAME:Ljava/lang/String; = "locksettings.db" .field private static final DATABASE_VERSION:I = 0x3 .field private static final TAG:Ljava/lang/String; = "LockSettingsDB" # instance fields .field private mCallback:Lcom/android/server/LockSettingsStorage$Callback; .field final synthetic this$0:Lcom/android/server/LockSettingsStorage; # direct methods .method public constructor <init>(Lcom/android/server/LockSettingsStorage;Landroid/content/Context;)V .locals 3 iput-object p1, p0, Lcom/android/server/LockSettingsStorage$DatabaseHelper;->this$0:Lcom/android/server/LockSettingsStorage; const-string/jumbo v0, "locksettings.db" const/4 v1, 0x0 const/4 v2, 0x3 invoke-direct {p0, p2, v0, v1, v2}, Landroid/database/sqlite/SQLiteOpenHelper;-><init>(Landroid/content/Context;Ljava/lang/String;Landroid/database/sqlite/SQLiteDatabase$CursorFactory;I)V const/4 v0, 0x1 invoke-virtual {p0, v0}, Lcom/android/server/LockSettingsStorage$DatabaseHelper;->setWriteAheadLoggingEnabled(Z)V return-void .end method .method private createTable(Landroid/database/sqlite/SQLiteDatabase;)V .locals 1 const-string/jumbo v0, "CREATE TABLE locksettings (_id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,user INTEGER,value TEXT);" invoke-virtual {p1, v0}, Landroid/database/sqlite/SQLiteDatabase;->execSQL(Ljava/lang/String;)V return-void .end method # virtual methods .method public onCreate(Landroid/database/sqlite/SQLiteDatabase;)V .locals 1 invoke-direct {p0, p1}, Lcom/android/server/LockSettingsStorage$DatabaseHelper;->createTable(Landroid/database/sqlite/SQLiteDatabase;)V iget-object v0, p0, Lcom/android/server/LockSettingsStorage$DatabaseHelper;->mCallback:Lcom/android/server/LockSettingsStorage$Callback; if-eqz v0, :cond_0 iget-object v0, p0, Lcom/android/server/LockSettingsStorage$DatabaseHelper;->mCallback:Lcom/android/server/LockSettingsStorage$Callback; invoke-interface {v0, p1}, Lcom/android/server/LockSettingsStorage$Callback;->initialize(Landroid/database/sqlite/SQLiteDatabase;)V :cond_0 return-void .end method .method public onUpgrade(Landroid/database/sqlite/SQLiteDatabase;II)V .locals 3 move v0, p2 const/4 v1, 0x1 if-eq p2, v1, :cond_0 const/4 v1, 0x2 if-ne p2, v1, :cond_1 :cond_0 const/4 v0, 0x3 :cond_1 const/4 v1, 0x3 if-eq v0, v1, :cond_2 const-string/jumbo v1, "LockSettingsDB" const-string/jumbo v2, "Failed to upgrade database!" invoke-static {v1, v2}, Landroid/util/Log;->w(Ljava/lang/String;Ljava/lang/String;)I :cond_2 return-void .end method .method public setCallback(Lcom/android/server/LockSettingsStorage$Callback;)V .locals 0 iput-object p1, p0, Lcom/android/server/LockSettingsStorage$DatabaseHelper;->mCallback:Lcom/android/server/LockSettingsStorage$Callback; return-void .end method
{ "content_hash": "4d6657ee14deda7961630388f1082078", "timestamp": "", "source": "github", "line_count": 118, "max_line_length": 191, "avg_line_length": 28.60169491525424, "alnum_prop": 0.7576296296296297, "repo_name": "BatMan-Rom/ModdedFiles", "id": "d9fca784d7c3d72b4217d248e41333d9471dd4ab", "size": "3375", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "services.jar.out/smali/com/android/server/LockSettingsStorage$DatabaseHelper.smali", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "GLSL", "bytes": "15069" }, { "name": "HTML", "bytes": "139176" }, { "name": "Smali", "bytes": "541934400" } ], "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.6.0_22) on Sun Aug 26 15:13:09 EDT 2012 --> <TITLE> SlickXMLException (Slick - The 2D Library) </TITLE> <META NAME="date" CONTENT="2012-08-26"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="SlickXMLException (Slick - The 2D Library)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= 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="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/SlickXMLException.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</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;<A HREF="../../../../../org/newdawn/slick/util/xml/ObjectTreeParser.html" title="class in org.newdawn.slick.util.xml"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../../org/newdawn/slick/util/xml/XMLElement.html" title="class in org.newdawn.slick.util.xml"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/newdawn/slick/util/xml/SlickXMLException.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="SlickXMLException.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> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#methods_inherited_from_class_java.lang.Throwable">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;METHOD</FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> org.newdawn.slick.util.xml</FONT> <BR> Class SlickXMLException</H2> <PRE> java.lang.Object <IMG SRC="../../../../../resources/inherit.gif" ALT="extended by ">java.lang.Throwable <IMG SRC="../../../../../resources/inherit.gif" ALT="extended by ">java.lang.Exception <IMG SRC="../../../../../resources/inherit.gif" ALT="extended by "><A HREF="../../../../../org/newdawn/slick/SlickException.html" title="class in org.newdawn.slick">org.newdawn.slick.SlickException</A> <IMG SRC="../../../../../resources/inherit.gif" ALT="extended by "><B>org.newdawn.slick.util.xml.SlickXMLException</B> </PRE> <DL> <DT><B>All Implemented Interfaces:</B> <DD>java.io.Serializable</DD> </DL> <HR> <DL> <DT><PRE>public class <B>SlickXMLException</B><DT>extends <A HREF="../../../../../org/newdawn/slick/SlickException.html" title="class in org.newdawn.slick">SlickException</A></DL> </PRE> <P> An exception to describe failures in XML. Made a special case because with XML to object parsing you might want to handle it differently <P> <P> <DL> <DT><B>Author:</B></DT> <DD>kevin</DD> <DT><B>See Also:</B><DD><A HREF="../../../../../serialized-form.html#org.newdawn.slick.util.xml.SlickXMLException">Serialized Form</A></DL> <HR> <P> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <A NAME="constructor_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../../../org/newdawn/slick/util/xml/SlickXMLException.html#SlickXMLException(java.lang.String)">SlickXMLException</A></B>(java.lang.String&nbsp;message)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Create a new exception</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../../../org/newdawn/slick/util/xml/SlickXMLException.html#SlickXMLException(java.lang.String, java.lang.Throwable)">SlickXMLException</A></B>(java.lang.String&nbsp;message, java.lang.Throwable&nbsp;e)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Create a new exception</TD> </TR> </TABLE> &nbsp; <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Throwable"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class java.lang.Throwable</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString</CODE></TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ========= CONSTRUCTOR DETAIL ======== --> <A NAME="constructor_detail"><!-- --></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>Constructor Detail</B></FONT></TH> </TR> </TABLE> <A NAME="SlickXMLException(java.lang.String)"><!-- --></A><H3> SlickXMLException</H3> <PRE> public <B>SlickXMLException</B>(java.lang.String&nbsp;message)</PRE> <DL> <DD>Create a new exception <P> <DL> <DT><B>Parameters:</B><DD><CODE>message</CODE> - The message describing the failure</DL> </DL> <HR> <A NAME="SlickXMLException(java.lang.String, java.lang.Throwable)"><!-- --></A><H3> SlickXMLException</H3> <PRE> public <B>SlickXMLException</B>(java.lang.String&nbsp;message, java.lang.Throwable&nbsp;e)</PRE> <DL> <DD>Create a new exception <P> <DL> <DT><B>Parameters:</B><DD><CODE>message</CODE> - The message describing the failure<DD><CODE>e</CODE> - The exception causing this failure</DL> </DL> <!-- ========= END OF CLASS DATA ========= --> <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="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/SlickXMLException.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</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;<A HREF="../../../../../org/newdawn/slick/util/xml/ObjectTreeParser.html" title="class in org.newdawn.slick.util.xml"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../../org/newdawn/slick/util/xml/XMLElement.html" title="class in org.newdawn.slick.util.xml"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/newdawn/slick/util/xml/SlickXMLException.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="SlickXMLException.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> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#methods_inherited_from_class_java.lang.Throwable">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;METHOD</FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> <i>Copyright &#169; 2006 New Dawn Software. All Rights Reserved.</i> </BODY> </HTML>
{ "content_hash": "d09a950d70f2c62b1cf8c99fe9f173bd", "timestamp": "", "source": "github", "line_count": 272, "max_line_length": 211, "avg_line_length": 44.24264705882353, "alnum_prop": 0.6224862888482633, "repo_name": "dxiao/PPBunnies", "id": "a7936419c305fa3b8777bcaad5c416b19c4cbb0f", "size": "12034", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "slick/trunk/Slick/javadoc/org/newdawn/slick/util/xml/SlickXMLException.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1420" }, { "name": "GLSL", "bytes": "2454" }, { "name": "HTML", "bytes": "15369548" }, { "name": "Java", "bytes": "2574972" }, { "name": "Shell", "bytes": "2301" } ], "symlink_target": "" }
var mongoose = require('mongoose'), Schema = mongoose.Schema, ObjectId = Schema.ObjectId; var messureSchema = Schema({ volume: Number, cityid: String, created: { type: Date, default: Date.now }, city: String }, { collection: 'messures' }); module.exports = mongoose.model('Messure', messureSchema);
{ "content_hash": "8e10ad309d964f52b4a8110ca5aeb270", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 58, "avg_line_length": 22.857142857142858, "alnum_prop": 0.678125, "repo_name": "BuenosAiresIOT-CBA/NoiseMatch", "id": "2da34dfc9682fc73823a32bead00c65b2de5dbac", "size": "320", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "models/messure.js", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "19210" }, { "name": "HTML", "bytes": "2720" }, { "name": "JavaScript", "bytes": "13319" } ], "symlink_target": "" }
project_path: /web/fundamentals/_project.yaml book_path: /web/fundamentals/_book.yaml description: Thanks to mobile device and network proliferation, more people are using the web than ever before. As this user base grows, performance is more important than ever. In this article, find out why performance matters, and learn what you can do to make the web faster for everyone. {# wf_updated_on: 2018-10-04 #} {# wf_published_on: 2018-03-08 #} {# wf_blink_components: N/A #} # Why Performance Matters {: .page-title } {% include "web/_shared/contributors/jeremywagner.html" %} In our shared pursuit to push the web to do more, we're running into a common problem: performance. Sites have more features than ever before. So much so, that many sites now struggle to achieve a high level of performance across a variety of network conditions and devices. Performance issues vary. At best, they create small delays that are only briefly annoying to your users. At worst, they make your site completely inaccessible, unresponsive to user input, or both. ## Performance is about retaining users We want users to interact meaningfully with what we build. If it's a blog, we want people to read posts. If it's an online store, we want them to buy stuff. If it's a social network, we want them to interact with each other. Performance plays a major role in the success of any online venture. Here are some case studies that show how high-performing sites engage and retain users better than low-performing ones: - [Pinterest increased search engine traffic and sign-ups by 15%][pinterest] when they reduced perceived wait times by 40%. - [COOK increased conversions by 7%, decreased bounce rates by 7%, and increased pages per session by 10%][COOK] when they reduced average page load time by 850 milliseconds. [pinterest]: https://medium.com/@Pinterest_Engineering/driving-user-growth-with-performance-improvements-cfc50dafadd7 [COOK]: https://www.nccgroup.trust/globalassets/resources/uk/case-studies/web-performance/cook-case-study.pdf Here are a couple case studies where low performance had a negative impact on business goals: - [The BBC found they lost an additional 10% of users][BBC] for every additional second their site took to load. - [DoubleClick by Google found 53% of mobile site visits were abandoned][DoubleClick] if a page took longer than 3 seconds to load. [BBC]: https://www.creativebloq.com/features/how-the-bbc-builds-websites-that-scale [DoubleClick]: https://www.doubleclickbygoogle.com/articles/mobile-speed-matters/ In the same DoubleClick by Google study cited above, it was found that sites loading within 5 seconds had 70% longer sessions, 35% lower bounce rates, and 25% higher ad viewability than sites taking nearly four times longer at 19 seconds. To get a rough idea of how your site's performance compares with your competitors, [check out the Speed Scorecard tool](https://www.thinkwithgoogle.com/feature/mobile/). <figure> <img srcset="images/speed-scorecard-2x.png 2x, images/speed-scorecard-1x.png 1x" src="images/speed-scorecard-1x.png" alt="A screenshot of the Speed Scorecard tool, comparing performance across four popular news outlets."> <figcaption><b>Figure 1</b>. Speed Scorecard comparing the performance of four competing sites using Chrome UX Report data from 4G network users in the United States.</figcaption> </figure> ## Performance is about improving conversions Retaining users is crucial to improving conversions. Slow sites have a negative impact on revenue, and the opposite is also true. Here are some examples of how performance has played a role in making businesses more (or less) profitable: - For Mobify, [every 100ms decrease in homepage load speed worked out to a **1.11% increase** in session-based conversion, yielding an average annual revenue increase of **nearly $380,000**](http://resources.mobify.com/2016-Q2-mobile-insights-benchmark-report.html). Additionally, a 100ms decrease in checkout page load speed amounted to a **1.55% increase** in session-based conversion, which in turn yielded an average annual revenue increase of **nearly $530,000**. - DoubleClick found [publishers whose sites loaded within five seconds earned up to **twice as much ad revenue** than sites loading within 19 seconds](https://www.doubleclickbygoogle.com/articles/mobile-speed-matters/). - [When AutoAnything reduced page load time by half, they saw **a boost of 12-13% in sales**](https://www.digitalcommerce360.com/2010/08/19/web-accelerator-revs-conversion-and-sales-autoanything/). If you run a business on the web, performance is crucial. If your site's user experience is fast and responsive to user input, it can only serve you well. To see how performance could potentially affect your revenue, check out the [Impact Calculator](https://www.thinkwithgoogle.com/feature/mobile/) tool. <figure> <img srcset="images/impact-calculator-2x.png 2x, images/impact-calculator-1x.png 1x" src="images/impact-calculator-1x.png" alt="A screenshot of the Impact Calculator, estimating how much revenue a site could stand to gain if performance improvements are made."> <figcaption><b>Figure 2</b>. The Impact Calculator estimates how much revenue you stand to gain by improving site performance.</figcaption> </figure> ## Performance is about the user experience When you navigate to a URL, you do so from any number of potential starting points. Depending on a number of conditions, such as connection quality and the device you're using, your experience could be quite different from another user's. <figure> <img src="images/speed-comparison.png" alt="A comparison of two filmstrip reels of a page loading. The first shows a page loading on a slow connection, while the second shows the same page loading on a fast connection."> <figcaption><b>Figure 3</b>. A comparison of page load on a very slow connection (top) versus a faster connection (bottom).</figcaption> </figure> As a site begins to load, there's a period of time where users wait for content to appear. Until this happens, there's no user experience to speak of. This lack of an experience is fleeting on fast connections. On slower connections, however, users are forced to wait. Users may experience more problems as page resources slowly trickle in. Performance is a foundational aspect of good user experiences. When sites ship a lot of code, browsers must use megabytes of the user's data plan in order to download the code. Mobile devices have limited CPU power and memory. They often get overwhelmed with what we might consider a small amount of unoptimized code. This creates poor performance which leads to unresponsiveness. Knowing what we know about human behavior, users will only tolerate low performing applications for so long before abandoning them. If you want to know more about how to assess your site's performance and find opportunities for improvement, check out [_How to Think About Speed Tools_](/web/fundamentals/performance/speed-tools/). <figure> <img srcset="images/lighthouse-2x.png 2x, images/lighthouse-1x.png 1x" src="images/lighthouse-1x.png" alt="Page performance overview as seen in Lighthouse."> <figcaption><b>Figure 4</b>. Page performance overview as seen in <a href="/web/tools/lighthouse/">Lighthouse</a>.</figcaption> </figure> ## Performance is about people Poorly performing sites and applications can also pose real costs for the people who use them. [As mobile users continue to make up a larger portion of internet users worldwide](http://gs.statcounter.com/platform-market-share/desktop-mobile-tablet), it's important to bear in mind that many of these users access the web through mobile LTE, 4G, 3G and even 2G networks. As Ben Schwarz of Calibre points out in [this study of real world performance](https://building.calibreapp.com/beyond-the-bubble-real-world-performance-9c991dcd5342), the cost of prepaid data plans is decreasing, which in turn is making access to the internet more affordable in places where it once wasn't. Mobile devices and internet access are no longer luxuries. They are common tools necessary to navigate and function in an increasingly interconnected world. [Total page size has been steadily increasing since at least 2011](http://beta.httparchive.org/reports/state-of-the-web#bytesTotal), and the trend appears to be continuing. As the typical page sends more data, users must replenish their metered data plans more often, which costs them money. In addition to saving your users money, fast and lightweight user experiences can also prove crucial for users in crisis. Public resources such as hospitals, clinics, and crisis centers have online resources that give users important and specific information that they need during a crisis. [While design is pivotal in presenting important information efficiently in stressful moments](https://aneventapart.com/news/post/eric-meyer-designing-for-crisis), the importance of delivering this information fast can't be understated. It's part of our job. ## Where to go from here While the lists below may seem daunting, understand you don't need to do _all_ of these things to improve the performance of your site. They are just starting points, so don't feel overwhelmed! _Anything_ you can do to improve performance will be helpful to your users. ### Mind what resources you send An effective method of building high performance applications is to [audit _what_ resources you send to users](/web/fundamentals/performance/optimizing-content-efficiency/eliminate-downloads). While the [Network panel in Chrome DevTools](/web/tools/chrome-devtools/network-performance/) does a fantastic job of summarizing all the resources used on a given page, it can be daunting to know where to start if you haven't considered performance until now. Here are a few suggestions: - If you use Bootstrap or Foundation to build your UI, ask yourself if they're necessary. Such abstractions add heaps of CSS the browser must download, parse, and apply to a page, all before your site-specific CSS enters the picture. [Flexbox](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout) and [Grid](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout) are superb at creating both simple and complex layouts with relatively little code. [Because CSS is a render blocking resource](/web/fundamentals/performance/critical-rendering-path/render-blocking-css), the overhead of a CSS framework can delay rendering significantly. You can speed up your rendering by removing unnecessary overhead whenever possible. - JavaScript libraries are convenient, but not always necessary. Take jQuery for example: Element selection has been greatly simplified thanks to methods like [`querySelector`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector) and [`querySelectorAll`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll). Event binding is easy with [`addEventListener`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener). [`classList`](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList), [`setAttribute`](https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute), and [`getAttribute`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute) offer easy ways of working with classes and element attributes. If you must use a library, research for leaner alternatives. For example, [Zepto](http://zeptojs.com/) is a smaller jQuery alternative, and [Preact](https://preactjs.com/) is a much smaller alternative to React. - Not all websites need to be single page applications (SPAs), as they often make extensive use of JavaScript. [JavaScript is the most expensive resource we serve on the web byte for byte](https://medium.com/dev-channel/the-cost-of-javascript-84009f51e99e), as it must not only be downloaded, but parsed, compiled and executed as well. For example, news and blog sites with optimized front end architecture can perform well as traditional multipage experiences. Particularly if [HTTP caching](/web/fundamentals/performance/optimizing-content-efficiency/http-caching) is configured properly, and optionally, if a [service worker](/web/fundamentals/primers/service-workers/) is used. ### Mind how you send resources Efficient delivery is vital to building fast user experiences. - [Migrate to HTTP/2](/web/fundamentals/performance/http2/). HTTP/2 addresses many performance problems inherent in HTTP/1.1, such as concurrent request limits and the lack of header compression. - [Download resources earlier using resource hints](/web/fundamentals/performance/resource-prioritization). `rel=preload` is one such resource hint that allows early fetches of critical resources before the browser would otherwise discover them. [This can have a pronounced positive effect](https://medium.com/reloading/preload-prefetch-and-priorities-in-chrome-776165961bbf#0106) on page rendering and lowering [Time to Interactive](/web/tools/lighthouse/audits/time-to-interactive) when used judiciously. [`rel=preconnect` is another resource hint that can mask the latency of opening new connections for resources hosted on third party domains](https://www.igvita.com/2015/08/17/eliminating-roundtrips-with-preconnect/). - Modern sites ship [a _lot_ of JavaScript](http://httparchive.org/trends.php#bytesJS&reqJS) [and CSS](http://httparchive.org/trends.php#bytesCSS&reqCSS) on average. It was common to bundle styles and scripts into large bundles in HTTP/1 environments. This was done because a large amount of requests was detrimental to performance. This is no longer the case now that HTTP/2 is on the scene, as multiple, simultaneous requests are cheaper. [Consider using code splitting in webpack](https://webpack.js.org/guides/code-splitting/) to limit the amount of scripts downloaded to only what is needed by the current page or view. Separate your CSS into smaller template or component-specific files, and only include those resources where they're likely to be used. ### Mind how much data you send Here are some suggestions for limiting _how much_ data you send: - [Minify text assets](/web/fundamentals/performance/optimizing-content-efficiency/optimize-encoding-and-transfer#minification_preprocessing_context-specific_optimizations). Minification is the removal of unnecessary whitespace, comments and other content in text-based resources. It significantly reduces the amount of data you send to users without impacting functionality. [Use uglification in JavaScript](https://www.npmjs.com/package/uglifyjs) to get more savings through shortening variable and method names. Since SVG is a text-based image format, [it can be optimized with SVGO](https://github.com/svg/svgo). - [Configure your server to compress resources](/web/fundamentals/performance/optimizing-content-efficiency/optimize-encoding-and-transfer). Compression drastically reduces the amount of data you send to users, _especially_ text assets. GZIP is a popular option, but [Brotli compression can go further](https://www.smashingmagazine.com/2016/10/next-generation-server-compression-with-brotli/). Understand, however, that compression is _not_ a catch-all for performance woes: Some file formats which are implicitly compressed (e.g., JPEG, PNG, GIF, WOFF, et cetera) don't respond to compression because they're already compressed. - [Optimize images](/web/fundamentals/performance/optimizing-content-efficiency/automating-image-optimization/) to ensure your site sends as little image data as possible. [Since images make up a large portion of the average per-page payload on the web](http://httparchive.org/trends.php#bytesImg&reqImg), image optimization represents a uniquely large opportunity to boost performance. - If you have time, consider serving alternative image formats. [WebP](/speed/webp/) enjoys reasonably [broad browser support](https://caniuse.com/#feat=webp), and uses less data than JPEG and PNG while keeping visual quality high. [JPEG XR is another alternative format](https://jpeg.org/jpegxr/index.html) supported in IE and Edge offering similar savings. - [Deliver images responsively](https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images). The huge diversity of devices and their screens presents a tremendous opportunity to improve performance by sending images that are the best fit for the screens that view them. In the simplest use cases, you can add an [`srcset` attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-srcset) to an `<img>` element to specify an array of images the browser can choose from. On the more complex side of things, you can use `<picture>` to help the browser choose the most optimal format (e.g., WebP over JPEG or PNG), or serve altogether different treatments of images for different screen sizes. - [Use video instead of animated GIFs](/web/fundamentals/performance/optimizing-content-efficiency/replace-animated-gifs-with-video/). Animated GIFs are _massive_. Videos of similar quality are _far_ smaller, often by 80% or so. If your site makes heavy use of animated GIFs, this is probably the most impactful thing you can do to improve loading performance. - [Client hints](http://httpwg.org/http-extensions/client-hints.html) can tailor resource delivery based on current network conditions and device characteristics. The `DPR`, `Width` and `Viewport-Width` headers can help you [deliver the best images for a device using server-side code _and_ deliver less markup](/web/updates/2015/09/automating-resource-selection-with-client-hints). The `Save-Data` header can help you [deliver lighter application experiences for users who are specifically asking you to do so](/web/updates/2016/02/save-data). - The [`NetworkInformation` API](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation) exposes information about the user's network connection. This information can be used to modify application experiences for users on slower networks. For a more holistic guide on improving performance, check out our writeup on [the RAIL performance model](/web/fundamentals/performance/rail), which focuses on improving both load time and application responsiveness. [Our PRPL pattern guide is also an excellent resource](/web/fundamentals/performance/prpl-pattern/) for improving the performance of modern single page applications. If you're excited to learn more about performance and how to make your site faster, browse through our performance documentation for guides on a variety of topics. We're constantly adding new guides and updating existing ones, so keep coming back! _Special thanks to [Addy Osmani](/web/resources/contributors/addyosmani), [Jeff Posnick](/web/resources/contributors/jeffposnick), [Matt Gaunt](/web/resources/contributors/mattgaunt), [Philip Walton](/web/resources/contributors/philipwalton), [Vinamrata Singal](/web/resources/contributors/vinamratasingal), [Daniel An](https://www.thinkwithgoogle.com/marketing-resources/data-measurement/mobile-page-speed-new-industry-benchmarks/), and [Pete LePage](/web/resources/contributors/petelepage) for their extensive feedback in improving and launching this resource!_ ## Feedback {: #feedback } {% include "web/_shared/helpful.html" %}
{ "content_hash": "8f812e8a4127ca901c5b82bad3dfc078", "timestamp": "", "source": "github", "line_count": 340, "max_line_length": 291, "avg_line_length": 56.92941176470588, "alnum_prop": 0.7952056209960736, "repo_name": "lucab85/WebFundamentals", "id": "19cc99f579a287d6b47dee358bba7821aaa54180", "size": "19356", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/content/en/fundamentals/performance/why-performance-matters/index.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "36004" }, { "name": "HTML", "bytes": "4131868" }, { "name": "JavaScript", "bytes": "380518" }, { "name": "Python", "bytes": "256072" }, { "name": "Shell", "bytes": "5165" }, { "name": "Smarty", "bytes": "3872" } ], "symlink_target": "" }
package org.cryptoworkshop.ximix.node.mixnet.service; import org.bouncycastle.asn1.ASN1Encodable; import org.cryptoworkshop.ximix.common.asn1.message.BoardCapabilities; import org.cryptoworkshop.ximix.common.asn1.message.CapabilityMessage; /** * Simple class for providing lookup of board presence based on caoability messages. */ public class BoardIndex { private final CapabilityMessage capabilityMessage; public BoardIndex(CapabilityMessage capabilityMessage) { this.capabilityMessage = capabilityMessage; } public boolean hasBoard(String boardName) { for (ASN1Encodable enc : capabilityMessage.getDetails()) { BoardCapabilities details = BoardCapabilities.getInstance(enc); if (details.getBoardName().equals(boardName)) { return true; } } return false; } }
{ "content_hash": "d24dcf645f44d1e2df3ca1a62d2eba54", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 84, "avg_line_length": 25.8, "alnum_prop": 0.6932447397563677, "repo_name": "cwgit/ximix", "id": "378d7ff8d9c4e5517fdb3cffdade8b277eba9b01", "size": "1512", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "node/src/main/java/org/cryptoworkshop/ximix/node/mixnet/service/BoardIndex.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package io.fabric8.api; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class DynamicReferenceTest { @Test public void testWithReference() { DynamicReference<String> dynamic = new DynamicReference<String>(); dynamic.bind("foo"); Assert.assertEquals("foo", dynamic.get()); } @Test public void testNoReference() { DynamicReference<String> dynamic = new DynamicReference<String>("noref", 100, TimeUnit.MILLISECONDS); try { dynamic.get(); Assert.fail("DynamicReferenceException expected"); } catch (DynamicReferenceException ex) { Assert.assertEquals("Gave up waiting for: noref", ex.getMessage()); } } @Test public void testUnbind() { DynamicReference<String> dynamic = new DynamicReference<String>("unbind", 100, TimeUnit.MILLISECONDS); String value = "foo"; dynamic.bind(value); Assert.assertEquals(value, dynamic.get()); dynamic.unbind(value); try { dynamic.get(); Assert.fail("DynamicReferenceException expected"); } catch (DynamicReferenceException ex) { Assert.assertEquals("Gave up waiting for: unbind", ex.getMessage()); } } @Test public void testUpdate() { DynamicReference<String> dynamic = new DynamicReference<String>("update", 100, TimeUnit.MILLISECONDS); dynamic.bind("foo"); dynamic.bind("bar"); dynamic.unbind("foo"); Assert.assertEquals("bar", dynamic.get()); dynamic.unbind("bar"); try { dynamic.get(); Assert.fail("DynamicReferenceException expected"); } catch (DynamicReferenceException ex) { Assert.assertEquals("Gave up waiting for: update", ex.getMessage()); } } @Test public void testWithConcurrency() { final DynamicReference<String> dynamic = new DynamicReference<String>(); ExecutorService executor = Executors.newFixedThreadPool(1); executor.submit(new Runnable() { @Override public void run() { int counter = 1; while (true) { try { String value = String.valueOf(counter++); dynamic.bind(value); Thread.sleep(10); dynamic.unbind(value); } catch (InterruptedException e) { //ignore } } } }); for (int i = 0; i < 100; i++) { String msg = dynamic.get(); try { if (i % 10 == 0) { Thread.sleep(10); System.out.println(msg); } } catch (InterruptedException e) { //ignore } } } }
{ "content_hash": "9bd8fd6001e8c6bb7ce6c9735e96c25e", "timestamp": "", "source": "github", "line_count": 97, "max_line_length": 110, "avg_line_length": 31.422680412371133, "alnum_prop": 0.5462598425196851, "repo_name": "alexeev/jboss-fuse-mirror", "id": "5c909fa767b9ed2156edd6e6c1ab82996fd46246", "size": "3671", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "fabric/fabric-api/src/test/java/io/fabric8/api/DynamicReferenceTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "313969" }, { "name": "CoffeeScript", "bytes": "278706" }, { "name": "Java", "bytes": "8498768" }, { "name": "JavaScript", "bytes": "2483260" }, { "name": "Kotlin", "bytes": "14282" }, { "name": "Scala", "bytes": "484151" }, { "name": "Shell", "bytes": "11547" }, { "name": "XSLT", "bytes": "26098" } ], "symlink_target": "" }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/bigquery/datatransfer/v1/datatransfer.proto package com.google.cloud.bigquery.datatransfer.v1; /** * * * <pre> * A request to start manual transfer runs. * </pre> * * Protobuf type {@code google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest} */ public final class StartManualTransferRunsRequest extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest) StartManualTransferRunsRequestOrBuilder { private static final long serialVersionUID = 0L; // Use StartManualTransferRunsRequest.newBuilder() to construct. private StartManualTransferRunsRequest( com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private StartManualTransferRunsRequest() { parent_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new StartManualTransferRunsRequest(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.bigquery.datatransfer.v1.DataTransferProto .internal_static_google_cloud_bigquery_datatransfer_v1_StartManualTransferRunsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.bigquery.datatransfer.v1.DataTransferProto .internal_static_google_cloud_bigquery_datatransfer_v1_StartManualTransferRunsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.class, com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.Builder.class); } public interface TimeRangeOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * Start time of the range of transfer runs. For example, * `"2017-05-25T00:00:00+00:00"`. The start_time must be strictly less than * the end_time. Creates transfer runs where run_time is in the range * between start_time (inclusive) and end_time (exclusive). * </pre> * * <code>.google.protobuf.Timestamp start_time = 1;</code> * * @return Whether the startTime field is set. */ boolean hasStartTime(); /** * * * <pre> * Start time of the range of transfer runs. For example, * `"2017-05-25T00:00:00+00:00"`. The start_time must be strictly less than * the end_time. Creates transfer runs where run_time is in the range * between start_time (inclusive) and end_time (exclusive). * </pre> * * <code>.google.protobuf.Timestamp start_time = 1;</code> * * @return The startTime. */ com.google.protobuf.Timestamp getStartTime(); /** * * * <pre> * Start time of the range of transfer runs. For example, * `"2017-05-25T00:00:00+00:00"`. The start_time must be strictly less than * the end_time. Creates transfer runs where run_time is in the range * between start_time (inclusive) and end_time (exclusive). * </pre> * * <code>.google.protobuf.Timestamp start_time = 1;</code> */ com.google.protobuf.TimestampOrBuilder getStartTimeOrBuilder(); /** * * * <pre> * End time of the range of transfer runs. For example, * `"2017-05-30T00:00:00+00:00"`. The end_time must not be in the future. * Creates transfer runs where run_time is in the range between start_time * (inclusive) and end_time (exclusive). * </pre> * * <code>.google.protobuf.Timestamp end_time = 2;</code> * * @return Whether the endTime field is set. */ boolean hasEndTime(); /** * * * <pre> * End time of the range of transfer runs. For example, * `"2017-05-30T00:00:00+00:00"`. The end_time must not be in the future. * Creates transfer runs where run_time is in the range between start_time * (inclusive) and end_time (exclusive). * </pre> * * <code>.google.protobuf.Timestamp end_time = 2;</code> * * @return The endTime. */ com.google.protobuf.Timestamp getEndTime(); /** * * * <pre> * End time of the range of transfer runs. For example, * `"2017-05-30T00:00:00+00:00"`. The end_time must not be in the future. * Creates transfer runs where run_time is in the range between start_time * (inclusive) and end_time (exclusive). * </pre> * * <code>.google.protobuf.Timestamp end_time = 2;</code> */ com.google.protobuf.TimestampOrBuilder getEndTimeOrBuilder(); } /** * * * <pre> * A specification for a time range, this will request transfer runs with * run_time between start_time (inclusive) and end_time (exclusive). * </pre> * * Protobuf type {@code * google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange} */ public static final class TimeRange extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange) TimeRangeOrBuilder { private static final long serialVersionUID = 0L; // Use TimeRange.newBuilder() to construct. private TimeRange(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private TimeRange() {} @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new TimeRange(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.bigquery.datatransfer.v1.DataTransferProto .internal_static_google_cloud_bigquery_datatransfer_v1_StartManualTransferRunsRequest_TimeRange_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.bigquery.datatransfer.v1.DataTransferProto .internal_static_google_cloud_bigquery_datatransfer_v1_StartManualTransferRunsRequest_TimeRange_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange .class, com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange .Builder.class); } public static final int START_TIME_FIELD_NUMBER = 1; private com.google.protobuf.Timestamp startTime_; /** * * * <pre> * Start time of the range of transfer runs. For example, * `"2017-05-25T00:00:00+00:00"`. The start_time must be strictly less than * the end_time. Creates transfer runs where run_time is in the range * between start_time (inclusive) and end_time (exclusive). * </pre> * * <code>.google.protobuf.Timestamp start_time = 1;</code> * * @return Whether the startTime field is set. */ @java.lang.Override public boolean hasStartTime() { return startTime_ != null; } /** * * * <pre> * Start time of the range of transfer runs. For example, * `"2017-05-25T00:00:00+00:00"`. The start_time must be strictly less than * the end_time. Creates transfer runs where run_time is in the range * between start_time (inclusive) and end_time (exclusive). * </pre> * * <code>.google.protobuf.Timestamp start_time = 1;</code> * * @return The startTime. */ @java.lang.Override public com.google.protobuf.Timestamp getStartTime() { return startTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : startTime_; } /** * * * <pre> * Start time of the range of transfer runs. For example, * `"2017-05-25T00:00:00+00:00"`. The start_time must be strictly less than * the end_time. Creates transfer runs where run_time is in the range * between start_time (inclusive) and end_time (exclusive). * </pre> * * <code>.google.protobuf.Timestamp start_time = 1;</code> */ @java.lang.Override public com.google.protobuf.TimestampOrBuilder getStartTimeOrBuilder() { return getStartTime(); } public static final int END_TIME_FIELD_NUMBER = 2; private com.google.protobuf.Timestamp endTime_; /** * * * <pre> * End time of the range of transfer runs. For example, * `"2017-05-30T00:00:00+00:00"`. The end_time must not be in the future. * Creates transfer runs where run_time is in the range between start_time * (inclusive) and end_time (exclusive). * </pre> * * <code>.google.protobuf.Timestamp end_time = 2;</code> * * @return Whether the endTime field is set. */ @java.lang.Override public boolean hasEndTime() { return endTime_ != null; } /** * * * <pre> * End time of the range of transfer runs. For example, * `"2017-05-30T00:00:00+00:00"`. The end_time must not be in the future. * Creates transfer runs where run_time is in the range between start_time * (inclusive) and end_time (exclusive). * </pre> * * <code>.google.protobuf.Timestamp end_time = 2;</code> * * @return The endTime. */ @java.lang.Override public com.google.protobuf.Timestamp getEndTime() { return endTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : endTime_; } /** * * * <pre> * End time of the range of transfer runs. For example, * `"2017-05-30T00:00:00+00:00"`. The end_time must not be in the future. * Creates transfer runs where run_time is in the range between start_time * (inclusive) and end_time (exclusive). * </pre> * * <code>.google.protobuf.Timestamp end_time = 2;</code> */ @java.lang.Override public com.google.protobuf.TimestampOrBuilder getEndTimeOrBuilder() { return getEndTime(); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (startTime_ != null) { output.writeMessage(1, getStartTime()); } if (endTime_ != null) { output.writeMessage(2, getEndTime()); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (startTime_ != null) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getStartTime()); } if (endTime_ != null) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getEndTime()); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange)) { return super.equals(obj); } com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange other = (com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange) obj; if (hasStartTime() != other.hasStartTime()) return false; if (hasStartTime()) { if (!getStartTime().equals(other.getStartTime())) return false; } if (hasEndTime() != other.hasEndTime()) return false; if (hasEndTime()) { if (!getEndTime().equals(other.getEndTime())) return false; } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasStartTime()) { hash = (37 * hash) + START_TIME_FIELD_NUMBER; hash = (53 * hash) + getStartTime().hashCode(); } if (hasEndTime()) { hash = (37 * hash) + END_TIME_FIELD_NUMBER; hash = (53 * hash) + getEndTime().hashCode(); } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange parseFrom(com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * A specification for a time range, this will request transfer runs with * run_time between start_time (inclusive) and end_time (exclusive). * </pre> * * Protobuf type {@code * google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange) com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest .TimeRangeOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.bigquery.datatransfer.v1.DataTransferProto .internal_static_google_cloud_bigquery_datatransfer_v1_StartManualTransferRunsRequest_TimeRange_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.bigquery.datatransfer.v1.DataTransferProto .internal_static_google_cloud_bigquery_datatransfer_v1_StartManualTransferRunsRequest_TimeRange_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange .class, com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange .Builder.class); } // Construct using // com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); if (startTimeBuilder_ == null) { startTime_ = null; } else { startTime_ = null; startTimeBuilder_ = null; } if (endTimeBuilder_ == null) { endTime_ = null; } else { endTime_ = null; endTimeBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.bigquery.datatransfer.v1.DataTransferProto .internal_static_google_cloud_bigquery_datatransfer_v1_StartManualTransferRunsRequest_TimeRange_descriptor; } @java.lang.Override public com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange getDefaultInstanceForType() { return com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange .getDefaultInstance(); } @java.lang.Override public com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange build() { com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange buildPartial() { com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange result = new com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange( this); if (startTimeBuilder_ == null) { result.startTime_ = startTime_; } else { result.startTime_ = startTimeBuilder_.build(); } if (endTimeBuilder_ == null) { result.endTime_ = endTime_; } else { result.endTime_ = endTimeBuilder_.build(); } onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange) { return mergeFrom( (com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange other) { if (other == com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange .getDefaultInstance()) return this; if (other.hasStartTime()) { mergeStartTime(other.getStartTime()); } if (other.hasEndTime()) { mergeEndTime(other.getEndTime()); } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { input.readMessage(getStartTimeFieldBuilder().getBuilder(), extensionRegistry); break; } // case 10 case 18: { input.readMessage(getEndTimeFieldBuilder().getBuilder(), extensionRegistry); break; } // case 18 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private com.google.protobuf.Timestamp startTime_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> startTimeBuilder_; /** * * * <pre> * Start time of the range of transfer runs. For example, * `"2017-05-25T00:00:00+00:00"`. The start_time must be strictly less than * the end_time. Creates transfer runs where run_time is in the range * between start_time (inclusive) and end_time (exclusive). * </pre> * * <code>.google.protobuf.Timestamp start_time = 1;</code> * * @return Whether the startTime field is set. */ public boolean hasStartTime() { return startTimeBuilder_ != null || startTime_ != null; } /** * * * <pre> * Start time of the range of transfer runs. For example, * `"2017-05-25T00:00:00+00:00"`. The start_time must be strictly less than * the end_time. Creates transfer runs where run_time is in the range * between start_time (inclusive) and end_time (exclusive). * </pre> * * <code>.google.protobuf.Timestamp start_time = 1;</code> * * @return The startTime. */ public com.google.protobuf.Timestamp getStartTime() { if (startTimeBuilder_ == null) { return startTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : startTime_; } else { return startTimeBuilder_.getMessage(); } } /** * * * <pre> * Start time of the range of transfer runs. For example, * `"2017-05-25T00:00:00+00:00"`. The start_time must be strictly less than * the end_time. Creates transfer runs where run_time is in the range * between start_time (inclusive) and end_time (exclusive). * </pre> * * <code>.google.protobuf.Timestamp start_time = 1;</code> */ public Builder setStartTime(com.google.protobuf.Timestamp value) { if (startTimeBuilder_ == null) { if (value == null) { throw new NullPointerException(); } startTime_ = value; onChanged(); } else { startTimeBuilder_.setMessage(value); } return this; } /** * * * <pre> * Start time of the range of transfer runs. For example, * `"2017-05-25T00:00:00+00:00"`. The start_time must be strictly less than * the end_time. Creates transfer runs where run_time is in the range * between start_time (inclusive) and end_time (exclusive). * </pre> * * <code>.google.protobuf.Timestamp start_time = 1;</code> */ public Builder setStartTime(com.google.protobuf.Timestamp.Builder builderForValue) { if (startTimeBuilder_ == null) { startTime_ = builderForValue.build(); onChanged(); } else { startTimeBuilder_.setMessage(builderForValue.build()); } return this; } /** * * * <pre> * Start time of the range of transfer runs. For example, * `"2017-05-25T00:00:00+00:00"`. The start_time must be strictly less than * the end_time. Creates transfer runs where run_time is in the range * between start_time (inclusive) and end_time (exclusive). * </pre> * * <code>.google.protobuf.Timestamp start_time = 1;</code> */ public Builder mergeStartTime(com.google.protobuf.Timestamp value) { if (startTimeBuilder_ == null) { if (startTime_ != null) { startTime_ = com.google.protobuf.Timestamp.newBuilder(startTime_) .mergeFrom(value) .buildPartial(); } else { startTime_ = value; } onChanged(); } else { startTimeBuilder_.mergeFrom(value); } return this; } /** * * * <pre> * Start time of the range of transfer runs. For example, * `"2017-05-25T00:00:00+00:00"`. The start_time must be strictly less than * the end_time. Creates transfer runs where run_time is in the range * between start_time (inclusive) and end_time (exclusive). * </pre> * * <code>.google.protobuf.Timestamp start_time = 1;</code> */ public Builder clearStartTime() { if (startTimeBuilder_ == null) { startTime_ = null; onChanged(); } else { startTime_ = null; startTimeBuilder_ = null; } return this; } /** * * * <pre> * Start time of the range of transfer runs. For example, * `"2017-05-25T00:00:00+00:00"`. The start_time must be strictly less than * the end_time. Creates transfer runs where run_time is in the range * between start_time (inclusive) and end_time (exclusive). * </pre> * * <code>.google.protobuf.Timestamp start_time = 1;</code> */ public com.google.protobuf.Timestamp.Builder getStartTimeBuilder() { onChanged(); return getStartTimeFieldBuilder().getBuilder(); } /** * * * <pre> * Start time of the range of transfer runs. For example, * `"2017-05-25T00:00:00+00:00"`. The start_time must be strictly less than * the end_time. Creates transfer runs where run_time is in the range * between start_time (inclusive) and end_time (exclusive). * </pre> * * <code>.google.protobuf.Timestamp start_time = 1;</code> */ public com.google.protobuf.TimestampOrBuilder getStartTimeOrBuilder() { if (startTimeBuilder_ != null) { return startTimeBuilder_.getMessageOrBuilder(); } else { return startTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : startTime_; } } /** * * * <pre> * Start time of the range of transfer runs. For example, * `"2017-05-25T00:00:00+00:00"`. The start_time must be strictly less than * the end_time. Creates transfer runs where run_time is in the range * between start_time (inclusive) and end_time (exclusive). * </pre> * * <code>.google.protobuf.Timestamp start_time = 1;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> getStartTimeFieldBuilder() { if (startTimeBuilder_ == null) { startTimeBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder>( getStartTime(), getParentForChildren(), isClean()); startTime_ = null; } return startTimeBuilder_; } private com.google.protobuf.Timestamp endTime_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> endTimeBuilder_; /** * * * <pre> * End time of the range of transfer runs. For example, * `"2017-05-30T00:00:00+00:00"`. The end_time must not be in the future. * Creates transfer runs where run_time is in the range between start_time * (inclusive) and end_time (exclusive). * </pre> * * <code>.google.protobuf.Timestamp end_time = 2;</code> * * @return Whether the endTime field is set. */ public boolean hasEndTime() { return endTimeBuilder_ != null || endTime_ != null; } /** * * * <pre> * End time of the range of transfer runs. For example, * `"2017-05-30T00:00:00+00:00"`. The end_time must not be in the future. * Creates transfer runs where run_time is in the range between start_time * (inclusive) and end_time (exclusive). * </pre> * * <code>.google.protobuf.Timestamp end_time = 2;</code> * * @return The endTime. */ public com.google.protobuf.Timestamp getEndTime() { if (endTimeBuilder_ == null) { return endTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : endTime_; } else { return endTimeBuilder_.getMessage(); } } /** * * * <pre> * End time of the range of transfer runs. For example, * `"2017-05-30T00:00:00+00:00"`. The end_time must not be in the future. * Creates transfer runs where run_time is in the range between start_time * (inclusive) and end_time (exclusive). * </pre> * * <code>.google.protobuf.Timestamp end_time = 2;</code> */ public Builder setEndTime(com.google.protobuf.Timestamp value) { if (endTimeBuilder_ == null) { if (value == null) { throw new NullPointerException(); } endTime_ = value; onChanged(); } else { endTimeBuilder_.setMessage(value); } return this; } /** * * * <pre> * End time of the range of transfer runs. For example, * `"2017-05-30T00:00:00+00:00"`. The end_time must not be in the future. * Creates transfer runs where run_time is in the range between start_time * (inclusive) and end_time (exclusive). * </pre> * * <code>.google.protobuf.Timestamp end_time = 2;</code> */ public Builder setEndTime(com.google.protobuf.Timestamp.Builder builderForValue) { if (endTimeBuilder_ == null) { endTime_ = builderForValue.build(); onChanged(); } else { endTimeBuilder_.setMessage(builderForValue.build()); } return this; } /** * * * <pre> * End time of the range of transfer runs. For example, * `"2017-05-30T00:00:00+00:00"`. The end_time must not be in the future. * Creates transfer runs where run_time is in the range between start_time * (inclusive) and end_time (exclusive). * </pre> * * <code>.google.protobuf.Timestamp end_time = 2;</code> */ public Builder mergeEndTime(com.google.protobuf.Timestamp value) { if (endTimeBuilder_ == null) { if (endTime_ != null) { endTime_ = com.google.protobuf.Timestamp.newBuilder(endTime_).mergeFrom(value).buildPartial(); } else { endTime_ = value; } onChanged(); } else { endTimeBuilder_.mergeFrom(value); } return this; } /** * * * <pre> * End time of the range of transfer runs. For example, * `"2017-05-30T00:00:00+00:00"`. The end_time must not be in the future. * Creates transfer runs where run_time is in the range between start_time * (inclusive) and end_time (exclusive). * </pre> * * <code>.google.protobuf.Timestamp end_time = 2;</code> */ public Builder clearEndTime() { if (endTimeBuilder_ == null) { endTime_ = null; onChanged(); } else { endTime_ = null; endTimeBuilder_ = null; } return this; } /** * * * <pre> * End time of the range of transfer runs. For example, * `"2017-05-30T00:00:00+00:00"`. The end_time must not be in the future. * Creates transfer runs where run_time is in the range between start_time * (inclusive) and end_time (exclusive). * </pre> * * <code>.google.protobuf.Timestamp end_time = 2;</code> */ public com.google.protobuf.Timestamp.Builder getEndTimeBuilder() { onChanged(); return getEndTimeFieldBuilder().getBuilder(); } /** * * * <pre> * End time of the range of transfer runs. For example, * `"2017-05-30T00:00:00+00:00"`. The end_time must not be in the future. * Creates transfer runs where run_time is in the range between start_time * (inclusive) and end_time (exclusive). * </pre> * * <code>.google.protobuf.Timestamp end_time = 2;</code> */ public com.google.protobuf.TimestampOrBuilder getEndTimeOrBuilder() { if (endTimeBuilder_ != null) { return endTimeBuilder_.getMessageOrBuilder(); } else { return endTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : endTime_; } } /** * * * <pre> * End time of the range of transfer runs. For example, * `"2017-05-30T00:00:00+00:00"`. The end_time must not be in the future. * Creates transfer runs where run_time is in the range between start_time * (inclusive) and end_time (exclusive). * </pre> * * <code>.google.protobuf.Timestamp end_time = 2;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> getEndTimeFieldBuilder() { if (endTimeBuilder_ == null) { endTimeBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder>( getEndTime(), getParentForChildren(), isClean()); endTime_ = null; } return endTimeBuilder_; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange) } // @@protoc_insertion_point(class_scope:google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange) private static final com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest .TimeRange DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange(); } public static com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<TimeRange> PARSER = new com.google.protobuf.AbstractParser<TimeRange>() { @java.lang.Override public TimeRange parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException() .setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<TimeRange> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<TimeRange> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } private int timeCase_ = 0; private java.lang.Object time_; public enum TimeCase implements com.google.protobuf.Internal.EnumLite, com.google.protobuf.AbstractMessage.InternalOneOfEnum { REQUESTED_TIME_RANGE(3), REQUESTED_RUN_TIME(4), TIME_NOT_SET(0); private final int value; private TimeCase(int value) { this.value = value; } /** * @param value The number of the enum to look for. * @return The enum associated with the given number. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static TimeCase valueOf(int value) { return forNumber(value); } public static TimeCase forNumber(int value) { switch (value) { case 3: return REQUESTED_TIME_RANGE; case 4: return REQUESTED_RUN_TIME; case 0: return TIME_NOT_SET; default: return null; } } public int getNumber() { return this.value; } }; public TimeCase getTimeCase() { return TimeCase.forNumber(timeCase_); } public static final int PARENT_FIELD_NUMBER = 1; private volatile java.lang.Object parent_; /** * * * <pre> * Transfer configuration name in the form: * `projects/{project_id}/transferConfigs/{config_id}` or * `projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}`. * </pre> * * <code>string parent = 1 [(.google.api.resource_reference) = { ... }</code> * * @return The parent. */ @java.lang.Override public java.lang.String getParent() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } } /** * * * <pre> * Transfer configuration name in the form: * `projects/{project_id}/transferConfigs/{config_id}` or * `projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}`. * </pre> * * <code>string parent = 1 [(.google.api.resource_reference) = { ... }</code> * * @return The bytes for parent. */ @java.lang.Override public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int REQUESTED_TIME_RANGE_FIELD_NUMBER = 3; /** * * * <pre> * Time range for the transfer runs that should be started. * </pre> * * <code> * .google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange requested_time_range = 3; * </code> * * @return Whether the requestedTimeRange field is set. */ @java.lang.Override public boolean hasRequestedTimeRange() { return timeCase_ == 3; } /** * * * <pre> * Time range for the transfer runs that should be started. * </pre> * * <code> * .google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange requested_time_range = 3; * </code> * * @return The requestedTimeRange. */ @java.lang.Override public com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange getRequestedTimeRange() { if (timeCase_ == 3) { return (com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange) time_; } return com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange .getDefaultInstance(); } /** * * * <pre> * Time range for the transfer runs that should be started. * </pre> * * <code> * .google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange requested_time_range = 3; * </code> */ @java.lang.Override public com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRangeOrBuilder getRequestedTimeRangeOrBuilder() { if (timeCase_ == 3) { return (com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange) time_; } return com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange .getDefaultInstance(); } public static final int REQUESTED_RUN_TIME_FIELD_NUMBER = 4; /** * * * <pre> * Specific run_time for a transfer run to be started. The * requested_run_time must not be in the future. * </pre> * * <code>.google.protobuf.Timestamp requested_run_time = 4;</code> * * @return Whether the requestedRunTime field is set. */ @java.lang.Override public boolean hasRequestedRunTime() { return timeCase_ == 4; } /** * * * <pre> * Specific run_time for a transfer run to be started. The * requested_run_time must not be in the future. * </pre> * * <code>.google.protobuf.Timestamp requested_run_time = 4;</code> * * @return The requestedRunTime. */ @java.lang.Override public com.google.protobuf.Timestamp getRequestedRunTime() { if (timeCase_ == 4) { return (com.google.protobuf.Timestamp) time_; } return com.google.protobuf.Timestamp.getDefaultInstance(); } /** * * * <pre> * Specific run_time for a transfer run to be started. The * requested_run_time must not be in the future. * </pre> * * <code>.google.protobuf.Timestamp requested_run_time = 4;</code> */ @java.lang.Override public com.google.protobuf.TimestampOrBuilder getRequestedRunTimeOrBuilder() { if (timeCase_ == 4) { return (com.google.protobuf.Timestamp) time_; } return com.google.protobuf.Timestamp.getDefaultInstance(); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_); } if (timeCase_ == 3) { output.writeMessage( 3, (com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange) time_); } if (timeCase_ == 4) { output.writeMessage(4, (com.google.protobuf.Timestamp) time_); } getUnknownFields().writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_); } if (timeCase_ == 3) { size += com.google.protobuf.CodedOutputStream.computeMessageSize( 3, (com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange) time_); } if (timeCase_ == 4) { size += com.google.protobuf.CodedOutputStream.computeMessageSize( 4, (com.google.protobuf.Timestamp) time_); } size += getUnknownFields().getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest)) { return super.equals(obj); } com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest other = (com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest) obj; if (!getParent().equals(other.getParent())) return false; if (!getTimeCase().equals(other.getTimeCase())) return false; switch (timeCase_) { case 3: if (!getRequestedTimeRange().equals(other.getRequestedTimeRange())) return false; break; case 4: if (!getRequestedRunTime().equals(other.getRequestedRunTime())) return false; break; case 0: default: } if (!getUnknownFields().equals(other.getUnknownFields())) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PARENT_FIELD_NUMBER; hash = (53 * hash) + getParent().hashCode(); switch (timeCase_) { case 3: hash = (37 * hash) + REQUESTED_TIME_RANGE_FIELD_NUMBER; hash = (53 * hash) + getRequestedTimeRange().hashCode(); break; case 4: hash = (37 * hash) + REQUESTED_RUN_TIME_FIELD_NUMBER; hash = (53 * hash) + getRequestedRunTime().hashCode(); break; case 0: default: } hash = (29 * hash) + getUnknownFields().hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest parseFrom( byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * A request to start manual transfer runs. * </pre> * * Protobuf type {@code google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest) com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.bigquery.datatransfer.v1.DataTransferProto .internal_static_google_cloud_bigquery_datatransfer_v1_StartManualTransferRunsRequest_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.bigquery.datatransfer.v1.DataTransferProto .internal_static_google_cloud_bigquery_datatransfer_v1_StartManualTransferRunsRequest_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.class, com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.Builder .class); } // Construct using // com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.newBuilder() private Builder() {} private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); } @java.lang.Override public Builder clear() { super.clear(); parent_ = ""; if (requestedTimeRangeBuilder_ != null) { requestedTimeRangeBuilder_.clear(); } if (requestedRunTimeBuilder_ != null) { requestedRunTimeBuilder_.clear(); } timeCase_ = 0; time_ = null; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.bigquery.datatransfer.v1.DataTransferProto .internal_static_google_cloud_bigquery_datatransfer_v1_StartManualTransferRunsRequest_descriptor; } @java.lang.Override public com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest getDefaultInstanceForType() { return com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest .getDefaultInstance(); } @java.lang.Override public com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest build() { com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest buildPartial() { com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest result = new com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest(this); result.parent_ = parent_; if (timeCase_ == 3) { if (requestedTimeRangeBuilder_ == null) { result.time_ = time_; } else { result.time_ = requestedTimeRangeBuilder_.build(); } } if (timeCase_ == 4) { if (requestedRunTimeBuilder_ == null) { result.time_ = time_; } else { result.time_ = requestedRunTimeBuilder_.build(); } } result.timeCase_ = timeCase_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest) { return mergeFrom( (com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom( com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest other) { if (other == com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest .getDefaultInstance()) return this; if (!other.getParent().isEmpty()) { parent_ = other.parent_; onChanged(); } switch (other.getTimeCase()) { case REQUESTED_TIME_RANGE: { mergeRequestedTimeRange(other.getRequestedTimeRange()); break; } case REQUESTED_RUN_TIME: { mergeRequestedRunTime(other.getRequestedRunTime()); break; } case TIME_NOT_SET: { break; } } this.mergeUnknownFields(other.getUnknownFields()); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { parent_ = input.readStringRequireUtf8(); break; } // case 10 case 26: { input.readMessage( getRequestedTimeRangeFieldBuilder().getBuilder(), extensionRegistry); timeCase_ = 3; break; } // case 26 case 34: { input.readMessage( getRequestedRunTimeFieldBuilder().getBuilder(), extensionRegistry); timeCase_ = 4; break; } // case 34 default: { if (!super.parseUnknownField(input, extensionRegistry, tag)) { done = true; // was an endgroup tag } break; } // default: } // switch (tag) } // while (!done) } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.unwrapIOException(); } finally { onChanged(); } // finally return this; } private int timeCase_ = 0; private java.lang.Object time_; public TimeCase getTimeCase() { return TimeCase.forNumber(timeCase_); } public Builder clearTime() { timeCase_ = 0; time_ = null; onChanged(); return this; } private java.lang.Object parent_ = ""; /** * * * <pre> * Transfer configuration name in the form: * `projects/{project_id}/transferConfigs/{config_id}` or * `projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}`. * </pre> * * <code>string parent = 1 [(.google.api.resource_reference) = { ... }</code> * * @return The parent. */ public java.lang.String getParent() { java.lang.Object ref = parent_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); parent_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Transfer configuration name in the form: * `projects/{project_id}/transferConfigs/{config_id}` or * `projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}`. * </pre> * * <code>string parent = 1 [(.google.api.resource_reference) = { ... }</code> * * @return The bytes for parent. */ public com.google.protobuf.ByteString getParentBytes() { java.lang.Object ref = parent_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); parent_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Transfer configuration name in the form: * `projects/{project_id}/transferConfigs/{config_id}` or * `projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}`. * </pre> * * <code>string parent = 1 [(.google.api.resource_reference) = { ... }</code> * * @param value The parent to set. * @return This builder for chaining. */ public Builder setParent(java.lang.String value) { if (value == null) { throw new NullPointerException(); } parent_ = value; onChanged(); return this; } /** * * * <pre> * Transfer configuration name in the form: * `projects/{project_id}/transferConfigs/{config_id}` or * `projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}`. * </pre> * * <code>string parent = 1 [(.google.api.resource_reference) = { ... }</code> * * @return This builder for chaining. */ public Builder clearParent() { parent_ = getDefaultInstance().getParent(); onChanged(); return this; } /** * * * <pre> * Transfer configuration name in the form: * `projects/{project_id}/transferConfigs/{config_id}` or * `projects/{project_id}/locations/{location_id}/transferConfigs/{config_id}`. * </pre> * * <code>string parent = 1 [(.google.api.resource_reference) = { ... }</code> * * @param value The bytes for parent to set. * @return This builder for chaining. */ public Builder setParentBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); parent_ = value; onChanged(); return this; } private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange, com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange .Builder, com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest .TimeRangeOrBuilder> requestedTimeRangeBuilder_; /** * * * <pre> * Time range for the transfer runs that should be started. * </pre> * * <code> * .google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange requested_time_range = 3; * </code> * * @return Whether the requestedTimeRange field is set. */ @java.lang.Override public boolean hasRequestedTimeRange() { return timeCase_ == 3; } /** * * * <pre> * Time range for the transfer runs that should be started. * </pre> * * <code> * .google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange requested_time_range = 3; * </code> * * @return The requestedTimeRange. */ @java.lang.Override public com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange getRequestedTimeRange() { if (requestedTimeRangeBuilder_ == null) { if (timeCase_ == 3) { return (com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest .TimeRange) time_; } return com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange .getDefaultInstance(); } else { if (timeCase_ == 3) { return requestedTimeRangeBuilder_.getMessage(); } return com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange .getDefaultInstance(); } } /** * * * <pre> * Time range for the transfer runs that should be started. * </pre> * * <code> * .google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange requested_time_range = 3; * </code> */ public Builder setRequestedTimeRange( com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange value) { if (requestedTimeRangeBuilder_ == null) { if (value == null) { throw new NullPointerException(); } time_ = value; onChanged(); } else { requestedTimeRangeBuilder_.setMessage(value); } timeCase_ = 3; return this; } /** * * * <pre> * Time range for the transfer runs that should be started. * </pre> * * <code> * .google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange requested_time_range = 3; * </code> */ public Builder setRequestedTimeRange( com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange.Builder builderForValue) { if (requestedTimeRangeBuilder_ == null) { time_ = builderForValue.build(); onChanged(); } else { requestedTimeRangeBuilder_.setMessage(builderForValue.build()); } timeCase_ = 3; return this; } /** * * * <pre> * Time range for the transfer runs that should be started. * </pre> * * <code> * .google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange requested_time_range = 3; * </code> */ public Builder mergeRequestedTimeRange( com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange value) { if (requestedTimeRangeBuilder_ == null) { if (timeCase_ == 3 && time_ != com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest .TimeRange.getDefaultInstance()) { time_ = com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange .newBuilder( (com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest .TimeRange) time_) .mergeFrom(value) .buildPartial(); } else { time_ = value; } onChanged(); } else { if (timeCase_ == 3) { requestedTimeRangeBuilder_.mergeFrom(value); } else { requestedTimeRangeBuilder_.setMessage(value); } } timeCase_ = 3; return this; } /** * * * <pre> * Time range for the transfer runs that should be started. * </pre> * * <code> * .google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange requested_time_range = 3; * </code> */ public Builder clearRequestedTimeRange() { if (requestedTimeRangeBuilder_ == null) { if (timeCase_ == 3) { timeCase_ = 0; time_ = null; onChanged(); } } else { if (timeCase_ == 3) { timeCase_ = 0; time_ = null; } requestedTimeRangeBuilder_.clear(); } return this; } /** * * * <pre> * Time range for the transfer runs that should be started. * </pre> * * <code> * .google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange requested_time_range = 3; * </code> */ public com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange .Builder getRequestedTimeRangeBuilder() { return getRequestedTimeRangeFieldBuilder().getBuilder(); } /** * * * <pre> * Time range for the transfer runs that should be started. * </pre> * * <code> * .google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange requested_time_range = 3; * </code> */ @java.lang.Override public com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest .TimeRangeOrBuilder getRequestedTimeRangeOrBuilder() { if ((timeCase_ == 3) && (requestedTimeRangeBuilder_ != null)) { return requestedTimeRangeBuilder_.getMessageOrBuilder(); } else { if (timeCase_ == 3) { return (com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest .TimeRange) time_; } return com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange .getDefaultInstance(); } } /** * * * <pre> * Time range for the transfer runs that should be started. * </pre> * * <code> * .google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange requested_time_range = 3; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange, com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange .Builder, com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest .TimeRangeOrBuilder> getRequestedTimeRangeFieldBuilder() { if (requestedTimeRangeBuilder_ == null) { if (!(timeCase_ == 3)) { time_ = com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange .getDefaultInstance(); } requestedTimeRangeBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange, com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange .Builder, com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest .TimeRangeOrBuilder>( (com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest.TimeRange) time_, getParentForChildren(), isClean()); time_ = null; } timeCase_ = 3; onChanged(); ; return requestedTimeRangeBuilder_; } private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> requestedRunTimeBuilder_; /** * * * <pre> * Specific run_time for a transfer run to be started. The * requested_run_time must not be in the future. * </pre> * * <code>.google.protobuf.Timestamp requested_run_time = 4;</code> * * @return Whether the requestedRunTime field is set. */ @java.lang.Override public boolean hasRequestedRunTime() { return timeCase_ == 4; } /** * * * <pre> * Specific run_time for a transfer run to be started. The * requested_run_time must not be in the future. * </pre> * * <code>.google.protobuf.Timestamp requested_run_time = 4;</code> * * @return The requestedRunTime. */ @java.lang.Override public com.google.protobuf.Timestamp getRequestedRunTime() { if (requestedRunTimeBuilder_ == null) { if (timeCase_ == 4) { return (com.google.protobuf.Timestamp) time_; } return com.google.protobuf.Timestamp.getDefaultInstance(); } else { if (timeCase_ == 4) { return requestedRunTimeBuilder_.getMessage(); } return com.google.protobuf.Timestamp.getDefaultInstance(); } } /** * * * <pre> * Specific run_time for a transfer run to be started. The * requested_run_time must not be in the future. * </pre> * * <code>.google.protobuf.Timestamp requested_run_time = 4;</code> */ public Builder setRequestedRunTime(com.google.protobuf.Timestamp value) { if (requestedRunTimeBuilder_ == null) { if (value == null) { throw new NullPointerException(); } time_ = value; onChanged(); } else { requestedRunTimeBuilder_.setMessage(value); } timeCase_ = 4; return this; } /** * * * <pre> * Specific run_time for a transfer run to be started. The * requested_run_time must not be in the future. * </pre> * * <code>.google.protobuf.Timestamp requested_run_time = 4;</code> */ public Builder setRequestedRunTime(com.google.protobuf.Timestamp.Builder builderForValue) { if (requestedRunTimeBuilder_ == null) { time_ = builderForValue.build(); onChanged(); } else { requestedRunTimeBuilder_.setMessage(builderForValue.build()); } timeCase_ = 4; return this; } /** * * * <pre> * Specific run_time for a transfer run to be started. The * requested_run_time must not be in the future. * </pre> * * <code>.google.protobuf.Timestamp requested_run_time = 4;</code> */ public Builder mergeRequestedRunTime(com.google.protobuf.Timestamp value) { if (requestedRunTimeBuilder_ == null) { if (timeCase_ == 4 && time_ != com.google.protobuf.Timestamp.getDefaultInstance()) { time_ = com.google.protobuf.Timestamp.newBuilder((com.google.protobuf.Timestamp) time_) .mergeFrom(value) .buildPartial(); } else { time_ = value; } onChanged(); } else { if (timeCase_ == 4) { requestedRunTimeBuilder_.mergeFrom(value); } else { requestedRunTimeBuilder_.setMessage(value); } } timeCase_ = 4; return this; } /** * * * <pre> * Specific run_time for a transfer run to be started. The * requested_run_time must not be in the future. * </pre> * * <code>.google.protobuf.Timestamp requested_run_time = 4;</code> */ public Builder clearRequestedRunTime() { if (requestedRunTimeBuilder_ == null) { if (timeCase_ == 4) { timeCase_ = 0; time_ = null; onChanged(); } } else { if (timeCase_ == 4) { timeCase_ = 0; time_ = null; } requestedRunTimeBuilder_.clear(); } return this; } /** * * * <pre> * Specific run_time for a transfer run to be started. The * requested_run_time must not be in the future. * </pre> * * <code>.google.protobuf.Timestamp requested_run_time = 4;</code> */ public com.google.protobuf.Timestamp.Builder getRequestedRunTimeBuilder() { return getRequestedRunTimeFieldBuilder().getBuilder(); } /** * * * <pre> * Specific run_time for a transfer run to be started. The * requested_run_time must not be in the future. * </pre> * * <code>.google.protobuf.Timestamp requested_run_time = 4;</code> */ @java.lang.Override public com.google.protobuf.TimestampOrBuilder getRequestedRunTimeOrBuilder() { if ((timeCase_ == 4) && (requestedRunTimeBuilder_ != null)) { return requestedRunTimeBuilder_.getMessageOrBuilder(); } else { if (timeCase_ == 4) { return (com.google.protobuf.Timestamp) time_; } return com.google.protobuf.Timestamp.getDefaultInstance(); } } /** * * * <pre> * Specific run_time for a transfer run to be started. The * requested_run_time must not be in the future. * </pre> * * <code>.google.protobuf.Timestamp requested_run_time = 4;</code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> getRequestedRunTimeFieldBuilder() { if (requestedRunTimeBuilder_ == null) { if (!(timeCase_ == 4)) { time_ = com.google.protobuf.Timestamp.getDefaultInstance(); } requestedRunTimeBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder>( (com.google.protobuf.Timestamp) time_, getParentForChildren(), isClean()); time_ = null; } timeCase_ = 4; onChanged(); ; return requestedRunTimeBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest) } // @@protoc_insertion_point(class_scope:google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest) private static final com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest(); } public static com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<StartManualTransferRunsRequest> PARSER = new com.google.protobuf.AbstractParser<StartManualTransferRunsRequest>() { @java.lang.Override public StartManualTransferRunsRequest parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { Builder builder = newBuilder(); try { builder.mergeFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(builder.buildPartial()); } catch (com.google.protobuf.UninitializedMessageException e) { throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial()); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e) .setUnfinishedMessage(builder.buildPartial()); } return builder.buildPartial(); } }; public static com.google.protobuf.Parser<StartManualTransferRunsRequest> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<StartManualTransferRunsRequest> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.bigquery.datatransfer.v1.StartManualTransferRunsRequest getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
{ "content_hash": "9cb62e664d8548fa7af72ecff5db0b80", "timestamp": "", "source": "github", "line_count": 2528, "max_line_length": 134, "avg_line_length": 33.94897151898734, "alnum_prop": 0.6297496009228295, "repo_name": "googleapis/java-bigquerydatatransfer", "id": "9ac68ad626e12111e62645949e1567b9a0bdd570", "size": "86417", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "proto-google-cloud-bigquerydatatransfer-v1/src/main/java/com/google/cloud/bigquery/datatransfer/v1/StartManualTransferRunsRequest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "801" }, { "name": "Java", "bytes": "3124458" }, { "name": "Python", "bytes": "2473" }, { "name": "Shell", "bytes": "22603" } ], "symlink_target": "" }
layout: global displayTitle: One Hot Encoder title: One Hot Encoder description: One Hot Encoder usesMathJax: true includeOperationsMenu: true --- Maps a column of category indices to a column of binary vectors. This operation is ported from Spark ML. For a comprehensive introduction, see <a target="_blank" href="https://spark.apache.org/docs/2.0.0/ml-features.html#onehotencoder">Spark documentation</a>. For scala docs details, see <a target="_blank" href="https://spark.apache.org/docs/2.0.0/api/scala/index.html#org.apache.spark.ml.feature.OneHotEncoder">org.apache.spark.ml.feature.OneHotEncoder documentation</a>. **Since**: Seahorse 1.0.0 ## Input <table> <thead> <tr> <th style="width:15%">Port</th> <th style="width:15%">Type Qualifier</th> <th style="width:70%">Description</th> </tr> </thead> <tbody> <tr><td><code>0</code></td><td><code><a href="../classes/dataframe.html">DataFrame</a></code></td><td>The input <code>DataFrame</code>.</td></tr> </tbody> </table> ## Output <table> <thead> <tr> <th style="width:15%">Port</th> <th style="width:15%">Type Qualifier</th> <th style="width:70%">Description</th> </tr> </thead> <tbody> <tr><td><code>0</code></td><td><code><a href="../classes/dataframe.html">DataFrame</a></code></td><td>The output <code>DataFrame</code>.</td></tr><tr><td><code>1</code></td><td><code><a href="../classes/transformer.html">Transformer</a></code></td><td>A <code>Transformer</code> that allows to apply the operation on other <code>DataFrames</code> using a <a href="transform.html">Transform</a>.</td></tr> </tbody> </table> ## Parameters <table class="table"> <thead> <tr> <th style="width:15%">Name</th> <th style="width:15%">Type</th> <th style="width:70%">Description</th> </tr> </thead> <tbody> <tr> <td><code>drop last</code></td> <td><code><a href="../parameter_types.html#boolean">Boolean</a></code></td> <td>Whether to drop the last category in the encoded vector.</td> </tr> <tr> <td><code>operate on</code></td> <td><code><a href="../parameter_types.html#input-output-column-selector">InputOutputColumnSelector</a></code></td> <td>The input and output columns for the operation.</td> </tr> </tbody> </table> {% markdown operations/examples/OneHotEncode.md %}
{ "content_hash": "7938a7e5e444092a0669afecd6996af4", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 408, "avg_line_length": 26.388235294117646, "alnum_prop": 0.6879179670084707, "repo_name": "deepsense-io/seahorse-workflow-executor", "id": "739258022bdfbe806a0fde174a7de5989838b579", "size": "2247", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/operations/one_hot_encoder.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1056" }, { "name": "Python", "bytes": "20258" }, { "name": "R", "bytes": "3044" }, { "name": "Scala", "bytes": "2515300" }, { "name": "Shell", "bytes": "3350" } ], "symlink_target": "" }
<?php namespace Invoker\ParameterResolver\Container; use Interop\Container\ContainerInterface; use Invoker\ParameterResolver\ParameterResolver; use ReflectionFunctionAbstract; /** * Inject entries from a DI container using the type-hints. * * @author Matthieu Napoli <[email protected]> */ class TypeHintContainerResolver implements ParameterResolver { /** * @var ContainerInterface */ private $container; /** * @param ContainerInterface $container The container to get entries from. */ public function __construct(ContainerInterface $container) { $this->container = $container; } public function getParameters( ReflectionFunctionAbstract $reflection, array $providedParameters, array $resolvedParameters ) { $parameters = $reflection->getParameters(); // Skip parameters already resolved if (! empty($resolvedParameters)) { $parameters = array_diff_key($parameters, $resolvedParameters); } foreach ($parameters as $index => $parameter) { $parameterClass = $parameter->getClass(); if ($parameterClass && $this->container->has($parameterClass->name)) { $resolvedParameters[$index] = $this->container->get($parameterClass->name); } } return $resolvedParameters; } }
{ "content_hash": "d535f0145bdf7d310f42842d0a72bd84", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 91, "avg_line_length": 27.19607843137255, "alnum_prop": 0.6524873828406633, "repo_name": "christophbuehler/onyx", "id": "65a407949759f425ef140cdc5587bd0ebf3eeda1", "size": "1387", "binary": false, "copies": "19", "ref": "refs/heads/master", "path": "vendor/php-di/invoker/src/ParameterResolver/Container/TypeHintContainerResolver.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "43" }, { "name": "HTML", "bytes": "50605" }, { "name": "JavaScript", "bytes": "138426" }, { "name": "PHP", "bytes": "85601" } ], "symlink_target": "" }
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 3.0.12 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ package org.pjsip.pjsua2; public class VideoWindow { private transient long swigCPtr; protected transient boolean swigCMemOwn; protected VideoWindow(long cPtr, boolean cMemoryOwn) { swigCMemOwn = cMemoryOwn; swigCPtr = cPtr; } protected static long getCPtr(VideoWindow obj) { return (obj == null) ? 0 : obj.swigCPtr; } protected void finalize() { delete(); } public synchronized void delete() { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; pjsua2JNI.delete_VideoWindow(swigCPtr); } swigCPtr = 0; } } public VideoWindow(int win_id) { this(pjsua2JNI.new_VideoWindow(win_id), true); } public VideoWindowInfo getInfo() throws java.lang.Exception { return new VideoWindowInfo(pjsua2JNI.VideoWindow_getInfo(swigCPtr, this), true); } public void Show(boolean show) throws java.lang.Exception { pjsua2JNI.VideoWindow_Show(swigCPtr, this, show); } public void setPos(MediaCoordinate pos) throws java.lang.Exception { pjsua2JNI.VideoWindow_setPos(swigCPtr, this, MediaCoordinate.getCPtr(pos), pos); } public void setSize(MediaSize size) throws java.lang.Exception { pjsua2JNI.VideoWindow_setSize(swigCPtr, this, MediaSize.getCPtr(size), size); } public void rotate(int angle) throws java.lang.Exception { pjsua2JNI.VideoWindow_rotate(swigCPtr, this, angle); } public void setWindow(VideoWindowHandle win) throws java.lang.Exception { pjsua2JNI.VideoWindow_setWindow(swigCPtr, this, VideoWindowHandle.getCPtr(win), win); } }
{ "content_hash": "7803e91e8089837b5955decba0e3bc3c", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 89, "avg_line_length": 29.545454545454547, "alnum_prop": 0.6502564102564102, "repo_name": "symeonmattes/pjsip", "id": "e3155c45b7e122b252967b2a6fd29d6e224c4b4e", "size": "1950", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/android/api/pjsua2/VideoWindow.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2595813" }, { "name": "C++", "bytes": "523871" }, { "name": "Java", "bytes": "861553" }, { "name": "JavaScript", "bytes": "3456" }, { "name": "Objective-C", "bytes": "99065" }, { "name": "Shell", "bytes": "545" } ], "symlink_target": "" }
<h1>Angular 2 skeleton !!!</h1> <hello name="Matthias"></hello>
{ "content_hash": "14073846d3e657dee2f4695fd55e34d8", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 31, "avg_line_length": 21.333333333333332, "alnum_prop": 0.65625, "repo_name": "mattjmattj/ng2-skeleton", "id": "707b318dd5c6cbe37b7622b2f9c7a7ae8106a410", "size": "64", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/templates/application.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "912" }, { "name": "JavaScript", "bytes": "2413" }, { "name": "TypeScript", "bytes": "1052" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="ProjectModuleManager"> <modules> <module fileurl="file://$PROJECT_DIR$/.idea/Gulp-with-foundation-and-sass.iml" filepath="$PROJECT_DIR$/.idea/Gulp-with-foundation-and-sass.iml" /> </modules> </component> </project>
{ "content_hash": "4ce1cc60edd18eb1deaf94998fb4a48a", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 152, "avg_line_length": 38.75, "alnum_prop": 0.6806451612903226, "repo_name": "CharlieGreenman/react-demo1", "id": "3e36c5f48f23ecf3e6a3df0fa43fabff99e2d3ad", "size": "310", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": ".idea/modules.xml", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "219641" }, { "name": "HTML", "bytes": "4074" }, { "name": "JavaScript", "bytes": "683885" } ], "symlink_target": "" }
<!doctype html> <html> <head> <title>Screenshotter test</title> <script src="/katex.js" type="text/javascript"></script> <link href="/katex.css" rel="stylesheet" type="text/css"> <style type="text/css"> #math, #pre, #post { font-size: 4em; } body { font-family: "DejaVu Serif",serif; } </style> </head> <body> <span id="pre"></span> <span id="math"></span> <span id="post"></span> <script type="text/javascript"> var query = {}; var re = /(?:^\?|&)([^&=]+)(?:=([^&]+))?/g; var match; while (match = re.exec(window.location.search)) { query[match[1]] = decodeURIComponent(match[2]); } var mathNode = document.getElementById("math"); var settings = { displayMode: !!query["display"], throwOnError: !query["noThrow"] }; if (query["errorColor"]) { settings.errorColor = query["errorColor"]; } katex.render(query["tex"], mathNode, settings); document.getElementById("pre").innerHTML = query["pre"] || ""; document.getElementById("post").innerHTML = query["post"] || ""; </script> </body> </html>
{ "content_hash": "d5b5a41867fa08dea1f4670aadf41b30", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 70, "avg_line_length": 28.547619047619047, "alnum_prop": 0.5379482902418682, "repo_name": "gavin66/blog", "id": "4da2a8b8f98ae1bffc4e2285e73c19fc4d96073f", "size": "1199", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "public/vendor/KaTeX-0.5.1/test/screenshotter/test.html", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "356" }, { "name": "CSS", "bytes": "395826" }, { "name": "JavaScript", "bytes": "196797" }, { "name": "PHP", "bytes": "252906" } ], "symlink_target": "" }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.parquet; import java.io.Closeable; import java.io.IOException; public interface ParquetDataSource extends Closeable { ParquetDataSourceId getId(); long getReadBytes(); long getReadTimeNanos(); long getSize(); void readFully(long position, byte[] buffer); void readFully(long position, byte[] buffer, int bufferOffset, int bufferLength); @Override default void close() throws IOException { } }
{ "content_hash": "133a5739ff119d54cd66e80fab1ff066", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 85, "avg_line_length": 26.94871794871795, "alnum_prop": 0.7145575642245481, "repo_name": "stewartpark/presto", "id": "e28e982953257eec37a2dc3b950082683b87fc72", "size": "1051", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "presto-parquet/src/main/java/com/facebook/presto/parquet/ParquetDataSource.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "28328" }, { "name": "CSS", "bytes": "13018" }, { "name": "HTML", "bytes": "28633" }, { "name": "Java", "bytes": "32309831" }, { "name": "JavaScript", "bytes": "214692" }, { "name": "Makefile", "bytes": "6830" }, { "name": "PLSQL", "bytes": "2797" }, { "name": "PLpgSQL", "bytes": "11504" }, { "name": "Python", "bytes": "7664" }, { "name": "SQLPL", "bytes": "926" }, { "name": "Shell", "bytes": "29871" }, { "name": "Thrift", "bytes": "12631" } ], "symlink_target": "" }
package com.google.security.zynamics.reil.translators.mips; import com.google.security.zynamics.reil.OperandSize; import com.google.security.zynamics.reil.ReilHelpers; import com.google.security.zynamics.reil.ReilInstruction; import com.google.security.zynamics.reil.translators.IInstructionTranslator; import com.google.security.zynamics.reil.translators.ITranslationEnvironment; import com.google.security.zynamics.reil.translators.InternalTranslationException; import com.google.security.zynamics.reil.translators.TranslationHelpers; import com.google.security.zynamics.zylib.disassembly.IInstruction; import com.google.security.zynamics.zylib.disassembly.IOperandTree; import java.util.List; public class JalrTranslator implements IInstructionTranslator { @Override public void translate(final ITranslationEnvironment environment, final IInstruction instruction, final List<ReilInstruction> instructions) throws InternalTranslationException { TranslationHelpers.checkTranslationArguments(environment, instruction, instructions, "jalr"); final List<? extends IOperandTree> operands = instruction.getOperands(); // this differs to the documentation but in the spim emulator this is the behaviour final long returnAddress = instruction.getAddress().toLong() + 4; final String rd = operands.size() == 1 ? "$ra" : operands.get(0).getRootNode().getChildren().get(0) .getValue(); final String rs = operands.size() == 1 ? operands.get(0).getRootNode().getChildren().get(0).getValue() : operands.get(1).getRootNode().getChildren().get(0).getValue(); final OperandSize dw = OperandSize.DWORD; final long baseOffset = ReilHelpers.toReilAddress(instruction.getAddress()).toLong(); long offset = baseOffset; instructions.add(ReilHelpers.createStr(offset++, dw, String.valueOf(returnAddress), dw, rd)); instructions.add(ReilHelpers.createJcc(offset++, dw, String.valueOf(1L), dw, rs, "isCall", "true")); } }
{ "content_hash": "c3395eb4735d751e8daa73ab1b769f0b", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 98, "avg_line_length": 46.7906976744186, "alnum_prop": 0.7664015904572564, "repo_name": "google/binnavi", "id": "c41026fa39f0560eaba665a9cd771817fb470f40", "size": "2601", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/com/google/security/zynamics/reil/translators/mips/JalrTranslator.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1489" }, { "name": "C", "bytes": "8997" }, { "name": "C++", "bytes": "982064" }, { "name": "CMake", "bytes": "1953" }, { "name": "CSS", "bytes": "12843" }, { "name": "GAP", "bytes": "3637" }, { "name": "HTML", "bytes": "437459" }, { "name": "Java", "bytes": "21714625" }, { "name": "Makefile", "bytes": "3498" }, { "name": "PLpgSQL", "bytes": "180849" }, { "name": "Python", "bytes": "23981" }, { "name": "Shell", "bytes": "713" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/1998/REC-html40-19980424/loose.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Y</title> <link rel="stylesheet" href="doc.css" type="text/css"> </head> <body> <h1>Y</h1> <dl> <dt><a name="yield"><code>(yield 'any ['sym]) -> any</code></a> <dd>(64-bit version only) Transfers control from the current <a href="ref.html#coroutines">coroutine</a> back to the caller (when the <code>sym</code> tag is not given), or to some other coroutine (specified by <code>sym</code>) to continue execution at the point where that coroutine had called <code>yield</code> before. In the first case, the value <code>any</code> will be returned from the corresponding <code><a href="refC.html#co">co</a></code> call, in the second case it will be the return value of that <code>yield</code> call. See also <code><a href="refS.html#stack">stack</a></code>, <code><a href="refC.html#catch">catch</a></code> and <code><a href="refT.html#throw">throw</a></code>. <pre><code> : (co "rt1" # Start first routine (msg (yield 1) " in rt1 from rt2") # Return '1', wait for value from "rt2" 7 ) # Then return '7' -> 1 : (co "rt2" # Start second routine (yield 2 "rt1") ) # Send '2' to "rt1" 2 in rt1 from rt2 -> 7 </code></pre> <dt><a name="yoke"><code>(yoke 'any ..) -> any</code></a> <dd>Inserts one or several new elements <code>any</code> in front of the list in the current <code><a href="refM.html#make">make</a></code> environment. <code>yoke</code> returns the last inserted argument. See also <code><a href="refL.html#link">link</a></code>, <code><a href="refC.html#chain">chain</a></code> and <code><a href="refM.html#made">made</a></code>. <pre><code> : (make (link 2 3) (yoke 1) (link 4)) -> (1 2 3 4) </code></pre> </dl> </body> </html>
{ "content_hash": "403cfef508fd244b192d90ddb4715200", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 120, "avg_line_length": 36.054545454545455, "alnum_prop": 0.626828038325769, "repo_name": "tangentstorm/picolisp", "id": "a15140ec4defd54ba648feaab6978386e6a16262", "size": "1983", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "doc/refY.html", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "402054" }, { "name": "C++", "bytes": "19295" }, { "name": "CSS", "bytes": "5304" }, { "name": "Emacs Lisp", "bytes": "91763" }, { "name": "JavaScript", "bytes": "34780" }, { "name": "Nu", "bytes": "539" }, { "name": "Prolog", "bytes": "8778" }, { "name": "Shell", "bytes": "2050" }, { "name": "VimL", "bytes": "5193" } ], "symlink_target": "" }
namespace Slot { partial class MainForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm)); this.splitContainer = new Slot.SplitContainerEx(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer)).BeginInit(); this.splitContainer.SuspendLayout(); this.SuspendLayout(); // // splitContainer // this.splitContainer.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer.FixedPanel = System.Windows.Forms.FixedPanel.Panel2; this.splitContainer.IsSplitterFixed = true; this.splitContainer.Location = new System.Drawing.Point(0, 0); this.splitContainer.Name = "splitContainer"; this.splitContainer.Orientation = System.Windows.Forms.Orientation.Horizontal; this.splitContainer.Panel2Collapsed = true; this.splitContainer.Size = new System.Drawing.Size(979, 560); this.splitContainer.SplitterDistance = 483; this.splitContainer.SplitterWidth = 1; this.splitContainer.TabIndex = 0; // // MainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(979, 560); this.Controls.Add(this.splitContainer); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "MainForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; this.Text = "CodeBox"; this.Activated += new System.EventHandler(this.Form1_Activated); this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainForm_FormClosing); this.Shown += new System.EventHandler(this.Form1_Shown); ((System.ComponentModel.ISupportInitialize)(this.splitContainer)).EndInit(); this.splitContainer.ResumeLayout(false); this.ResumeLayout(false); } #endregion private SplitContainerEx splitContainer; } }
{ "content_hash": "18eea8739c094769a9bc1e87f6a51b7f", "timestamp": "", "source": "github", "line_count": 75, "max_line_length": 140, "avg_line_length": 42.12, "alnum_prop": 0.6141183918961697, "repo_name": "vorov2/slot", "id": "8c8029a5a43e697fa66356293a219e9079a80585", "size": "3161", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Slot/MainForm.Designer.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "682176" }, { "name": "HTML", "bytes": "6600" }, { "name": "SCSS", "bytes": "1203" } ], "symlink_target": "" }
#include <sys/cdefs.h> __FBSDID("$FreeBSD$"); /* * Authors: * Christian König <[email protected]> */ #include <dev/drm2/drmP.h> #include "radeon.h" int radeon_semaphore_create(struct radeon_device *rdev, struct radeon_semaphore **semaphore) { int r; *semaphore = malloc(sizeof(struct radeon_semaphore), DRM_MEM_DRIVER, M_WAITOK); if (*semaphore == NULL) { return -ENOMEM; } r = radeon_sa_bo_new(rdev, &rdev->ring_tmp_bo, &(*semaphore)->sa_bo, 8, 8, true); if (r) { free(*semaphore, DRM_MEM_DRIVER); *semaphore = NULL; return r; } (*semaphore)->waiters = 0; (*semaphore)->gpu_addr = radeon_sa_bo_gpu_addr((*semaphore)->sa_bo); *((uint64_t*)radeon_sa_bo_cpu_addr((*semaphore)->sa_bo)) = 0; return 0; } void radeon_semaphore_emit_signal(struct radeon_device *rdev, int ring, struct radeon_semaphore *semaphore) { --semaphore->waiters; radeon_semaphore_ring_emit(rdev, ring, &rdev->ring[ring], semaphore, false); } void radeon_semaphore_emit_wait(struct radeon_device *rdev, int ring, struct radeon_semaphore *semaphore) { ++semaphore->waiters; radeon_semaphore_ring_emit(rdev, ring, &rdev->ring[ring], semaphore, true); } /* caller must hold ring lock */ int radeon_semaphore_sync_rings(struct radeon_device *rdev, struct radeon_semaphore *semaphore, int signaler, int waiter) { int r; /* no need to signal and wait on the same ring */ if (signaler == waiter) { return 0; } /* prevent GPU deadlocks */ if (!rdev->ring[signaler].ready) { dev_err(rdev->dev, "Trying to sync to a disabled ring!"); return -EINVAL; } r = radeon_ring_alloc(rdev, &rdev->ring[signaler], 8); if (r) { return r; } radeon_semaphore_emit_signal(rdev, signaler, semaphore); radeon_ring_commit(rdev, &rdev->ring[signaler]); /* we assume caller has already allocated space on waiters ring */ radeon_semaphore_emit_wait(rdev, waiter, semaphore); /* for debugging lockup only, used by sysfs debug files */ rdev->ring[signaler].last_semaphore_signal_addr = semaphore->gpu_addr; rdev->ring[waiter].last_semaphore_wait_addr = semaphore->gpu_addr; return 0; } void radeon_semaphore_free(struct radeon_device *rdev, struct radeon_semaphore **semaphore, struct radeon_fence *fence) { if (semaphore == NULL || *semaphore == NULL) { return; } if ((*semaphore)->waiters > 0) { dev_err(rdev->dev, "semaphore %p has more waiters than signalers," " hardware lockup imminent!\n", *semaphore); } radeon_sa_bo_free(rdev, &(*semaphore)->sa_bo, fence); free(*semaphore, DRM_MEM_DRIVER); *semaphore = NULL; }
{ "content_hash": "463cab1dc281a1e045164d887f220302", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 77, "avg_line_length": 26.11, "alnum_prop": 0.6729222520107239, "repo_name": "jhbsz/OSI-OS", "id": "717a94a482db5c57d3899acb059bcadd7248ac49", "size": "3814", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sys/dev/drm2/radeon/radeon_semaphore.c", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ProjectTracker.DAL.Entity.ProjectEntity; namespace ProjectTracker.DAL.Entity.ResourceEntity { public class Resource : BaseEntity { public string FirstName { get; set; } public string Name { get; set; } public ICollection<ProjectTask> ProjectTasks { get; set; } public ICollection<ProjectTaskEntry> ProjectTaskEntries { get; set; } } }
{ "content_hash": "7c43a0941c636d3e1f2fe98bfdb46f5e", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 77, "avg_line_length": 28.529411764705884, "alnum_prop": 0.7175257731958763, "repo_name": "cedricjacobs/extant-cringe", "id": "a6e872d068788b618c1b79dc04c9d6e892d3e41a", "size": "487", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ProjectTracker/DAL/Entity/ResourceEntity/Resource.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "105106" } ], "symlink_target": "" }
<?php namespace Doctrine\Common\DataFixtures\Purger; use Doctrine\ORM\EntityManager; use Doctrine\ORM\Internal\CommitOrderCalculator; use Doctrine\ORM\Mapping\ClassMetadata; /** * Class responsible for purging databases of data before reloading data fixtures. * * @author Jonathan H. Wage <[email protected]> */ class ORMPurger implements PurgerInterface { /** EntityManager instance used for persistence. */ private $em; /** * Construct new purger instance. * * @param EntityManager $em EntityManager instance used for persistence. */ public function __construct(EntityManager $em = null) { $this->em = $em; } /** * Set the EntityManager instance this purger instance should use. * * @param EntityManager $em */ public function setEntityManager(EntityManager $em) { $this->em = $em; } /** @inheritDoc */ public function purge() { $classes = array(); $metadatas = $this->em->getMetadataFactory()->getAllMetadata(); foreach ($metadatas as $metadata) { if ( ! $metadata->isMappedSuperclass) { $classes[] = $metadata; } } $commitOrder = $this->getCommitOrder($this->em, $classes); // Drop association tables first $orderedTables = $this->getAssociationTables($commitOrder); // Drop tables in reverse commit order for ($i = count($commitOrder) - 1; $i >= 0; --$i) { $class = $commitOrder[$i]; if (($class->isInheritanceTypeSingleTable() && $class->name != $class->rootEntityName) || $class->isMappedSuperclass) { continue; } $orderedTables[] = $class->getTableName(); } $platform = $this->em->getConnection()->getDatabasePlatform(); foreach($orderedTables as $tbl) { $this->em->getConnection()->executeUpdate($platform->getTruncateTableSQL($tbl, true)); } } private function getCommitOrder(EntityManager $em, array $classes) { $calc = new CommitOrderCalculator; foreach ($classes as $class) { $calc->addClass($class); foreach ($class->associationMappings as $assoc) { if ($assoc['isOwningSide']) { $targetClass = $em->getClassMetadata($assoc['targetEntity']); if ( ! $calc->hasClass($targetClass->name)) { $calc->addClass($targetClass); } // add dependency ($targetClass before $class) $calc->addDependency($targetClass, $class); } } } return $calc->getCommitOrder(); } private function getAssociationTables(array $classes) { $associationTables = array(); foreach ($classes as $class) { foreach ($class->associationMappings as $assoc) { if ($assoc['isOwningSide'] && $assoc['type'] == ClassMetadata::MANY_TO_MANY) { $associationTables[] = $assoc['joinTable']['name']; } } } return $associationTables; } }
{ "content_hash": "dc2402a11df2e90f7b03d39abb26e026", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 98, "avg_line_length": 28.58407079646018, "alnum_prop": 0.5603715170278638, "repo_name": "BEmmanuel/BlogBundle4Symfony", "id": "a580c1f7f07644d8a59a0e56cdde7ef0c0fcee89", "size": "4204", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "vendor/doctrine-fixtures/lib/Doctrine/Common/DataFixtures/Purger/ORMPurger.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "78908" } ], "symlink_target": "" }
<?php namespace Hubzero\Form; use Exception; use Lang; // Detect if we have full UTF-8 and unicode PCRE support. if (!defined('JCOMPAT_UNICODE_PROPERTIES')) { define('JCOMPAT_UNICODE_PROPERTIES', (bool) @preg_match('/\pL/u', 'a')); } /** * Form Rule class. * * Inspired by Joomla's JFormRule class * * @todo Rewrite all of this. */ class Rule { /** * The regular expression to use in testing a form field value. * * @var string */ protected $regex; /** * The regular expression modifiers to use when testing a form field value. * * @var string */ protected $modifiers; /** * Method to test the value. * * @param object &$element The SimpleXMLElement object representing the <field /> tag for the form field object. * @param mixed $value The form field value to validate. * @param string $group The field name group control value. This acts as as an array container for the field. * For example if the field has name="foo" and the group value is set to "bar" then the * full field name would end up being "bar[foo]". * @param object &$input An optional Registry object with the entire data set to validate against the entire form. * @param object &$form The form object for which the field is being tested. * @return boolean True if the value is valid, false otherwise. * @throws Exception on invalid rule. */ public function test(&$element, $value, $group = null, &$input = null, &$form = null) { // Check for a valid regex. if (empty($this->regex)) { throw new Exception(Lang::txt('JLIB_FORM_INVALID_FORM_RULE', get_class($this))); } // Add unicode property support if available. if (JCOMPAT_UNICODE_PROPERTIES) { $this->modifiers = (strpos($this->modifiers, 'u') !== false) ? $this->modifiers : $this->modifiers . 'u'; } // Test the value against the regular expression. if (preg_match(chr(1) . $this->regex . chr(1) . $this->modifiers, $value)) { return true; } return false; } }
{ "content_hash": "d1009d8c3e381dfc1024cffeca7f8fa4", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 122, "avg_line_length": 28.54794520547945, "alnum_prop": 0.6396353166986565, "repo_name": "zweidner/framework", "id": "369907a41197ff1da8ea012dee4a1a2249afb48d", "size": "2230", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Form/Rule.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "3792916" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in Biblthca Mycol. 133: 182 (1990) #### Original name Phaeosphaeria glebosoverrucosa Nograsek ### Remarks null
{ "content_hash": "1a9a9bfb3be55e21297161578d8bec0f", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 13.153846153846153, "alnum_prop": 0.7368421052631579, "repo_name": "mdoering/backbone", "id": "14acd5ea288d5bd931776adfb9658d76368a35a5", "size": "234", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Dothideomycetes/Pleosporales/Phaeosphaeriaceae/Phaeosphaeria/Phaeosphaeria glebosoverrucosa/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
/* runtime.hpp provides C++ runtime support functions when building a pure C * version of yaSSL, user must define YASSL_PURE_C */ #ifndef yaSSL_NEW_HPP #define yaSSL_NEW_HPP #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifdef __sun // Handler for pure virtual functions namespace __Crun { void pure_error(void); } // namespace __Crun #endif // __sun #if defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER)) #if __GNUC__ > 2 extern "C" { #if defined(DO_TAOCRYPT_KERNEL_MODE) #include "kernelc.hpp" #endif int __cxa_pure_virtual () __attribute__ ((weak)); } // extern "C" #endif // __GNUC__ > 2 #endif // compiler check #endif // yaSSL_NEW_HPP
{ "content_hash": "3e0607367b9837cbb450f06cc77a9174", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 76, "avg_line_length": 16.829268292682926, "alnum_prop": 0.644927536231884, "repo_name": "billwiliams/Yui", "id": "328c8e9e978cd7d1eb8c49eac9f5fd7489001e69", "size": "1441", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "node_modules/mariasql/deps/libmariadbclient/extra/yassl/taocrypt/include/runtime.hpp", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package com.sop4j.base.google.common.util.concurrent; import com.sop4j.base.google.common.annotations.Beta; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * An object with an operational state, plus asynchronous {@link #startAsync()} and * {@link #stopAsync()} lifecycle methods to transition between states. Example services include * webservers, RPC servers and timers. * * <p>The normal lifecycle of a service is: * <ul> * <li>{@linkplain State#NEW NEW} -&gt; * <li>{@linkplain State#STARTING STARTING} -&gt; * <li>{@linkplain State#RUNNING RUNNING} -&gt; * <li>{@linkplain State#STOPPING STOPPING} -&gt; * <li>{@linkplain State#TERMINATED TERMINATED} * </ul> * * <p>There are deviations from this if there are failures or if {@link Service#stopAsync} is called * before the {@link Service} reaches the {@linkplain State#RUNNING RUNNING} state. The set of legal * transitions form a <a href="http://en.wikipedia.org/wiki/Directed_acyclic_graph">DAG</a>, * therefore every method of the listener will be called at most once. N.B. The {@link State#FAILED} * and {@link State#TERMINATED} states are terminal states, once a service enters either of these * states it cannot ever leave them. * * <p>Implementors of this interface are strongly encouraged to extend one of the abstract classes * in this package which implement this interface and make the threading and state management * easier. * * @author Jesse Wilson * @author Luke Sandberg * @since 9.0 (in 1.0 as {@code com.sop4j.base.google.common.base.Service}) */ @Beta public interface Service { /** * If the service state is {@link State#NEW}, this initiates service startup and returns * immediately. If the service has already been started, this method returns immediately without * taking action. A stopped service may not be restarted. * * @deprecated Use {@link #startAsync()} instead of this method to start the {@link Service} or * use a {@link Listener} to asynchronously wait for service startup. * * @return a future for the startup result, regardless of whether this call initiated startup. * Calling {@link ListenableFuture#get} will block until the service has finished * starting, and returns one of {@link State#RUNNING}, {@link State#STOPPING} or * {@link State#TERMINATED}. If the service fails to start, {@link ListenableFuture#get} * will throw an {@link ExecutionException}, and the service's state will be * {@link State#FAILED}. If it has already finished starting, {@link ListenableFuture#get} * returns immediately. Cancelling this future has no effect on the service. */ @Deprecated ListenableFuture<State> start(); /** * Initiates service startup (if necessary), returning once the service has finished starting. * Unlike calling {@code start().get()}, this method throws no checked exceptions, and it cannot * be {@linkplain Thread#interrupt interrupted}. * * @deprecated Use {@link #startAsync()} and {@link #awaitRunning} instead of this method. * * @throws UncheckedExecutionException if startup failed * @return the state of the service when startup finished. */ @Deprecated State startAndWait(); /** * If the service state is {@link State#NEW}, this initiates service startup and returns * immediately. A stopped service may not be restarted. * * @return this * @throws IllegalStateException if the service is not {@link State#NEW} * * @since 15.0 */ Service startAsync(); /** * Returns {@code true} if this service is {@linkplain State#RUNNING running}. */ boolean isRunning(); /** * Returns the lifecycle state of the service. */ State state(); /** * If the service is {@linkplain State#STARTING starting} or {@linkplain State#RUNNING running}, * this initiates service shutdown and returns immediately. If the service is * {@linkplain State#NEW new}, it is {@linkplain State#TERMINATED terminated} without having been * started nor stopped. If the service has already been stopped, this method returns immediately * without taking action. * * @deprecated Use {@link #stopAsync} instead of this method to initiate service shutdown or use a * service {@link Listener} to asynchronously wait for service shutdown. * * @return a future for the shutdown result, regardless of whether this call initiated shutdown. * Calling {@link ListenableFuture#get} will block until the service has finished shutting * down, and either returns {@link State#TERMINATED} or throws an * {@link ExecutionException}. If it has already finished stopping, * {@link ListenableFuture#get} returns immediately. Cancelling this future has no effect * on the service. */ @Deprecated ListenableFuture<State> stop(); /** * Initiates service shutdown (if necessary), returning once the service has finished stopping. If * this is {@link State#STARTING}, startup will be cancelled. If this is {@link State#NEW}, it is * {@link State#TERMINATED terminated} without having been started nor stopped. Unlike calling * {@code stop().get()}, this method throws no checked exceptions. * * @deprecated Use {@link #stopAsync} and {@link #awaitTerminated} instead of this method. * * @throws UncheckedExecutionException if the service has failed or fails during shutdown * @return the state of the service when shutdown finished. */ @Deprecated State stopAndWait(); /** * If the service is {@linkplain State#STARTING starting} or {@linkplain State#RUNNING running}, * this initiates service shutdown and returns immediately. If the service is * {@linkplain State#NEW new}, it is {@linkplain State#TERMINATED terminated} without having been * started nor stopped. If the service has already been stopped, this method returns immediately * without taking action. * * @return this * @since 15.0 */ Service stopAsync(); /** * Waits for the {@link Service} to reach the {@linkplain State#RUNNING running state}. * * @throws IllegalStateException if the service reaches a state from which it is not possible to * enter the {@link State#RUNNING} state. e.g. if the {@code state} is * {@code State#TERMINATED} when this method is called then this will throw an * IllegalStateException. * * @since 15.0 */ void awaitRunning(); /** * Waits for the {@link Service} to reach the {@linkplain State#RUNNING running state} for no * more than the given time. * * @param timeout the maximum time to wait * @param unit the time unit of the timeout argument * @throws TimeoutException if the service has not reached the given state within the deadline * @throws IllegalStateException if the service reaches a state from which it is not possible to * enter the {@link State#RUNNING RUNNING} state. e.g. if the {@code state} is * {@code State#TERMINATED} when this method is called then this will throw an * IllegalStateException. * * @since 15.0 */ void awaitRunning(long timeout, TimeUnit unit) throws TimeoutException; /** * Waits for the {@link Service} to reach the {@linkplain State#TERMINATED terminated state}. * * @throws IllegalStateException if the service {@linkplain State#FAILED fails}. * * @since 15.0 */ void awaitTerminated(); /** * Waits for the {@link Service} to reach a terminal state (either * {@link Service.State#TERMINATED terminated} or {@link Service.State#FAILED failed}) for no * more than the given time. * * @param timeout the maximum time to wait * @param unit the time unit of the timeout argument * @throws TimeoutException if the service has not reached the given state within the deadline * @throws IllegalStateException if the service {@linkplain State#FAILED fails}. * @since 15.0 */ void awaitTerminated(long timeout, TimeUnit unit) throws TimeoutException; /** * Returns the {@link Throwable} that caused this service to fail. * * @throws IllegalStateException if this service's state isn't {@linkplain State#FAILED FAILED}. * * @since 14.0 */ Throwable failureCause(); /** * Registers a {@link Listener} to be {@linkplain Executor#execute executed} on the given * executor. The listener will have the corresponding transition method called whenever the * service changes state. The listener will not have previous state changes replayed, so it is * suggested that listeners are added before the service starts. * * <p>There is no guaranteed ordering of execution of listeners, but any listener added through * this method is guaranteed to be called whenever there is a state change. * * <p>Exceptions thrown by a listener will be propagated up to the executor. Any exception thrown * during {@code Executor.execute} (e.g., a {@code RejectedExecutionException} or an exception * thrown by {@linkplain MoreExecutors#sameThreadExecutor inline execution}) will be caught and * logged. * * @param listener the listener to run when the service changes state is complete * @param executor the executor in which the listeners callback methods will be run. For fast, * lightweight listeners that would be safe to execute in any thread, consider * {@link MoreExecutors#sameThreadExecutor}. * @since 13.0 */ void addListener(Listener listener, Executor executor); /** * The lifecycle states of a service. * * <p>The ordering of the {@link State} enum is defined such that if there is a state transition * from {@code A -> B} then {@code A.compareTo(B} < 0}. N.B. The converse is not true, i.e. if * {@code A.compareTo(B} < 0} then there is <b>not</b> guaranteed to be a valid state transition * {@code A -> B}. * * @since 9.0 (in 1.0 as {@code com.sop4j.base.google.common.base.Service.State}) */ @Beta // should come out of Beta when Service does enum State { /** * A service in this state is inactive. It does minimal work and consumes * minimal resources. */ NEW { @Override boolean isTerminal() { return false; } }, /** * A service in this state is transitioning to {@link #RUNNING}. */ STARTING { @Override boolean isTerminal() { return false; } }, /** * A service in this state is operational. */ RUNNING { @Override boolean isTerminal() { return false; } }, /** * A service in this state is transitioning to {@link #TERMINATED}. */ STOPPING { @Override boolean isTerminal() { return false; } }, /** * A service in this state has completed execution normally. It does minimal work and consumes * minimal resources. */ TERMINATED { @Override boolean isTerminal() { return true; } }, /** * A service in this state has encountered a problem and may not be operational. It cannot be * started nor stopped. */ FAILED { @Override boolean isTerminal() { return true; } }; /** Returns true if this state is terminal. */ abstract boolean isTerminal(); } /** * A listener for the various state changes that a {@link Service} goes through in its lifecycle. * * <p>All methods are no-ops by default, implementors should override the ones they care about. * * @author Luke Sandberg * @since 15.0 (present as an interface in 13.0) */ @Beta // should come out of Beta when Service does abstract class Listener { /** * Called when the service transitions from {@linkplain State#NEW NEW} to * {@linkplain State#STARTING STARTING}. This occurs when {@link Service#start} or * {@link Service#startAndWait} is called the first time. */ public void starting() {} /** * Called when the service transitions from {@linkplain State#STARTING STARTING} to * {@linkplain State#RUNNING RUNNING}. This occurs when a service has successfully started. */ public void running() {} /** * Called when the service transitions to the {@linkplain State#STOPPING STOPPING} state. The * only valid values for {@code from} are {@linkplain State#STARTING STARTING} or * {@linkplain State#RUNNING RUNNING}. This occurs when {@link Service#stop} is called. * * @param from The previous state that is being transitioned from. */ public void stopping(State from) {} /** * Called when the service transitions to the {@linkplain State#TERMINATED TERMINATED} state. * The {@linkplain State#TERMINATED TERMINATED} state is a terminal state in the transition * diagram. Therefore, if this method is called, no other methods will be called on the * {@link Listener}. * * @param from The previous state that is being transitioned from. The only valid values for * this are {@linkplain State#NEW NEW}, {@linkplain State#RUNNING RUNNING} or * {@linkplain State#STOPPING STOPPING}. */ public void terminated(State from) {} /** * Called when the service transitions to the {@linkplain State#FAILED FAILED} state. The * {@linkplain State#FAILED FAILED} state is a terminal state in the transition diagram. * Therefore, if this method is called, no other methods will be called on the {@link Listener}. * * @param from The previous state that is being transitioned from. Failure can occur in any * state with the exception of {@linkplain State#NEW NEW} or * {@linkplain State#TERMINATED TERMINATED}. * @param failure The exception that caused the failure. */ public void failed(State from, Throwable failure) {} } }
{ "content_hash": "fa261b81a9e1eeb3a8c7085c3198b519", "timestamp": "", "source": "github", "line_count": 348, "max_line_length": 100, "avg_line_length": 40.37356321839081, "alnum_prop": 0.6874021352313168, "repo_name": "wspeirs/sop4j-base", "id": "a478f757c6d15b8c765e340e3b8916cd2d42a26b", "size": "14650", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/sop4j/base/google/common/util/concurrent/Service.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "10731267" } ], "symlink_target": "" }
package main import ( "os" "time" "github.com/cloudfoundry/binary-buildpack/src/binary/supply" "github.com/cloudfoundry/libbuildpack" ) func main() { logger := libbuildpack.NewLogger(os.Stdout) buildpackDir, err := libbuildpack.GetBuildpackDir() if err != nil { logger.Error("Unable to determine buildpack directory: %s", err.Error()) os.Exit(9) } manifest, err := libbuildpack.NewManifest(buildpackDir, logger, time.Now()) if err != nil { logger.Error("Unable to load buildpack manifest: %s", err.Error()) os.Exit(10) } stager := libbuildpack.NewStager(os.Args[1:], logger, manifest) if err := stager.CheckBuildpackValid(); err != nil { os.Exit(11) } if err = stager.SetStagingEnvironment(); err != nil { logger.Error("Unable to setup environment variables: %s", err.Error()) os.Exit(13) } supplier := supply.New(stager, manifest, logger) if err := supplier.Run(); err != nil { os.Exit(14) } if err := stager.WriteConfigYml(nil); err != nil { logger.Error("Error writing config.yml: %s", err.Error()) os.Exit(15) } stager.StagingComplete() }
{ "content_hash": "9c62f02a8bd498d53c29ae88ec5581da", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 76, "avg_line_length": 22.387755102040817, "alnum_prop": 0.6818596171376481, "repo_name": "cloudfoundry/binary-buildpack", "id": "d87e8a8c3d06481a0dfccf7166202e9a11537175", "size": "1097", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/binary/supply/cli/main.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "989" }, { "name": "Go", "bytes": "16969" }, { "name": "Procfile", "bytes": "32" }, { "name": "Ruby", "bytes": "778" }, { "name": "Shell", "bytes": "16103" } ], "symlink_target": "" }
import importlib import pianette.config import sys from pianette.Pianette import Pianette from pianette.PianetteArgumentParser import PianetteArgumentParser from pianette.utils import Debug Debug.println("INFO", " ") Debug.println("INFO", " ################################## ") Debug.println("INFO", " | PIANETTE | ") Debug.println("INFO", " ################################## ") Debug.println("INFO", " ") configobj = pianette.config.get_all_configobj() parser = PianetteArgumentParser(configobj=configobj) args = parser.parse_args() # Instanciate the global Pianette # Its responsibility is to translate Piano actions to Console actions pianette = Pianette(configobj=configobj) # We MUST select a player before we select a game. # This allow for per-player mappings # The game can be changed afterwards, but not the player, as we don't expect # to be able to unplug the controller from the console. pianette.select_player(args.selected_player) pianette.select_game(args.selected_game) if args.enabled_sources is not None: for source in args.enabled_sources: pianette.load_source(source) # Run the main loop of interactive Pianette Debug.println("NOTICE", "Entering main loop") pianette.cmd.cmdloop()
{ "content_hash": "e1c22ae416ad140a9d607d04d11e935a", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 76, "avg_line_length": 33.648648648648646, "alnum_prop": 0.7132530120481928, "repo_name": "tchapi/pianette", "id": "3dc86c2ec6e724ee83aaa26e05e8506e067dbd26", "size": "1524", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "main.py", "mode": "33261", "license": "mit", "language": [ { "name": "Arduino", "bytes": "4155" }, { "name": "CSS", "bytes": "5331" }, { "name": "HTML", "bytes": "14483" }, { "name": "JavaScript", "bytes": "2539" }, { "name": "Python", "bytes": "76257" }, { "name": "Shell", "bytes": "1708" } ], "symlink_target": "" }
class Project < ActiveRecord::Base belongs_to :user has_many :tasks, -> { order(position: :asc) }, dependent: :destroy validates :name, presence: true, length: { maximum: 250 } end
{ "content_hash": "fae3b8ba0638daff3c8ad9bc1337efed", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 68, "avg_line_length": 31.333333333333332, "alnum_prop": 0.6861702127659575, "repo_name": "fanantoxa/todo-app", "id": "81f8adb3c97576f06c8d2377d2a684e877b4c331", "size": "188", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/models/project.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "7358" }, { "name": "CoffeeScript", "bytes": "34706" }, { "name": "HTML", "bytes": "15952" }, { "name": "Ruby", "bytes": "95766" } ], "symlink_target": "" }
package org.apache.beam.runners.dataflow.worker.fn; import java.util.concurrent.SynchronousQueue; import java.util.function.Function; import java.util.function.Supplier; import org.apache.beam.model.fnexecution.v1.BeamFnApi; import org.apache.beam.model.fnexecution.v1.BeamFnControlGrpc; import org.apache.beam.model.pipeline.v1.Endpoints; import org.apache.beam.runners.dataflow.worker.fn.grpc.BeamFnService; import org.apache.beam.runners.fnexecution.HeaderAccessor; import org.apache.beam.runners.fnexecution.control.FnApiControlClient; import org.apache.beam.vendor.grpc.v1p21p0.io.grpc.stub.StreamObserver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Starts a gRPC server hosting the BeamFnControl service. Clients returned by {@link #get()} are * owned by the caller and must be shutdown. */ public class BeamFnControlService extends BeamFnControlGrpc.BeamFnControlImplBase implements BeamFnService, Supplier<FnApiControlClient> { private static final Logger LOGGER = LoggerFactory.getLogger(BeamFnControlService.class); private final Endpoints.ApiServiceDescriptor apiServiceDescriptor; private final Function< StreamObserver<BeamFnApi.InstructionRequest>, StreamObserver<BeamFnApi.InstructionRequest>> streamObserverFactory; private final SynchronousQueue<FnApiControlClient> newClients; private final HeaderAccessor headerAccessor; public BeamFnControlService( Endpoints.ApiServiceDescriptor serviceDescriptor, Function< StreamObserver<BeamFnApi.InstructionRequest>, StreamObserver<BeamFnApi.InstructionRequest>> streamObserverFactory, HeaderAccessor headerAccessor) throws Exception { this.headerAccessor = headerAccessor; this.newClients = new SynchronousQueue<>(true /* fair */); this.streamObserverFactory = streamObserverFactory; this.apiServiceDescriptor = serviceDescriptor; LOGGER.info("Launched Beam Fn Control service {}", this.apiServiceDescriptor); } @Override public Endpoints.ApiServiceDescriptor getApiServiceDescriptor() { return apiServiceDescriptor; } @Override public StreamObserver<BeamFnApi.InstructionResponse> control( StreamObserver<BeamFnApi.InstructionRequest> outboundObserver) { LOGGER.info("Beam Fn Control client connected with id {}", headerAccessor.getSdkWorkerId()); FnApiControlClient newClient = FnApiControlClient.forRequestObserver( headerAccessor.getSdkWorkerId(), streamObserverFactory.apply(outboundObserver)); try { newClients.put(newClient); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } return newClient.asResponseObserver(); } /** Callers own the client returned and must shut it down before shutting down the service. */ @Override public FnApiControlClient get() { try { return newClients.take(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } } @Override public void close() throws Exception { // TODO: Track multiple clients and disconnect them cleanly instead of forcing termination } }
{ "content_hash": "8c9663e2cbe51fb6de28cdfcac852769", "timestamp": "", "source": "github", "line_count": 83, "max_line_length": 97, "avg_line_length": 39.12048192771084, "alnum_prop": 0.7631659993840468, "repo_name": "markflyhigh/incubator-beam", "id": "d701083977721c152e3c364d4a8ffbdc33246595", "size": "4052", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "runners/google-cloud-dataflow-java/worker/src/main/java/org/apache/beam/runners/dataflow/worker/fn/BeamFnControlService.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "1596" }, { "name": "CSS", "bytes": "40964" }, { "name": "Dockerfile", "bytes": "22983" }, { "name": "FreeMarker", "bytes": "7428" }, { "name": "Go", "bytes": "2508482" }, { "name": "Groovy", "bytes": "300669" }, { "name": "HTML", "bytes": "54277" }, { "name": "Java", "bytes": "24796055" }, { "name": "JavaScript", "bytes": "16472" }, { "name": "Jupyter Notebook", "bytes": "54182" }, { "name": "Python", "bytes": "4544133" }, { "name": "Ruby", "bytes": "4099" }, { "name": "Shell", "bytes": "180209" } ], "symlink_target": "" }
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.contentwarehouse.v1.model; /** * Model definition for LensDiscoveryStyleStyleImageTypeSignalsStyleImageTypePrediction. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the contentwarehouse API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class LensDiscoveryStyleStyleImageTypeSignalsStyleImageTypePrediction extends com.google.api.client.json.GenericJson { /** * Style image type confidence discretized into range [0, 100]. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Integer discretizedStyleImageTypeConfidence; /** * Predicted style image type. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String styleImageType; /** * Style image type confidence discretized into range [0, 100]. * @return value or {@code null} for none */ public java.lang.Integer getDiscretizedStyleImageTypeConfidence() { return discretizedStyleImageTypeConfidence; } /** * Style image type confidence discretized into range [0, 100]. * @param discretizedStyleImageTypeConfidence discretizedStyleImageTypeConfidence or {@code null} for none */ public LensDiscoveryStyleStyleImageTypeSignalsStyleImageTypePrediction setDiscretizedStyleImageTypeConfidence(java.lang.Integer discretizedStyleImageTypeConfidence) { this.discretizedStyleImageTypeConfidence = discretizedStyleImageTypeConfidence; return this; } /** * Predicted style image type. * @return value or {@code null} for none */ public java.lang.String getStyleImageType() { return styleImageType; } /** * Predicted style image type. * @param styleImageType styleImageType or {@code null} for none */ public LensDiscoveryStyleStyleImageTypeSignalsStyleImageTypePrediction setStyleImageType(java.lang.String styleImageType) { this.styleImageType = styleImageType; return this; } @Override public LensDiscoveryStyleStyleImageTypeSignalsStyleImageTypePrediction set(String fieldName, Object value) { return (LensDiscoveryStyleStyleImageTypeSignalsStyleImageTypePrediction) super.set(fieldName, value); } @Override public LensDiscoveryStyleStyleImageTypeSignalsStyleImageTypePrediction clone() { return (LensDiscoveryStyleStyleImageTypeSignalsStyleImageTypePrediction) super.clone(); } }
{ "content_hash": "53af1f71f78afd4917f8a26d0a4b371e", "timestamp": "", "source": "github", "line_count": 90, "max_line_length": 182, "avg_line_length": 37.8, "alnum_prop": 0.7657260435038212, "repo_name": "googleapis/google-api-java-client-services", "id": "7a4cb7ca821a81e9d74b856db014eea4c1226ba7", "size": "3402", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "clients/google-api-services-contentwarehouse/v1/2.0.0/com/google/api/services/contentwarehouse/v1/model/LensDiscoveryStyleStyleImageTypeSignalsStyleImageTypePrediction.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php namespace SEIDS\Arrays; //============================================================================== // PHP SEIDS: Supplementary, Easily Interchangeable Data Structures // // Copyright 2015, Daniel A.C. Martin // Distributed under the MIT License. // (See LICENSE file for details.) //============================================================================== class InvalidIndexException extends \RuntimeException implements ExceptionInterface { }
{ "content_hash": "ab7614bbcbbd90d5b9dde3ea3c80fde6", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 83, "avg_line_length": 38.666666666666664, "alnum_prop": 0.5086206896551724, "repo_name": "daniel-ac-martin/php-seids", "id": "c47f336d7ea29e98b4adb16b21e15f437696cc8f", "size": "464", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/SEIDS/Arrays/InvalidIndexException.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "150154" } ], "symlink_target": "" }
var R = require('ramda'); var path = require('path'); var lutils = require('loader-utils'); var svgToReact = require('./index'); var titleCase = require('./util/title-case'); function titleCaseBasename (filepath, delim) { var ext = path.extname(filepath); var base = path.basename(filepath, ext); return titleCase(delim)(base); } function mapKeyValue (acc, cur) { var keyValue = cur.split(':'); acc[keyValue[0]] = keyValue[1]; return acc; } module.exports = function svgReactLoader (source) { var context = this; var callback = context.async(); var ctxOpts = context.svgReactLoader; var filters = ctxOpts && ctxOpts.filters || []; var query = lutils.getOptions(context); var rsrcQuery = context.resourceQuery && lutils.parseQuery(context.resourceQuery); var params = R.merge(query || {}, rsrcQuery || {}); var titleCaseDelim = params.titleCaseDelim || /[._-]/; var displayName = params.name || titleCaseBasename(context.resourcePath, titleCaseDelim); var tagname = params.tag; var tagprops = params.props || params.attrs; var propsMap = params.propsMap || {}; var raw = params.raw; var xmlnsTest = params.xmlnsTest; var classIdPrefix = params.classIdPrefix || false; context.cacheable(); var options = { displayName: displayName }; if (typeof raw !== 'undefined') { options.raw = raw; } if (typeof xmlnsTest === 'string') { options.xmlnsTest = new RegExp(xmlnsTest); } if (Array.isArray(tagprops)) { tagprops = tagprops. reduce(mapKeyValue, {}); } if (tagname || tagprops) { options.root = {}; if (tagname) { options.root.tagname = tagname; } if (tagprops) { options.root.props = tagprops; } } options.propsMap = Array.isArray(propsMap)? propsMap.reduce(mapKeyValue, {}) : propsMap; options.classIdPrefix = classIdPrefix === true ? displayName + '__' : typeof classIdPref === 'string' ? lutils.interpolatename(context, classIdPrefix) : classIdPrefix; if (params.filters) { filters = filters. concat( params. filters. map(function (name) { return typeof name === 'function' ? name : require(context.resolveSync(context.context, name)); }) ); } options.filters = filters; svgToReact(options, source). subscribe( function (result) { callback(null, result); }, callback ); };
{ "content_hash": "29e44dd75b1467e4295ba0597fb73f39", "timestamp": "", "source": "github", "line_count": 96, "max_line_length": 96, "avg_line_length": 29.25, "alnum_prop": 0.5541310541310541, "repo_name": "jhamlet/svg-react-loader", "id": "1333e5e9e287e51ad7def5d97576d5458dfd1e45", "size": "2808", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/loader.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "40669" }, { "name": "Shell", "bytes": "227" } ], "symlink_target": "" }
get_filename_component( CMAKE_CURRENT_LIST_FILENAME ${CMAKE_CURRENT_LIST_FILE} NAME_WE ) if( ${CMAKE_CURRENT_LIST_FILENAME}_FILE_INCLUDED ) return() endif( ${CMAKE_CURRENT_LIST_FILENAME}_FILE_INCLUDED ) set( ${CMAKE_CURRENT_LIST_FILENAME}_FILE_INCLUDED 1 ) set( proj ITK ) # Sanity checks. if( DEFINED ${proj}_DIR AND NOT EXISTS ${${proj}_DIR} ) message( FATAL_ERROR "${proj}_DIR variable is defined but corresponds to a nonexistent directory (${${proj}_DIR})" ) endif( DEFINED ${proj}_DIR AND NOT EXISTS ${${proj}_DIR} ) set( ${proj}_DEPENDENCIES "" ) # Include dependent projects, if any. TubeTKMacroCheckExternalProjectDependency( ${proj} ) if( NOT DEFINED ${proj}_DIR AND NOT ${USE_SYSTEM_${proj}} ) set( ${proj}_SOURCE_DIR ${CMAKE_BINARY_DIR}/${proj} ) set( ${proj}_DIR ${CMAKE_BINARY_DIR}/${proj}-build ) set( TubeTK_ITKHDF5_VALGRIND_ARGS ) if( TubeTK_USE_VALGRIND ) list( APPEND TubeTK_ITKHDF5_VALGRIND_ARGS -DHDF5_ENABLE_USING_MEMCHECKER:BOOL=ON ) endif( TubeTK_USE_VALGRIND ) ExternalProject_Add( ${proj} GIT_REPOSITORY ${${proj}_URL} GIT_TAG ${${proj}_HASH_OR_TAG} DOWNLOAD_DIR ${${proj}_SOURCE_DIR} SOURCE_DIR ${${proj}_SOURCE_DIR} BINARY_DIR ${${proj}_DIR} INSTALL_DIR ${${proj}_DIR} LOG_DOWNLOAD 1 LOG_UPDATE 0 LOG_CONFIGURE 0 LOG_BUILD 0 LOG_TEST 0 LOG_INSTALL 0 CMAKE_GENERATOR ${gen} CMAKE_ARGS -DCMAKE_C_COMPILER:FILEPATH=${CMAKE_C_COMPILER} -DCMAKE_CXX_COMPILER:FILEPATH=${CMAKE_CXX_COMPILER} -DCMAKE_C_FLAGS:STRING=${CMAKE_C_FLAGS} -DCMAKE_CXX_FLAGS:STRING=${CMAKE_CXX_FLAGS} -DCMAKE_EXE_LINKER_FLAGS:STRING=${CMAKE_EXE_LINKER_FLAGS} -DCMAKE_SHARED_LINKER_FLAGS:STRING=${CMAKE_SHARED_LINKER_FLAGS} -DCMAKE_BUILD_TYPE:STRING=${build_type} ${CMAKE_OSX_EXTERNAL_PROJECT_ARGS} -DBUILD_SHARED_LIBS:BOOL=${shared} -DBUILD_EXAMPLES:BOOL=OFF -DBUILD_TESTING:BOOL=OFF -DITKV3_COMPATIBILITY:BOOL=ON -DITK_BUILD_DEFAULT_MODULES:BOOL=ON -DITK_INSTALL_NO_DEVELOPMENT:BOOL=ON -DITK_LEGACY_REMOVE:BOOL=OFF -DKWSYS_USE_MD5:BOOL=ON -DModule_ITKReview:BOOL=ON ${TubeTK_ITKHDF5_VALGRIND_ARGS} INSTALL_COMMAND "" ) else( NOT DEFINED ${proj}_DIR AND NOT ${USE_SYSTEM_${proj}} ) if( ${USE_SYSTEM_${proj}} ) find_package( ${proj} REQUIRED ) endif( ${USE_SYSTEM_${proj}} ) TubeTKMacroEmptyExternalProject( ${proj} "${${proj}_DEPENDENCIES}" ) endif( NOT DEFINED ${proj}_DIR AND NOT ${USE_SYSTEM_${proj}} ) list( APPEND TubeTK_EXTERNAL_PROJECTS_ARGS -D${proj}_DIR:PATH=${${proj}_DIR} )
{ "content_hash": "f937b299ad6ea9b9ee2f848d46cc35a6", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 118, "avg_line_length": 35.54794520547945, "alnum_prop": 0.6655105973025048, "repo_name": "matthieuheitz/TubeTK", "id": "b7fd93d3a9b880d6c88508d46551928d60b47428", "size": "3480", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "CMake/Superbuild/External_ITK.cmake", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "114312" }, { "name": "C++", "bytes": "3293954" }, { "name": "CSS", "bytes": "17428" }, { "name": "Python", "bytes": "283223" }, { "name": "Shell", "bytes": "34482" }, { "name": "XSLT", "bytes": "8636" } ], "symlink_target": "" }
<?php namespace Drupal\views\Plugin\Derivative; use Drupal\Component\Plugin\Derivative\DeriverBase; use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface; use Drupal\views\Plugin\views\display\DisplayMenuInterface; use Drupal\views\Views; use Drupal\Core\Entity\EntityStorageInterface; use Symfony\Component\DependencyInjection\ContainerInterface; /** * Provides menu links for Views. * * @see \Drupal\views\Plugin\Menu\ViewsMenuLink */ class ViewsMenuLink extends DeriverBase implements ContainerDeriverInterface { /** * The view storage. * * @var \Drupal\Core\Entity\EntityStorageInterface */ protected $viewStorage; /** * Constructs a \Drupal\views\Plugin\Derivative\ViewsLocalTask instance. * * @param \Drupal\Core\Entity\EntityStorageInterface $view_storage * The view storage. */ public function __construct(EntityStorageInterface $view_storage) { $this->viewStorage = $view_storage; } /** * {@inheritdoc} */ public static function create(ContainerInterface $container, $base_plugin_id) { return new static( $container->get('entity_type.manager')->getStorage('view') ); } /** * {@inheritdoc} */ public function getDerivativeDefinitions($base_plugin_definition) { $links = []; $views = Views::getApplicableViews('uses_menu_links'); foreach ($views as $data) { [$view_id, $display_id] = $data; /** @var \Drupal\views\ViewExecutable $executable */ $executable = $this->viewStorage->load($view_id)->getExecutable(); $executable->initDisplay(); $display = $executable->displayHandlers->get($display_id); if (($display instanceof DisplayMenuInterface) && ($result = $display->getMenuLinks())) { foreach ($result as $link_id => $link) { $links[$link_id] = $link + $base_plugin_definition; } } } return $links; } }
{ "content_hash": "80e9a6fd979af05523e70e8091e0bae2", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 95, "avg_line_length": 27.565217391304348, "alnum_prop": 0.6798107255520505, "repo_name": "electric-eloquence/fepper-drupal", "id": "7ddca09b3e8195cc270ebff15b5039a361d4c766", "size": "1902", "binary": false, "copies": "9", "ref": "refs/heads/dev", "path": "backend/drupal/core/modules/views/src/Plugin/Derivative/ViewsMenuLink.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2300765" }, { "name": "HTML", "bytes": "68444" }, { "name": "JavaScript", "bytes": "2453602" }, { "name": "Mustache", "bytes": "40698" }, { "name": "PHP", "bytes": "41684915" }, { "name": "PowerShell", "bytes": "755" }, { "name": "Shell", "bytes": "72896" }, { "name": "Stylus", "bytes": "32803" }, { "name": "Twig", "bytes": "1820730" }, { "name": "VBScript", "bytes": "466" } ], "symlink_target": "" }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("02. ReverseString")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("02. ReverseString")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d252e8a6-20fd-45e4-b6f2-ce26708ed662")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
{ "content_hash": "da41754958d9c0ceb5275e594644e759", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 84, "avg_line_length": 39.083333333333336, "alnum_prop": 0.744136460554371, "repo_name": "dushka-dragoeva/Telerik", "id": "e14185a4ce5335f8bd8d620523821cc4f0c70564", "size": "1410", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Homeworks/CSharp/C#PartTow/Strings-And-Text-Processing/02. ReverseString/Properties/AssemblyInfo.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "50534" }, { "name": "Batchfile", "bytes": "3572" }, { "name": "C", "bytes": "991" }, { "name": "C#", "bytes": "930008" }, { "name": "CSS", "bytes": "53730" }, { "name": "HTML", "bytes": "147975" }, { "name": "JavaScript", "bytes": "101700" }, { "name": "Python", "bytes": "29737" }, { "name": "Smalltalk", "bytes": "107906" }, { "name": "Visual Basic", "bytes": "63723" }, { "name": "XSLT", "bytes": "3874" } ], "symlink_target": "" }
<?php namespace Drupal\views\Tests\Wizard; /** * Tests the ability of the views wizard to specify the number of items per * page. * * @group views */ class ItemsPerPageTest extends WizardTestBase { protected function setUp() { parent::setUp(); $this->drupalPlaceBlock('page_title_block'); } /** * Tests the number of items per page. */ public function testItemsPerPage() { $this->drupalCreateContentType(['type' => 'article']); // Create articles, each with a different creation time so that we can do a // meaningful sort. $node1 = $this->drupalCreateNode(['type' => 'article', 'created' => REQUEST_TIME]); $node2 = $this->drupalCreateNode(['type' => 'article', 'created' => REQUEST_TIME + 1]); $node3 = $this->drupalCreateNode(['type' => 'article', 'created' => REQUEST_TIME + 2]); $node4 = $this->drupalCreateNode(['type' => 'article', 'created' => REQUEST_TIME + 3]); $node5 = $this->drupalCreateNode(['type' => 'article', 'created' => REQUEST_TIME + 4]); // Create a page. This should never appear in the view created below. $page_node = $this->drupalCreateNode(['type' => 'page', 'created' => REQUEST_TIME + 2]); // Create a view that sorts newest first, and shows 4 items in the page and // 3 in the block. $view = []; $view['label'] = $this->randomMachineName(16); $view['id'] = strtolower($this->randomMachineName(16)); $view['description'] = $this->randomMachineName(16); $view['show[wizard_key]'] = 'node'; $view['show[type]'] = 'article'; $view['show[sort]'] = 'node_field_data-created:DESC'; $view['page[create]'] = 1; $view['page[title]'] = $this->randomMachineName(16); $view['page[path]'] = $this->randomMachineName(16); $view['page[items_per_page]'] = 4; $view['block[create]'] = 1; $view['block[title]'] = $this->randomMachineName(16); $view['block[items_per_page]'] = 3; $this->drupalPostForm('admin/structure/views/add', $view, t('Save and edit')); $this->drupalGet($view['page[path]']); $this->assertResponse(200); // Make sure the page display shows the nodes we expect, and that they // appear in the expected order. $this->assertUrl($view['page[path]']); $this->assertText($view['page[title]']); $content = $this->getRawContent(); $this->assertText($node5->label()); $this->assertText($node4->label()); $this->assertText($node3->label()); $this->assertText($node2->label()); $this->assertNoText($node1->label()); $this->assertNoText($page_node->label()); $pos5 = strpos($content, $node5->label()); $pos4 = strpos($content, $node4->label()); $pos3 = strpos($content, $node3->label()); $pos2 = strpos($content, $node2->label()); $this->assertTrue($pos5 < $pos4 && $pos4 < $pos3 && $pos3 < $pos2, 'The nodes appear in the expected order in the page display.'); // Confirm that the block is listed in the block administration UI. $this->drupalGet('admin/structure/block/list/' . $this->config('system.theme')->get('default')); $this->clickLinkPartialName('Place block'); $this->assertText($view['label']); // Place the block, visit a page that displays the block, and check that the // nodes we expect appear in the correct order. $this->drupalPlaceBlock("views_block:{$view['id']}-block_1"); $this->drupalGet('user'); $content = $this->getRawContent(); $this->assertText($node5->label()); $this->assertText($node4->label()); $this->assertText($node3->label()); $this->assertNoText($node2->label()); $this->assertNoText($node1->label()); $this->assertNoText($page_node->label()); $pos5 = strpos($content, $node5->label()); $pos4 = strpos($content, $node4->label()); $pos3 = strpos($content, $node3->label()); $this->assertTrue($pos5 < $pos4 && $pos4 < $pos3, 'The nodes appear in the expected order in the block display.'); } }
{ "content_hash": "0d16ca0e1f9ffc16f9cf5941b5df95b9", "timestamp": "", "source": "github", "line_count": 96, "max_line_length": 134, "avg_line_length": 41.104166666666664, "alnum_prop": 0.6267105930055753, "repo_name": "sukottokun/jenkins-001-001", "id": "58f22a8424686aecfefda2f404b1d2b3a1ced020", "size": "3946", "binary": false, "copies": "76", "ref": "refs/heads/master", "path": "web/core/modules/views/src/Tests/Wizard/ItemsPerPageTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "673" }, { "name": "CSS", "bytes": "481085" }, { "name": "Gherkin", "bytes": "3374" }, { "name": "HTML", "bytes": "525716" }, { "name": "JavaScript", "bytes": "911696" }, { "name": "PHP", "bytes": "32448348" }, { "name": "Shell", "bytes": "54644" } ], "symlink_target": "" }
const Stream = require('mithril/stream'); const s = require('string-plus'); const Mixins = require('models/mixins/model_mixins'); const PluginConfigurations = require('models/shared/plugin_configurations'); const Routes = require('gen/js-routes'); const Validatable = require('models/mixins/validatable_mixin'); const CrudMixins = require('models/mixins/crud_mixins'); const $ = require('jquery'); const mrequest = require('helpers/mrequest'); const AuthConfigs = function (data) { Mixins.HasMany.call(this, { factory: AuthConfigs.AuthConfig.create, as: 'AuthConfig', collection: data, uniqueOn: 'id' }); this.findById = function (authConfigId) { return this.findAuthConfig((authConfig) => authConfig.id() === authConfigId); }; }; AuthConfigs.API_VERSION = 'v1'; CrudMixins.Index({ type: AuthConfigs, indexUrl: Routes.apiv1AdminSecurityAuthConfigsPath(), version: AuthConfigs.API_VERSION, dataPath: '_embedded.auth_configs' }); AuthConfigs.AuthConfig = function (data) { this.id = Stream(s.defaultToIfBlank(data.id, '')); this.pluginId = Stream(s.defaultToIfBlank(data.pluginId, '')); this.properties = s.collectionToJSON(Stream(s.defaultToIfBlank(data.properties, new PluginConfigurations()))); this.parent = Mixins.GetterSetter(); this.etag = Mixins.GetterSetter(); Mixins.HasUUID.call(this); Validatable.call(this, data); this.validatePresenceOf('id'); this.validatePresenceOf('pluginId'); this.validateFormatOf('id', { format: /^[-a-zA-Z0-9_][-a-zA-Z0-9_.]*$/, message: 'Invalid id. This must be alphanumeric and can contain underscores and periods (however, it cannot start ' + 'with a period). The maximum allowed length is 255 characters.' }); CrudMixins.AllOperations.call(this, ['refresh', 'update', 'delete', 'create'], { type: AuthConfigs.AuthConfig, indexUrl: Routes.apiv1AdminSecurityAuthConfigsPath(), resourceUrl (authConfig) { return Routes.apiv1AdminSecurityAuthConfigPath(authConfig.id()); }, version: AuthConfigs.API_VERSION }); this.verifyConnection = () => { const entity = this; return $.Deferred(function () { const deferred = this; const jqXHR = $.ajax({ method: 'POST', url: Routes.apiv1AdminInternalVerifyConnectionPath(), timeout: mrequest.timeout, beforeSend: mrequest.xhrConfig.forVersion(AuthConfigs.API_VERSION), data: JSON.stringify(entity, s.snakeCaser), contentType: 'application/json' }); const didFulfill = (data, _textStatus, jqXHR) => { if (jqXHR.status === 200) { const responseEntity = AuthConfigs.AuthConfig.fromJSON(data.auth_config); responseEntity.etag(entity.etag()); deferred.resolve(responseEntity); } }; const didReject = (jqXHR, _textStatus, _errorThrown) => { deferred.reject(VerifyConnectionResponse(jqXHR, entity.etag())); }; jqXHR.then(didFulfill, didReject); }).promise(); }; }; AuthConfigs.AuthConfig.get = function (id) { return new AuthConfigs.AuthConfig({id}).refresh(); }; AuthConfigs.AuthConfig.create = function (data) { return new AuthConfigs.AuthConfig(data); }; AuthConfigs.AuthConfig.fromJSON = function (data) { return new AuthConfigs.AuthConfig({ id: data.id, pluginId: data.plugin_id, errors: data.errors, properties: PluginConfigurations.fromJSON(data.properties) }); }; Mixins.fromJSONCollection({ parentType: AuthConfigs, childType: AuthConfigs.AuthConfig, via: 'addAuthConfig' }); const VerifyConnectionResponse = function (xhr, etag) { if (xhr.status === 422) { const authConfig = AuthConfigs.AuthConfig.fromJSON(xhr.responseJSON.auth_config); authConfig.etag(etag); return { authConfig, errorMessage: xhr.responseJSON.message, status: xhr.responseJSON.status }; } else { return {errorMessage: mrequest.unwrapErrorExtractMessage(xhr.responseJSON, xhr)}; } }; module.exports = AuthConfigs;
{ "content_hash": "67e9842a870e7f290f484f2132bc1b5c", "timestamp": "", "source": "github", "line_count": 131, "max_line_length": 121, "avg_line_length": 32.37404580152672, "alnum_prop": 0.6547983966045744, "repo_name": "stevem999/gocd", "id": "ae10fb79ac258236753e787cba757d93a876e728", "size": "4842", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server/webapp/WEB-INF/rails.new/webpack/models/auth_configs/auth_configs.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "8637" }, { "name": "CSS", "bytes": "524172" }, { "name": "FreeMarker", "bytes": "182" }, { "name": "Groovy", "bytes": "18840" }, { "name": "HTML", "bytes": "661683" }, { "name": "Java", "bytes": "16697275" }, { "name": "JavaScript", "bytes": "2983309" }, { "name": "NSIS", "bytes": "19211" }, { "name": "PowerShell", "bytes": "743" }, { "name": "Ruby", "bytes": "3301148" }, { "name": "SQLPL", "bytes": "9050" }, { "name": "Shell", "bytes": "197638" }, { "name": "XSLT", "bytes": "156205" } ], "symlink_target": "" }
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Group extends CI_Controller { public function __construct(){ parent::__construct(); $this->load->database(); $this->load->helper('url'); $this->load->model('M_group'); $this->load->model('m_category'); if(empty($this->session->userdata('data')->user_id)){ $msg = ' <div class="alert alert-danger alert-dismissible"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> <h4>Anda Harus Login Dulu!</h4> </div> '; $this->session->set_flashdata(array('msg'=>$msg)); // var_dump($msg, $this->session);die; redirect(site_url('home/login')); } } public function view(){ //var_dump($this->session->userdata['msg']); if(isset($this->session->userdata['msg'])){ $data['message'] = $this->session->userdata['msg']; } $data['group'] = $this->M_group->getGroup(); $this->load->view('pages/group_view', $data); } public function input($id=null){ $data = array(); if(!is_null($id)){ $data['group'] = $this->M_group->getGroupById($id); } $data['category'] = $this->m_category->select_all(); //var_dump($data); $this->load->view('pages/group_input', $data); } public function process(){ var_dump($_POST); $this->db->trans_start(); if($_POST['group_id'] == ''){ $data['is_container'] = $this->input->post('is_container'); $data['group_category_id'] = $this->input->post('group_category'); $data['group_name'] = $this->input->post('group_name'); $data['group_desc'] = $this->input->post('group_desc'); $result = $this->M_group->addGroup($data); if($result){ $msg = ' <div class="alert alert-success alert-dismissible"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> <h4><i class="icon fa fa-check"></i> berhasil!</h4> Tambah Data Group Berhasil. </div> '; $this->session->set_flashdata(array('msg'=>$msg)); }else{ $msg = ' <div class="alert alert-danger alert-dismissible"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> <h4><i class="icon fa fa-check"></i> Gagal!</h4> Tambah Data Group Gagal. </div> '; $this->session->set_flashdata(array('msg'=>$msg)); } }else{ //$data['class_id'] = $this->input->post('class_id'); $data['group_name'] = $this->input->post('group_name'); $data['is_container'] = $this->input->post('is_container'); $data['group_category_id'] = $this->input->post('group_category'); $data['group_desc'] = $this->input->post('group_desc'); $result = $this->M_group->editGroup($this->input->post('group_id'), $data); if($result){ $msg = ' <div class="alert alert-success alert-dismissible"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> <h4><i class="icon fa fa-check"></i> berhasil!</h4> Edit Data Group Berhasil. </div> '; $this->session->set_flashdata('msg', $msg); }else{ $msg = ' <div class="alert alert-danger alert-dismissible"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> <h4><i class="icon fa fa-check"></i> Gagal!</h4> Edit Data Group Gagal. </div> '; $this->session->set_flashdata('msg', $msg); } } var_dump($result); var_dump($this->db->last_query()); //die; $this->db->trans_complete($result); redirect(site_url('group/view')); } public function do_delete($class_id){ $result = $this->M_group->deleteGroup($class_id); if($result){ $msg = ' <div class="alert alert-success alert-dismissible"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> <h4><i class="icon fa fa-check"></i> berhasil!</h4> Hapus Data Group Berhasil. </div> '; $this->session->set_flashdata('msg', $msg); }else{ $msg = ' <div class="alert alert-danger alert-dismissible"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> <h4><i class="icon fa fa-check"></i> Gagal!</h4> Hapus Data Group Gagal. </div> '; $this->session->set_flashdata('msg', $msg); } redirect(site_url('group/view')); } public function edit($class_id){ $data['class_res'] = $this->M_group->select_by_id($class_id)->row(); $data['category'] = $this->M_group->getCat(); $this->load->view('pages/class_edit', $data); } public function do_edit(){ //var_dump($_POST);die(); $data['class_code'] = $this->input->post('kode_tipe'); $data['class_name'] = $this->input->post('nama_tipe'); $data['class_category_id'] = $this->input->post('category'); $data['class_desc'] = $this->input->post('keterangan'); $class_id=$this->input->post('id_tipe'); //var_dump($class_id);die(); $this->M_group->editType($class_id, $data); $this->class_read(); } }
{ "content_hash": "eed9d76beb612bc881f5a74c9ef7e568", "timestamp": "", "source": "github", "line_count": 155, "max_line_length": 98, "avg_line_length": 33.84516129032258, "alnum_prop": 0.5745329775066718, "repo_name": "kokowijanarko/just-for-fun", "id": "0485ce03783d145256a208d01cd95631b272a77f", "size": "5246", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/controllers/Group.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "240" }, { "name": "CSS", "bytes": "30470" }, { "name": "HTML", "bytes": "8276" }, { "name": "JavaScript", "bytes": "14391" }, { "name": "PHP", "bytes": "9745357" } ], "symlink_target": "" }
package org.apache.ignite.internal.processors.cache.persistence.metastorage; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.internal.pagemem.PageIdAllocator; import org.apache.ignite.internal.processors.cache.persistence.Storable; /** * */ public class MetastorageDataRow implements MetastorageSearchRow, Storable { /** */ private long link; /** */ private String key; /** */ private byte[] value; /** */ public MetastorageDataRow(long link, String key, byte[] value) { this.link = link; this.key = key; this.value = value; } /** */ public MetastorageDataRow(String key, byte[] value) { this.key = key; this.value = value; } /** * @return Key. */ @Override public String key() { return key; } /** {@inheritDoc} */ @Override public int hash() { return key.hashCode(); } /** {@inheritDoc} */ @Override public int partition() { return MetaStorage.PRESERVE_LEGACY_METASTORAGE_PARTITION_ID ? PageIdAllocator.OLD_METASTORE_PARTITION: PageIdAllocator.METASTORE_PARTITION; } /** {@inheritDoc} */ @Override public int size() throws IgniteCheckedException { return 4 + value().length; } /** {@inheritDoc} */ @Override public int headerSize() { return 0; } /** {@inheritDoc} */ @Override public void link(long link) { this.link = link; } /** {@inheritDoc} */ @Override public long link() { return link; } /** * @return Value. */ public byte[] value() { return value; } /** {@inheritDoc} */ @Override public String toString() { return "key=" + key; } }
{ "content_hash": "a208a8df4d0d1a67ae4091cc06b8db41", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 147, "avg_line_length": 20.397727272727273, "alnum_prop": 0.5788300835654596, "repo_name": "BiryukovVA/ignite", "id": "2d7b0a66e47a41282b08f620d49fd93c8ced41ea", "size": "2597", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "modules/core/src/main/java/org/apache/ignite/internal/processors/cache/persistence/metastorage/MetastorageDataRow.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "61156" }, { "name": "C", "bytes": "5286" }, { "name": "C#", "bytes": "6134000" }, { "name": "C++", "bytes": "3594158" }, { "name": "CSS", "bytes": "304650" }, { "name": "Dockerfile", "bytes": "14859" }, { "name": "Groovy", "bytes": "15081" }, { "name": "HTML", "bytes": "1454824" }, { "name": "Java", "bytes": "39390646" }, { "name": "JavaScript", "bytes": "1756829" }, { "name": "M4", "bytes": "21724" }, { "name": "Makefile", "bytes": "121163" }, { "name": "PHP", "bytes": "486991" }, { "name": "PLpgSQL", "bytes": "623" }, { "name": "PowerShell", "bytes": "12344" }, { "name": "Python", "bytes": "340696" }, { "name": "Scala", "bytes": "1011929" }, { "name": "Shell", "bytes": "615867" }, { "name": "Smalltalk", "bytes": "1908" }, { "name": "TypeScript", "bytes": "472483" } ], "symlink_target": "" }
START_ATF_NAMESPACE struct _open_world_success_acwr { char byWorldCode; char szDBName[32]; char szDBIP[17]; char m_byWorldType; }; END_ATF_NAMESPACE
{ "content_hash": "aaf00356797164c7ee7fa718730cf081", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 35, "avg_line_length": 21.444444444444443, "alnum_prop": 0.5958549222797928, "repo_name": "goodwinxp/Yorozuya", "id": "8122b9382fdbd23cb55fe13481e973c18bb14e2b", "size": "345", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "library/ATF/_open_world_success_acwr.hpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "207291" }, { "name": "C++", "bytes": "21670817" } ], "symlink_target": "" }
<h3>Search <small>Search and filter results</small> </h3> <div class="row"> <div class="col-lg-9"> <div class="form-group mb-xl"> <input type="text" placeholder="Search products, people, apps, etc." class="form-control mb" /> <div class="clearfix"> <button type="button" class="pull-left btn btn-default">Search</button> <div class="pull-right"> <label class="checkbox-inline c-checkbox"> <input id="inlineCheckbox10" type="checkbox" value="option1" /> <span class="fa fa-check"></span>Products</label> <label class="checkbox-inline c-checkbox"> <input id="inlineCheckbox20" type="checkbox" value="option2" /> <span class="fa fa-check"></span>People</label> <label class="checkbox-inline c-checkbox"> <input id="inlineCheckbox30" type="checkbox" value="option3" /> <span class="fa fa-check"></span>Apps</label> </div> </div> </div> <!-- START panel--> <div class="panel panel-default"> <div class="panel-heading">Search Results <paneltool tool-refresh="traditional"></paneltool> </div> <!-- START table-responsive--> <div class="table-responsive"> <table class="table table-striped table-bordered table-hover"> <thead> <tr> <th check-all="check-all"> <div data-toggle="tooltip" data-title="Check All" class="checkbox c-checkbox"> <label> <input type="checkbox" /> <span class="fa fa-check"></span> </label> </div> </th> <th>Description</th> </tr> </thead> <tbody> <tr> <td> <div class="checkbox c-checkbox"> <label> <input type="checkbox" /> <span class="fa fa-check"></span> </label> </div> </td> <td> <div class="media-box"> <a href="#" class="pull-left"> <img src="app/img/dummy.png" alt="" class="media-box-object img-responsive img-rounded thumb64" /> </a> <div class="media-box-body"> <div class="pull-right btn btn-info btn-sm">View</div> <h4 class="media-box-heading">Product 1</h4> <small class="text-muted">Category1, Category2</small> <p>Sed gravida auctor odio. Sed viverra rutrum hendrerit. Praesent dapibus justo dolor. Suspendisse rhoncus consectetur eros vehicula accumsan.</p> </div> </div> </td> </tr> <tr> <td> <div class="checkbox c-checkbox"> <label> <input type="checkbox" /> <span class="fa fa-check"></span> </label> </div> </td> <td> <div class="media-box"> <a href="#" class="pull-left"> <img src="app/img/dummy.png" alt="" class="media-box-object img-responsive img-rounded thumb64" /> </a> <div class="media-box-body"> <div class="pull-right btn btn-info btn-sm">View</div> <h4 class="media-box-heading">Product 2</h4> <small class="text-muted">Category1, Category2</small> <p>Sed gravida auctor odio. Sed viverra rutrum hendrerit. Praesent dapibus justo dolor. Suspendisse rhoncus consectetur eros vehicula accumsan.</p> </div> </div> </td> </tr> <tr> <td> <div class="checkbox c-checkbox"> <label> <input type="checkbox" /> <span class="fa fa-check"></span> </label> </div> </td> <td> <div class="media-box"> <a href="#" class="pull-left"> <img src="app/img/dummy.png" alt="" class="media-box-object img-responsive img-rounded thumb64" /> </a> <div class="media-box-body"> <div class="pull-right btn btn-info btn-sm">View</div> <h4 class="media-box-heading">Product 3</h4> <small class="text-muted">Category1, Category2</small> <p>Sed gravida auctor odio. Sed viverra rutrum hendrerit. Praesent dapibus justo dolor. Suspendisse rhoncus consectetur eros vehicula accumsan.</p> </div> </div> </td> </tr> <tr> <td> <div class="checkbox c-checkbox"> <label> <input type="checkbox" /> <span class="fa fa-check"></span> </label> </div> </td> <td> <div class="media-box"> <a href="#" class="pull-left"> <img src="app/img/dummy.png" alt="" class="media-box-object img-responsive img-rounded thumb64" /> </a> <div class="media-box-body"> <div class="pull-right btn btn-info btn-sm">View</div> <h4 class="media-box-heading">Product 4</h4> <small class="text-muted">Category1, Category2</small> <p>Sed gravida auctor odio. Sed viverra rutrum hendrerit. Praesent dapibus justo dolor. Suspendisse rhoncus consectetur eros vehicula accumsan.</p> </div> </div> </td> </tr> <tr> <td> <div class="checkbox c-checkbox"> <label> <input type="checkbox" /> <span class="fa fa-check"></span> </label> </div> </td> <td> <div class="media-box"> <a href="#" class="pull-left"> <img src="app/img/dummy.png" alt="" class="media-box-object img-responsive img-rounded thumb64" /> </a> <div class="media-box-body"> <div class="pull-right btn btn-info btn-sm">View</div> <h4 class="media-box-heading">Product 5</h4> <small class="text-muted">Category1, Category2</small> <p>Sed gravida auctor odio. Sed viverra rutrum hendrerit. Praesent dapibus justo dolor. Suspendisse rhoncus consectetur eros vehicula accumsan.</p> </div> </div> </td> </tr> </tbody> </table> </div> <!-- END table-responsive--> <div class="panel-footer"> <div class="row"> <div class="col-lg-2"> <button class="btn btn-sm btn-default">Clear</button> </div> <div class="col-lg-8"></div> <div class="col-lg-2 text-right"> <ul class="pagination pagination-sm"> <li class="active"><a href="#">1</a> </li> <li><a href="#">2</a> </li> <li><a href="#">3</a> </li> <li><a href="#">»</a> </li> </ul> </div> </div> </div> </div> <!-- END panel--> </div> <div class="col-lg-3"> <h3 class="m0 pb-lg">Filters</h3> <div class="form-group mb-xl"> <label class="control-label mb">by Text</label> <br/> <select chosen="" ng-model="searchState" class="chosen-select form-control"> <optgroup label="Alaskan/Hawaiian Time Zone"> <option value="AK">Alaska</option> <option value="HI">Hawaii</option> </optgroup> <optgroup label="Pacific Time Zone"> <option value="CA">California</option> <option value="NV">Nevada</option> <option value="OR">Oregon</option> <option value="WA">Washington</option> </optgroup> <optgroup label="Mountain Time Zone"> <option value="AZ">Arizona</option> <option value="CO">Colorado</option> <option value="ID">Idaho</option> <option value="MT">Montana</option> <option value="NE">Nebraska</option> <option value="NM">New Mexico</option> <option value="ND">North Dakota</option> <option value="UT">Utah</option> <option value="WY">Wyoming</option> </optgroup> <optgroup label="Central Time Zone"> <option value="AL">Alabama</option> <option value="AR">Arkansas</option> <option value="IL">Illinois</option> <option value="IA">Iowa</option> <option value="KS">Kansas</option> <option value="KY">Kentucky</option> <option value="LA">Louisiana</option> <option value="MN">Minnesota</option> <option value="MS">Mississippi</option> <option value="MO">Missouri</option> <option value="OK">Oklahoma</option> <option value="SD">South Dakota</option> <option value="TX">Texas</option> <option value="TN">Tennessee</option> <option value="WI">Wisconsin</option> </optgroup> <optgroup label="Eastern Time Zone"> <option value="CT">Connecticut</option> <option value="DE">Delaware</option> <option value="FL">Florida</option> <option value="GA">Georgia</option> <option value="IN">Indiana</option> <option value="ME">Maine</option> <option value="MD">Maryland</option> <option value="MA">Massachusetts</option> <option value="MI">Michigan</option> <option value="NH">New Hampshire</option> <option value="NJ">New Jersey</option> <option value="NY">New York</option> <option value="NC">North Carolina</option> <option value="OH">Ohio</option> <option value="PA">Pennsylvania</option> <option value="RI">Rhode Island</option> <option value="SC">South Carolina</option> <option value="VT">Vermont</option> <option value="VA">Virginia</option> <option value="WV">West Virginia</option> </optgroup> </select> </div> <div ng-controller="DatepickerDemoCtrl as dp" class="form-group mb-xl"> <label class="control-label mb">by Date</label> <br/> <p class="input-group"> <input type="text" datepicker-popup="{{dp.format}}" ng-model="dp.dt" is-open="dp.opened" max-date="'2017-06-22'" datepicker-options="dp.dateOptions" date-disabled="dp.disabled(date, mode)" ng-required="true" close-text="Close" class="form-control" /> <span class="input-group-btn"> <button type="button" ng-click="dp.open($event)" class="btn btn-default"> <em class="fa fa-calendar"></em> </button> </span> </p> </div> <div class="form-group mb-xl"> <label class="control-label mb">by Range</label> <br/> <input id="sl2" ui-slider="" type="text" value="" data-slider-min="10" data-slider-max="1000" data-slider-step="5" data-slider-value="[250,750]" class="slider slider-lg form-control" /> </div> <button class="btn btn-default btn-lg">Apply</button> </div> </div>
{ "content_hash": "8a57c6fd4d875f60f052a437a3f03d8c", "timestamp": "", "source": "github", "line_count": 275, "max_line_length": 259, "avg_line_length": 48.95272727272727, "alnum_prop": 0.43477937899272023, "repo_name": "Bedbug/sportimo_dashboard", "id": "e632c4fccdc47469c361503c90ecf3eab8dfdad3", "size": "13463", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/app/views/search.html", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "2240519" }, { "name": "HTML", "bytes": "2057906" }, { "name": "JavaScript", "bytes": "3140850" }, { "name": "PHP", "bytes": "454" } ], "symlink_target": "" }
/** * @fileoverview English strings. * @author [email protected] (Neil Fraser) * * After modifying this file, either run "build.py" from the parent directory, * or run (from this directory): * ../i18n/js_to_json.py * to regenerate json/{en,qqq,synonyms}.json. * * To convert all of the json files to .js files, run: * ../i18n/create_messages.py json/*.json */ 'use strict'; goog.provide('Blockly.Msg.en'); goog.require('Blockly.Msg'); /** * Due to the frequency of long strings, the 80-column wrap rule need not apply * to message files. */ /** * Each message is preceded with a tripple-slash comment that becomes the * message descriptor. The build process extracts these descriptors, adds * them to msg/json/qqq.json, and they show up in the translation console. */ /// default name - A simple, general default name for a variable, preferably short. /// For more context, see /// [[Translating:Blockly#infrequent_message_types]].\n{{Identical|Item}} Blockly.Msg.VARIABLES_DEFAULT_NAME = 'item'; /// button text - Button that sets a calendar to today's date.\n{{Identical|Today}} Blockly.Msg.TODAY = 'Today'; // Context menus. /// context menu - Make a copy of the selected block (and any blocks it contains).\n{{Identical|Duplicate}} Blockly.Msg.DUPLICATE_BLOCK = 'Duplicate'; /// context menu - Add a descriptive comment to the selected block. Blockly.Msg.ADD_COMMENT = 'Add Comment'; /// context menu - Remove the descriptive comment from the selected block. Blockly.Msg.REMOVE_COMMENT = 'Remove Comment'; /// context menu - Change from 'external' to 'inline' mode for displaying blocks used as inputs to the selected block. See [[Translating:Blockly#context_menus]]. Blockly.Msg.EXTERNAL_INPUTS = 'External Inputs'; /// context menu - Change from 'internal' to 'external' mode for displaying blocks used as inputs to the selected block. See [[Translating:Blockly#context_menus]]. Blockly.Msg.INLINE_INPUTS = 'Inline Inputs'; /// context menu - Permanently delete the selected block. Blockly.Msg.DELETE_BLOCK = 'Delete Block'; /// context menu - Permanently delete the %1 selected blocks.\n\nParameters:\n* %1 - an integer greater than 1. Blockly.Msg.DELETE_X_BLOCKS = 'Delete %1 Blocks'; /// confirmation prompt - Question the user if they really wanted to permanently delete all %1 blocks.\n\nParameters:\n* %1 - an integer greater than 1. Blockly.Msg.DELETE_ALL_BLOCKS = 'Delete all %1 blocks?'; /// context menu - Reposition all the blocks so that they form a neat line. Blockly.Msg.CLEAN_UP = 'Clean up Blocks'; /// context menu - Make the appearance of the selected block smaller by hiding some information about it. Blockly.Msg.COLLAPSE_BLOCK = 'Collapse Block'; /// context menu - Make the appearance of all blocks smaller by hiding some information about it. Use the same terminology as in the previous message. Blockly.Msg.COLLAPSE_ALL = 'Collapse Blocks'; /// context menu - Restore the appearance of the selected block by showing information about it that was hidden (collapsed) earlier. Blockly.Msg.EXPAND_BLOCK = 'Expand Block'; /// context menu - Restore the appearance of all blocks by showing information about it that was hidden (collapsed) earlier. Use the same terminology as in the previous message. Blockly.Msg.EXPAND_ALL = 'Expand Blocks'; /// context menu - Make the selected block have no effect (unless reenabled). Blockly.Msg.DISABLE_BLOCK = 'Disable Block'; /// context menu - Make the selected block have effect (after having been disabled earlier). Blockly.Msg.ENABLE_BLOCK = 'Enable Block'; /// context menu - Provide helpful information about the selected block.\n{{Identical|Help}} Blockly.Msg.HELP = 'Help'; /// context menu - Undo the previous action.\n{{Identical|Undo}} Blockly.Msg.UNDO = 'Undo'; /// context menu - Undo the previous undo action.\n{{Identical|Redo}} Blockly.Msg.REDO = 'Redo'; // Realtime collaboration. /// collaboration instruction - Tell the user that they can talk with other users. Blockly.Msg.CHAT = 'Chat with your collaborator by typing in this box!'; /// authorization instruction - Ask the user to authorize this app so it can be saved and shared by them. Blockly.Msg.AUTH = 'Please authorize this app to enable your work to be saved and to allow it to be shared by you.'; /// First person singular - objective case Blockly.Msg.ME = 'Me'; // Variable renaming. /// prompt - This message is only seen in the Opera browser. With most browsers, users can edit numeric values in blocks by just clicking and typing. Opera does not allows this, so we have to open a new window and prompt users with this message to chanage a value. Blockly.Msg.CHANGE_VALUE_TITLE = 'Change value:'; /// dropdown choice - When the user clicks on a variable block, this is one of the dropdown menu choices. It is used to define a new variable. See [https://github.com/google/blockly/wiki/Variables#dropdown-menu https://github.com/google/blockly/wiki/Variables#dropdown-menu]. Blockly.Msg.NEW_VARIABLE = 'New variable...'; /// prompt - Prompts the user to enter the name for a new variable. See [https://github.com/google/blockly/wiki/Variables#dropdown-menu https://github.com/google/blockly/wiki/Variables#dropdown-menu]. Blockly.Msg.NEW_VARIABLE_TITLE = 'New variable name:'; /// dropdown choice - When the user clicks on a variable block, this is one of the dropdown menu choices. It is used to rename the current variable. See [https://github.com/google/blockly/wiki/Variables#dropdown-menu https://github.com/google/blockly/wiki/Variables#dropdown-menu]. Blockly.Msg.RENAME_VARIABLE = 'Rename variable...'; /// prompt - Prompts the user to enter the new name for the selected variable. See [https://github.com/google/blockly/wiki/Variables#dropdown-menu https://github.com/google/blockly/wiki/Variables#dropdown-menu].\n\nParameters:\n* %1 - the name of the variable to be renamed. Blockly.Msg.RENAME_VARIABLE_TITLE = 'Rename all "%1" variables to:'; // Colour Blocks. /// url - Information about colour. Blockly.Msg.COLOUR_PICKER_HELPURL = 'https://en.wikipedia.org/wiki/Color'; /// tooltip - See [https://github.com/google/blockly/wiki/Colour#picking-a-colour-from-a-palette https://github.com/google/blockly/wiki/Colour#picking-a-colour-from-a-palette]. Blockly.Msg.COLOUR_PICKER_TOOLTIP = 'Choose a colour from the palette.'; /// url - A link that displays a random colour each time you visit it. Blockly.Msg.COLOUR_RANDOM_HELPURL = 'http://randomcolour.com'; /// block text - Title of block that generates a colour at random. Blockly.Msg.COLOUR_RANDOM_TITLE = 'random colour'; /// tooltip - See [https://github.com/google/blockly/wiki/Colour#generating-a-random-colour https://github.com/google/blockly/wiki/Colour#generating-a-random-colour]. Blockly.Msg.COLOUR_RANDOM_TOOLTIP = 'Choose a colour at random.'; /// url - A link for color codes with percentages (0-100%) for each component, instead of the more common 0-255, which may be more difficult for beginners. Blockly.Msg.COLOUR_RGB_HELPURL = 'http://www.december.com/html/spec/colorper.html'; /// block text - Title of block for [https://github.com/google/blockly/wiki/Colour#creating-a-colour-from-red-green-and-blue-components https://github.com/google/blockly/wiki/Colour#creating-a-colour-from-red-green-and-blue-components]. Blockly.Msg.COLOUR_RGB_TITLE = 'colour with'; /// block input text - The amount of red (from 0 to 100) to use when [https://github.com/google/blockly/wiki/Colour#creating-a-colour-from-red-green-and-blue-components https://github.com/google/blockly/wiki/Colour#creating-a-colour-from-red-green-and-blue-components].\n{{Identical|Red}} Blockly.Msg.COLOUR_RGB_RED = 'red'; /// block input text - The amount of green (from 0 to 100) to use when [https://github.com/google/blockly/wiki/Colour#creating-a-colour-from-red-green-and-blue-components https://github.com/google/blockly/wiki/Colour#creating-a-colour-from-red-green-and-blue-components]. Blockly.Msg.COLOUR_RGB_GREEN = 'green'; /// block input text - The amount of blue (from 0 to 100) to use when [https://github.com/google/blockly/wiki/Colour#creating-a-colour-from-red-green-and-blue-components https://github.com/google/blockly/wiki/Colour#creating-a-colour-from-red-green-and-blue-components].\n{{Identical|Blue}} Blockly.Msg.COLOUR_RGB_BLUE = 'blue'; /// tooltip - See [https://github.com/google/blockly/wiki/Colour#creating-a-colour-from-red-green-and-blue-components https://github.com/google/blockly/wiki/Colour#creating-a-colour-from-red-green-and-blue-components]. Blockly.Msg.COLOUR_RGB_TOOLTIP = 'Create a colour with the specified amount of red, green, and blue. All values must be between 0 and 100.'; /// url - A useful link that displays blending of two colors. Blockly.Msg.COLOUR_BLEND_HELPURL = 'http://meyerweb.com/eric/tools/color-blend/'; /// block text - A verb for blending two shades of paint. Blockly.Msg.COLOUR_BLEND_TITLE = 'blend'; /// block input text - The first of two colours to [https://github.com/google/blockly/wiki/Colour#blending-colours blend]. Blockly.Msg.COLOUR_BLEND_COLOUR1 = 'colour 1'; /// block input text - The second of two colours to [https://github.com/google/blockly/wiki/Colour#blending-colours blend]. Blockly.Msg.COLOUR_BLEND_COLOUR2 = 'colour 2'; /// block input text - The proportion of the [https://github.com/google/blockly/wiki/Colour#blending-colours blend] containing the first color; the remaining proportion is of the second colour. For example, if the first colour is red and the second color blue, a ratio of 1 would yield pure red, a ratio of .5 would yield purple (equal amounts of red and blue), and a ratio of 0 would yield pure blue.\n{{Identical|Ratio}} Blockly.Msg.COLOUR_BLEND_RATIO = 'ratio'; /// tooltip - See [https://github.com/google/blockly/wiki/Colour#blending-colours https://github.com/google/blockly/wiki/Colour#blending-colours]. Blockly.Msg.COLOUR_BLEND_TOOLTIP = 'Blends two colours together with a given ratio (0.0 - 1.0).'; // Loop Blocks. /// url - Describes 'repeat loops' in computer programs; consider using the translation of the page [https://en.wikipedia.org/wiki/Control_flow http://en.wikipedia.org/wiki/Control_flow]. Blockly.Msg.CONTROLS_REPEAT_HELPURL = 'https://en.wikipedia.org/wiki/For_loop'; /// block input text - Title of [https://github.com/google/blockly/wiki/Loops#repeat repeat block].\n\nParameters:\n* %1 - the number of times the body of the loop should be repeated. Blockly.Msg.CONTROLS_REPEAT_TITLE = 'repeat %1 times'; /// block text - Preceding the blocks in the body of the loop. See [https://github.com/google/blockly/wiki/Loops https://github.com/google/blockly/wiki/Loops].\n{{Identical|Do}} Blockly.Msg.CONTROLS_REPEAT_INPUT_DO = 'do'; /// tooltip - See [https://github.com/google/blockly/wiki/Loops#repeat https://github.com/google/blockly/wiki/Loops#repeat]. Blockly.Msg.CONTROLS_REPEAT_TOOLTIP = 'Do some statements several times.'; /// url - Describes 'while loops' in computer programs; consider using the translation of [https://en.wikipedia.org/wiki/While_loop https://en.wikipedia.org/wiki/While_loop], if present, or [https://en.wikipedia.org/wiki/Control_flow https://en.wikipedia.org/wiki/Control_flow]. Blockly.Msg.CONTROLS_WHILEUNTIL_HELPURL = 'https://github.com/google/blockly/wiki/Loops#repeat'; Blockly.Msg.CONTROLS_WHILEUNTIL_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO; /// dropdown - Specifies that a loop should [https://github.com/google/blockly/wiki/Loops#repeat-while repeat while] the following condition is true. Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_WHILE = 'repeat while'; /// dropdown - Specifies that a loop should [https://github.com/google/blockly/wiki/Loops#repeat-until repeat until] the following condition becomes true. Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_UNTIL = 'repeat until'; /// tooltip - See [https://github.com/google/blockly/wiki/Loops#repeat-while Loops#repeat-while https://github.com/google/blockly/wiki/Loops#repeat-while Loops#repeat-while]. Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_WHILE = 'While a value is true, then do some statements.'; /// tooltip - See [https://github.com/google/blockly/wiki/Loops#repeat-until https://github.com/google/blockly/wiki/Loops#repeat-until]. Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_UNTIL = 'While a value is false, then do some statements.'; /// url - Describes 'for loops' in computer programs. Consider using your language's translation of [https://en.wikipedia.org/wiki/For_loop https://en.wikipedia.org/wiki/For_loop], if present. Blockly.Msg.CONTROLS_FOR_HELPURL = 'https://github.com/google/blockly/wiki/Loops#count-with'; /// tooltip - See [https://github.com/google/blockly/wiki/Loops#count-with https://github.com/google/blockly/wiki/Loops#count-with].\n\nParameters:\n* %1 - the name of the loop variable. Blockly.Msg.CONTROLS_FOR_TOOLTIP = 'Have the variable "%1" take on the values from the start number to the end number, counting by the specified interval, and do the specified blocks.'; /// block text - Repeatedly counts a variable (%1) /// starting with a (usually lower) number in a range (%2), /// ending with a (usually higher) number in a range (%3), and counting the /// iterations by a number of steps (%4). As in /// [https://github.com/google/blockly/wiki/Loops#count-with /// https://github.com/google/blockly/wiki/Loops#count-with]. /// [[File:Blockly-count-with.png]] Blockly.Msg.CONTROLS_FOR_TITLE = 'count with %1 from %2 to %3 by %4'; Blockly.Msg.CONTROLS_FOR_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO; /// url - Describes 'for-each loops' in computer programs. Consider using your language's translation of [https://en.wikipedia.org/wiki/Foreach https://en.wikipedia.org/wiki/Foreach] if present. Blockly.Msg.CONTROLS_FOREACH_HELPURL = 'https://github.com/google/blockly/wiki/Loops#for-each'; /// block text - Title of [https://github.com/google/blockly/wiki/Loops#for-each for each block]. /// Sequentially assigns every item in array %2 to the valiable %1. Blockly.Msg.CONTROLS_FOREACH_TITLE = 'for each item %1 in list %2'; Blockly.Msg.CONTROLS_FOREACH_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO; /// block text - Description of [https://github.com/google/blockly/wiki/Loops#for-each for each blocks].\n\nParameters:\n* %1 - the name of the loop variable. Blockly.Msg.CONTROLS_FOREACH_TOOLTIP = 'For each item in a list, set the variable "%1" to the item, and then do some statements.'; /// url - Describes control flow in computer programs. Consider using your language's translation of [https://en.wikipedia.org/wiki/Control_flow https://en.wikipedia.org/wiki/Control_flow], if it exists. Blockly.Msg.CONTROLS_FLOW_STATEMENTS_HELPURL = 'https://github.com/google/blockly/wiki/Loops#loop-termination-blocks'; /// dropdown - The current loop should be exited. See [https://github.com/google/blockly/wiki/Loops#break https://github.com/google/blockly/wiki/Loops#break]. Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_BREAK = 'break out of loop'; /// dropdown - The current iteration of the loop should be ended and the next should begin. See [https://github.com/google/blockly/wiki/Loops#continue-with-next-iteration https://github.com/google/blockly/wiki/Loops#continue-with-next-iteration]. Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_CONTINUE = 'continue with next iteration of loop'; /// tooltip - See [https://github.com/google/blockly/wiki/Loops#break-out-of-loop https://github.com/google/blockly/wiki/Loops#break-out-of-loop]. Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_BREAK = 'Break out of the containing loop.'; /// tooltip - See [https://github.com/google/blockly/wiki/Loops#continue-with-next-iteration https://github.com/google/blockly/wiki/Loops#continue-with-next-iteration]. Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_CONTINUE = 'Skip the rest of this loop, and continue with the next iteration.'; /// warning - The user has tried placing a block outside of a loop (for each, while, repeat, etc.), but this type of block may only be used within a loop. See [https://github.com/google/blockly/wiki/Loops#loop-termination-blocks https://github.com/google/blockly/wiki/Loops#loop-termination-blocks]. Blockly.Msg.CONTROLS_FLOW_STATEMENTS_WARNING = 'Warning: This block may only be used within a loop.'; // Logic Blocks. /// url - Describes conditional statements (if-then-else) in computer programs. Consider using your language's translation of [https://en.wikipedia.org/wiki/If_else https://en.wikipedia.org/wiki/If_else], if present. Blockly.Msg.CONTROLS_IF_HELPURL = 'https://github.com/google/blockly/wiki/IfElse'; /// tooltip - Describes [https://github.com/google/blockly/wiki/IfElse#if-blocks 'if' blocks]. Consider using your language's translation of [https://en.wikipedia.org/wiki/If_statement https://en.wikipedia.org/wiki/If_statement], if present. Blockly.Msg.CONTROLS_IF_TOOLTIP_1 = 'If a value is true, then do some statements.'; /// tooltip - Describes [https://github.com/google/blockly/wiki/IfElse#if-else-blocks if-else blocks]. Consider using your language's translation of [https://en.wikipedia.org/wiki/If_statement https://en.wikipedia.org/wiki/If_statement], if present. Blockly.Msg.CONTROLS_IF_TOOLTIP_2 = 'If a value is true, then do the first block of statements. Otherwise, do the second block of statements.'; /// tooltip - Describes [https://github.com/google/blockly/wiki/IfElse#if-else-if-blocks if-else-if blocks]. Consider using your language's translation of [https://en.wikipedia.org/wiki/If_statement https://en.wikipedia.org/wiki/If_statement], if present. Blockly.Msg.CONTROLS_IF_TOOLTIP_3 = 'If the first value is true, then do the first block of statements. Otherwise, if the second value is true, do the second block of statements.'; /// tooltip - Describes [https://github.com/google/blockly/wiki/IfElse#if-else-if-else-blocks if-else-if-else blocks]. Consider using your language's translation of [https://en.wikipedia.org/wiki/If_statement https://en.wikipedia.org/wiki/If_statement], if present. Blockly.Msg.CONTROLS_IF_TOOLTIP_4 = 'If the first value is true, then do the first block of statements. Otherwise, if the second value is true, do the second block of statements. If none of the values are true, do the last block of statements.'; /// block text - See [https://github.com/google/blockly/wiki/IfElse https://github.com/google/blockly/wiki/IfElse]. /// It is recommended, but not essential, that this have text in common with the translation of 'else if' Blockly.Msg.CONTROLS_IF_MSG_IF = 'if'; /// block text - See [https://github.com/google/blockly/wiki/IfElse https://github.com/google/blockly/wiki/IfElse]. The English words "otherwise if" would probably be clearer than "else if", but the latter is used because it is traditional and shorter. Blockly.Msg.CONTROLS_IF_MSG_ELSEIF = 'else if'; /// block text - See [https://github.com/google/blockly/wiki/IfElse https://github.com/google/blockly/wiki/IfElse]. The English word "otherwise" would probably be superior to "else", but the latter is used because it is traditional and shorter. Blockly.Msg.CONTROLS_IF_MSG_ELSE = 'else'; Blockly.Msg.CONTROLS_IF_MSG_THEN = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO; Blockly.Msg.CONTROLS_IF_IF_TITLE_IF = Blockly.Msg.CONTROLS_IF_MSG_IF; /// tooltip - Describes [https://github.com/google/blockly/wiki/IfElse#block-modification if block modification]. Blockly.Msg.CONTROLS_IF_IF_TOOLTIP = 'Add, remove, or reorder sections to reconfigure this if block.'; Blockly.Msg.CONTROLS_IF_ELSEIF_TITLE_ELSEIF = Blockly.Msg.CONTROLS_IF_MSG_ELSEIF; /// tooltip - Describes the 'else if' subblock during [https://github.com/google/blockly/wiki/IfElse#block-modification if block modification]. Blockly.Msg.CONTROLS_IF_ELSEIF_TOOLTIP = 'Add a condition to the if block.'; Blockly.Msg.CONTROLS_IF_ELSE_TITLE_ELSE = Blockly.Msg.CONTROLS_IF_MSG_ELSE; /// tooltip - Describes the 'else' subblock during [https://github.com/google/blockly/wiki/IfElse#block-modification if block modification]. Blockly.Msg.CONTROLS_IF_ELSE_TOOLTIP = 'Add a final, catch-all condition to the if block.'; /// url - Information about comparisons. Blockly.Msg.LOGIC_COMPARE_HELPURL = 'https://en.wikipedia.org/wiki/Inequality_(mathematics)'; /// tooltip - Describes the equals (=) block. Blockly.Msg.LOGIC_COMPARE_TOOLTIP_EQ = 'Return true if both inputs equal each other.'; /// tooltip - Describes the not equals (≠) block. Blockly.Msg.LOGIC_COMPARE_TOOLTIP_NEQ = 'Return true if both inputs are not equal to each other.'; /// tooltip - Describes the less than (<) block. Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LT = 'Return true if the first input is smaller than the second input.'; /// tooltip - Describes the less than or equals (≤) block. Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LTE = 'Return true if the first input is smaller than or equal to the second input.'; /// tooltip - Describes the greater than (>) block. Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GT = 'Return true if the first input is greater than the second input.'; /// tooltip - Describes the greater than or equals (≥) block. Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GTE = 'Return true if the first input is greater than or equal to the second input.'; /// url - Information about the Boolean conjunction ("and") and disjunction ("or") operators. Consider using the translation of [https://en.wikipedia.org/wiki/Boolean_logic https://en.wikipedia.org/wiki/Boolean_logic], if it exists in your language. Blockly.Msg.LOGIC_OPERATION_HELPURL = 'https://github.com/google/blockly/wiki/Logic#logical-operations'; /// tooltip - See [https://en.wikipedia.org/wiki/Logical_conjunction https://en.wikipedia.org/wiki/Logical_conjunction]. Blockly.Msg.LOGIC_OPERATION_TOOLTIP_AND = 'Return true if both inputs are true.'; /// block text - See [https://en.wikipedia.org/wiki/Logical_conjunction https://en.wikipedia.org/wiki/Logical_conjunction].\n{{Identical|And}} Blockly.Msg.LOGIC_OPERATION_AND = 'and'; /// block text - See [https://en.wikipedia.org/wiki/Disjunction https://en.wikipedia.org/wiki/Disjunction]. Blockly.Msg.LOGIC_OPERATION_TOOLTIP_OR = 'Return true if at least one of the inputs is true.'; /// block text - See [https://en.wikipedia.org/wiki/Disjunction https://en.wikipedia.org/wiki/Disjunction].\n{{Identical|Or}} Blockly.Msg.LOGIC_OPERATION_OR = 'or'; /// url - Information about logical negation. The translation of [https://en.wikipedia.org/wiki/Logical_negation https://en.wikipedia.org/wiki/Logical_negation] is recommended if it exists in the target language. Blockly.Msg.LOGIC_NEGATE_HELPURL = 'https://github.com/google/blockly/wiki/Logic#not'; /// block text - This is a unary operator that returns ''false'' when the input is ''true'', and ''true'' when the input is ''false''. /// \n\nParameters:\n* %1 - the input (which should be either the value "true" or "false") Blockly.Msg.LOGIC_NEGATE_TITLE = 'not %1'; /// tooltip - See [https://en.wikipedia.org/wiki/Logical_negation https://en.wikipedia.org/wiki/Logical_negation]. Blockly.Msg.LOGIC_NEGATE_TOOLTIP = 'Returns true if the input is false. Returns false if the input is true.'; /// url - Information about the logic values ''true'' and ''false''. Consider using the translation of [https://en.wikipedia.org/wiki/Truth_value https://en.wikipedia.org/wiki/Truth_value] if it exists in your language. Blockly.Msg.LOGIC_BOOLEAN_HELPURL = 'https://github.com/google/blockly/wiki/Logic#values'; /// block text - The word for the [https://en.wikipedia.org/wiki/Truth_value logical value] ''true''.\n{{Identical|True}} Blockly.Msg.LOGIC_BOOLEAN_TRUE = 'true'; /// block text - The word for the [https://en.wikipedia.org/wiki/Truth_value logical value] ''false''.\n{{Identical|False}} Blockly.Msg.LOGIC_BOOLEAN_FALSE = 'false'; /// tooltip - Indicates that the block returns either of the two possible [https://en.wikipedia.org/wiki/Truth_value logical values]. Blockly.Msg.LOGIC_BOOLEAN_TOOLTIP = 'Returns either true or false.'; /// url - Provide a link to the translation of [https://en.wikipedia.org/wiki/Nullable_type https://en.wikipedia.org/wiki/Nullable_type], if it exists in your language; otherwise, do not worry about translating this advanced concept. Blockly.Msg.LOGIC_NULL_HELPURL = 'https://en.wikipedia.org/wiki/Nullable_type'; /// block text - In computer languages, ''null'' is a special value that indicates that no value has been set. You may use your language's word for "nothing" or "invalid".\n{{Identical|Null}} Blockly.Msg.LOGIC_NULL = 'null'; /// tooltip - This should use the word from the previous message. Blockly.Msg.LOGIC_NULL_TOOLTIP = 'Returns null.'; /// url - Describes the programming language operator known as the ''ternary'' or ''conditional'' operator. It is recommended that you use the translation of [https://en.wikipedia.org/wiki/%3F: https://en.wikipedia.org/wiki/%3F:] if it exists. Blockly.Msg.LOGIC_TERNARY_HELPURL = 'https://en.wikipedia.org/wiki/%3F:'; /// block input text - Label for the input whose value determines which of the other two inputs is returned. In some programming languages, this is called a ''''predicate''''. Blockly.Msg.LOGIC_TERNARY_CONDITION = 'test'; /// block input text - Indicates that the following input should be returned (used as output) if the test input is true. Remember to try to keep block text terse (short). Blockly.Msg.LOGIC_TERNARY_IF_TRUE = 'if true'; /// block input text - Indicates that the following input should be returned (used as output) if the test input is false. Blockly.Msg.LOGIC_TERNARY_IF_FALSE = 'if false'; /// tooltip - See [https://en.wikipedia.org/wiki/%3F: https://en.wikipedia.org/wiki/%3F:]. Blockly.Msg.LOGIC_TERNARY_TOOLTIP = 'Check the condition in "test". If the condition is true, returns the "if true" value; otherwise returns the "if false" value.'; // Math Blocks. /// url - Information about (real) numbers. Blockly.Msg.MATH_NUMBER_HELPURL = 'https://en.wikipedia.org/wiki/Number'; /// tooltip - Any positive or negative number, not necessarily an integer. Blockly.Msg.MATH_NUMBER_TOOLTIP = 'A number.'; /// {{optional}}\nmath - The symbol for the binary operation addition. Blockly.Msg.MATH_ADDITION_SYMBOL = '+'; /// {{optional}}\nmath - The symbol for the binary operation indicating that the right operand should be /// subtracted from the left operand. Blockly.Msg.MATH_SUBTRACTION_SYMBOL = '-'; /// {{optional}}\nmath - The binary operation indicating that the left operand should be divided by /// the right operand. Blockly.Msg.MATH_DIVISION_SYMBOL = '÷'; /// {{optional}}\nmath - The symbol for the binary operation multiplication. Blockly.Msg.MATH_MULTIPLICATION_SYMBOL = '×'; /// {{optional}}\nmath - The symbol for the binary operation exponentiation. Specifically, if the /// value of the left operand is L and the value of the right operand (the exponent) is /// R, multiply L by itself R times. (Fractional and negative exponents are also legal.) Blockly.Msg.MATH_POWER_SYMBOL = '^'; /// math - The short name of the trigonometric function /// [https://en.wikipedia.org/wiki/Trigonometric_functions#Sine.2C_cosine_and_tangent sine]. Blockly.Msg.MATH_TRIG_SIN = 'sin'; /// math - The short name of the trigonometric function /// [https://en.wikipedia.org/wiki/Trigonometric_functions#Sine.2C_cosine_and_tangent cosine]. Blockly.Msg.MATH_TRIG_COS = 'cos'; /// math - The short name of the trigonometric function /// [https://en.wikipedia.org/wiki/Trigonometric_functions#Sine.2C_cosine_and_tangent tangent]. Blockly.Msg.MATH_TRIG_TAN = 'tan'; /// math - The short name of the ''inverse of'' the trigonometric function /// [https://en.wikipedia.org/wiki/Trigonometric_functions#Sine.2C_cosine_and_tangent sine]. Blockly.Msg.MATH_TRIG_ASIN = 'asin'; /// math - The short name of the ''inverse of'' the trigonometric function /// [https://en.wikipedia.org/wiki/Trigonometric_functions#Sine.2C_cosine_and_tangent cosine]. Blockly.Msg.MATH_TRIG_ACOS = 'acos'; /// math - The short name of the ''inverse of'' the trigonometric function /// [https://en.wikipedia.org/wiki/Trigonometric_functions#Sine.2C_cosine_and_tangent tangent]. Blockly.Msg.MATH_TRIG_ATAN = 'atan'; /// url - Information about addition, subtraction, multiplication, division, and exponentiation. Blockly.Msg.MATH_ARITHMETIC_HELPURL = 'https://en.wikipedia.org/wiki/Arithmetic'; /// tooltip - See [https://en.wikipedia.org/wiki/Addition https://en.wikipedia.org/wiki/Addition]. Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_ADD = 'Return the sum of the two numbers.'; /// tooltip - See [https://en.wikipedia.org/wiki/Subtraction https://en.wikipedia.org/wiki/Subtraction]. Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MINUS = 'Return the difference of the two numbers.'; /// tooltip - See [https://en.wikipedia.org/wiki/Multiplication https://en.wikipedia.org/wiki/Multiplication]. Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MULTIPLY = 'Return the product of the two numbers.'; /// tooltip - See [https://en.wikipedia.org/wiki/Division_(mathematics) https://en.wikipedia.org/wiki/Division_(mathematics)]. Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_DIVIDE = 'Return the quotient of the two numbers.'; /// tooltip - See [https://en.wikipedia.org/wiki/Exponentiation https://en.wikipedia.org/wiki/Exponentiation]. Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_POWER = 'Return the first number raised to the power of the second number.'; /// url - Information about the square root operation. Blockly.Msg.MATH_SINGLE_HELPURL = 'https://en.wikipedia.org/wiki/Square_root'; /// dropdown - This computes the positive [https://en.wikipedia.org/wiki/Square_root square root] of its input. For example, the square root of 16 is 4. Blockly.Msg.MATH_SINGLE_OP_ROOT = 'square root'; /// tooltip - Please use the same term as in the previous message. Blockly.Msg.MATH_SINGLE_TOOLTIP_ROOT = 'Return the square root of a number.'; /// dropdown - This leaves positive numeric inputs changed and inverts negative inputs. For example, the absolute value of 5 is 5; the absolute value of -5 is also 5. For more information, see [https://en.wikipedia.org/wiki/Absolute_value https://en.wikipedia.org/wiki/Absolute_value]. Blockly.Msg.MATH_SINGLE_OP_ABSOLUTE = 'absolute'; /// tooltip - Please use the same term as in the previous message. Blockly.Msg.MATH_SINGLE_TOOLTIP_ABS = 'Return the absolute value of a number.'; /// tooltip - Calculates '''0-n''', where '''n''' is the single numeric input. Blockly.Msg.MATH_SINGLE_TOOLTIP_NEG = 'Return the negation of a number.'; /// tooltip - Calculates the [https://en.wikipedia.org/wiki/Natural_logarithm|natural logarithm] of its single numeric input. Blockly.Msg.MATH_SINGLE_TOOLTIP_LN = 'Return the natural logarithm of a number.'; /// tooltip - Calculates the [https://en.wikipedia.org/wiki/Common_logarithm common logarithm] of its single numeric input. Blockly.Msg.MATH_SINGLE_TOOLTIP_LOG10 = 'Return the base 10 logarithm of a number.'; /// tooltip - Multiplies [https://en.wikipedia.org/wiki/E_%28mathematical_constant%29 e] by itself n times, where n is the single numeric input. Blockly.Msg.MATH_SINGLE_TOOLTIP_EXP = 'Return e to the power of a number.'; /// tooltip - Multiplies 10 by itself n times, where n is the single numeric input. Blockly.Msg.MATH_SINGLE_TOOLTIP_POW10 = 'Return 10 to the power of a number.'; /// url - Information about the trigonometric functions sine, cosine, tangent, and their inverses (ideally using degrees, not radians). Blockly.Msg.MATH_TRIG_HELPURL = 'https://en.wikipedia.org/wiki/Trigonometric_functions'; /// tooltip - Return the [https://en.wikipedia.org/wiki/Trigonometric_functions#Sine.2C_cosine_and_tangent sine] of an [https://en.wikipedia.org/wiki/Degree_(angle) angle in degrees], not radians. Blockly.Msg.MATH_TRIG_TOOLTIP_SIN = 'Return the sine of a degree (not radian).'; /// tooltip - Return the [https://en.wikipedia.org/wiki/Trigonometric_functions#Sine.2C_cosine_and_tangent cosine] of an [https://en.wikipedia.org/wiki/Degree_(angle) angle in degrees], not radians. Blockly.Msg.MATH_TRIG_TOOLTIP_COS = 'Return the cosine of a degree (not radian).'; /// tooltip - Return the [https://en.wikipedia.org/wiki/Trigonometric_functions#Sine.2C_cosine_and_tangent tangent] of an [https://en.wikipedia.org/wiki/Degree_(angle) angle in degrees], not radians. Blockly.Msg.MATH_TRIG_TOOLTIP_TAN = 'Return the tangent of a degree (not radian).'; /// tooltip - The [https://en.wikipedia.org/wiki/Inverse_trigonometric_functions inverse] of the [https://en.wikipedia.org/wiki/Cosine#Sine.2C_cosine_and_tangent sine function], using [https://en.wikipedia.org/wiki/Degree_(angle) degrees], not radians. Blockly.Msg.MATH_TRIG_TOOLTIP_ASIN = 'Return the arcsine of a number.'; /// tooltip - The [https://en.wikipedia.org/wiki/Inverse_trigonometric_functions inverse] of the [https://en.wikipedia.org/wiki/Cosine#Sine.2C_cosine_and_tangent cosine] function, using [https://en.wikipedia.org/wiki/Degree_(angle) degrees], not radians. Blockly.Msg.MATH_TRIG_TOOLTIP_ACOS = 'Return the arccosine of a number.'; /// tooltip - The [https://en.wikipedia.org/wiki/Inverse_trigonometric_functions inverse] of the [https://en.wikipedia.org/wiki/Cosine#Sine.2C_cosine_and_tangent tangent] function, using [https://en.wikipedia.org/wiki/Degree_(angle) degrees], not radians. Blockly.Msg.MATH_TRIG_TOOLTIP_ATAN = 'Return the arctangent of a number.'; /// url - Information about the mathematical constants Pi (π), e, the golden ratio (φ), √ 2, √ 1/2, and infinity (∞). Blockly.Msg.MATH_CONSTANT_HELPURL = 'https://en.wikipedia.org/wiki/Mathematical_constant'; /// tooltip - Provides the specified [https://en.wikipedia.org/wiki/Mathematical_constant mathematical constant]. Blockly.Msg.MATH_CONSTANT_TOOLTIP = 'Return one of the common constants: π (3.141…), e (2.718…), φ (1.618…), sqrt(2) (1.414…), sqrt(½) (0.707…), or ∞ (infinity).'; /// dropdown - A number is '''even''' if it is a multiple of 2. For example, 4 is even (yielding true), but 3 is not (false). Blockly.Msg.MATH_IS_EVEN = 'is even'; /// dropdown - A number is '''odd''' if it is not a multiple of 2. For example, 3 is odd (yielding true), but 4 is not (false). The opposite of "odd" is "even". Blockly.Msg.MATH_IS_ODD = 'is odd'; /// dropdown - A number is [https://en.wikipedia.org/wiki/Prime prime] if it cannot be evenly divided by any positive integers except for 1 and itself. For example, 5 is prime, but 6 is not because 2 × 3 = 6. Blockly.Msg.MATH_IS_PRIME = 'is prime'; /// dropdown - A number is '''whole''' if it is an [https://en.wikipedia.org/wiki/Integer integer]. For example, 5 is whole, but 5.1 is not. Blockly.Msg.MATH_IS_WHOLE = 'is whole'; /// dropdown - A number is '''positive''' if it is greater than 0. (0 is neither negative nor positive.) Blockly.Msg.MATH_IS_POSITIVE = 'is positive'; /// dropdown - A number is '''negative''' if it is less than 0. (0 is neither negative nor positive.) Blockly.Msg.MATH_IS_NEGATIVE = 'is negative'; /// dropdown - A number x is divisible by y if y goes into x evenly. For example, 10 is divisible by 5, but 10 is not divisible by 3. Blockly.Msg.MATH_IS_DIVISIBLE_BY = 'is divisible by'; /// tooltip - This block lets the user specify via a dropdown menu whether to check if the numeric input is even, odd, prime, whole, positive, negative, or divisible by a given value. Blockly.Msg.MATH_IS_TOOLTIP = 'Check if a number is an even, odd, prime, whole, positive, negative, or if it is divisible by certain number. Returns true or false.'; /// url - Information about incrementing (increasing the value of) a variable. /// For other languages, just use the translation of the Wikipedia page about /// addition ([https://en.wikipedia.org/wiki/Addition https://en.wikipedia.org/wiki/Addition]). Blockly.Msg.MATH_CHANGE_HELPURL = 'https://en.wikipedia.org/wiki/Programming_idiom#Incrementing_a_counter'; /// - As in: ''change'' [the value of variable] ''item'' ''by'' 1 (e.g., if the variable named 'item' had the value 5, change it to 6). /// %1 is a variable name. /// %2 is the amount of change. Blockly.Msg.MATH_CHANGE_TITLE = 'change %1 by %2'; Blockly.Msg.MATH_CHANGE_TITLE_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME; /// tooltip - This updates the value of the variable by adding to it the following numeric input.\n\nParameters:\n* %1 - the name of the variable whose value should be increased. Blockly.Msg.MATH_CHANGE_TOOLTIP = 'Add a number to variable "%1".'; /// url - Information about how numbers are rounded to the nearest integer Blockly.Msg.MATH_ROUND_HELPURL = 'https://en.wikipedia.org/wiki/Rounding'; /// tooltip - See [https://en.wikipedia.org/wiki/Rounding https://en.wikipedia.org/wiki/Rounding]. Blockly.Msg.MATH_ROUND_TOOLTIP = 'Round a number up or down.'; /// dropdown - This rounds its input to the nearest whole number. For example, 3.4 is rounded to 3. Blockly.Msg.MATH_ROUND_OPERATOR_ROUND = 'round'; /// dropdown - This rounds its input up to the nearest whole number. For example, if the input was 2.2, the result would be 3. Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDUP = 'round up'; /// dropdown - This rounds its input down to the nearest whole number. For example, if the input was 3.8, the result would be 3. Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDDOWN = 'round down'; /// url - Information about applying a function to a list of numbers. (We were unable to find such information in English. Feel free to skip this and any other URLs that are difficult.) Blockly.Msg.MATH_ONLIST_HELPURL = ''; /// dropdown - This computes the sum of the numeric elements in the list. For example, the sum of the list {1, 4} is 5. Blockly.Msg.MATH_ONLIST_OPERATOR_SUM = 'sum of list'; /// tooltip - Please use the same term for "sum" as in the previous message. Blockly.Msg.MATH_ONLIST_TOOLTIP_SUM = 'Return the sum of all the numbers in the list.'; /// dropdown - This finds the smallest (minimum) number in a list. For example, the smallest number in the list [-5, 0, 3] is -5. Blockly.Msg.MATH_ONLIST_OPERATOR_MIN = 'min of list'; /// tooltip - Please use the same term for "min" or "minimum" as in the previous message. Blockly.Msg.MATH_ONLIST_TOOLTIP_MIN = 'Return the smallest number in the list.'; /// dropdown - This finds the largest (maximum) number in a list. For example, the largest number in the list [-5, 0, 3] is 3. Blockly.Msg.MATH_ONLIST_OPERATOR_MAX = 'max of list'; /// tooltip Blockly.Msg.MATH_ONLIST_TOOLTIP_MAX = 'Return the largest number in the list.'; /// dropdown - This adds up all of the numbers in a list and divides the sum by the number of elements in the list. For example, the [https://en.wikipedia.org/wiki/Arithmetic_mean average] of the list [1, 2, 3, 4] is 2.5 (10/4). Blockly.Msg.MATH_ONLIST_OPERATOR_AVERAGE = 'average of list'; /// tooltip - See [https://en.wikipedia.org/wiki/Arithmetic_mean https://en.wikipedia.org/wiki/Arithmetic_mean] for more informatin. Blockly.Msg.MATH_ONLIST_TOOLTIP_AVERAGE = 'Return the average (arithmetic mean) of the numeric values in the list.'; /// dropdown - This finds the [https://en.wikipedia.org/wiki/Median median] of the numeric values in a list. For example, the median of the list {1, 2, 7, 12, 13} is 7. Blockly.Msg.MATH_ONLIST_OPERATOR_MEDIAN = 'median of list'; /// tooltip - See [https://en.wikipedia.org/wiki/Median median https://en.wikipedia.org/wiki/Median median] for more information. Blockly.Msg.MATH_ONLIST_TOOLTIP_MEDIAN = 'Return the median number in the list.'; /// dropdown - This finds the most common numbers ([https://en.wikipedia.org/wiki/Mode_(statistics) modes]) in a list. For example, the modes of the list {1, 3, 9, 3, 9} are {3, 9}. Blockly.Msg.MATH_ONLIST_OPERATOR_MODE = 'modes of list'; /// tooltip - See [https://en.wikipedia.org/wiki/Mode_(statistics) https://en.wikipedia.org/wiki/Mode_(statistics)] for more information. Blockly.Msg.MATH_ONLIST_TOOLTIP_MODE = 'Return a list of the most common item(s) in the list.'; /// dropdown - This finds the [https://en.wikipedia.org/wiki/Standard_deviation standard deviation] of the numeric values in a list. Blockly.Msg.MATH_ONLIST_OPERATOR_STD_DEV = 'standard deviation of list'; /// tooltip - See [https://en.wikipedia.org/wiki/Standard_deviation https://en.wikipedia.org/wiki/Standard_deviation] for more information. Blockly.Msg.MATH_ONLIST_TOOLTIP_STD_DEV = 'Return the standard deviation of the list.'; /// dropdown - This choose an element at random from a list. Each element is chosen with equal probability. Blockly.Msg.MATH_ONLIST_OPERATOR_RANDOM = 'random item of list'; /// tooltip - Please use same term for 'random' as in previous entry. Blockly.Msg.MATH_ONLIST_TOOLTIP_RANDOM = 'Return a random element from the list.'; /// url - information about the modulo (remainder) operation. Blockly.Msg.MATH_MODULO_HELPURL = 'https://en.wikipedia.org/wiki/Modulo_operation'; /// block text - Title of block providing the remainder when dividing the first numerical input by the second. For example, the remainder of 10 divided by 3 is 1.\n\nParameters:\n* %1 - the dividend (10, in our example)\n* %2 - the divisor (3 in our example). Blockly.Msg.MATH_MODULO_TITLE = 'remainder of %1 ÷ %2'; /// tooltip - For example, the remainder of 10 divided by 3 is 1. Blockly.Msg.MATH_MODULO_TOOLTIP = 'Return the remainder from dividing the two numbers.'; /// url - Information about constraining a numeric value to be in a specific range. (The English URL is not ideal. Recall that translating URLs is the lowest priority.) Blockly.Msg.MATH_CONSTRAIN_HELPURL = 'https://en.wikipedia.org/wiki/Clamping_%28graphics%29'; /// block text - The title of the block that '''constrain'''s (forces) a number to be in a given range. ///For example, if the number 150 is constrained to be between 5 and 100, the result will be 100. ///\n\nParameters:\n* %1 - the value to constrain (e.g., 150)\n* %2 - the minimum value (e.g., 5)\n* %3 - the maximum value (e.g., 100). Blockly.Msg.MATH_CONSTRAIN_TITLE = 'constrain %1 low %2 high %3'; /// tooltip - This compares a number ''x'' to a low value ''L'' and a high value ''H''. If ''x'' is less then ''L'', the result is ''L''. If ''x'' is greater than ''H'', the result is ''H''. Otherwise, the result is ''x''. Blockly.Msg.MATH_CONSTRAIN_TOOLTIP = 'Constrain a number to be between the specified limits (inclusive).'; /// url - Information about how computers generate random numbers. Blockly.Msg.MATH_RANDOM_INT_HELPURL = 'https://en.wikipedia.org/wiki/Random_number_generation'; /// block text - The title of the block that generates a random integer (whole number) in the specified range. For example, if the range is from 5 to 7, this returns 5, 6, or 7 with equal likelihood. %1 is a placeholder for the lower number, %2 is the placeholder for the larger number. Blockly.Msg.MATH_RANDOM_INT_TITLE = 'random integer from %1 to %2'; /// tooltip - Return a random integer between two values specified as inputs. For example, if one input was 7 and another 9, any of the numbers 7, 8, or 9 could be produced. Blockly.Msg.MATH_RANDOM_INT_TOOLTIP = 'Return a random integer between the two specified limits, inclusive.'; /// url - Information about how computers generate random numbers (specifically, numbers in the range from 0 to just below 1). Blockly.Msg.MATH_RANDOM_FLOAT_HELPURL = 'https://en.wikipedia.org/wiki/Random_number_generation'; /// block text - The title of the block that generates a random number greater than or equal to 0 and less than 1. Blockly.Msg.MATH_RANDOM_FLOAT_TITLE_RANDOM = 'random fraction'; /// tooltip - Return a random fraction between 0 and 1. The value may be equal to 0 but must be less than 1. Blockly.Msg.MATH_RANDOM_FLOAT_TOOLTIP = 'Return a random fraction between 0.0 (inclusive) and 1.0 (exclusive).'; // Text Blocks. /// url - Information about how computers represent text (sometimes referred to as ''string''s). Blockly.Msg.TEXT_TEXT_HELPURL = 'https://en.wikipedia.org/wiki/String_(computer_science)'; /// tooltip - See [https://github.com/google/blockly/wiki/Text https://github.com/google/blockly/wiki/Text]. Blockly.Msg.TEXT_TEXT_TOOLTIP = 'A letter, word, or line of text.'; /// url - Information on concatenating/appending pieces of text. Blockly.Msg.TEXT_JOIN_HELPURL = 'https://github.com/google/blockly/wiki/Text#text-creation'; /// block text - See [https://github.com/google/blockly/wiki/Text#text-creation https://github.com/google/blockly/wiki/Text#text-creation]. Blockly.Msg.TEXT_JOIN_TITLE_CREATEWITH = 'create text with'; /// tooltip - See [https://github.com/google/blockly/wiki/Text#text-creation create text with] for more information. Blockly.Msg.TEXT_JOIN_TOOLTIP = 'Create a piece of text by joining together any number of items.'; /// block text - This is shown when the programmer wants to change the number of pieces of text being joined together. See [https://github.com/google/blockly/wiki/Text#text-creation https://github.com/google/blockly/wiki/Text#text-creation], specifically the last picture in the 'Text creation' section.\n{{Identical|Join}} Blockly.Msg.TEXT_CREATE_JOIN_TITLE_JOIN = 'join'; /// tooltip - See [https://github.com/google/blockly/wiki/Text#text-creation https://github.com/google/blockly/wiki/Text#text-creation], specifically the last picture in the 'Text creation' section. Blockly.Msg.TEXT_CREATE_JOIN_TOOLTIP = 'Add, remove, or reorder sections to reconfigure this text block.'; Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TITLE_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME; /// block text - See [https://github.com/google/blockly/wiki/Text#text-creation https://github.com/google/blockly/wiki/Text#text-creation], specifically the last picture in the 'Text creation' section. Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TOOLTIP = 'Add an item to the text.'; /// url - This and the other text-related URLs are going to be hard to translate. As always, it is okay to leave untranslated or paste in the English-language URL. For these URLs, you might also consider a general URL about how computers represent text (such as the translation of [https://en.wikipedia.org/wiki/String_(computer_science) this Wikipedia page]). Blockly.Msg.TEXT_APPEND_HELPURL = 'https://github.com/google/blockly/wiki/Text#text-modification'; /// block input text - Message preceding the name of a variable to which text should be appended. /// [[File:blockly-append-text.png]] Blockly.Msg.TEXT_APPEND_TO = 'to'; /// block input text - Message following the variable and preceding the piece of text that should /// be appended, as shown below. /// [[File:blockly-append-text.png]] Blockly.Msg.TEXT_APPEND_APPENDTEXT = 'append text'; Blockly.Msg.TEXT_APPEND_VARIABLE = Blockly.Msg.VARIABLES_DEFAULT_NAME; /// tooltip - See [https://github.com/google/blockly/wiki/Text#text-modification https://github.com/google/blockly/wiki/Text#text-modification] for more information.\n\nParameters:\n* %1 - the name of the variable to which text should be appended Blockly.Msg.TEXT_APPEND_TOOLTIP = 'Append some text to variable "%1".'; /// url - Information about text on computers (usually referred to as 'strings'). Blockly.Msg.TEXT_LENGTH_HELPURL = 'https://github.com/google/blockly/wiki/Text#text-modification'; /// block text - See [https://github.com/google/blockly/wiki/Text#text-length https://github.com/google/blockly/wiki/Text#text-length]. /// \n\nParameters:\n* %1 - the piece of text to take the length of Blockly.Msg.TEXT_LENGTH_TITLE = 'length of %1'; /// tooltip - See [https://github.com/google/blockly/wiki/Text#text-length https://github.com/google/blockly/wiki/Text#text-length]. Blockly.Msg.TEXT_LENGTH_TOOLTIP = 'Returns the number of letters (including spaces) in the provided text.'; /// url - Information about empty pieces of text on computers (usually referred to as 'empty strings'). Blockly.Msg.TEXT_ISEMPTY_HELPURL = 'https://github.com/google/blockly/wiki/Text#checking-for-empty-text'; /// block text - See [https://github.com/google/blockly/wiki/Text#checking-for-empty-text https://github.com/google/blockly/wiki/Text#checking-for-empty-text]. /// \n\nParameters:\n* %1 - the piece of text to test for emptiness Blockly.Msg.TEXT_ISEMPTY_TITLE = '%1 is empty'; /// tooltip - See [https://github.com/google/blockly/wiki/Text#checking-for-empty-text https://github.com/google/blockly/wiki/Text#checking-for-empty-text]. Blockly.Msg.TEXT_ISEMPTY_TOOLTIP = 'Returns true if the provided text is empty.'; /// url - Information about finding a character in a piece of text. Blockly.Msg.TEXT_INDEXOF_HELPURL = 'https://github.com/google/blockly/wiki/Text#finding-text'; /// tooltip - See [https://github.com/google/blockly/wiki/Text#finding-text https://github.com/google/blockly/wiki/Text#finding-text]. Blockly.Msg.TEXT_INDEXOF_TOOLTIP = 'Returns the index of the first/last occurrence of the first text in the second text. Returns 0 if text is not found.'; /// block text - Title of blocks allowing users to find text. See /// [https://github.com/google/blockly/wiki/Text#finding-text /// https://github.com/google/blockly/wiki/Text#finding-text]. /// [[File:Blockly-find-text.png]]. Blockly.Msg.TEXT_INDEXOF_INPUT_INTEXT = 'in text'; /// dropdown - See [https://github.com/google/blockly/wiki/Text#finding-text /// https://github.com/google/blockly/wiki/Text#finding-text]. /// [[File:Blockly-find-text.png]]. Blockly.Msg.TEXT_INDEXOF_OPERATOR_FIRST = 'find first occurrence of text'; /// dropdown - See [https://github.com/google/blockly/wiki/Text#finding-text /// https://github.com/google/blockly/wiki/Text#finding-text]. This would /// replace "find first occurrence of text" below. (For more information on /// how common text is factored out of dropdown menus, see /// [https://translatewiki.net/wiki/Translating:Blockly#Drop-Down_Menus /// https://translatewiki.net/wiki/Translating:Blockly#Drop-Down_Menus)].) /// [[File:Blockly-find-text.png]]. Blockly.Msg.TEXT_INDEXOF_OPERATOR_LAST = 'find last occurrence of text'; /// block text - Optional text to follow the rightmost block in a /// [https://github.com/google/blockly/wiki/Text#finding-text /// https://github.com/google/blockly/wiki/Text#finding-text in text ... find block] /// (after the "a" in the below picture). This will be the empty string in most languages. /// [[File:Blockly-find-text.png]]. Blockly.Msg.TEXT_INDEXOF_TAIL = ''; /// url - Information about extracting characters (letters, number, symbols, etc.) from text. Blockly.Msg.TEXT_CHARAT_HELPURL = 'https://github.com/google/blockly/wiki/Text#extracting-text'; /// block text - Appears before the piece of text from which a letter (or number, /// punctuation character, etc.) should be extracted, as shown below. See /// [https://github.com/google/blockly/wiki/Text#extracting-a-single-character /// https://github.com/google/blockly/wiki/Text#extracting-a-single-character]. /// [[File:Blockly-text-get.png]] Blockly.Msg.TEXT_CHARAT_INPUT_INTEXT = 'in text'; /// dropdown - Indicates that the letter (or number, punctuation character, etc.) with the /// specified index should be obtained from the preceding piece of text. See /// [https://github.com/google/blockly/wiki/Text#extracting-a-single-character /// https://github.com/google/blockly/wiki/Text#extracting-a-single-character]. /// [[File:Blockly-text-get.png]] Blockly.Msg.TEXT_CHARAT_FROM_START = 'get letter #'; /// block text - Indicates that the letter (or number, punctuation character, etc.) with the /// specified index from the end of a given piece of text should be obtained. See /// [https://github.com/google/blockly/wiki/Text#extracting-a-single-character /// https://github.com/google/blockly/wiki/Text#extracting-a-single-character]. /// [[File:Blockly-text-get.png]] Blockly.Msg.TEXT_CHARAT_FROM_END = 'get letter # from end'; /// block text - Indicates that the first letter of the following piece of text should be /// retrieved. See [https://github.com/google/blockly/wiki/Text#extracting-a-single-character /// https://github.com/google/blockly/wiki/Text#extracting-a-single-character]. /// [[File:Blockly-text-get.png]] Blockly.Msg.TEXT_CHARAT_FIRST = 'get first letter'; /// block text - Indicates that the last letter (or number, punctuation mark, etc.) of the /// following piece of text should be retrieved. See /// [https://github.com/google/blockly/wiki/Text#extracting-a-single-character /// https://github.com/google/blockly/wiki/Text#extracting-a-single-character]. /// [[File:Blockly-text-get.png]] Blockly.Msg.TEXT_CHARAT_LAST = 'get last letter'; /// block text - Indicates that any letter (or number, punctuation mark, etc.) in the /// following piece of text should be randomly selected. See /// [https://github.com/google/blockly/wiki/Text#extracting-a-single-character /// https://github.com/google/blockly/wiki/Text#extracting-a-single-character]. /// [[File:Blockly-text-get.png]] Blockly.Msg.TEXT_CHARAT_RANDOM = 'get random letter'; /// block text - Text that goes after the rightmost block/dropdown when getting a single letter from /// a piece of text, as in [https://blockly-demo.appspot.com/static/apps/code/index.html#3m23km these /// blocks] or shown below. For most languages, this will be blank. /// [[File:Blockly-text-get.png]] Blockly.Msg.TEXT_CHARAT_TAIL = ''; /// tooltip - See [https://github.com/google/blockly/wiki/Text#extracting-a-single-character /// https://github.com/google/blockly/wiki/Text#extracting-a-single-character]. /// [[File:Blockly-text-get.png]] Blockly.Msg.TEXT_CHARAT_TOOLTIP = 'Returns the letter at the specified position.'; /// See [https://github.com/google/blockly/wiki/Text#extracting-a-region-of-text /// https://github.com/google/blockly/wiki/Text#extracting-a-region-of-text]. Blockly.Msg.TEXT_GET_SUBSTRING_TOOLTIP = 'Returns a specified portion of the text.'; /// url - Information about extracting characters from text. Reminder: urls are the /// lowest priority translations. Feel free to skip. Blockly.Msg.TEXT_GET_SUBSTRING_HELPURL = 'https://github.com/google/blockly/wiki/Text#extracting-a-region-of-text'; /// block text - Precedes a piece of text from which a portion should be extracted. /// [[File:Blockly-get-substring.png]] Blockly.Msg.TEXT_GET_SUBSTRING_INPUT_IN_TEXT = 'in text'; /// dropdown - Indicates that the following number specifies the position (relative to the start /// position) of the beginning of the region of text that should be obtained from the preceding /// piece of text. See [https://github.com/google/blockly/wiki/Text#extracting-a-region-of-text /// https://github.com/google/blockly/wiki/Text#extracting-a-region-of-text]. /// [[File:Blockly-get-substring.png]] Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_START = 'get substring from letter #'; /// dropdown - Indicates that the following number specifies the position (relative to the end /// position) of the beginning of the region of text that should be obtained from the preceding /// piece of text. See [https://github.com/google/blockly/wiki/Text#extracting-a-region-of-text /// https://github.com/google/blockly/wiki/Text#extracting-a-region-of-text]. /// Note: If {{msg-Blockly|ORDINAL_NUMBER_SUFFIX}} is defined, it will /// automatically appear ''after'' this and any other /// [https://translatewiki.net/wiki/Translating:Blockly#Ordinal_numbers ordinal numbers] /// on this block. /// [[File:Blockly-get-substring.png]] Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_END = 'get substring from letter # from end'; /// block text - Indicates that a region starting with the first letter of the preceding piece /// of text should be extracted. See /// [https://github.com/google/blockly/wiki/Text#extracting-a-region-of-text /// https://github.com/google/blockly/wiki/Text#extracting-a-region-of-text]. /// [[File:Blockly-get-substring.png]] Blockly.Msg.TEXT_GET_SUBSTRING_START_FIRST = 'get substring from first letter'; /// dropdown - Indicates that the following number specifies the position (relative to /// the start position) of the end of the region of text that should be obtained from the /// preceding piece of text. See /// [https://github.com/google/blockly/wiki/Text#extracting-a-region-of-text /// https://github.com/google/blockly/wiki/Text#extracting-a-region-of-text]. /// [[File:Blockly-get-substring.png]] Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_START = 'to letter #'; /// dropdown - Indicates that the following number specifies the position (relative to the /// end position) of the end of the region of text that should be obtained from the preceding /// piece of text. See /// [https://github.com/google/blockly/wiki/Text#extracting-a-region-of-text /// https://github.com/google/blockly/wiki/Text#extracting-a-region-of-text]. /// [[File:Blockly-get-substring.png]] Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_END = 'to letter # from end'; /// block text - Indicates that a region ending with the last letter of the preceding piece /// of text should be extracted. See /// [https://github.com/google/blockly/wiki/Text#extracting-a-region-of-text /// https://github.com/google/blockly/wiki/Text#extracting-a-region-of-text]. /// [[File:Blockly-get-substring.png]] Blockly.Msg.TEXT_GET_SUBSTRING_END_LAST = 'to last letter'; /// block text - Text that should go after the rightmost block/dropdown when /// [https://github.com/google/blockly/wiki/Text#extracting-a-region-of-text /// extracting a region of text]. In most languages, this will be the empty string. /// [[File:Blockly-get-substring.png]] Blockly.Msg.TEXT_GET_SUBSTRING_TAIL = ''; /// url - Information about the case of letters (upper-case and lower-case). Blockly.Msg.TEXT_CHANGECASE_HELPURL = 'https://github.com/google/blockly/wiki/Text#adjusting-text-case'; /// tooltip - Describes a block to adjust the case of letters. For more information on this block, /// see [https://github.com/google/blockly/wiki/Text#adjusting-text-case /// https://github.com/google/blockly/wiki/Text#adjusting-text-case]. Blockly.Msg.TEXT_CHANGECASE_TOOLTIP = 'Return a copy of the text in a different case.'; /// block text - Indicates that all of the letters in the following piece of text should be /// capitalized. If your language does not use case, you may indicate that this is not /// applicable to your language. For more information on this block, see /// [https://github.com/google/blockly/wiki/Text#adjusting-text-case /// https://github.com/google/blockly/wiki/Text#adjusting-text-case]. Blockly.Msg.TEXT_CHANGECASE_OPERATOR_UPPERCASE = 'to UPPER CASE'; /// block text - Indicates that all of the letters in the following piece of text should be converted to lower-case. If your language does not use case, you may indicate that this is not applicable to your language. For more information on this block, see [https://github.com/google/blockly/wiki/Text#adjusting-text-case https://github.com/google/blockly/wiki/Text#adjusting-text-case]. Blockly.Msg.TEXT_CHANGECASE_OPERATOR_LOWERCASE = 'to lower case'; /// block text - Indicates that the first letter of each of the following words should be capitalized and the rest converted to lower-case. If your language does not use case, you may indicate that this is not applicable to your language. For more information on this block, see [https://github.com/google/blockly/wiki/Text#adjusting-text-case https://github.com/google/blockly/wiki/Text#adjusting-text-case]. Blockly.Msg.TEXT_CHANGECASE_OPERATOR_TITLECASE = 'to Title Case'; /// url - Information about trimming (removing) text off the beginning and ends of pieces of text. Blockly.Msg.TEXT_TRIM_HELPURL = 'https://github.com/google/blockly/wiki/Text#trimming-removing-spaces'; /// tooltip - See [https://github.com/google/blockly/wiki/Text#trimming-removing-spaces /// https://github.com/google/blockly/wiki/Text#trimming-removing-spaces]. Blockly.Msg.TEXT_TRIM_TOOLTIP = 'Return a copy of the text with spaces removed from one or both ends.'; /// dropdown - Removes spaces from the beginning and end of a piece of text. See /// [https://github.com/google/blockly/wiki/Text#trimming-removing-spaces /// https://github.com/google/blockly/wiki/Text#trimming-removing-spaces]. Note that neither /// this nor the other options modify the original piece of text (that follows); /// the block just returns a version of the text without the specified spaces. Blockly.Msg.TEXT_TRIM_OPERATOR_BOTH = 'trim spaces from both sides of'; /// dropdown - Removes spaces from the beginning of a piece of text. See /// [https://github.com/google/blockly/wiki/Text#trimming-removing-spaces /// https://github.com/google/blockly/wiki/Text#trimming-removing-spaces]. /// Note that in right-to-left scripts, this will remove spaces from the right side. Blockly.Msg.TEXT_TRIM_OPERATOR_LEFT = 'trim spaces from left side of'; /// dropdown - Removes spaces from the end of a piece of text. See /// [https://github.com/google/blockly/wiki/Text#trimming-removing-spaces /// https://github.com/google/blockly/wiki/Text#trimming-removing-spaces]. /// Note that in right-to-left scripts, this will remove spaces from the left side. Blockly.Msg.TEXT_TRIM_OPERATOR_RIGHT = 'trim spaces from right side of'; /// url - Information about displaying text on computers. Blockly.Msg.TEXT_PRINT_HELPURL = 'https://github.com/google/blockly/wiki/Text#printing-text'; /// block text - Display the input on the screen. See /// [https://github.com/google/blockly/wiki/Text#printing-text /// https://github.com/google/blockly/wiki/Text#printing-text]. /// \n\nParameters:\n* %1 - the value to print Blockly.Msg.TEXT_PRINT_TITLE = 'print %1'; /// tooltip - See [https://github.com/google/blockly/wiki/Text#printing-text /// https://github.com/google/blockly/wiki/Text#printing-text]. Blockly.Msg.TEXT_PRINT_TOOLTIP = 'Print the specified text, number or other value.'; /// url - Information about getting text from users. Blockly.Msg.TEXT_PROMPT_HELPURL = 'https://github.com/google/blockly/wiki/Text#getting-input-from-the-user'; /// dropdown - Specifies that a piece of text should be requested from the user with /// the following message. See [https://github.com/google/blockly/wiki/Text#printing-text /// https://github.com/google/blockly/wiki/Text#printing-text]. Blockly.Msg.TEXT_PROMPT_TYPE_TEXT = 'prompt for text with message'; /// dropdown - Specifies that a number should be requested from the user with the /// following message. See [https://github.com/google/blockly/wiki/Text#printing-text /// https://github.com/google/blockly/wiki/Text#printing-text]. Blockly.Msg.TEXT_PROMPT_TYPE_NUMBER = 'prompt for number with message'; /// dropdown - Precedes the message with which the user should be prompted for /// a number. See [https://github.com/google/blockly/wiki/Text#printing-text /// https://github.com/google/blockly/wiki/Text#printing-text]. Blockly.Msg.TEXT_PROMPT_TOOLTIP_NUMBER = 'Prompt for user for a number.'; /// dropdown - Precedes the message with which the user should be prompted for some text. /// See [https://github.com/google/blockly/wiki/Text#printing-text /// https://github.com/google/blockly/wiki/Text#printing-text]. Blockly.Msg.TEXT_PROMPT_TOOLTIP_TEXT = 'Prompt for user for some text.'; // Lists Blocks. /// url - Information on empty lists. Blockly.Msg.LISTS_CREATE_EMPTY_HELPURL = 'https://github.com/google/blockly/wiki/Lists#create-empty-list'; /// block text - See [https://github.com/google/blockly/wiki/Lists#create-empty-list https://github.com/google/blockly/wiki/Lists#create-empty-list]. Blockly.Msg.LISTS_CREATE_EMPTY_TITLE = 'create empty list'; /// block text - See [https://github.com/google/blockly/wiki/Lists#create-empty-list https://github.com/google/blockly/wiki/Lists#create-empty-list]. Blockly.Msg.LISTS_CREATE_EMPTY_TOOLTIP = 'Returns a list, of length 0, containing no data records'; /// url - Information on building lists. Blockly.Msg.LISTS_CREATE_WITH_HELPURL = 'https://github.com/google/blockly/wiki/Lists#create-list-with'; /// tooltip - See [https://github.com/google/blockly/wiki/Lists#create-list-with https://github.com/google/blockly/wiki/Lists#create-list-with]. Blockly.Msg.LISTS_CREATE_WITH_TOOLTIP = 'Create a list with any number of items.'; /// block text - See [https://github.com/google/blockly/wiki/Lists#create-list-with https://github.com/google/blockly/wiki/Lists#create-list-with]. Blockly.Msg.LISTS_CREATE_WITH_INPUT_WITH = 'create list with'; /// block text - This appears in a sub-block when [https://github.com/google/blockly/wiki/Lists#changing-number-of-inputs changing the number of inputs in a ''''create list with'''' block].\n{{Identical|List}} Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD = 'list'; /// tooltip - See [https://github.com/google/blockly/wiki/Lists#changing-number-of-inputs https://github.com/google/blockly/wiki/Lists#changing-number-of-inputs]. Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TOOLTIP = 'Add, remove, or reorder sections to reconfigure this list block.'; Blockly.Msg.LISTS_CREATE_WITH_ITEM_TITLE = Blockly.Msg.VARIABLES_DEFAULT_NAME; /// tooltip - See [https://github.com/google/blockly/wiki/Lists#changing-number-of-inputs https://github.com/google/blockly/wiki/Lists#changing-number-of-inputs]. Blockly.Msg.LISTS_CREATE_WITH_ITEM_TOOLTIP = 'Add an item to the list.'; /// url - Information about [https://github.com/google/blockly/wiki/Lists#create-list-with creating a list with multiple copies of a single item]. Blockly.Msg.LISTS_REPEAT_HELPURL = 'https://github.com/google/blockly/wiki/Lists#create-list-with'; /// url - See [https://github.com/google/blockly/wiki/Lists#create-list-with creating a list with multiple copies of a single item]. Blockly.Msg.LISTS_REPEAT_TOOLTIP = 'Creates a list consisting of the given value repeated the specified number of times.'; /// block text - See [https://github.com/google/blockly/wiki/Lists#create-list-with /// https://github.com/google/blockly/wiki/Lists#create-list-with]. ///\n\nParameters:\n* %1 - the item (text) to be repeated\n* %2 - the number of times to repeat it Blockly.Msg.LISTS_REPEAT_TITLE = 'create list with item %1 repeated %2 times'; /// url - Information about how the length of a list is computed (i.e., by the total number of elements, not the number of different elements). Blockly.Msg.LISTS_LENGTH_HELPURL = 'https://github.com/google/blockly/wiki/Lists#length-of'; /// block text - See [https://github.com/google/blockly/wiki/Lists#length-of https://github.com/google/blockly/wiki/Lists#length-of]. /// \n\nParameters:\n* %1 - the list whose length is desired Blockly.Msg.LISTS_LENGTH_TITLE = 'length of %1'; /// tooltip - See [https://github.com/google/blockly/wiki/Lists#length-of https://github.com/google/blockly/wiki/Lists#length-of Blockly:Lists:length of]. Blockly.Msg.LISTS_LENGTH_TOOLTIP = 'Returns the length of a list.'; /// url - See [https://github.com/google/blockly/wiki/Lists#is-empty https://github.com/google/blockly/wiki/Lists#is-empty]. Blockly.Msg.LISTS_ISEMPTY_HELPURL = 'https://github.com/google/blockly/wiki/Lists#is-empty'; /// block text - See [https://github.com/google/blockly/wiki/Lists#is-empty /// https://github.com/google/blockly/wiki/Lists#is-empty]. /// \n\nParameters:\n* %1 - the list to test Blockly.Msg.LISTS_ISEMPTY_TITLE = '%1 is empty'; /// block tooltip - See [https://github.com/google/blockly/wiki/Lists#is-empty /// https://github.com/google/blockly/wiki/Lists#is-empty]. Blockly.Msg.LISTS_ISEMPTY_TOOLTIP = 'Returns true if the list is empty.'; /// block text - Title of blocks operating on [https://github.com/google/blockly/wiki/Lists lists]. Blockly.Msg.LISTS_INLIST = 'in list'; /// url - See [https://github.com/google/blockly/wiki/Lists#getting-items-from-a-list /// https://github.com/google/blockly/wiki/Lists#getting-items-from-a-list]. Blockly.Msg.LISTS_INDEX_OF_HELPURL = 'https://github.com/google/blockly/wiki/Lists#getting-items-from-a-list'; Blockly.Msg.LISTS_INDEX_OF_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST; /// dropdown - See [https://github.com/google/blockly/wiki/Lists#finding-items-in-a-list /// Lists#finding-items-in-a-list]. /// [[File:Blockly-list-find.png]] Blockly.Msg.LISTS_INDEX_OF_FIRST = 'find first occurrence of item'; /// dropdown - See [https://github.com/google/blockly/wiki/Lists#finding-items-in-a-list /// https://github.com/google/blockly/wiki/Lists#finding-items-in-a-list]. /// [[File:Blockly-list-find.png]] Blockly.Msg.LISTS_INDEX_OF_LAST = 'find last occurrence of item'; /// dropdown - See [https://github.com/google/blockly/wiki/Lists#finding-items-in-a-list /// https://github.com/google/blockly/wiki/Lists#finding-items-in-a-list]. /// [[File:Blockly-list-find.png]] Blockly.Msg.LISTS_INDEX_OF_TOOLTIP = 'Returns the index of the first/last occurrence of the item in the list. Returns 0 if item is not found.'; Blockly.Msg.LISTS_GET_INDEX_HELPURL = Blockly.Msg.LISTS_INDEX_OF_HELPURL; /// dropdown - Indicates that the user wishes to /// [https://github.com/google/blockly/wiki/Lists#getting-a-single-item /// get an item from a list] without removing it from the list. Blockly.Msg.LISTS_GET_INDEX_GET = 'get'; /// dropdown - Indicates that the user wishes to /// [https://github.com/google/blockly/wiki/Lists#getting-a-single-item /// get and remove an item from a list], as opposed to merely getting /// it without modifying the list. Blockly.Msg.LISTS_GET_INDEX_GET_REMOVE = 'get and remove'; /// dropdown - Indicates that the user wishes to /// [https://github.com/google/blockly/wiki/Lists#removing-an-item /// remove an item from a list].\n{{Identical|Remove}} Blockly.Msg.LISTS_GET_INDEX_REMOVE = 'remove'; /// dropdown - Indicates that an index relative to the front of the list should be used to /// [https://github.com/google/blockly/wiki/Lists#getting-a-single-item get and/or remove /// an item from a list]. Note: If {{msg-Blockly|ORDINAL_NUMBER_SUFFIX}} is defined, it will /// automatically appear ''after'' this number (and any other ordinal numbers on this block). /// See [[Translating:Blockly#Ordinal_numbers]] for more information on ordinal numbers in Blockly. /// [[File:Blockly-list-get-item.png]] Blockly.Msg.LISTS_GET_INDEX_FROM_START = '#'; /// dropdown - Indicates that an index relative to the end of the list should be used /// to [https://github.com/google/blockly/wiki/Lists#getting-a-single-item access an item in a list]. /// [[File:Blockly-list-get-item.png]] Blockly.Msg.LISTS_GET_INDEX_FROM_END = '# from end'; /// dropdown - Indicates that the '''first''' item should be /// [https://github.com/google/blockly/wiki/Lists#getting-a-single-item accessed in a list]. /// [[File:Blockly-list-get-item.png]] Blockly.Msg.LISTS_GET_INDEX_FIRST = 'first'; /// dropdown - Indicates that the '''last''' item should be /// [https://github.com/google/blockly/wiki/Lists#getting-a-single-item accessed in a list]. /// [[File:Blockly-list-get-item.png]] Blockly.Msg.LISTS_GET_INDEX_LAST = 'last'; /// dropdown - Indicates that a '''random''' item should be /// [https://github.com/google/blockly/wiki/Lists#getting-a-single-item accessed in a list]. /// [[File:Blockly-list-get-item.png]] Blockly.Msg.LISTS_GET_INDEX_RANDOM = 'random'; /// block text - Text that should go after the rightmost block/dropdown when /// [https://github.com/google/blockly/wiki/Lists#getting-a-single-item /// accessing an item from a list]. In most languages, this will be the empty string. /// [[File:Blockly-list-get-item.png]] Blockly.Msg.LISTS_GET_INDEX_TAIL = ''; Blockly.Msg.LISTS_GET_INDEX_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST; /// tooltip - See [https://github.com/google/blockly/wiki/Lists#getting-a-single-item /// https://github.com/google/blockly/wiki/Lists#getting-a-single-item] for more information. Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM_START = 'Returns the item at the specified position in a list. #1 is the first item.'; /// tooltip - See [https://github.com/google/blockly/wiki/Lists#getting-a-single-item /// https://github.com/google/blockly/wiki/Lists#getting-a-single-item] for more information. Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM_END = 'Returns the item at the specified position in a list. #1 is the last item.'; /// tooltip - See [https://github.com/google/blockly/wiki/Lists#getting-a-single-item /// https://github.com/google/blockly/wiki/Lists#getting-a-single-item] for more information. Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FIRST = 'Returns the first item in a list.'; /// tooltip - See [https://github.com/google/blockly/wiki/Lists#getting-a-single-item /// https://github.com/google/blockly/wiki/Lists#getting-a-single-item] for more information. Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_LAST = 'Returns the last item in a list.'; /// tooltip - See [https://github.com/google/blockly/wiki/Lists#getting-a-single-item /// https://github.com/google/blockly/wiki/Lists#getting-a-single-item] for more information. Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_RANDOM = 'Returns a random item in a list.'; /// tooltip - See [https://github.com/google/blockly/wiki/Lists#getting-and-removing-an-item] /// (for remove and return) and /// [https://github.com/google/blockly/wiki/Lists#getting-a-single-item] for '# from start'. Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM_START = 'Removes and returns the item at the specified position in a list. #1 is the first item.'; /// tooltip - See [https://github.com/google/blockly/wiki/Lists#getting-and-removing-an-item] (for remove and return) and [https://github.com/google/blockly/wiki/Lists#getting-a-single-item] for '# from end'. Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM_END = 'Removes and returns the item at the specified position in a list. #1 is the last item.'; /// tooltip - See [https://github.com/google/blockly/wiki/Lists#getting-and-removing-an-item] (for remove and return) and [https://github.com/google/blockly/wiki/Lists#getting-a-single-item] for 'first'. Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FIRST = 'Removes and returns the first item in a list.'; /// tooltip - See [https://github.com/google/blockly/wiki/Lists#getting-and-removing-an-item] (for remove and return) and [https://github.com/google/blockly/wiki/Lists#getting-a-single-item] for 'last'. Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_LAST = 'Removes and returns the last item in a list.'; /// tooltip - See [https://github.com/google/blockly/wiki/Lists#getting-and-removing-an-item] (for remove and return) and [https://github.com/google/blockly/wiki/Lists#getting-a-single-item] for 'random'. Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_RANDOM = 'Removes and returns a random item in a list.'; /// tooltip - See [https://github.com/google/blockly/wiki/Lists#getting-and-removing-an-item] (for remove and return) and [https://github.com/google/blockly/wiki/Lists#getting-a-single-item] for '# from start'. Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM_START = 'Removes the item at the specified position in a list. #1 is the first item.'; /// tooltip - See [https://github.com/google/blockly/wiki/Lists#getting-and-removing-an-item] (for remove and return) and [https://github.com/google/blockly/wiki/Lists#getting-a-single-item] for '# from end'. Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM_END = 'Removes the item at the specified position in a list. #1 is the last item.'; /// tooltip - See [https://github.com/google/blockly/wiki/Lists#getting-and-removing-an-item] (for remove and return) and [https://github.com/google/blockly/wiki/Lists#getting-a-single-item] for 'first'. Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FIRST = 'Removes the first item in a list.'; /// tooltip - See [https://github.com/google/blockly/wiki/Lists#getting-and-removing-an-item] (for remove and return) and [https://github.com/google/blockly/wiki/Lists#getting-a-single-item] for 'last'. Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_LAST = 'Removes the last item in a list.'; /// tooltip - See [https://github.com/google/blockly/wiki/Lists#getting-and-removing-an-item] (for remove and return) and [https://github.com/google/blockly/wiki/Lists#getting-a-single-item] for 'random'. Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_RANDOM = 'Removes a random item in a list.'; /// url - Information about putting items in lists. Blockly.Msg.LISTS_SET_INDEX_HELPURL = 'https://github.com/google/blockly/wiki/Lists#in-list--set'; Blockly.Msg.LISTS_SET_INDEX_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST; /// block text - [https://github.com/google/blockly/wiki/Lists#in-list--set /// Replaces an item in a list]. /// [[File:Blockly-in-list-set-insert.png]] Blockly.Msg.LISTS_SET_INDEX_SET = 'set'; /// block text - [https://github.com/google/blockly/wiki/Lists#in-list--insert-at /// Inserts an item into a list]. /// [[File:Blockly-in-list-set-insert.png]] Blockly.Msg.LISTS_SET_INDEX_INSERT = 'insert at'; /// block text - The word(s) after the position in the list and before the item to be set/inserted. /// [[File:Blockly-in-list-set-insert.png]] Blockly.Msg.LISTS_SET_INDEX_INPUT_TO = 'as'; /// tooltip - See [https://github.com/google/blockly/wiki/Lists#getting-a-single-item} (even though the page describes the "get" block, the idea is the same for the "set" block). Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM_START = 'Sets the item at the specified position in a list. #1 is the first item.'; /// tooltip - See [https://github.com/google/blockly/wiki/Lists#getting-a-single-item} (even though the page describes the "get" block, the idea is the same for the "set" block). Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM_END = 'Sets the item at the specified position in a list. #1 is the last item.'; /// tooltip - See [https://github.com/google/blockly/wiki/Lists#getting-a-single-item} (even though the page describes the "get" block, the idea is the same for the "set" block). Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FIRST = 'Sets the first item in a list.'; /// tooltip - See [https://github.com/google/blockly/wiki/Lists#getting-a-single-item} (even though the page describes the "get" block, the idea is the same for the "set" block). Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_LAST = 'Sets the last item in a list.'; /// tooltip - See [https://github.com/google/blockly/wiki/Lists#getting-a-single-item} (even though the page describes the "get" block, the idea is the same for the "set" block). Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_RANDOM = 'Sets a random item in a list.'; /// tooltip - See [https://github.com/google/blockly/wiki/Lists#getting-a-single-item} (even though the page describes the "get" block, the idea is the same for the "insert" block). Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM_START = 'Inserts the item at the specified position in a list. #1 is the first item.'; /// tooltip - See [https://github.com/google/blockly/wiki/Lists#getting-a-single-item} (even though the page describes the "get" block, the idea is the same for the "insert" block). Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM_END = 'Inserts the item at the specified position in a list. #1 is the last item.'; /// tooltip - See [https://github.com/google/blockly/wiki/Lists#getting-a-single-item} (even though the page describes the "get" block, the idea is the same for the "insert" block). Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FIRST = 'Inserts the item at the start of a list.'; /// tooltip - See [https://github.com/google/blockly/wiki/Lists#getting-a-single-item} (even though the page describes the "get" block, the idea is the same for the "insert" block). Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_LAST = 'Append the item to the end of a list.'; /// tooltip - See [https://github.com/google/blockly/wiki/Lists#getting-a-single-item} (even though the page describes the "get" block, the idea is the same for the "insert" block). Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_RANDOM = 'Inserts the item randomly in a list.'; /// url - Information describing extracting a sublist from an existing list. Blockly.Msg.LISTS_GET_SUBLIST_HELPURL = 'https://github.com/google/blockly/wiki/Lists#getting-a-sublist'; Blockly.Msg.LISTS_GET_SUBLIST_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST; /// dropdown - Indicates that an index relative to the front of the list should be used /// to specify the beginning of the range from which to /// [https://github.com/google/blockly/wiki/Lists#getting-a-sublist get a sublist]. /// [[File:Blockly-get-sublist.png]] /// Note: If {{msg-Blockly|ORDINAL_NUMBER_SUFFIX}} is defined, it will /// automatically appear ''after'' this number (and any other ordinal numbers on this block). /// See [[Translating:Blockly#Ordinal_numbers]] for more information on ordinal numbers in Blockly. Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_START = 'get sub-list from #'; /// dropdown - Indicates that an index relative to the end of the list should be used /// to specify the beginning of the range from which to /// [https://github.com/google/blockly/wiki/Lists#getting-a-sublist get a sublist]. Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_END = 'get sub-list from # from end'; /// dropdown - Indicates that the /// [https://github.com/google/blockly/wiki/Lists#getting-a-sublist sublist to extract] /// should begin with the list's first item. Blockly.Msg.LISTS_GET_SUBLIST_START_FIRST = 'get sub-list from first'; /// dropdown - Indicates that an index relative to the front of the list should be /// used to specify the end of the range from which to /// [https://github.com/google/blockly/wiki/Lists#getting-a-sublist get a sublist]. /// [[File:Blockly-get-sublist.png]] Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_START = 'to #'; /// dropdown - Indicates that an index relative to the end of the list should be /// used to specify the end of the range from which to /// [https://github.com/google/blockly/wiki/Lists#getting-a-sublist get a sublist]. /// [[File:Blockly-get-sublist.png]] Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_END = 'to # from end'; /// dropdown - Indicates that the '''last''' item in the given list should be /// [https://github.com/google/blockly/wiki/Lists#getting-a-sublist the end /// of the selected sublist]. /// [[File:Blockly-get-sublist.png]] Blockly.Msg.LISTS_GET_SUBLIST_END_LAST = 'to last'; /// block text - This appears in the rightmost position ("tail") of the /// sublist block, as described at /// [https://github.com/google/blockly/wiki/Lists#getting-a-sublist /// https://github.com/google/blockly/wiki/Lists#getting-a-sublist]. /// In English and most other languages, this is the empty string. /// [[File:Blockly-get-sublist.png]] Blockly.Msg.LISTS_GET_SUBLIST_TAIL = ''; /// tooltip - See [https://github.com/google/blockly/wiki/Lists#getting-a-sublist /// https://github.com/google/blockly/wiki/Lists#getting-a-sublist] for more information. /// [[File:Blockly-get-sublist.png]] Blockly.Msg.LISTS_GET_SUBLIST_TOOLTIP = 'Creates a copy of the specified portion of a list.'; /// url - Information describing sorting a list. Blockly.Msg.LISTS_SORT_HELPURL = 'https://github.com/google/blockly/wiki/Lists#sorting-a-list'; /// Sort as type %1 (numeric or alphabetic) in order %2 (ascending or descending) a list of items %3. Blockly.Msg.LISTS_SORT_TITLE = 'sort %1 %2 %3'; /// tooltip - See [https://github.com/google/blockly/wiki/Lists#sorting-a-list]. Blockly.Msg.LISTS_SORT_TOOLTIP = 'Sort a copy of a list.'; /// sorting order or direction from low to high value for numeric, or A-Z for alphabetic.\n{{Identical|Ascending}} Blockly.Msg.LISTS_SORT_ORDER_ASCENDING = 'ascending'; /// sorting order or direction from high to low value for numeric, or Z-A for alphabetic.\n{{Identical|Descending}} Blockly.Msg.LISTS_SORT_ORDER_DESCENDING = 'descending'; /// sort by treating each item as a number. Blockly.Msg.LISTS_SORT_TYPE_NUMERIC = 'numeric'; /// sort by treating each item alphabetically, case-sensitive. Blockly.Msg.LISTS_SORT_TYPE_TEXT = 'alphabetic'; /// sort by treating each item alphabetically, ignoring differences in case. Blockly.Msg.LISTS_SORT_TYPE_IGNORECASE = 'alphabetic, ignore case'; /// url - Information describing splitting text into a list, or joining a list into text. Blockly.Msg.LISTS_SPLIT_HELPURL = 'https://github.com/google/blockly/wiki/Lists#splitting-strings-and-joining-lists'; /// dropdown - Indicates that text will be split up into a list (e.g. "a-b-c" -> ["a", "b", "c"]). Blockly.Msg.LISTS_SPLIT_LIST_FROM_TEXT = 'make list from text'; /// dropdown - Indicates that a list will be joined together to form text (e.g. ["a", "b", "c"] -> "a-b-c"). Blockly.Msg.LISTS_SPLIT_TEXT_FROM_LIST = 'make text from list'; /// block text - Prompts for a letter to be used as a separator when splitting or joining text. Blockly.Msg.LISTS_SPLIT_WITH_DELIMITER = 'with delimiter'; /// tooltip - See [https://github.com/google/blockly/wiki/Lists#make-list-from-text /// https://github.com/google/blockly/wiki/Lists#make-list-from-text] for more information. Blockly.Msg.LISTS_SPLIT_TOOLTIP_SPLIT = 'Split text into a list of texts, breaking at each delimiter.'; /// tooltip - See [https://github.com/google/blockly/wiki/Lists#make-text-from-list /// https://github.com/google/blockly/wiki/Lists#make-text-from-list] for more information. Blockly.Msg.LISTS_SPLIT_TOOLTIP_JOIN = 'Join a list of texts into one text, separated by a delimiter.'; /// grammar - Text that follows an ordinal number (a number that indicates /// position relative to other numbers). In most languages, such text appears /// before the number, so this should be blank. An exception is Hungarian. /// See [[Translating:Blockly#Ordinal_numbers]] for more information. Blockly.Msg.ORDINAL_NUMBER_SUFFIX = ''; // Variables Blocks. /// url - Information about ''variables'' in computer programming. Consider using your language's translation of [https://en.wikipedia.org/wiki/Variable_(computer_science) https://en.wikipedia.org/wiki/Variable_(computer_science)], if it exists. Blockly.Msg.VARIABLES_GET_HELPURL = 'https://github.com/google/blockly/wiki/Variables#get'; /// tooltip - This gets the value of the named variable without modifying it. Blockly.Msg.VARIABLES_GET_TOOLTIP = 'Returns the value of this variable.'; /// context menu - Selecting this creates a block to set (change) the value of this variable. /// \n\nParameters:\n* %1 - the name of the variable. Blockly.Msg.VARIABLES_GET_CREATE_SET = 'Create "set %1"'; /// url - Information about ''variables'' in computer programming. Consider using your language's translation of [https://en.wikipedia.org/wiki/Variable_(computer_science) https://en.wikipedia.org/wiki/Variable_(computer_science)], if it exists. Blockly.Msg.VARIABLES_SET_HELPURL = 'https://github.com/google/blockly/wiki/Variables#set'; /// block text - Change the value of a mathematical variable: '''set [the value of] x to 7'''.\n\nParameters:\n* %1 - the name of the variable.\n* %2 - the value to be assigned. Blockly.Msg.VARIABLES_SET = 'set %1 to %2'; /// tooltip - This initializes or changes the value of the named variable. Blockly.Msg.VARIABLES_SET_TOOLTIP = 'Sets this variable to be equal to the input.'; /// context menu - Selecting this creates a block to get (change) the value of /// this variable.\n\nParameters:\n* %1 - the name of the variable. Blockly.Msg.VARIABLES_SET_CREATE_GET = 'Create "get %1"'; // Procedures Blocks. /// url - Information about defining [https://en.wikipedia.org/wiki/Procedure_(computer_science) functions] that do not have return values. Blockly.Msg.PROCEDURES_DEFNORETURN_HELPURL = 'https://en.wikipedia.org/wiki/Procedure_%28computer_science%29'; /// block text - This precedes the name of the function when defining it. See /// [https://blockly-demo.appspot.com/static/apps/code/index.html?lang=en#c84aoc this sample /// function definition]. Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE = 'to'; /// default name - This acts as a placeholder for the name of a function on a /// function definition block, as shown on /// [https://blockly-demo.appspot.com/static/apps/code/index.html?lang=en#w7cfju this block]. /// The user will replace it with the function's name. Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE = 'do something'; /// block text - This precedes the list of parameters on a function's defiition block. See /// [https://blockly-demo.appspot.com/static/apps/code/index.html?lang=en#voztpd this sample /// function with parameters]. Blockly.Msg.PROCEDURES_BEFORE_PARAMS = 'with:'; /// block text - This precedes the list of parameters on a function's caller block. See /// [https://blockly-demo.appspot.com/static/apps/code/index.html?lang=en#voztpd this sample /// function with parameters]. Blockly.Msg.PROCEDURES_CALL_BEFORE_PARAMS = 'with:'; /// block text - This appears next to the function's "body", the blocks that should be /// run when the function is called, as shown in /// [https://blockly-demo.appspot.com/static/apps/code/index.html?lang=en#voztpd this sample /// function definition]. Blockly.Msg.PROCEDURES_DEFNORETURN_DO = ''; /// tooltip Blockly.Msg.PROCEDURES_DEFNORETURN_TOOLTIP = 'Creates a function with no output.'; /// Placeholder text that the user is encouraged to replace with a description of what their function does. Blockly.Msg.PROCEDURES_DEFNORETURN_COMMENT = 'Describe this function...'; /// url - Information about defining [https://en.wikipedia.org/wiki/Procedure_(computer_science) functions] that have return values. Blockly.Msg.PROCEDURES_DEFRETURN_HELPURL = 'https://en.wikipedia.org/wiki/Procedure_%28computer_science%29'; Blockly.Msg.PROCEDURES_DEFRETURN_TITLE = Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE; Blockly.Msg.PROCEDURES_DEFRETURN_PROCEDURE = Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE; Blockly.Msg.PROCEDURES_DEFRETURN_DO = Blockly.Msg.PROCEDURES_DEFNORETURN_DO; Blockly.Msg.PROCEDURES_DEFRETURN_COMMENT = Blockly.Msg.PROCEDURES_DEFNORETURN_COMMENT; /// block text - This imperative or infinite verb precedes the value that is used as the return value /// (output) of this function. See /// [https://blockly-demo.appspot.com/static/apps/code/index.html?lang=en#6ot5y5 this sample /// function that returns a value]. Blockly.Msg.PROCEDURES_DEFRETURN_RETURN = 'return'; /// tooltip Blockly.Msg.PROCEDURES_DEFRETURN_TOOLTIP = 'Creates a function with an output.'; /// Label for a checkbox that controls if statements are allowed in a function. Blockly.Msg.PROCEDURES_ALLOW_STATEMENTS = 'allow statements'; /// alert - The user has created a function with two parameters that have the same name. Every parameter must have a different name. Blockly.Msg.PROCEDURES_DEF_DUPLICATE_WARNING = 'Warning: This function has duplicate parameters.'; /// url - Information about calling [https://en.wikipedia.org/wiki/Procedure_(computer_science) functions] that do not return values. Blockly.Msg.PROCEDURES_CALLNORETURN_HELPURL = 'https://en.wikipedia.org/wiki/Procedure_%28computer_science%29'; /// tooltip - This block causes the body (blocks inside) of the named function definition to be run. Blockly.Msg.PROCEDURES_CALLNORETURN_TOOLTIP = 'Run the user-defined function "%1".'; /// url - Information about calling [https://en.wikipedia.org/wiki/Procedure_(computer_science) functions] that return values. Blockly.Msg.PROCEDURES_CALLRETURN_HELPURL = 'https://en.wikipedia.org/wiki/Procedure_%28computer_science%29'; /// tooltip - This block causes the body (blocks inside) of the named function definition to be run.\n\nParameters:\n* %1 - the name of the function. Blockly.Msg.PROCEDURES_CALLRETURN_TOOLTIP = 'Run the user-defined function "%1" and use its output.'; /// block text - This text appears on a block in a window that appears when the user clicks /// on the plus sign or star on a function definition block. It refers to the set of parameters /// (referred to by the simpler term "inputs") to the function. See /// [[Translating:Blockly#function_definitions]]. Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TITLE = 'inputs'; /// tooltip Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TOOLTIP = 'Add, remove, or reorder inputs to this function.'; /// block text - This text appears on a block in a window that appears when the user clicks /// on the plus sign or star on a function definition block]. It appears on the block for /// adding an individual parameter (referred to by the simpler term "inputs") to the function. /// See [[Translating:Blockly#function_definitions]]. Blockly.Msg.PROCEDURES_MUTATORARG_TITLE = 'input name:'; /// tooltip Blockly.Msg.PROCEDURES_MUTATORARG_TOOLTIP = 'Add an input to the function.'; /// context menu - This appears on the context menu for function calls. Selecting /// it causes the corresponding function definition to be highlighted (as shown at /// [[Translating:Blockly#context_menus]]. Blockly.Msg.PROCEDURES_HIGHLIGHT_DEF = 'Highlight function definition'; /// context menu - This appears on the context menu for function definitions. /// Selecting it creates a block to call the function.\n\nParameters:\n* %1 - the name of the function.\n{{Identical|Create}} Blockly.Msg.PROCEDURES_CREATE_DO = 'Create "%1"'; /// tooltip - If the first value is true, this causes the second value to be returned /// immediately from the enclosing function. Blockly.Msg.PROCEDURES_IFRETURN_TOOLTIP = 'If a value is true, then return a second value.'; /// url - Information about guard clauses. Blockly.Msg.PROCEDURES_IFRETURN_HELPURL = 'http://c2.com/cgi/wiki?GuardClause'; /// warning - This appears if the user tries to use this block outside of a function definition. Blockly.Msg.PROCEDURES_IFRETURN_WARNING = 'Warning: This block may be used only within a function definition.'; Blockly.Msg.TYPE_WARN01 = 'The variable "'; Blockly.Msg.TYPE_WARN02 = '" has been first assigned to the "'; Blockly.Msg.TYPE_WARN03 = '" type and this block tries to assign the type "'; Blockly.Msg.TYPE_WARN04 = '"!';
{ "content_hash": "990d8e0b2086dc3eea9ccefbe320370f", "timestamp": "", "source": "github", "line_count": 1109, "max_line_length": 423, "avg_line_length": 84.2560865644725, "alnum_prop": 0.7473137842465754, "repo_name": "ingegno/Blockly4Arduino", "id": "597e445c686a6b131888aead17f1a86ff912c8b0", "size": "94149", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Blockly4Arduino/msg/messages.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "30823" }, { "name": "HTML", "bytes": "97040" }, { "name": "JavaScript", "bytes": "6585090" }, { "name": "Python", "bytes": "2421" } ], "symlink_target": "" }
#include "GLMesh.hpp" RomOpenGL::Mesh::Mesh() { this->_textureID = 0; this->_normalID = 0; this->_materialID = 0; this->_isCgVProgramSet = false; } RomOpenGL::Mesh::~Mesh() { } RomOpenGL::Mesh::MeshEntry::MeshEntry() { this->_indexCount = 0; this->IB = INVALID_OGL_VALUE; this->VB = INVALID_OGL_VALUE; //this->TB = INVALID_OGL_VALUE; } RomOpenGL::Mesh::MeshEntry::~MeshEntry() { if(this->VB != INVALID_OGL_VALUE) { glDeleteBuffers(1, &this->VB); } if(this->IB != INVALID_OGL_VALUE) { glDeleteBuffers(1, &this->IB); } /* if(this->TB != INVALID_OGL_VALUE) { glDeleteBuffers(1, &this->TB); }*/ } void RomOpenGL::Mesh::MeshEntry::Init(const std::vector<RomCommon::Vertex3D>& Vertices, const std::vector<unsigned int>& Indices) { this->_indexCount = Indices.size(); glGenBuffers(1, &this->VB); glBindBuffer(GL_ARRAY_BUFFER, this->VB); glBufferData(GL_ARRAY_BUFFER, sizeof(RomCommon::Vertex3D) * Vertices.size(), &Vertices[0], GL_STATIC_DRAW); /* glGenBuffers(1, &this->TB); glBindBuffer(GL_ARRAY_BUFFER, this->TB); glBufferData(GL_ARRAY_BUFFER, sizeof(RomCommon::Vector2D) * TextureCoords.size(), &TextureCoords[0], GL_STATIC_DRAW); */ glGenBuffers(1, &this->IB); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->IB); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * this->_indexCount, &Indices[0], GL_STATIC_DRAW); } void RomOpenGL::Mesh::MeshEntry::Unload() { glDeleteBuffers(1, &this->IB); glDeleteBuffers(1, &this->VB); } void RomOpenGL::Mesh::Destroy() { boost::shared_ptr<GLTextureManager> tManager = boost::dynamic_pointer_cast<GLTextureManager>(RomCommon::CoreFramework::getInstance()->GetCurrentRenderSystem()->GetTextureManager()); if(this->GetTextureID() > 0) { tManager->DestroyTexture(this->GetTextureID()); } if(this->GetNormalID() > 0) { tManager->DestroyTexture(this->GetNormalID()); } if(this->GetMaterialID() > 0) { MaterialManager::getInstance()->RemoveMaterial(this->GetMaterialID()); } while(!this->_entries.empty()) { this->_entries.back().Unload(); this->_entries.pop_back(); } /* delete [] this->_vertices; delete [] this->_indices; */ } bool RomOpenGL::Mesh::Load(const aiScene* pScene, const std::string& filename) { this->_entries.resize(pScene->mNumMeshes); bool result = true; // Load the actual meshes for(RomCommon::UINT32 i = 0; i < this->_entries.size(); i++) { const aiMesh* paiMesh = pScene->mMeshes[i]; if(!this->LoadMesh(i, paiMesh)) result = false; } return result; } bool RomOpenGL::Mesh::LoadMeshVertexShader(pugi::xml_node shaderNode) { std::string type = shaderNode.attribute("type").as_string(); if(type == "CG") { // TODO: Implement } if(type == "HSLS") { // TODO: Implement } if(type == "GSLS") { // TODO: Implement } //return this->_isCgVProgramSet; return true; } bool RomOpenGL::Mesh::LoadMeshMaterial(pugi::xml_node materialNode) { bool result = MaterialManager::getInstance()->CreateMaterial(materialNode); if(result) { this->SetMaterialID(MaterialManager::getInstance()->GetCurrID()); /*if(this->_shader) { this->_shader->SetCurrentMaterial(MaterialManager::getInstance()->FindMaterial(this->_materialID)->GetName()); }*/ } return result; } bool RomOpenGL::Mesh::LoadMesh(RomCommon::UINT32 index, const aiMesh* paiMesh) { std::vector<RomCommon::Vertex3D> Vertices; std::vector<RomCommon::UINT32> Indices; const RomCommon::Vector3D Zero3D(0.0f, 0.0f, 0.0f); for(RomCommon::UINT32 i = 0; i < paiMesh->mNumVertices; i++) { const aiVector3D* pos = &(paiMesh->mVertices[i]); const aiVector3D* normal = &(paiMesh->mNormals[i]); const aiVector3D* texCoord; if(paiMesh->HasTextureCoords(0)) { texCoord = &(paiMesh->mTextureCoords[0][i]); } else { texCoord = new aiVector3D(0.0f, 0.0f, 0.0f); } RomCommon::Vertex3D vertex; vertex.position.X = pos->x; vertex.position.Y = pos->y; vertex.position.Z = pos->z; vertex.normal.X = normal->x; vertex.normal.Y = normal->y; vertex.normal.Z = normal->z; vertex.textureCoordinate.X = texCoord->x; vertex.textureCoordinate.Y = texCoord->y; const aiVector3D* tangent ; if( paiMesh->HasTangentsAndBitangents() ) { tangent = &(paiMesh->mTangents[i]); vertex.tangent.X = tangent->x; vertex.tangent.Y = tangent->y; vertex.tangent.Z = tangent->z; } else { tangent = new aiVector3D(0.0f, 0.0f, 0.0f); } Vertices.push_back(vertex); } for(RomCommon::UINT32 i = 0; i < paiMesh->mNumFaces; i++) { const aiFace& Face = paiMesh->mFaces[i]; #ifdef _DEBUG assert(Face.mNumIndices == 3); #endif Indices.push_back(Face.mIndices[0]); Indices.push_back(Face.mIndices[1]); Indices.push_back(Face.mIndices[2]); } this->_entries[index].Init(Vertices, Indices); return true; } void RomOpenGL::Mesh::PrepareShader() { /* RomCommon::Vector3D camPos = RomCommon::CoreFramework::getInstance()->GetCurrentRenderSystem()->GetRenderCamera()->GetOwner()->GetPosition(); RomCommon::Vector3D camTarget = RomCommon::CoreFramework::getInstance()->GetCurrentRenderSystem()->GetRenderCamera()->GetOwner()->GetTarget(); RomCommon::Vector3D camUp = RomCommon::CoreFramework::getInstance()->GetCurrentRenderSystem()->GetRenderCamera()->GetOwner()->GetUp(); RomCommon::FLOAT32 viewMatrix[16]; RomCommon::MathHelper::BuildLookAtMatrix( camPos.X, camPos.Y, camPos.Z, camTarget.X, camTarget.Y, camTarget.Z, camUp.X, camTarget.Y, camTarget.Z, viewMatrix); RomCommon::FLOAT64 fov = RomCommon::CoreFramework::getInstance()->GetCurrentRenderSystem()->GetFieldOfView(); RomCommon::FLOAT64 aspectRatio = RomCommon::CoreFramework::getInstance()->GetCurrentRenderSystem()->GetScreenWidth() / RomCommon::CoreFramework::getInstance()->GetCurrentRenderSystem()->GetScreenHeight(); RomCommon::FLOAT64 zNear = RomCommon::CoreFramework::getInstance()->GetCurrentRenderSystem()->GetZNear(); RomCommon::FLOAT64 zFar = RomCommon::CoreFramework::getInstance()->GetCurrentRenderSystem()->GetZFar(); RomCommon::FLOAT32 projectionMatrix[16]; RomCommon::MathHelper::BuildPerspectiveMatrix( fov, aspectRatio, zNear, zFar, projectionMatrix); RomCommon::FLOAT32* transformationMatrix = this->GetOwner()->GetOwner()->GetWorldTransformationMatrix(); int t1 = sizeof(&transformationMatrix); for(int i = 0; i <= 15; i++) { RomCommon::FLOAT32 test = *(transformationMatrix + i); } RomCommon::FLOAT32 modelViewProjection[16]; RomCommon::MathHelper::MultiplyMatrix(modelViewProjection, viewMatrix, projectionMatrix); RomCommon::MathHelper::MultiplyMatrix(modelViewProjection, modelViewProjection, transformationMatrix); this->_shader->SetModelViewProjection(modelViewProjection); this->_shader->SetModelMatrix(transformationMatrix); RomCommon::FLOAT32* transformationMatrixIT = RomCommon::MathHelper::Convert4x4To3x3Matrix<RomCommon::FLOAT32>(transformationMatrix); RomCommon::MathHelper::Invert3x3Matrix<RomCommon::FLOAT32>(transformationMatrixIT); RomCommon::MathHelper::Transponse3x3Matrix<RomCommon::FLOAT32>(transformationMatrixIT); this->_shader->SetModelMatrixIT(transformationMatrixIT); delete transformationMatrix; delete transformationMatrixIT;*/ } void RomOpenGL::Mesh::Render() { if(this->GetOwner()->GetType() == RomCommon::SKYBOX) { //glDisable(GL_DEPTH_TEST); glDisable(GL_DEPTH_TEST); } else { glEnable(GL_TEXTURE_2D); } boost::shared_ptr<GLTextureManager> tManager; if(this->_textureID != 0 || this->_normalID != 0) { tManager = boost::dynamic_pointer_cast<GLTextureManager>(RomCommon::CoreFramework::getInstance()->GetCurrentRenderSystem()->GetTextureManager()); } glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); glEnableVertexAttribArray(3); for(RomCommon::UINT32 i = 0; i < this->_entries.size(); i++) { glBindBuffer(GL_ARRAY_BUFFER, this->_entries[i].VB); glVertexAttribPointer(0,3, GL_FLOAT, GL_FALSE, sizeof(RomCommon::Vertex3D), 0); glVertexAttribPointer(1,2, GL_FLOAT, GL_FALSE, sizeof(RomCommon::Vertex3D), (const GLvoid*)12); glVertexAttribPointer(2,3, GL_FLOAT, GL_FALSE, sizeof(RomCommon::Vertex3D), (const GLvoid*)20); glVertexAttribPointer(3,3, GL_FLOAT, GL_FALSE, sizeof(RomCommon::Vertex3D), (const GLvoid*)32); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->_entries[i].IB); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glTexCoordPointer(2, GL_FLOAT, sizeof(RomCommon::Vertex3D), (const GLvoid*)12); // Below is temporary // TODO: Change that the texture ID would be per entry if(this->_textureID != 0) { boost::shared_ptr<GLTexture> texture = boost::dynamic_pointer_cast<GLTexture>(tManager->GetTexture(this->_textureID)); if(texture) { switch(texture->GetTextureType()) { case RomCommon::TEXTURE_2D: { texture->Bind(GL_TEXTURE0, GL_TEXTURE_2D); } break; case RomCommon::CUBEMAP: { texture->Bind(GL_TEXTURE0, GL_TEXTURE_CUBE_MAP); glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, 0.0f); }break; } } } if(this->_normalID != 0) { boost::shared_ptr<GLTexture> texture = boost::dynamic_pointer_cast<GLTexture>(tManager->GetTexture(this->_normalID)); if(texture) { texture->Bind(NORMAL_TEXTURE_UNIT, GL_TEXTURE_2D); } } glDrawElements(GL_TRIANGLES, this->_entries[i]._indexCount, GL_UNSIGNED_INT, 0); glDisableClientState(GL_TEXTURE_COORD_ARRAY); /*if(this->_textureID != 0) { boost::shared_ptr<GLTexture> texture = boost::dynamic_pointer_cast<GLTexture>(tManager->GetTexture(this->_textureID)); if(texture) { texture->Unbind(); } }*/ } glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); glDisableVertexAttribArray(3); if(this->_normalID != 0) glActiveTexture(GL_TEXTURE0); tManager.reset(); if(this->GetOwner()->GetType() == RomCommon::SKYBOX) { //glEnable(GL_DEPTH_TEST); glEnable(GL_DEPTH_TEST); } else { glDisable(GL_TEXTURE_2D); } } void RomOpenGL::Mesh::LoadVertices(aiMesh* aimesh) { this->_vertices = new RomCommon::Vertex3D[this->_vertexCount]; for(UINT32 j = 0; j < aimesh->mNumVertices; j++) { const aiVector3D* pos = &(aimesh->mVertices[j]); const aiVector3D* normal = &(aimesh->mNormals[j]); const aiVector3D* texCoord; if(aimesh->HasTextureCoords(0)) { texCoord = &(aimesh->mTextureCoords[0][j]); } else { texCoord = new aiVector3D(0.0f, 0.0f, 0.0f); } RomCommon::Vertex3D vertex; vertex.position.X = pos->x; vertex.position.Y = pos->y; vertex.position.Z = pos->z; vertex.normal.X = normal->x; vertex.normal.Y = normal->y; vertex.normal.Z = normal->z; vertex.textureCoordinate.X = texCoord->x; vertex.textureCoordinate.Y = texCoord->y; this->_vertices[j] = vertex; } } void RomOpenGL::Mesh::LoadIndices(aiMesh* aimesh) { RomCommon::UINT32 vSize = 3, iterator = 0; RomCommon::UINT32 *indices = new RomCommon::UINT32[vSize]; for(UINT32 i = 0; i < aimesh->mNumFaces; ++i) { const aiFace& face = aimesh->mFaces[i]; #ifdef _DEBUG assert(face.mNumIndices == 3); #endif if(iterator == 0) { for(int j = 0; j < 3; j++) { indices[iterator++] = face.mIndices[j]; } } else { UINT32 *temp = new UINT32[iterator]; for(RomCommon::UINT32 j = 0; j < iterator; j++) { temp[j] = indices[j]; } iterator += 3; delete [] indices; indices = new UINT32[iterator]; memcpy(indices, temp, sizeof(temp)); for(int j = 0; j < 3; j++) { indices[iterator - 3 + j] = face.mIndices[j]; } } } this->_indices = indices; }
{ "content_hash": "4ef8021673f3333d86379e80aaa812e4", "timestamp": "", "source": "github", "line_count": 459, "max_line_length": 205, "avg_line_length": 25.363834422657952, "alnum_prop": 0.6899158220237073, "repo_name": "karmalis/Romuva", "id": "359402554171dc17c3cf7feda0c489c69a10be53", "size": "11642", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Code/RomEngine/RomOpenGL/Actors/Components/GLMesh.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "19319" }, { "name": "C++", "bytes": "666025" }, { "name": "CSS", "bytes": "2020" }, { "name": "Lua", "bytes": "37748" } ], "symlink_target": "" }
namespace base { class DictionaryValue; } namespace extensions { namespace chrome_manifest_urls { const GURL& GetDevToolsPage(const Extension* extension); } // Stores Chrome URL overrides specified in extensions manifests. struct URLOverrides : public Extension::ManifestData { typedef std::map<const std::string, GURL> URLOverrideMap; URLOverrides(); ~URLOverrides() override; static const URLOverrideMap& GetChromeURLOverrides( const Extension* extension); // A map of chrome:// hostnames (newtab, downloads, etc.) to Extension URLs // which override the handling of those URLs. (see ExtensionOverrideUI). URLOverrideMap chrome_url_overrides_; }; // Parses the "devtools_page" manifest key. class DevToolsPageHandler : public ManifestHandler { public: DevToolsPageHandler(); ~DevToolsPageHandler() override; bool Parse(Extension* extension, base::string16* error) override; private: const std::vector<std::string> Keys() const override; DISALLOW_COPY_AND_ASSIGN(DevToolsPageHandler); }; // Parses the "chrome_url_overrides" manifest key. class URLOverridesHandler : public ManifestHandler { public: URLOverridesHandler(); ~URLOverridesHandler() override; bool Parse(Extension* extension, base::string16* error) override; bool Validate(const Extension* extension, std::string* error, std::vector<InstallWarning>* warnings) const override; private: const std::vector<std::string> Keys() const override; DISALLOW_COPY_AND_ASSIGN(URLOverridesHandler); }; } // namespace extensions #endif // CHROME_COMMON_EXTENSIONS_CHROME_MANIFEST_URL_HANDLERS_H_
{ "content_hash": "0bffcaca732107e5f191e613c71f4294", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 77, "avg_line_length": 27.83050847457627, "alnum_prop": 0.743605359317905, "repo_name": "axinging/chromium-crosswalk", "id": "a698c4504194ad8947c33b90f1e879c817d12f7a", "size": "2130", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "chrome/common/extensions/chrome_manifest_url_handlers.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "8242" }, { "name": "AppleScript", "bytes": "6973" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "23945" }, { "name": "C", "bytes": "4103204" }, { "name": "C++", "bytes": "225022948" }, { "name": "CSS", "bytes": "949808" }, { "name": "Dart", "bytes": "74976" }, { "name": "Go", "bytes": "18155" }, { "name": "HTML", "bytes": "28206993" }, { "name": "Java", "bytes": "7651204" }, { "name": "JavaScript", "bytes": "18831169" }, { "name": "Makefile", "bytes": "96270" }, { "name": "Objective-C", "bytes": "1228122" }, { "name": "Objective-C++", "bytes": "7563676" }, { "name": "PHP", "bytes": "97817" }, { "name": "Perl", "bytes": "63937" }, { "name": "Protocol Buffer", "bytes": "418221" }, { "name": "Python", "bytes": "7855597" }, { "name": "Shell", "bytes": "472586" }, { "name": "Standard ML", "bytes": "4965" }, { "name": "XSLT", "bytes": "418" }, { "name": "nesC", "bytes": "18335" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp; namespace SME.AST.Transform { /// <summary> /// Rebuilds switch statements that are decomposed into GOTO statements. /// </summary> public class RecontructSwitchStatement : IASTTransform { /// <summary> /// Lookup table of visited statements to speed up the lookup. /// </summary> private HashSet<AST.SwitchStatement> m_visited = new HashSet<SwitchStatement>(); /// <summary> /// Applies the transformation. /// </summary> /// <returns>The transformed item.</returns> /// <param name="item">The item to visit.</param> public virtual ASTItem Transform(ASTItem item) { var ss = item as AST.SwitchStatement; if (ss == null) return item; if (m_visited.Contains(ss)) return item; m_visited.Add(ss); // Figure out if the switch is using goto statements var goto_statements = ss.Cases.SelectMany(x => x.Item2).SelectMany(x => x.All()).OfType<GotoStatement>().ToList(); if (goto_statements.Count == 0) return item; // Extract the cases that we will work with var cases = ss.Cases.ToList(); // Grab the name of the label, so we can look for it var labelname = goto_statements.First().Label; if (goto_statements.Any(x => x.Label != labelname)) return item; // We assume that there is just one label with the given name in the method var mp = item.GetNearestParent<Method>(); if (mp == null) return item; // Find the one label statement that is the goto target var lbltarget = mp.All().OfType<LabelStatement>().Where(x => x.Label == labelname).FirstOrDefault(); if (lbltarget == null) return item; // Find the if(...) statements that are actually stray case statements foreach (var ifs in ((Method)mp).Statements.SelectMany(x => x.All()).OfType<IfElseStatement>()) { // Goldilocks testing, we only accept something like: // if (switch_var == value) { // ... // goto label; // } if (!(ifs.FalseStatement is EmptyStatement)) continue; if (!(ifs.TrueStatement.All().Last() is GotoStatement)) continue; if ((ifs.TrueStatement.All().Last() as GotoStatement).Label != labelname) continue; if (!(ifs.Condition is BinaryOperatorExpression)) continue; var beo = ifs.Condition as BinaryOperatorExpression; if (beo.Operator != SyntaxKind.EqualsEqualsToken) continue; Expression casetarget; if (beo.Left.GetTarget() == ss.SwitchExpression.GetTarget()) casetarget = beo.Right; else if (beo.Right.GetTarget() == ss.SwitchExpression.GetTarget()) casetarget = beo.Left; else continue; if (casetarget == null) continue; // We have a case that looks just right :) cases.Add(new Tuple<Expression[], Statement[]>( new Expression[] { casetarget }, new Statement[] { ifs.TrueStatement } )); ifs.ReplaceWith(new EmptyStatement()); ifs.TrueStatement.Parent = ss; ifs.TrueStatement.UpdateParents(); } // Sometimes we have an added filter on the outside if (ss.Parent != lbltarget.Parent) { var ssp = ss.Parent; while (ssp != null && !(ssp is IfElseStatement)) ssp = ssp.Parent; var ssifp = ssp as IfElseStatement; if (ssifp != null) { var beo = ssifp.Condition as BinaryOperatorExpression; if (beo != null) { if (beo.Left.GetTarget() == ss.SwitchExpression.GetTarget() || beo.Right.GetTarget() == ss.SwitchExpression.GetTarget()) { var replace = false; if (ssifp.TrueStatement.All().Contains(ss)) replace = !ssifp.FalseStatement.LeavesOnly().Any(x => !(x is EmptyStatement)); else if (ssifp.FalseStatement.All().Contains(ss)) replace = !ssifp.TrueStatement.LeavesOnly().Any(x => !(x is EmptyStatement)); if (replace) ssifp.ReplaceWith(ss); } } } } // Find the container for the goto label Statement[] ps; if (lbltarget.Parent is BlockStatement) ps = (lbltarget.Parent as BlockStatement).Statements; else ps = (lbltarget.Parent as Method).Statements; // Find the switch and label taget in the list var labelindex = Array.IndexOf(ps, lbltarget); var switchindex = Array.IndexOf(ps, ss); // If we have different parents, the index does not point to the switch, // so we figure out where the switch ends if (switchindex < 0) { var ssp = ss.Parent; while (ssp != null && ssp.Parent != lbltarget.Parent) ssp = ssp.Parent; if (ssp == null) return item; switchindex = Array.IndexOf(ps, ssp); } if (labelindex < 0 || switchindex < 0 || switchindex > labelindex) return item; // Extract the items between the switch and the label target and use as the default case var defaultstatements = ps.Skip(switchindex + 1).Take(labelindex - switchindex - 1).Where(x => !(x is EmptyStatement)).ToList(); var remainingstatements = ps.Take(switchindex + 1).Concat(ps.Skip(labelindex + 1)).ToArray(); // We can get an empty case due to the transformations above cases = cases.Where(x => !x.Item2.All(y => y is EmptyStatement)).ToList(); // If we have default actions, or the switch is missing a default entry, add it if (defaultstatements.Count != 0 || !cases.Any(x => x.Item1.All(y => y is EmptyExpression))) { cases.Add(new Tuple<Expression[], Statement[]>( new Expression[] { new EmptyExpression() }, defaultstatements.ToArray() )); foreach (var n in defaultstatements) n.Parent = ss; defaultstatements.UpdateParents(); } // Set up the switch and replace the statements ss.Cases = cases.ToArray(); ss.UpdateParents(); // Rewrite the list of statements back, excluding the default case if (lbltarget.Parent is BlockStatement) { (lbltarget.Parent as BlockStatement).Statements = remainingstatements; (lbltarget.Parent as BlockStatement).UpdateParents(); } else { (lbltarget.Parent as Method).Statements = remainingstatements; foreach (var n in remainingstatements) n.UpdateParents(); } // Rewrite all goto's into break statements, requery the cases as we may have changed them goto_statements = ss.Cases.SelectMany(x => x.Item2).SelectMany(x => x.All()).OfType<GotoStatement>().ToList(); foreach (var n in goto_statements) n.ReplaceWith(new EmptyStatement()); return null; } } }
{ "content_hash": "a1f86f0ffe1a8a1797a4366b53ac2d20", "timestamp": "", "source": "github", "line_count": 201, "max_line_length": 144, "avg_line_length": 40.57213930348259, "alnum_prop": 0.5242182709993869, "repo_name": "kenkendk/sme", "id": "001f954a36acf48234cf1b9ee3c0757c1adc73d6", "size": "8157", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/SME.AST/Transform/RecontructSwitchStatement.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "1847" }, { "name": "C#", "bytes": "1566600" }, { "name": "C++", "bytes": "2733" }, { "name": "HTML", "bytes": "1756" }, { "name": "JavaScript", "bytes": "15418" }, { "name": "Makefile", "bytes": "820" }, { "name": "VHDL", "bytes": "93790" } ], "symlink_target": "" }
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2015-2016 Rick Wargo. All Rights Reserved. // // Licensed under the MIT License (the "License"). You may not use this file // except in compliance with the License. A copy of the License is located at // http://opensource.org/licenses/MIT or in the "LICENSE" file accompanying // this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES // OR CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. //////////////////////////////////////////////////////////////////////////////// /*jslint node: true */ /*jslint todo: true */ 'use strict'; //TODO! This is getting used for node-aws-lambda and the Config settings. Probably need to separate/rename. module.exports = { //profile: '', // optional for loading AWS credentials from custom profile applicationId: 'amzn1.echo-sdk-ams.app.000000-d0ed-0000-ad00-000000d00ebe', applicationName: 'template', namespace: 'TEMPLATE.', region: 'us-east-1', handler: 'index.handler', functionName: '', timeout: 3, memorySize: 128, runtime: 'nodejs' // default: 'nodejs' }; // Allow this module to be reloaded by hotswap when changed module.change_code = 1;
{ "content_hash": "d1a2a855472d691e94aeed09dee543e2", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 107, "avg_line_length": 43.483870967741936, "alnum_prop": 0.6313056379821959, "repo_name": "rickwargo/alexa-skill-template", "id": "7475a817ce73f5cd65c45b05deb111abe4be7ec2", "size": "1348", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "config/lambda-config.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "28298" } ], "symlink_target": "" }
#ifndef __PLATFORM_SECURE_LIB_H__ #define __PLATFORM_SECURE_LIB_H__ /** This function provides a platform-specific method to detect whether the platform is operating by a physically present user. Programmatic changing of platform security policy (such as disable Secure Boot, or switch between Standard/Custom Secure Boot mode) MUST NOT be possible during Boot Services or after exiting EFI Boot Services. Only a physically present user is allowed to perform these operations. NOTE THAT: This function cannot depend on any EFI Variable Service since they are not available when this function is called in AuthenticateVariable driver. @retval TRUE The platform is operated by a physically present user. @retval FALSE The platform is NOT operated by a physically present user. **/ BOOLEAN EFIAPI UserPhysicalPresent ( VOID ); #endif
{ "content_hash": "97c22358270b61a4696cc0f2b766520e", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 83, "avg_line_length": 30.266666666666666, "alnum_prop": 0.7389867841409692, "repo_name": "google/google-ctf", "id": "d645376917cbdc6986b7f4a904b08827d79abde9", "size": "1491", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "third_party/edk2/SecurityPkg/Include/Library/PlatformSecureLib.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AIDL", "bytes": "508" }, { "name": "Assembly", "bytes": "107617" }, { "name": "BASIC", "bytes": "6068" }, { "name": "Batchfile", "bytes": "1032" }, { "name": "Blade", "bytes": "14530" }, { "name": "C", "bytes": "1481904" }, { "name": "C++", "bytes": "2139472" }, { "name": "CMake", "bytes": "11595" }, { "name": "CSS", "bytes": "172375" }, { "name": "Dart", "bytes": "6282" }, { "name": "Dockerfile", "bytes": "232352" }, { "name": "EJS", "bytes": "92308" }, { "name": "Emacs Lisp", "bytes": "2668" }, { "name": "GDB", "bytes": "273" }, { "name": "GLSL", "bytes": "33392" }, { "name": "Go", "bytes": "3031142" }, { "name": "HTML", "bytes": "467647" }, { "name": "Java", "bytes": "174199" }, { "name": "JavaScript", "bytes": "2643200" }, { "name": "Lua", "bytes": "5944" }, { "name": "Makefile", "bytes": "149152" }, { "name": "NSIS", "bytes": "2800" }, { "name": "Nix", "bytes": "139" }, { "name": "PHP", "bytes": "311900" }, { "name": "Perl", "bytes": "32742" }, { "name": "Pug", "bytes": "8752" }, { "name": "Python", "bytes": "1756592" }, { "name": "Red", "bytes": "188" }, { "name": "Rust", "bytes": "541267" }, { "name": "Sage", "bytes": "39814" }, { "name": "Shell", "bytes": "382149" }, { "name": "Smali", "bytes": "2316656" }, { "name": "Starlark", "bytes": "8216" }, { "name": "SystemVerilog", "bytes": "16466" }, { "name": "VCL", "bytes": "895" }, { "name": "Verilog", "bytes": "7230" }, { "name": "Vim Script", "bytes": "890" }, { "name": "Vue", "bytes": "10248" } ], "symlink_target": "" }
using base::DictionaryValue; using content::BrowserThread; namespace content { struct LoadCommittedDetails; struct FrameNavigateParams; } namespace { static const char kFrontendHostId[] = "id"; static const char kFrontendHostMethod[] = "method"; static const char kFrontendHostParams[] = "params"; static const char kTitleFormat[] = "Developer Tools - %s"; static const char kDevToolsActionTakenHistogram[] = "DevTools.ActionTaken"; static const char kDevToolsPanelShownHistogram[] = "DevTools.PanelShown"; static const char kRemotePageActionInspect[] = "inspect"; static const char kRemotePageActionReload[] = "reload"; static const char kRemotePageActionActivate[] = "activate"; static const char kRemotePageActionClose[] = "close"; // This constant should be in sync with // the constant at shell_devtools_frontend.cc. const size_t kMaxMessageChunkSize = IPC::Channel::kMaximumMessageSize / 4; typedef std::vector<DevToolsUIBindings*> DevToolsUIBindingsList; base::LazyInstance<DevToolsUIBindingsList>::Leaky g_instances = LAZY_INSTANCE_INITIALIZER; base::DictionaryValue* CreateFileSystemValue( DevToolsFileHelper::FileSystem file_system) { base::DictionaryValue* file_system_value = new base::DictionaryValue(); file_system_value->SetString("fileSystemName", file_system.file_system_name); file_system_value->SetString("rootURL", file_system.root_url); file_system_value->SetString("fileSystemPath", file_system.file_system_path); return file_system_value; } Browser* FindBrowser(content::WebContents* web_contents) { for (chrome::BrowserIterator it; !it.done(); it.Next()) { int tab_index = it->tab_strip_model()->GetIndexOfWebContents( web_contents); if (tab_index != TabStripModel::kNoTab) return *it; } return NULL; } // DevToolsConfirmInfoBarDelegate --------------------------------------------- typedef base::Callback<void(bool)> InfoBarCallback; class DevToolsConfirmInfoBarDelegate : public ConfirmInfoBarDelegate { public: DevToolsConfirmInfoBarDelegate( const InfoBarCallback& callback, const base::string16& message); ~DevToolsConfirmInfoBarDelegate() override; private: base::string16 GetMessageText() const override; base::string16 GetButtonLabel(InfoBarButton button) const override; bool Accept() override; bool Cancel() override; InfoBarCallback callback_; const base::string16 message_; DISALLOW_COPY_AND_ASSIGN(DevToolsConfirmInfoBarDelegate); }; DevToolsConfirmInfoBarDelegate::DevToolsConfirmInfoBarDelegate( const InfoBarCallback& callback, const base::string16& message) : ConfirmInfoBarDelegate(), callback_(callback), message_(message) { } DevToolsConfirmInfoBarDelegate::~DevToolsConfirmInfoBarDelegate() { if (!callback_.is_null()) callback_.Run(false); } base::string16 DevToolsConfirmInfoBarDelegate::GetMessageText() const { return message_; } base::string16 DevToolsConfirmInfoBarDelegate::GetButtonLabel( InfoBarButton button) const { return l10n_util::GetStringUTF16((button == BUTTON_OK) ? IDS_DEV_TOOLS_CONFIRM_ALLOW_BUTTON : IDS_DEV_TOOLS_CONFIRM_DENY_BUTTON); } bool DevToolsConfirmInfoBarDelegate::Accept() { callback_.Run(true); callback_.Reset(); return true; } bool DevToolsConfirmInfoBarDelegate::Cancel() { callback_.Run(false); callback_.Reset(); return true; } // DevToolsUIDefaultDelegate -------------------------------------------------- class DefaultBindingsDelegate : public DevToolsUIBindings::Delegate { public: explicit DefaultBindingsDelegate(content::WebContents* web_contents) : web_contents_(web_contents) {} private: ~DefaultBindingsDelegate() override {} void ActivateWindow() override; void CloseWindow() override {} void SetInspectedPageBounds(const gfx::Rect& rect) override {} void InspectElementCompleted() override {} void SetIsDocked(bool is_docked) override {} void OpenInNewTab(const std::string& url) override; void SetWhitelistedShortcuts(const std::string& message) override {} using DispatchCallback = DevToolsEmbedderMessageDispatcher::Delegate::DispatchCallback; void InspectedContentsClosing() override; void OnLoadCompleted() override {} InfoBarService* GetInfoBarService() override; void RenderProcessGone(bool crashed) override {} content::WebContents* web_contents_; DISALLOW_COPY_AND_ASSIGN(DefaultBindingsDelegate); }; void DefaultBindingsDelegate::ActivateWindow() { web_contents_->GetDelegate()->ActivateContents(web_contents_); web_contents_->Focus(); } void DefaultBindingsDelegate::OpenInNewTab(const std::string& url) { content::OpenURLParams params( GURL(url), content::Referrer(), NEW_FOREGROUND_TAB, ui::PAGE_TRANSITION_LINK, false); Browser* browser = FindBrowser(web_contents_); browser->OpenURL(params); } void DefaultBindingsDelegate::InspectedContentsClosing() { web_contents_->ClosePage(); } InfoBarService* DefaultBindingsDelegate::GetInfoBarService() { return InfoBarService::FromWebContents(web_contents_); } // ResponseWriter ------------------------------------------------------------- class ResponseWriter : public net::URLFetcherResponseWriter { public: ResponseWriter(base::WeakPtr<DevToolsUIBindings> bindings, int stream_id); ~ResponseWriter() override; // URLFetcherResponseWriter overrides: int Initialize(const net::CompletionCallback& callback) override; int Write(net::IOBuffer* buffer, int num_bytes, const net::CompletionCallback& callback) override; int Finish(const net::CompletionCallback& callback) override; private: base::WeakPtr<DevToolsUIBindings> bindings_; int stream_id_; DISALLOW_COPY_AND_ASSIGN(ResponseWriter); }; ResponseWriter::ResponseWriter(base::WeakPtr<DevToolsUIBindings> bindings, int stream_id) : bindings_(bindings), stream_id_(stream_id) { } ResponseWriter::~ResponseWriter() { } int ResponseWriter::Initialize(const net::CompletionCallback& callback) { return net::OK; } int ResponseWriter::Write(net::IOBuffer* buffer, int num_bytes, const net::CompletionCallback& callback) { base::FundamentalValue* id = new base::FundamentalValue(stream_id_); base::StringValue* chunk = new base::StringValue(std::string(buffer->data(), num_bytes)); content::BrowserThread::PostTask( content::BrowserThread::UI, FROM_HERE, base::Bind(&DevToolsUIBindings::CallClientFunction, bindings_, "DevToolsAPI.streamWrite", base::Owned(id), base::Owned(chunk), nullptr)); return num_bytes; } int ResponseWriter::Finish(const net::CompletionCallback& callback) { return net::OK; } } // namespace // DevToolsUIBindings::FrontendWebContentsObserver ---------------------------- class DevToolsUIBindings::FrontendWebContentsObserver : public content::WebContentsObserver { public: explicit FrontendWebContentsObserver(DevToolsUIBindings* ui_bindings); ~FrontendWebContentsObserver() override; private: // contents::WebContentsObserver: void RenderProcessGone(base::TerminationStatus status) override; void DidStartNavigationToPendingEntry( const GURL& url, content::NavigationController::ReloadType reload_type) override; void DocumentOnLoadCompletedInMainFrame() override; void DidNavigateMainFrame( const content::LoadCommittedDetails& details, const content::FrameNavigateParams& params) override; DevToolsUIBindings* devtools_bindings_; DISALLOW_COPY_AND_ASSIGN(FrontendWebContentsObserver); }; DevToolsUIBindings::FrontendWebContentsObserver::FrontendWebContentsObserver( DevToolsUIBindings* devtools_ui_bindings) : WebContentsObserver(devtools_ui_bindings->web_contents()), devtools_bindings_(devtools_ui_bindings) { } DevToolsUIBindings::FrontendWebContentsObserver:: ~FrontendWebContentsObserver() { } void DevToolsUIBindings::FrontendWebContentsObserver::RenderProcessGone( base::TerminationStatus status) { bool crashed = true; switch (status) { case base::TERMINATION_STATUS_ABNORMAL_TERMINATION: case base::TERMINATION_STATUS_PROCESS_WAS_KILLED: #if defined(OS_CHROMEOS) case base::TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM: #endif case base::TERMINATION_STATUS_PROCESS_CRASHED: case base::TERMINATION_STATUS_LAUNCH_FAILED: if (devtools_bindings_->agent_host_.get()) devtools_bindings_->Detach(); break; default: crashed = false; break; } devtools_bindings_->delegate_->RenderProcessGone(crashed); } void DevToolsUIBindings::FrontendWebContentsObserver:: DidStartNavigationToPendingEntry( const GURL& url, content::NavigationController::ReloadType reload_type) { devtools_bindings_->frontend_host_.reset( content::DevToolsFrontendHost::Create( web_contents()->GetMainFrame(), base::Bind(&DevToolsUIBindings::HandleMessageFromDevToolsFrontend, base::Unretained(devtools_bindings_)))); } void DevToolsUIBindings::FrontendWebContentsObserver:: DocumentOnLoadCompletedInMainFrame() { devtools_bindings_->DocumentOnLoadCompletedInMainFrame(); } void DevToolsUIBindings::FrontendWebContentsObserver:: DidNavigateMainFrame(const content::LoadCommittedDetails& details, const content::FrameNavigateParams& params) { devtools_bindings_->DidNavigateMainFrame(); } // WebSocketAPIChannel -------------------------------------------------------- class WebSocketAPIChannel : public content::DevToolsExternalAgentProxyDelegate { public : WebSocketAPIChannel(); ~WebSocketAPIChannel() override; void DispatchOnClientHost(const std::string& message); void ConnectionClosed(); void AttachedToBindings(DevToolsUIBindings* bindings); private: // content::DevToolsExternalAgentProxyDelegate implementation. void Attach(content::DevToolsExternalAgentProxy* proxy) override; void Detach() override; void SendMessageToBackend(const std::string& message) override; std::set<std::string> suggested_folders_; content::DevToolsExternalAgentProxy* attached_proxy_; DISALLOW_COPY_AND_ASSIGN(WebSocketAPIChannel); }; // static WebSocketAPIChannel* g_web_socket_api_channel = nullptr; WebSocketAPIChannel::WebSocketAPIChannel() : attached_proxy_(nullptr) { CHECK(!g_web_socket_api_channel); g_web_socket_api_channel = this; } WebSocketAPIChannel::~WebSocketAPIChannel() { g_web_socket_api_channel = nullptr; } void WebSocketAPIChannel::DispatchOnClientHost( const std::string& message) { if (attached_proxy_) attached_proxy_->DispatchOnClientHost(message); } void WebSocketAPIChannel::ConnectionClosed() { for (DevToolsUIBindings* bindings : *g_instances.Pointer()) { bindings->CallClientFunction("DevToolsAPI.frontendAPIDetached", nullptr, nullptr, nullptr); } if (attached_proxy_) attached_proxy_->ConnectionClosed(); } void WebSocketAPIChannel::AttachedToBindings(DevToolsUIBindings* bindings) { bindings->CallClientFunction("DevToolsAPI.frontendAPIAttached", nullptr, nullptr, nullptr); } void WebSocketAPIChannel::Attach( content::DevToolsExternalAgentProxy* proxy) { attached_proxy_ = proxy; for (DevToolsUIBindings* bindings : *g_instances.Pointer()) AttachedToBindings(bindings); } void WebSocketAPIChannel::Detach() { attached_proxy_ = nullptr; for (DevToolsUIBindings* bindings : *g_instances.Pointer()) { bindings->CallClientFunction("DevToolsAPI.frontendAPIDetached", nullptr, nullptr, nullptr); } } void WebSocketAPIChannel::SendMessageToBackend( const std::string& message) { scoped_ptr<base::Value> value = base::JSONReader::Read(message); if (!value || !value->IsType(base::Value::TYPE_DICTIONARY)) return; int id = 0; std::string method; base::DictionaryValue* params = nullptr; if (!DevToolsProtocol::ParseCommand( static_cast<base::DictionaryValue*>(value.get()), &id, &method, &params)) return; if (method == "Frontend.addFileSystem") { base::ListValue* list; params->GetList("paths", &list); for (size_t i = 0; list && i < list->GetSize(); ++i) { std::string path; if (!list->GetString(i, &path)) continue; if (suggested_folders_.find(path) != suggested_folders_.end()) continue; suggested_folders_.insert(path); // All bindings are synchronized via preferences, only add once. DCHECK(!g_instances.Pointer()->empty()); (*g_instances.Pointer())[0]->AddFileSystem(path); } scoped_ptr<base::DictionaryValue> response = DevToolsProtocol::CreateSuccessResponse(id, nullptr); std::string response_message; base::JSONWriter::Write(*response.get(), &response_message); attached_proxy_->DispatchOnClientHost(response_message); return; } // Handle rest of the commands on the front-end. base::StringValue message_value(message); for (DevToolsUIBindings* bindings : *g_instances.Pointer()) { bindings->CallClientFunction("DevToolsAPI.dispatchFrontendAPIMessage", &message_value, nullptr, nullptr); } } // DevToolsUIBindings --------------------------------------------------------- DevToolsUIBindings* DevToolsUIBindings::ForWebContents( content::WebContents* web_contents) { if (g_instances == NULL) return NULL; DevToolsUIBindingsList* instances = g_instances.Pointer(); for (DevToolsUIBindingsList::iterator it(instances->begin()); it != instances->end(); ++it) { if ((*it)->web_contents() == web_contents) return *it; } return NULL; } DevToolsUIBindings::DevToolsUIBindings(content::WebContents* web_contents) : profile_(Profile::FromBrowserContext(web_contents->GetBrowserContext())), android_bridge_(DevToolsAndroidBridge::Factory::GetForProfile(profile_)), web_contents_(web_contents), delegate_(new DefaultBindingsDelegate(web_contents_)), devices_updates_enabled_(false), frontend_loaded_(false), weak_factory_(this) { g_instances.Get().push_back(this); frontend_contents_observer_.reset(new FrontendWebContentsObserver(this)); web_contents_->GetMutableRendererPrefs()->can_accept_load_drops = false; file_helper_.reset(new DevToolsFileHelper(web_contents_, profile_, this)); file_system_indexer_ = new DevToolsFileSystemIndexer(); extensions::ChromeExtensionWebContentsObserver::CreateForWebContents( web_contents_); // Register on-load actions. embedder_message_dispatcher_.reset( DevToolsEmbedderMessageDispatcher::CreateForDevToolsFrontend(this)); frontend_host_.reset(content::DevToolsFrontendHost::Create( web_contents_->GetMainFrame(), base::Bind(&DevToolsUIBindings::HandleMessageFromDevToolsFrontend, base::Unretained(this)))); } DevToolsUIBindings::~DevToolsUIBindings() { for (const auto& pair : pending_requests_) delete pair.first; if (agent_host_.get()) agent_host_->DetachClient(); for (IndexingJobsMap::const_iterator jobs_it(indexing_jobs_.begin()); jobs_it != indexing_jobs_.end(); ++jobs_it) { jobs_it->second->Stop(); } indexing_jobs_.clear(); SetDevicesUpdatesEnabled(false); // Remove self from global list. DevToolsUIBindingsList* instances = g_instances.Pointer(); DevToolsUIBindingsList::iterator it( std::find(instances->begin(), instances->end(), this)); DCHECK(it != instances->end()); instances->erase(it); if (instances->empty() && g_web_socket_api_channel) g_web_socket_api_channel->ConnectionClosed(); } // content::DevToolsFrontendHost::Delegate implementation --------------------- void DevToolsUIBindings::HandleMessageFromDevToolsFrontend( const std::string& message) { std::string method; base::ListValue empty_params; base::ListValue* params = &empty_params; base::DictionaryValue* dict = NULL; scoped_ptr<base::Value> parsed_message = base::JSONReader::Read(message); if (!parsed_message || !parsed_message->GetAsDictionary(&dict) || !dict->GetString(kFrontendHostMethod, &method) || (dict->HasKey(kFrontendHostParams) && !dict->GetList(kFrontendHostParams, &params))) { LOG(ERROR) << "Invalid message was sent to embedder: " << message; return; } int id = 0; dict->GetInteger(kFrontendHostId, &id); embedder_message_dispatcher_->Dispatch( base::Bind(&DevToolsUIBindings::SendMessageAck, weak_factory_.GetWeakPtr(), id), method, params); } // content::DevToolsAgentHostClient implementation -------------------------- void DevToolsUIBindings::DispatchProtocolMessage( content::DevToolsAgentHost* agent_host, const std::string& message) { DCHECK(agent_host == agent_host_.get()); if (message.length() < kMaxMessageChunkSize) { base::string16 javascript = base::UTF8ToUTF16( "DevToolsAPI.dispatchMessage(" + message + ");"); web_contents_->GetMainFrame()->ExecuteJavaScript(javascript); return; } base::FundamentalValue total_size(static_cast<int>(message.length())); for (size_t pos = 0; pos < message.length(); pos += kMaxMessageChunkSize) { base::StringValue message_value(message.substr(pos, kMaxMessageChunkSize)); CallClientFunction("DevToolsAPI.dispatchMessageChunk", &message_value, pos ? NULL : &total_size, NULL); } } void DevToolsUIBindings::AgentHostClosed( content::DevToolsAgentHost* agent_host, bool replaced_with_another_client) { DCHECK(agent_host == agent_host_.get()); agent_host_ = NULL; delegate_->InspectedContentsClosing(); } void DevToolsUIBindings::SendMessageAck(int request_id, const base::Value* arg) { base::FundamentalValue id_value(request_id); CallClientFunction("DevToolsAPI.embedderMessageAck", &id_value, arg, nullptr); } // DevToolsEmbedderMessageDispatcher::Delegate implementation ----------------- void DevToolsUIBindings::ActivateWindow() { delegate_->ActivateWindow(); } void DevToolsUIBindings::CloseWindow() { delegate_->CloseWindow(); } void DevToolsUIBindings::LoadCompleted() { FrontendLoaded(); } void DevToolsUIBindings::SetInspectedPageBounds(const gfx::Rect& rect) { delegate_->SetInspectedPageBounds(rect); } void DevToolsUIBindings::SetIsDocked(const DispatchCallback& callback, bool dock_requested) { delegate_->SetIsDocked(dock_requested); callback.Run(nullptr); } void DevToolsUIBindings::InspectElementCompleted() { delegate_->InspectElementCompleted(); } void DevToolsUIBindings::InspectedURLChanged(const std::string& url) { content::NavigationController& controller = web_contents()->GetController(); content::NavigationEntry* entry = controller.GetActiveEntry(); // DevTools UI is not localized. entry->SetTitle( base::UTF8ToUTF16(base::StringPrintf(kTitleFormat, url.c_str()))); web_contents()->NotifyNavigationStateChanged(content::INVALIDATE_TYPE_TITLE); } void DevToolsUIBindings::LoadNetworkResource(const DispatchCallback& callback, const std::string& url, const std::string& headers, int stream_id) { GURL gurl(url); if (!gurl.is_valid()) { base::DictionaryValue response; response.SetInteger("statusCode", 404); callback.Run(&response); return; } net::URLFetcher* fetcher = net::URLFetcher::Create(gurl, net::URLFetcher::GET, this).release(); pending_requests_[fetcher] = callback; fetcher->SetRequestContext(profile_->GetRequestContext()); fetcher->SetExtraRequestHeaders(headers); fetcher->SaveResponseWithWriter(scoped_ptr<net::URLFetcherResponseWriter>( new ResponseWriter(weak_factory_.GetWeakPtr(), stream_id))); fetcher->Start(); } void DevToolsUIBindings::OpenInNewTab(const std::string& url) { delegate_->OpenInNewTab(url); } void DevToolsUIBindings::SaveToFile(const std::string& url, const std::string& content, bool save_as) { file_helper_->Save(url, content, save_as, base::Bind(&DevToolsUIBindings::FileSavedAs, weak_factory_.GetWeakPtr(), url), base::Bind(&DevToolsUIBindings::CanceledFileSaveAs, weak_factory_.GetWeakPtr(), url)); } void DevToolsUIBindings::AppendToFile(const std::string& url, const std::string& content) { file_helper_->Append(url, content, base::Bind(&DevToolsUIBindings::AppendedTo, weak_factory_.GetWeakPtr(), url)); } void DevToolsUIBindings::RequestFileSystems() { CHECK(web_contents_->GetURL().SchemeIs(content::kChromeDevToolsScheme)); std::vector<DevToolsFileHelper::FileSystem> file_systems = file_helper_->GetFileSystems(); base::ListValue file_systems_value; for (size_t i = 0; i < file_systems.size(); ++i) file_systems_value.Append(CreateFileSystemValue(file_systems[i])); CallClientFunction("DevToolsAPI.fileSystemsLoaded", &file_systems_value, NULL, NULL); } void DevToolsUIBindings::AddFileSystem(const std::string& file_system_path) { CHECK(web_contents_->GetURL().SchemeIs(content::kChromeDevToolsScheme)); file_helper_->AddFileSystem( file_system_path, base::Bind(&DevToolsUIBindings::ShowDevToolsConfirmInfoBar, weak_factory_.GetWeakPtr())); } void DevToolsUIBindings::RemoveFileSystem(const std::string& file_system_path) { CHECK(web_contents_->GetURL().SchemeIs(content::kChromeDevToolsScheme)); file_helper_->RemoveFileSystem(file_system_path); } void DevToolsUIBindings::UpgradeDraggedFileSystemPermissions( const std::string& file_system_url) { CHECK(web_contents_->GetURL().SchemeIs(content::kChromeDevToolsScheme)); file_helper_->UpgradeDraggedFileSystemPermissions( file_system_url, base::Bind(&DevToolsUIBindings::ShowDevToolsConfirmInfoBar, weak_factory_.GetWeakPtr())); } void DevToolsUIBindings::IndexPath(int index_request_id, const std::string& file_system_path) { DCHECK_CURRENTLY_ON(BrowserThread::UI); CHECK(web_contents_->GetURL().SchemeIs(content::kChromeDevToolsScheme)); if (!file_helper_->IsFileSystemAdded(file_system_path)) { IndexingDone(index_request_id, file_system_path); return; } if (indexing_jobs_.count(index_request_id) != 0) return; indexing_jobs_[index_request_id] = scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>( file_system_indexer_->IndexPath( file_system_path, Bind(&DevToolsUIBindings::IndexingTotalWorkCalculated, weak_factory_.GetWeakPtr(), index_request_id, file_system_path), Bind(&DevToolsUIBindings::IndexingWorked, weak_factory_.GetWeakPtr(), index_request_id, file_system_path), Bind(&DevToolsUIBindings::IndexingDone, weak_factory_.GetWeakPtr(), index_request_id, file_system_path))); } void DevToolsUIBindings::StopIndexing(int index_request_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); IndexingJobsMap::iterator it = indexing_jobs_.find(index_request_id); if (it == indexing_jobs_.end()) return; it->second->Stop(); indexing_jobs_.erase(it); } void DevToolsUIBindings::SearchInPath(int search_request_id, const std::string& file_system_path, const std::string& query) { DCHECK_CURRENTLY_ON(BrowserThread::UI); CHECK(web_contents_->GetURL().SchemeIs(content::kChromeDevToolsScheme)); if (!file_helper_->IsFileSystemAdded(file_system_path)) { SearchCompleted(search_request_id, file_system_path, std::vector<std::string>()); return; } file_system_indexer_->SearchInPath(file_system_path, query, Bind(&DevToolsUIBindings::SearchCompleted, weak_factory_.GetWeakPtr(), search_request_id, file_system_path)); } void DevToolsUIBindings::SetWhitelistedShortcuts(const std::string& message) { delegate_->SetWhitelistedShortcuts(message); } void DevToolsUIBindings::ZoomIn() { ui_zoom::PageZoom::Zoom(web_contents(), content::PAGE_ZOOM_IN); } void DevToolsUIBindings::ZoomOut() { ui_zoom::PageZoom::Zoom(web_contents(), content::PAGE_ZOOM_OUT); } void DevToolsUIBindings::ResetZoom() { ui_zoom::PageZoom::Zoom(web_contents(), content::PAGE_ZOOM_RESET); } void DevToolsUIBindings::SetDevicesDiscoveryConfig( bool discover_usb_devices, bool port_forwarding_enabled, const std::string& port_forwarding_config) { base::DictionaryValue* config_dict = nullptr; scoped_ptr<base::Value> parsed_config = base::JSONReader::Read(port_forwarding_config); if (!parsed_config || !parsed_config->GetAsDictionary(&config_dict)) return; profile_->GetPrefs()->SetBoolean( prefs::kDevToolsDiscoverUsbDevicesEnabled, discover_usb_devices); profile_->GetPrefs()->SetBoolean( prefs::kDevToolsPortForwardingEnabled, port_forwarding_enabled); profile_->GetPrefs()->Set( prefs::kDevToolsPortForwardingConfig, *config_dict); } void DevToolsUIBindings::DevicesDiscoveryConfigUpdated() { CallClientFunction( "DevToolsAPI.devicesDiscoveryConfigChanged", profile_->GetPrefs()->FindPreference( prefs::kDevToolsDiscoverUsbDevicesEnabled)->GetValue(), profile_->GetPrefs()->FindPreference( prefs::kDevToolsPortForwardingEnabled)->GetValue(), profile_->GetPrefs()->FindPreference( prefs::kDevToolsPortForwardingConfig)->GetValue()); } void DevToolsUIBindings::SendPortForwardingStatus(const base::Value& status) { CallClientFunction("DevToolsAPI.devicesPortForwardingStatusChanged", &status, nullptr, nullptr); } void DevToolsUIBindings::SetDevicesUpdatesEnabled(bool enabled) { if (devices_updates_enabled_ == enabled) return; devices_updates_enabled_ = enabled; if (enabled) { remote_targets_handler_ = DevToolsTargetsUIHandler::CreateForAdb( base::Bind(&DevToolsUIBindings::DevicesUpdated, base::Unretained(this)), profile_); pref_change_registrar_.Init(profile_->GetPrefs()); pref_change_registrar_.Add(prefs::kDevToolsDiscoverUsbDevicesEnabled, base::Bind(&DevToolsUIBindings::DevicesDiscoveryConfigUpdated, base::Unretained(this))); pref_change_registrar_.Add(prefs::kDevToolsPortForwardingEnabled, base::Bind(&DevToolsUIBindings::DevicesDiscoveryConfigUpdated, base::Unretained(this))); pref_change_registrar_.Add(prefs::kDevToolsPortForwardingConfig, base::Bind(&DevToolsUIBindings::DevicesDiscoveryConfigUpdated, base::Unretained(this))); port_status_serializer_.reset(new PortForwardingStatusSerializer( base::Bind(&DevToolsUIBindings::SendPortForwardingStatus, base::Unretained(this)), profile_)); DevicesDiscoveryConfigUpdated(); } else { remote_targets_handler_.reset(); port_status_serializer_.reset(); pref_change_registrar_.RemoveAll(); SendPortForwardingStatus(base::DictionaryValue()); } } void DevToolsUIBindings::PerformActionOnRemotePage(const std::string& page_id, const std::string& action) { if (!remote_targets_handler_) return; DevToolsTargetImpl* target = remote_targets_handler_->GetTarget(page_id); if (!target) return; if (action == kRemotePageActionInspect) target->Inspect(profile_); if (action == kRemotePageActionReload) target->Reload(); if (action == kRemotePageActionActivate) target->Activate(); if (action == kRemotePageActionClose) target->Close(); } void DevToolsUIBindings::OpenRemotePage(const std::string& browser_id, const std::string& url) { if (!remote_targets_handler_) return; remote_targets_handler_->Open(browser_id, url); } void DevToolsUIBindings::GetPreferences(const DispatchCallback& callback) { const DictionaryValue* prefs = profile_->GetPrefs()->GetDictionary(prefs::kDevToolsPreferences); callback.Run(prefs); } void DevToolsUIBindings::SetPreference(const std::string& name, const std::string& value) { DictionaryPrefUpdate update(profile_->GetPrefs(), prefs::kDevToolsPreferences); update.Get()->SetStringWithoutPathExpansion(name, value); } void DevToolsUIBindings::RemovePreference(const std::string& name) { DictionaryPrefUpdate update(profile_->GetPrefs(), prefs::kDevToolsPreferences); update.Get()->RemoveWithoutPathExpansion(name, nullptr); } void DevToolsUIBindings::ClearPreferences() { DictionaryPrefUpdate update(profile_->GetPrefs(), prefs::kDevToolsPreferences); update.Get()->Clear(); } void DevToolsUIBindings::DispatchProtocolMessageFromDevToolsFrontend( const std::string& message) { if (agent_host_.get()) agent_host_->DispatchProtocolMessage(message); } void DevToolsUIBindings::RecordEnumeratedHistogram(const std::string& name, int sample, int boundary_value) { if (!(boundary_value >= 0 && boundary_value <= 100 && sample >= 0 && sample < boundary_value)) { // TODO(nick): Replace with chrome::bad_message::ReceivedBadMessage(). frontend_host_->BadMessageRecieved(); return; } // Each histogram name must follow a different code path in // order to UMA_HISTOGRAM_ENUMERATION work correctly. if (name == kDevToolsActionTakenHistogram) UMA_HISTOGRAM_ENUMERATION(name, sample, boundary_value); else if (name == kDevToolsPanelShownHistogram) UMA_HISTOGRAM_ENUMERATION(name, sample, boundary_value); else frontend_host_->BadMessageRecieved(); } void DevToolsUIBindings::SendJsonRequest(const DispatchCallback& callback, const std::string& browser_id, const std::string& url) { if (!android_bridge_) { callback.Run(nullptr); return; } android_bridge_->SendJsonRequest(browser_id, url, base::Bind(&DevToolsUIBindings::JsonReceived, weak_factory_.GetWeakPtr(), callback)); } void DevToolsUIBindings::SendFrontendAPINotification( const std::string& message) { if (!g_web_socket_api_channel) return; g_web_socket_api_channel->DispatchOnClientHost(message); } void DevToolsUIBindings::JsonReceived(const DispatchCallback& callback, int result, const std::string& message) { if (result != net::OK) { callback.Run(nullptr); return; } base::StringValue message_value(message); callback.Run(&message_value); } void DevToolsUIBindings::OnURLFetchComplete(const net::URLFetcher* source) { DCHECK(source); PendingRequestsMap::iterator it = pending_requests_.find(source); DCHECK(it != pending_requests_.end()); base::DictionaryValue response; base::DictionaryValue* headers = new base::DictionaryValue(); net::HttpResponseHeaders* rh = source->GetResponseHeaders(); response.SetInteger("statusCode", rh ? rh->response_code() : 200); response.Set("headers", headers); void* iterator = NULL; std::string name; std::string value; while (rh && rh->EnumerateHeaderLines(&iterator, &name, &value)) headers->SetString(name, value); it->second.Run(&response); pending_requests_.erase(it); delete source; } void DevToolsUIBindings::DeviceCountChanged(int count) { base::FundamentalValue value(count); CallClientFunction("DevToolsAPI.deviceCountUpdated", &value, NULL, NULL); } void DevToolsUIBindings::DevicesUpdated( const std::string& source, const base::ListValue& targets) { CallClientFunction("DevToolsAPI.devicesUpdated", &targets, NULL, NULL); } void DevToolsUIBindings::FileSavedAs(const std::string& url) { base::StringValue url_value(url); CallClientFunction("DevToolsAPI.savedURL", &url_value, NULL, NULL); } void DevToolsUIBindings::CanceledFileSaveAs(const std::string& url) { base::StringValue url_value(url); CallClientFunction("DevToolsAPI.canceledSaveURL", &url_value, NULL, NULL); } void DevToolsUIBindings::AppendedTo(const std::string& url) { base::StringValue url_value(url); CallClientFunction("DevToolsAPI.appendedToURL", &url_value, NULL, NULL); } void DevToolsUIBindings::FileSystemAdded( const DevToolsFileHelper::FileSystem& file_system) { scoped_ptr<base::DictionaryValue> file_system_value( CreateFileSystemValue(file_system)); CallClientFunction("DevToolsAPI.fileSystemAdded", file_system_value.get(), NULL, NULL); } void DevToolsUIBindings::FileSystemRemoved( const std::string& file_system_path) { base::StringValue file_system_path_value(file_system_path); CallClientFunction("DevToolsAPI.fileSystemRemoved", &file_system_path_value, NULL, NULL); } void DevToolsUIBindings::FilePathsChanged( const std::vector<std::string>& file_paths) { base::ListValue list; for (auto path : file_paths) list.AppendString(path); CallClientFunction("DevToolsAPI.fileSystemFilesChanged", &list, NULL, NULL); } void DevToolsUIBindings::IndexingTotalWorkCalculated( int request_id, const std::string& file_system_path, int total_work) { DCHECK_CURRENTLY_ON(BrowserThread::UI); base::FundamentalValue request_id_value(request_id); base::StringValue file_system_path_value(file_system_path); base::FundamentalValue total_work_value(total_work); CallClientFunction("DevToolsAPI.indexingTotalWorkCalculated", &request_id_value, &file_system_path_value, &total_work_value); } void DevToolsUIBindings::IndexingWorked(int request_id, const std::string& file_system_path, int worked) { DCHECK_CURRENTLY_ON(BrowserThread::UI); base::FundamentalValue request_id_value(request_id); base::StringValue file_system_path_value(file_system_path); base::FundamentalValue worked_value(worked); CallClientFunction("DevToolsAPI.indexingWorked", &request_id_value, &file_system_path_value, &worked_value); } void DevToolsUIBindings::IndexingDone(int request_id, const std::string& file_system_path) { indexing_jobs_.erase(request_id); DCHECK_CURRENTLY_ON(BrowserThread::UI); base::FundamentalValue request_id_value(request_id); base::StringValue file_system_path_value(file_system_path); CallClientFunction("DevToolsAPI.indexingDone", &request_id_value, &file_system_path_value, NULL); } void DevToolsUIBindings::SearchCompleted( int request_id, const std::string& file_system_path, const std::vector<std::string>& file_paths) { DCHECK_CURRENTLY_ON(BrowserThread::UI); base::ListValue file_paths_value; for (std::vector<std::string>::const_iterator it(file_paths.begin()); it != file_paths.end(); ++it) { file_paths_value.AppendString(*it); } base::FundamentalValue request_id_value(request_id); base::StringValue file_system_path_value(file_system_path); CallClientFunction("DevToolsAPI.searchCompleted", &request_id_value, &file_system_path_value, &file_paths_value); } void DevToolsUIBindings::ShowDevToolsConfirmInfoBar( const base::string16& message, const InfoBarCallback& callback) { if (!delegate_->GetInfoBarService()) { callback.Run(false); return; } scoped_ptr<DevToolsConfirmInfoBarDelegate> delegate( new DevToolsConfirmInfoBarDelegate(callback, message)); GlobalConfirmInfoBar::Show(delegate.Pass()); } void DevToolsUIBindings::AddDevToolsExtensionsToClient() { const extensions::ExtensionRegistry* registry = extensions::ExtensionRegistry::Get(profile_->GetOriginalProfile()); if (!registry) return; base::ListValue results; for (const scoped_refptr<const extensions::Extension>& extension : registry->enabled_extensions()) { if (extensions::chrome_manifest_urls::GetDevToolsPage(extension.get()) .is_empty()) continue; base::DictionaryValue* extension_info = new base::DictionaryValue(); extension_info->Set( "startPage", new base::StringValue(extensions::chrome_manifest_urls::GetDevToolsPage( extension.get()).spec())); extension_info->Set("name", new base::StringValue(extension->name())); extension_info->Set("exposeExperimentalAPIs", new base::FundamentalValue( extension->permissions_data()->HasAPIPermission( extensions::APIPermission::kExperimental))); results.Append(extension_info); } CallClientFunction("DevToolsAPI.addExtensions", &results, NULL, NULL); } void DevToolsUIBindings::SetDelegate(Delegate* delegate) { delegate_.reset(delegate); } void DevToolsUIBindings::AttachTo( const scoped_refptr<content::DevToolsAgentHost>& agent_host) { if (agent_host_.get()) Detach(); agent_host_ = agent_host; agent_host_->AttachClient(this); } void DevToolsUIBindings::Reattach() { DCHECK(agent_host_.get()); agent_host_->DetachClient(); agent_host_->AttachClient(this); } void DevToolsUIBindings::Detach() { if (agent_host_.get()) agent_host_->DetachClient(); agent_host_ = NULL; } bool DevToolsUIBindings::IsAttachedTo(content::DevToolsAgentHost* agent_host) { return agent_host_.get() == agent_host; } // static content::DevToolsExternalAgentProxyDelegate* DevToolsUIBindings::CreateWebSocketAPIChannel() { if (g_web_socket_api_channel) g_web_socket_api_channel->ConnectionClosed(); if (!g_instances.Pointer()->empty()) g_web_socket_api_channel = new WebSocketAPIChannel(); return g_web_socket_api_channel; } void DevToolsUIBindings::CallClientFunction(const std::string& function_name, const base::Value* arg1, const base::Value* arg2, const base::Value* arg3) { std::string javascript = function_name + "("; if (arg1) { std::string json; base::JSONWriter::Write(*arg1, &json); javascript.append(json); if (arg2) { base::JSONWriter::Write(*arg2, &json); javascript.append(", ").append(json); if (arg3) { base::JSONWriter::Write(*arg3, &json); javascript.append(", ").append(json); } } } javascript.append(");"); web_contents_->GetMainFrame()->ExecuteJavaScript( base::UTF8ToUTF16(javascript)); } void DevToolsUIBindings::DocumentOnLoadCompletedInMainFrame() { // In the DEBUG_DEVTOOLS mode, the DocumentOnLoadCompletedInMainFrame event // arrives before the LoadCompleted event, thus it should not trigger the // frontend load handling. #if !defined(DEBUG_DEVTOOLS) FrontendLoaded(); #endif } void DevToolsUIBindings::DidNavigateMainFrame() { frontend_loaded_ = false; } void DevToolsUIBindings::FrontendLoaded() { if (frontend_loaded_) return; frontend_loaded_ = true; // Call delegate first - it seeds importants bit of information. delegate_->OnLoadCompleted(); AddDevToolsExtensionsToClient(); if (g_web_socket_api_channel) g_web_socket_api_channel->AttachedToBindings(this); }
{ "content_hash": "bcac659723b510c96559851652ad6a9b", "timestamp": "", "source": "github", "line_count": 1140, "max_line_length": 80, "avg_line_length": 35.507894736842104, "alnum_prop": 0.6818844339039996, "repo_name": "Workday/OpenFrame", "id": "acd7397bd037ed93d328383b7d014fea6ab04cda", "size": "43354", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chrome/browser/devtools/devtools_ui_bindings.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
@interface ABI43_0_0EXForegroundPermissionRequester : ABI43_0_0EXBaseLocationRequester @end
{ "content_hash": "7241acf0e65228bcae99f4b5bc2b4039", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 86, "avg_line_length": 23.5, "alnum_prop": 0.851063829787234, "repo_name": "exponent/exponent", "id": "8ad1123cd99a10b3162ee01c7dadf233ae12c949", "size": "224", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ios/versioned/sdk43/EXLocation/EXLocation/Requesters/ABI43_0_0EXForegroundPermissionRequester.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "113276" }, { "name": "Batchfile", "bytes": "127" }, { "name": "C", "bytes": "1744836" }, { "name": "C++", "bytes": "1801159" }, { "name": "CSS", "bytes": "7854" }, { "name": "HTML", "bytes": "176329" }, { "name": "IDL", "bytes": "897" }, { "name": "Java", "bytes": "6251130" }, { "name": "JavaScript", "bytes": "4416558" }, { "name": "Makefile", "bytes": "18061" }, { "name": "Objective-C", "bytes": "13971362" }, { "name": "Objective-C++", "bytes": "725480" }, { "name": "Perl", "bytes": "5860" }, { "name": "Prolog", "bytes": "287" }, { "name": "Python", "bytes": "125673" }, { "name": "Ruby", "bytes": "61190" }, { "name": "Shell", "bytes": "4441" } ], "symlink_target": "" }
import { InertiaOptions, PlaybackControls, AnimationOptions, SpringOptions, } from "./types" import { animate } from "." import { velocityPerSecond } from "../utils/velocity-per-second" import { getFrameData } from "framesync" export function inertia({ from = 0, velocity = 0, min, max, power = 0.8, timeConstant = 750, bounceStiffness = 500, bounceDamping = 10, restDelta = 1, modifyTarget, driver, onUpdate, onComplete, }: InertiaOptions) { let currentAnimation: PlaybackControls function isOutOfBounds(v: number) { return (min !== undefined && v < min) || (max !== undefined && v > max) } function boundaryNearest(v: number) { if (min === undefined) return max if (max === undefined) return min return Math.abs(min - v) < Math.abs(max - v) ? min : max } function startAnimation(options: AnimationOptions<number>) { currentAnimation?.stop() currentAnimation = animate({ ...options, driver, onUpdate: (v: number) => { onUpdate?.(v) options.onUpdate?.(v) }, onComplete, }) } function startSpring(options: SpringOptions) { startAnimation({ type: "spring", stiffness: bounceStiffness, damping: bounceDamping, restDelta, ...options, }) } if (isOutOfBounds(from)) { // Start the animation with spring if outside the defined boundaries startSpring({ from, velocity, to: boundaryNearest(from) }) } else { /** * Or if the value is out of bounds, simulate the inertia movement * with the decay animation. * * Pre-calculate the target so we can detect if it's out-of-bounds. * If it is, we want to check per frame when to switch to a spring * animation */ let target = power * velocity + from if (typeof modifyTarget !== "undefined") target = modifyTarget(target) const boundary = boundaryNearest(target) const heading = boundary === min ? -1 : 1 let prev: number let current: number const checkBoundary = (v: number) => { prev = current current = v velocity = velocityPerSecond(v - prev, getFrameData().delta) if ( (heading === 1 && v > boundary) || (heading === -1 && v < boundary) ) { startSpring({ from: v, to: boundary, velocity }) } } startAnimation({ type: "decay", from, velocity, timeConstant, power, restDelta, modifyTarget, onUpdate: isOutOfBounds(target) ? checkBoundary : undefined, }) } return { stop: () => currentAnimation?.stop(), } }
{ "content_hash": "467ce0627d8fe30dffd5ee41c6231911", "timestamp": "", "source": "github", "line_count": 110, "max_line_length": 79, "avg_line_length": 27.21818181818182, "alnum_prop": 0.5344021376085505, "repo_name": "InventingWithMonster/redshift", "id": "b4894ef7cadbef561f958d254c45ed0dacc2e58f", "size": "2994", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/popmotion/src/animations/inertia.ts", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "1011372" } ], "symlink_target": "" }
package fruit.sim; public class UniformFruitGenerator implements FruitGenerator { public int[] generate(int nplayers, int bowlsize) { int nfruits = nplayers * bowlsize; int[] dist = new int[12]; int unit = nfruits / 12; dist[0] = nfruits - unit * 11; for (int i = 1; i < 12; i++) dist[i] = unit; return dist; } }
{ "content_hash": "ce0274e61304b8e77c72077ec3b92763", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 60, "avg_line_length": 23.58823529411765, "alnum_prop": 0.5386533665835411, "repo_name": "rymo4/fruitsalad", "id": "5ae4cc588e1e2e08894226512e72c92c136a0ffc", "size": "401", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "fruit/sim/UniformFruitGenerator.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "330008" } ], "symlink_target": "" }
var config = new function() { NUM_LEDS = 120, DEFAULT_LAYOUT = 'german' } module.exports.config = config;
{ "content_hash": "a081de9d211f945a297c7633fd15aba6", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 31, "avg_line_length": 14.625, "alnum_prop": 0.6324786324786325, "repo_name": "romanwoessner/rpi_node_wordclock", "id": "a917e4d0cfe2f6e059475133c096386e571fb704", "size": "117", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/config.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "8127" } ], "symlink_target": "" }
<?php class House_model extends CI_Model { public function __construct() { $this->load->database(); } public function get_house($house_number) { $query = $this->db->get_where('Houses', array('house_id' => $house_number)); return $query->row_array(); } public function get_house_rooms($house_number) { $query = $this->db->get_where('Rooms', array('house_id' => $house_number)); return $query->result_array(); } public function set_house() { $data = array( 'name' => $this->input->post('housename'), 'description' => $this->input->post('housedescription') ); $this->db->insert('Houses', $data); return $this->db->insert_id(); } }
{ "content_hash": "b1f6866cdbe12c0d5dd47e2952c2f2ed", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 78, "avg_line_length": 25.576923076923077, "alnum_prop": 0.6270676691729323, "repo_name": "tylerbenzing/Chatterbox", "id": "cbc31ea18fc886700a40800145100939835ced1a", "size": "665", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/models/House_model.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "240" }, { "name": "CSS", "bytes": "15876" }, { "name": "HTML", "bytes": "8413296" }, { "name": "JavaScript", "bytes": "92173" }, { "name": "PHP", "bytes": "1763122" } ], "symlink_target": "" }
default[:wpcli][:config_path] = '/home/vagrant/.wp-cli/config.yml' default[:wpcli][:user] = 'vagrant' default[:wpcli][:group] = 'vagrant' default[:wpcli][:dir] = '/usr/share/wp-cli' default[:wpcli][:link] = '/usr/local/bin/wp' default[:wpcli][:locale] = "" default[:wpcli][:wp_version] = "latest" default[:wpcli][:wp_host] = "wordpress.local" default[:wpcli][:wp_home] = "" default[:wpcli][:wp_siteurl] = "" default[:wpcli][:wp_docroot] = "/var/www/wordpress" default[:wpcli][:title] = "Welcome to the WordPress" default[:wpcli][:dbhost] = "localhost" default[:wpcli][:dbname] = "wordpress" default[:wpcli][:dbuser] = "wordpress" default[:wpcli][:dbpassword] = "wordpress" default[:wpcli][:dbprefix] = "wp_" default[:wpcli][:admin_user] = "admin" default[:wpcli][:admin_password] = "admin" default[:wpcli][:admin_email] = "[email protected]" default[:wpcli][:default_plugins] = [] default[:wpcli][:default_theme] = '' default[:wpcli][:is_multisite] = false default[:wpcli][:debug_mode] = false default[:wpcli][:savequeries] = false default[:wpcli][:theme_unit_test] = true default[:wpcli][:theme_unit_test_data_url] = 'https://wpcom-themes.svn.automattic.com/demo/theme-unit-test-data.xml' default[:wpcli][:theme_unit_test_data] = '/tmp/theme-unit-test-data.xml' default[:wpcli][:gitignore_url] = 'https://raw.githubusercontent.com/github/gitignore/master/WordPress.gitignore' default[:wpcli][:gitignore] = '/var/www/wordpress/.gitignore' default[:wpcli][:is_multisite] = false default[:wpcli][:force_ssl_admin] = false default[:wpcli][:always_reset] = true default[:wpcli][:options] = {} default[:wpcli][:rewrite_structure] = '/archives/%post_id%'
{ "content_hash": "930aac0344cfac82db5d262fced38333", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 116, "avg_line_length": 36.130434782608695, "alnum_prop": 0.6937424789410349, "repo_name": "daikichi339/ATL_wp", "id": "2f3a847387f122bd5a2e6d5a67ce29aebeeae081", "size": "1967", "binary": false, "copies": "1", "ref": "refs/heads/staging", "path": "provision/site-cookbooks/wpcli/attributes/default.rb", "mode": "33261", "license": "mit", "language": [ { "name": "HTML", "bytes": "356763" }, { "name": "Perl", "bytes": "8609" }, { "name": "Ruby", "bytes": "288756" }, { "name": "Shell", "bytes": "12014" } ], "symlink_target": "" }
from aquilon.exceptions_ import NotFoundException, ArgumentError from aquilon.worker.broker import BrokerCommand from aquilon.worker.dbwrappers.host import hostname_to_host from aquilon.worker.dbwrappers.resources import get_resource_holder from aquilon.worker.dbwrappers.change_management import ChangeManagement class CommandDelClusterMemberPriority(BrokerCommand): requires_plenaries = True resource_class = None def render(self, session, logger, plenaries, cluster, resourcegroup, member, user, justification, reason, **kwargs): # pylint: disable=W0613 holder = get_resource_holder(session, logger, None, cluster, None, resourcegroup, compel=False) # Validate ChangeManagement cm = ChangeManagement(session, user, justification, reason, logger, self.command, **kwargs) cm.consider(holder) cm.validate() dbhost = hostname_to_host(session, member) name = self.resource_class.__mapper__.polymorphic_identity dbresource = self.resource_class.get_unique(session, name=name, holder=holder, compel=True) dbcluster = dbresource.holder.toplevel_holder_object if not dbhost.cluster or dbhost.cluster != dbcluster: raise ArgumentError("{0} is not a member of {1:l}." .format(dbhost, dbcluster)) plenaries.add(holder.holder_object) plenaries.add(dbresource) try: del dbresource.entries[dbhost] except KeyError: raise NotFoundException("{0} has no {1:c} entry." .format(dbhost, dbresource)) # Mostly cosmetic - don't leave empty containers behind if not dbresource.entries: holder.resources.remove(dbresource) session.flush() plenaries.write() return
{ "content_hash": "387d07235784659c9641b3d58f69ba63", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 99, "avg_line_length": 38.05882352941177, "alnum_prop": 0.639361154044307, "repo_name": "quattor/aquilon", "id": "1ebbfe1ccd3ac4d57f4260e92fa06616bf712b5a", "size": "2635", "binary": false, "copies": "1", "ref": "refs/heads/upstream", "path": "lib/aquilon/worker/commands/del_cluster_member_priority.py", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "DIGITAL Command Language", "bytes": "1823" }, { "name": "Makefile", "bytes": "5732" }, { "name": "Mako", "bytes": "4178" }, { "name": "PLSQL", "bytes": "102109" }, { "name": "PLpgSQL", "bytes": "8091" }, { "name": "Pan", "bytes": "1058" }, { "name": "Perl", "bytes": "6057" }, { "name": "Python", "bytes": "5884984" }, { "name": "SQLPL", "bytes": "869" }, { "name": "Shell", "bytes": "33547" }, { "name": "Smarty", "bytes": "4603" } ], "symlink_target": "" }
import DS from 'ember-data'; import Ember from 'ember'; import PartialModelRESTSerializer from 'ember-data-partial-model/mixins/rest-serializer'; import RESTSerializer from 'ember-data/serializers/rest'; const { EmbeddedRecordsMixin } = DS; const { Mixin } = Ember; export default RESTSerializer.extend(PartialModelRESTSerializer, { partialSerializersExtensions: { extended: { attrs: { clients: { embedded: 'always' } } } }, partialSerializersMixins: { extended: [EmbeddedRecordsMixin, Mixin.create({ __magicAttributeForTest__: true })] } });
{ "content_hash": "9d7d2c5c6573a4b4fffbe5637de949a7", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 89, "avg_line_length": 27.904761904761905, "alnum_prop": 0.71160409556314, "repo_name": "BookingSync/ember-data-partial-model", "id": "bc2949e31e508e1ad44f576645dcc3858a8ae5e4", "size": "586", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/dummy/app/serializers/user.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "2998" }, { "name": "JavaScript", "bytes": "42568" } ], "symlink_target": "" }
package org.codemucker.jfind.e; @TstAnnotation public class TstAnnotationBean { }
{ "content_hash": "31c5c9c5433bcb82bf5fa1dfee4280ec", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 32, "avg_line_length": 13.142857142857142, "alnum_prop": 0.7282608695652174, "repo_name": "codemucker/codemucker-jfind", "id": "81c13c7fc225db529df6b3db45fac163a05cec37", "size": "706", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/org/codemucker/jfind/e/TstAnnotationBean.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "159781" } ], "symlink_target": "" }
import cvxpy from .solver import Solver from sklearn.utils import check_array class NuclearNormMinimization(Solver): """ Simple implementation of "Exact Matrix Completion via Convex Optimization" by Emmanuel Candes and Benjamin Recht using cvxpy. """ def __init__( self, require_symmetric_solution=False, min_value=None, max_value=None, error_tolerance=0.0001, max_iters=50000, verbose=True): """ Parameters ---------- require_symmetric_solution : bool Add symmetry constraint to convex problem min_value : float Smallest possible imputed value max_value : float Largest possible imputed value error_tolerance : bool Degree of error allowed on reconstructed values. If omitted then defaults to 0.0001 max_iters : int Maximum number of iterations for the convex solver verbose : bool Print debug info """ Solver.__init__( self, min_value=min_value, max_value=max_value) self.require_symmetric_solution = require_symmetric_solution self.error_tolerance = error_tolerance self.max_iters = max_iters self.verbose = verbose def _constraints(self, X, missing_mask, S, error_tolerance): """ Parameters ---------- X : np.array Data matrix with missing values filled in missing_mask : np.array Boolean array indicating where missing values were S : cvxpy.Variable Representation of solution variable """ ok_mask = ~missing_mask masked_X = cvxpy.multiply(ok_mask, X) masked_S = cvxpy.multiply(ok_mask, S) abs_diff = cvxpy.abs(masked_S - masked_X) close_to_data = abs_diff <= error_tolerance constraints = [close_to_data] if self.require_symmetric_solution: constraints.append(S == S.T) if self.min_value is not None: constraints.append(S >= self.min_value) if self.max_value is not None: constraints.append(S <= self.max_value) return constraints def _create_objective(self, m, n): """ Parameters ---------- m, n : int Dimensions that of solution matrix Returns the objective function and a variable representing the solution to the convex optimization problem. """ # S is the completed matrix shape = (m, n) S = cvxpy.Variable(shape, name="S") norm = cvxpy.norm(S, "nuc") objective = cvxpy.Minimize(norm) return S, objective def solve(self, X, missing_mask): X = check_array(X, force_all_finite=False) m, n = X.shape S, objective = self._create_objective(m, n) constraints = self._constraints( X=X, missing_mask=missing_mask, S=S, error_tolerance=self.error_tolerance) problem = cvxpy.Problem(objective, constraints) problem.solve( verbose=self.verbose, solver=cvxpy.CVXOPT, max_iters=self.max_iters, # use_indirect, see: https://github.com/cvxgrp/cvxpy/issues/547 use_indirect=False) return S.value
{ "content_hash": "7bca3112742a1e07adc64de86269ab0c", "timestamp": "", "source": "github", "line_count": 116, "max_line_length": 78, "avg_line_length": 29.775862068965516, "alnum_prop": 0.569195136074117, "repo_name": "iskandr/fancyimpute", "id": "30c66b635561d3582cf392f27edad74131afb2b0", "size": "3999", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "fancyimpute/nuclear_norm_minimization.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "95506" } ], "symlink_target": "" }
module RT { var rayTracer = new RayTracer(); onmessage = (e: MessageEvent) => { var message = e.data; if (message.command == 'load scene') { RT.Scene.loadFromFile(message.data, (scene: Scene) => { rayTracer.scene = scene; (<any>postMessage)({ command: 'update scene data', data: { width: scene.renderSettings.camera.pixelWidth, height: scene.renderSettings.camera.pixelHeight, subpixelGridSize: scene.renderSettings.subpixelGridSize, recursionDepth: scene.renderSettings.recursionDepth } }); }); } else if (message.command == 'render') { rayTracer.scene.renderSettings.camera.pixelWidth = message.data.width; rayTracer.scene.renderSettings.camera.pixelHeight = message.data.height; rayTracer.scene.renderSettings.subpixelGridSize = message.data.subpixelGridSize; rayTracer.scene.renderSettings.recursionDepth = message.data.recursionDepth; rayTracer.render((rowColors: string[], row: number) => { (<any>postMessage)({ command: 'paint', data: { rowColors: rowColors, rowIndex: row } }); }); (<any>postMessage)({ command: 'render complete' }); } } }
{ "content_hash": "c3c0368904ba35c730842f6535af4f7f", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 92, "avg_line_length": 39.375, "alnum_prop": 0.5028571428571429, "repo_name": "sbnietert/TypeScript-Ray-Tracer", "id": "875db1782af20c5d446351ae93d143d9e7a050ec", "size": "1577", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "typescript/rayTracerWorker.ts", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "135" }, { "name": "CSS", "bytes": "2032" }, { "name": "HTML", "bytes": "384" }, { "name": "JavaScript", "bytes": "83248" }, { "name": "TypeScript", "bytes": "69571" } ], "symlink_target": "" }
namespace arc { class ArcBridgeService; // This class is responsible for forwarding incoming call to remote android // AccessibilityService process via mojo. class AccessibilityHelperInstanceRemoteProxy { public: explicit AccessibilityHelperInstanceRemoteProxy( ArcBridgeService* arc_bridge_service) : arc_bridge_service_(arc_bridge_service) {} ~AccessibilityHelperInstanceRemoteProxy() = default; AccessibilityHelperInstanceRemoteProxy( AccessibilityHelperInstanceRemoteProxy&&) = delete; AccessibilityHelperInstanceRemoteProxy& operator=( AccessibilityHelperInstanceRemoteProxy&&) = delete; bool SetFilter(mojom::AccessibilityFilterType filter_type) const; bool PerformAction( mojom::AccessibilityActionDataPtr action_data_ptr, mojom::AccessibilityHelperInstance::PerformActionCallback callback) const; bool SetNativeChromeVoxArcSupportForFocusedWindow( bool enabled, mojom::AccessibilityHelperInstance:: SetNativeChromeVoxArcSupportForFocusedWindowCallback callback) const; bool SetExploreByTouchEnabled(bool enabled) const; bool RefreshWithExtraData( mojom::AccessibilityActionDataPtr action_data_ptr, mojom::AccessibilityHelperInstance::RefreshWithExtraDataCallback callback) const; bool SetCaptionStyle(mojom::CaptionStylePtr style_ptr) const; bool RequestSendAccessibilityTree( mojom::AccessibilityWindowKeyPtr window_key_ptr) const; private: ArcBridgeService* const arc_bridge_service_; // Owned by ArcServiceManager. }; } // namespace arc #endif // CHROME_BROWSER_ASH_ARC_ACCESSIBILITY_ACCESSIBILITY_HELPER_INSTANCE_REMOTE_PROXY_H_
{ "content_hash": "6aab64a14fb1aca9dd250fac606408fe", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 93, "avg_line_length": 34.6875, "alnum_prop": 0.7903903903903904, "repo_name": "chromium/chromium", "id": "663dc77ea32db897d3d7997958661fb9f208e076", "size": "2058", "binary": false, "copies": "6", "ref": "refs/heads/main", "path": "chrome/browser/ash/arc/accessibility/accessibility_helper_instance_remote_proxy.h", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package com.farmerbb.taskbar.util; import android.content.Context; import org.json.JSONException; import org.json.JSONObject; import java.io.Serializable; public class DesktopIconInfo implements Serializable { public int column; public int row; public AppEntry entry; static final long serialVersionUID = 1L; public DesktopIconInfo(int column, int row, AppEntry entry) { this.column = column; this.row = row; this.entry = entry; } public JSONObject toJson(Context context) { JSONObject json = new JSONObject(); try { json.put("column", column); json.put("row", row); json.put("package_name", entry.getPackageName()); json.put("app_name", entry.getLabel()); json.put("component_name", entry.getComponentName()); json.put("user_id", entry.getUserId(context)); } catch (JSONException ignored) {} return json; } public static DesktopIconInfo fromJson(JSONObject json) { try { int column = json.getInt("column"); int row = json.getInt("row"); String packageName = json.getString("package_name"); String label = json.getString("app_name"); String componentName = json.getString("component_name"); long userId = json.getLong("user_id"); AppEntry entry = new AppEntry(packageName, componentName, label, null, false); entry.setUserId(userId); return new DesktopIconInfo(column, row, entry); } catch (JSONException e) { return null; } } }
{ "content_hash": "07517627783ecd38ed99bd4cb6262400", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 90, "avg_line_length": 29.035087719298247, "alnum_prop": 0.6078549848942598, "repo_name": "farmerbb/Taskbar", "id": "f18c5397c0fa9fc0e65f8dc31075b2dd1a24b5bb", "size": "2248", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/farmerbb/taskbar/util/DesktopIconInfo.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "810361" }, { "name": "Kotlin", "bytes": "206738" }, { "name": "Makefile", "bytes": "1440" } ], "symlink_target": "" }
import os import sys import time import getpass sys.path.append("./library") import argparse import ConfigParser from utils import * from na_funcs import * from cisco_funcs import * def check_on_switch(mds, zoneset, pwwns, zones, vsan, fabric, switch): non_existent_zones = [] alias_exists = {} zoneset_existent = False # http://www.cisco.com/c/en/us/td/docs/switches/datacenter/mds9000/sw/6_2/configuration/guides/config_limits/b_mds_9000_configuration_limits_6_2.html # Table 2 Fabric-level Fibre Channel Configuration Limits # Note: The preferred number of members per zone is 2, and the maximum recommended limit is 50. smartzone_members_limit = 50 print bcolors.OKGREEN + "Initiate validations ...\n" + bcolors.ENDC print bcolors.BOLD + "Validating ZoneSet %s and VSAN ID %s on MDS..." % (zoneset, vsan) + bcolors.ENDC if zoneset_exists(mds, zoneset, vsan) is not False: zoneset_existent = True for pwwn in pwwns: print bcolors.BOLD + "Validating if device-alias exists with pwwn %s on MDS..." % pwwn + bcolors.ENDC alias = device_alias_exists(mds, pwwn) if alias: alias_exists[pwwn] = alias for zone_name in zones.keys(): if len(zone_name) > 1: print bcolors.BOLD + "Validating %s on MDS..." % zone_name.strip() + bcolors.ENDC if zone_exists(mds, zone_name, vsan) is False: non_existent_zones.append(zone_name) print bcolors.BOLD + "Validating number of members of %s on MDS..." % zone_name.strip() + bcolors.ENDC members = count_smartzone_members(mds, zone_name) if alias_exists: print bcolors.OKBLUE + "\n### INFO! Some device-alias already exists ... ###\n" + bcolors.ENDC for pwwn, alias in alias_exists.iteritems(): print bcolors.BOLD + "device-alias %s already exists for %s" % (alias, pwwn) + bcolors.ENDC raw_input('\nPress ' + bcolors.BOLD + '[enter]' + bcolors.ENDC + ' to continue ...') if zoneset_existent is False or len(non_existent_zones) > 0 or members >= smartzone_members_limit: print bcolors.WARNING + "\n### ATENTION! Validation found some errors ... ###\n" + bcolors.ENDC if zoneset_existent is False: print bcolors.FAIL + "ZoneSet \"%s\" and/or VSAN ID %s doesn't exists!\n" % (zoneset, vsan) + bcolors.ENDC if len(non_existent_zones) > 0: for zone in non_existent_zones: print bcolors.FAIL + "Zone \"%s\" doesn't exists!" % zone.strip() + bcolors.ENDC if members >= smartzone_members_limit: print bcolors.FAIL + "Zone \"%s\" has more then 50 members\n" % zone_name.strip() + bcolors.ENDC if confirm("Are you sure you want to continue?"): generate_smartzones(config_file, zoneset, vsan, fabric, switch) else: print bcolors.OKGREEN + "\nValidation successfully!" + bcolors.ENDC generate_smartzones(config_file, zoneset, vsan, fabric, switch) def generate_smartzones(config_file, zoneset, vsan, fabric, switch=None, check=False, mds=None): try: config = ConfigParser.ConfigParser() config.read(config_file) except Exception, e: print bcolors.FAIL + "Error reading config file!" + bcolors.ENDC print bcolors.BOLD + "Exception:" + bcolors.ENDC + "\n%s" % e exit(1) hosts_per_zone = {} pwwns = [] for host in config.sections(): pwwns.append(config.get(host, fabric)) for host in config.sections(): for zone in config.get(host, 'zones').split(','): hosts_per_zone[zone] = [] for host in config.sections(): for zone in config.get(host, 'zones').split(','): hosts_per_zone[zone].append(host) if check: check_on_switch(mds, zoneset, pwwns, hosts_per_zone, vsan, fabric, switch) else: if switch: print bcolors.OKGREEN + "\nGenerating commands to switch %s ... \n" % switch + bcolors.ENDC else: print bcolors.OKGREEN + "\nGenerating commands to FABRIC %s ... \n" % fabric + bcolors.ENDC time.sleep(3) print "config t" print "device-alias database" for host in config.sections(): print " device-alias name %s pwwn %s" % (host.strip(), config.get(host, fabric)) print "device-alias commit\n" for zone, hosts in hosts_per_zone.iteritems(): if len(zone) > 1: print "zone name %s vsan %s" % (zone.strip(), vsan) for host in hosts: print " member device-alias %s initiator" % host.strip() print "exit\n" print "zoneset activate name %s vsan %s\n" % (zoneset, vsan) print "copy running-config startup-config\n" if __name__ == "__main__": arguments = argparse.ArgumentParser( description='Generate SmartZone commands from input config file listing of short hostnames, pwwns and zones which each host will belongs.') arguments.add_argument( '-c','--config_hosts', required=True, type=str, help='Configuration file with hosts, pwwns and zones') arguments.add_argument( '--vsan', required=True, type=str, help='VSAN ID') arguments.add_argument( '--zoneset', required=True, type=str, help='ZoneSet name') arguments.add_argument( '-f','--fabric', required=True, type=str, choices=['impar', 'par'], help='Fabric side') arguments.add_argument( '--check',default=False, action='store_true', help='[optional] Start a validation process by connection on MDS switch of all params') arguments.add_argument( '-s','--switch', required=False, type=str, help='MDS switch fqdn or IP') arguments.add_argument( '-u','--username', required=False, type=str, help='[optional] Username to ssh into mds switch. Alternate: set environment variable MDS_USERNAME. If neither exists, defaults to current OS username') arguments.add_argument( '-p','--password', required=False, type=str, help='[optional] Password to ssh into mds switch. Alternate: set environment variable MDS_PASSWORD. If unset use_keys defaults to True.') arguments.add_argument( '--use_keys', required=False, action='store_true', help='[optional] Use ssh keys to log into switch. If set key file will need be pass as param') arguments.add_argument( '--key_file', required=False, type=str, help='[optional] filename for ssh key file') args = arguments.parse_args() config_file = args.config_hosts if not os.path.exists(config_file): print bcolors.FAIL + "%s: No such file or directory!" % config_file + bcolors.ENDC exit(1) vsan = args.vsan zoneset = args.zoneset fabric = args.fabric switch = None if args.check: if args.password : use_keys = False password = args.password elif os.getenv('MDS_PASSWORD') : use_keys = False password = os.getenv('MDS_PASSWORD') else : use_keys = True password = '' if args.username : username = args.username elif os.getenv('MDS_USERNAME') : username = os.getenv('MDS_USERNAME') else: username = getpass.getuser() switch = args.switch # Params to connect on MDS mds = { 'device_type': 'cisco_nxos', 'ip': switch, 'verbose': False, 'username': username, 'password': password, 'use_keys': use_keys } generate_smartzones(config_file, zoneset, vsan, fabric, switch=switch, check=True, mds=mds) else: generate_smartzones(config_file, zoneset, vsan, fabric)
{ "content_hash": "007e1ea35eadd31e26506978eb73d0c1", "timestamp": "", "source": "github", "line_count": 198, "max_line_length": 161, "avg_line_length": 39.7979797979798, "alnum_prop": 0.6138324873096447, "repo_name": "scottharney/python-mdszoning", "id": "21495b33ee4516f2639ddb1bcaec64f13b7da72d", "size": "7960", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "smartzone/gen_smartzones.py", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "36475" } ], "symlink_target": "" }
<?php defined('C5_EXECUTE') or die("Access Denied."); Loader::model('attribute/categories/user'); Loader::model('user_list'); class DashboardUsersSearchController extends Controller { public function view() { $html = Loader::helper('html'); $form = Loader::helper('form'); $this->set('form', $form); $this->addHeaderItem('<script type="text/javascript">$(function() { ccm_setupAdvancedSearch(\'user\'); });</script>'); $userList = $this->getRequestedSearchResults(); $users = $userList->getPage(); $this->set('userList', $userList); $this->set('users', $users); $this->set('pagination', $userList->getPagination()); } public function getRequestedSearchResults() { $userList = new UserList(); $userList->sortBy('uDateAdded', 'desc'); $userList->showInactiveUsers = true; $userList->showInvalidatedUsers = true; if ($_GET['keywords'] != '') { $userList->filterByKeywords($_GET['keywords']); } if ($_REQUEST['numResults']) { $userList->setItemsPerPage($_REQUEST['numResults']); } if (isset($_REQUEST['gID']) && is_array($_REQUEST['gID'])) { foreach($_REQUEST['gID'] as $gID) { $userList->filterByGroupID($gID); } } if (is_array($_REQUEST['selectedSearchField'])) { foreach($_REQUEST['selectedSearchField'] as $i => $item) { // due to the way the form is setup, index will always be one more than the arrays if ($item != '') { switch($item) { case 'is_active': if ($_GET['active'] === '0') { $userList->filterByIsActive(0); } else if ($_GET['active'] === '1') { $userList->filterByIsActive(1); } break; case "date_added": $dateFrom = $_REQUEST['date_from']; $dateTo = $_REQUEST['date_to']; if ($dateFrom != '') { $dateFrom = date('Y-m-d', strtotime($dateFrom)); $userList->filterByDateAdded($dateFrom, '>='); $dateFrom .= ' 00:00:00'; } if ($dateTo != '') { $dateTo = date('Y-m-d', strtotime($dateTo)); $dateTo .= ' 23:59:59'; $userList->filterByDateAdded($dateTo, '<='); } break; default: $akID = $item; $fak = UserAttributeKey::get($akID); $type = $fak->getAttributeType(); $cnt = $type->getController(); $cnt->setAttributeKey($fak); $cnt->searchForm($userList); break; } } } } return $userList; } public function sign_in_as_user($uID, $token = null) { try { $u = new User(); $tp = new TaskPermission(); if (!$tp->canSudo()) { throw new Exception(t('You do not have permission to perform this action.')); } $ui = UserInfo::getByID($uID); if(!($ui instanceof UserInfo)) { throw new Exception(t('Invalid user ID.')); } $valt = Loader::helper('validation/token'); if (!$valt->validate('sudo', $token)) { throw new Exception($valt->getErrorMessage()); } User::loginByUserID($uID); $this->redirect('/'); } catch(Exception $e) { $this->set('error', $e); $this->view(); } } public function edit_attribute() { $uo = UserInfo::getByID($_POST['uID']); $u = new User(); if ($uo->getUserID() == USER_SUPER_ID && (!$u->isSuperUser())) { throw new Exception(t('Only the super user may edit this account.')); } $akID = $_REQUEST['uakID']; $ak = UserAttributeKey::get($akID); if ($_POST['task'] == 'update_extended_attribute') { $ak->saveAttributeForm($uo); $val = $uo->getAttributeValueObject($ak); print $val->getValue('displaySanitized','display'); exit; } if ($_POST['task'] == 'clear_extended_attribute') { $uo->clearAttribute($ak); $val = $uo->getAttributeValueObject($ak); print '<div class="ccm-attribute-field-none">' . t('None') . '</div>'; exit; } } public function delete($delUserId, $token = null){ $u=new User(); try { if(!$u->isSuperUser()) { throw new Exception(t('You do not have permission to perform this action.')); } if ($delUserId == USER_SUPER_ID) { throw new Exception(t('You may not remove the super user account.')); } if($delUserId==$u->getUserID()) { throw new Exception(t('You cannot delete your own user account.')); } $delUI=UserInfo::getByID($delUserId); if(!($delUI instanceof UserInfo)) { throw new Exception(t('Invalid user ID.')); } $valt = Loader::helper('validation/token'); if (!$valt->validate('delete_account', $token)) { throw new Exception($valt->getErrorMessage()); } $delUI->delete(); $resultMsg=t('User deleted successfully.'); $_REQUEST=array(); $_GET=array(); $_POST=array(); $this->set('message', $resultMsg); } catch (Exception $e) { $this->set('error', $e); } $this->view(); } } ?>
{ "content_hash": "d88d6384497ba91d6deb029785bd7815", "timestamp": "", "source": "github", "line_count": 181, "max_line_length": 120, "avg_line_length": 26.61878453038674, "alnum_prop": 0.5772104607721046, "repo_name": "homer6/concrete5", "id": "77acd4c03d56b94d4baf94dc7cda896d7562bbd0", "size": "4818", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "concrete/controllers/dashboard/users/search.php", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "172889" }, { "name": "JavaScript", "bytes": "761341" }, { "name": "PHP", "bytes": "6679489" }, { "name": "Python", "bytes": "2003" } ], "symlink_target": "" }
package eca.exercises.PROD.answers; import java.util.List; public class InvoicePrinter { public static void printInvoice(List<Product> products) { // Create 2 variables to accumulate the total price while looping through all the products var totalWithoutTax = 0.0; // The tax-exclusive total var totalTax = 0.0; // The total tax from all products /* For each product in products, tell the user: - The name - The quantity - The price, with and without tax, based on the quantity of the product */ for (var product : products) { // Calculate the tax amount from the price and tax percentage var taxAmount = product.getPrice() * (product.getTax() / 100); // Calculate the tax-inclusive price var itemWithTax = product.getPrice() + taxAmount; // Multiply the tax inclusive price by the quantity, which is the total price for this product var priceForQuantity = itemWithTax * product.getQuantity(); // Add to the totals totalWithoutTax = totalWithoutTax + (product.getPrice() * product.getQuantity()); totalTax = totalTax + (taxAmount * product.getQuantity()); // Print the total of the products with and without tax System.out.println(product.getName() + " | price: " + product.getPrice() + " | with tax: " + itemWithTax + " | for " + product.getQuantity() + ": " + priceForQuantity); } // Print the total of the products with and without tax System.out.println("Total: " + totalWithoutTax); System.out.println("Total with tax: " + (totalWithoutTax + totalTax)); } public static void main(String[] args) { var myBasket = List.of( new Product("Hotel Breakfast", 15.0, 1, 15.0), new Product("Wine", 8.0, 2, 25.0), new Product("Room Service", 10.0, 1, 10.0), new Product("Coffee", 4.0, 2, 15.0), new Product("Pastries", 2.50, 5, 15.0) ); printInvoice(myBasket); } }
{ "content_hash": "e6b50fdc9e8e921be7b239d60e5f2f1c", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 180, "avg_line_length": 40.37735849056604, "alnum_prop": 0.5957943925233645, "repo_name": "Ben-Woolley/java-for-beginners", "id": "9d3e2e5e60d70f984ed3277ee1ee7266555a7cf9", "size": "2140", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "intro-to-java/src/main/java/eca/exercises/PROD/answers/InvoicePrinter.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "32106" } ], "symlink_target": "" }
package janala.logger.inst; public class GETSTATIC extends Instruction { public int cIdx; public int fIdx; public String desc; public GETSTATIC(int iid, int mid, int cIdx, int fIdx, String desc) { super(iid, mid); this.cIdx = cIdx; this.fIdx = fIdx; this.desc = desc; } public void visit(IVisitor visitor) { visitor.visitGETSTATIC(this); } @Override public String toString() { return "GETSTATIC iid=" + iid + " mid=" + mid + " cIdx=" + cIdx + " fIdx=" + fIdx + " desc=" + desc; } }
{ "content_hash": "69dcf5c6aae4edc1c63ebc1b5ca6dc67", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 71, "avg_line_length": 18.8125, "alnum_prop": 0.5564784053156147, "repo_name": "ksen007/janala2", "id": "fee615b529c1c9984b6e29c974bc0f94086f6871", "size": "602", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "src/main/java/janala/logger/inst/GETSTATIC.java", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Groovy", "bytes": "246644" }, { "name": "HTML", "bytes": "2163" }, { "name": "Java", "bytes": "2578822" }, { "name": "Python", "bytes": "9967" }, { "name": "Roff", "bytes": "10556" }, { "name": "Shell", "bytes": "6919" } ], "symlink_target": "" }
<?php /** * Stores the Twig configuration. * * @author Fabien Potencier <[email protected]> */ class Twig_Environment { const VERSION = '1.33.2'; const VERSION_ID = 13302; const MAJOR_VERSION = 1; const MINOR_VERSION = 33; const RELEASE_VERSION = 1; const EXTRA_VERSION = 'DEV'; protected $charset; protected $loader; protected $debug; protected $autoReload; protected $cache; protected $lexer; protected $parser; protected $compiler; protected $baseTemplateClass; protected $extensions; protected $parsers; protected $visitors; protected $filters; protected $tests; protected $functions; protected $globals; protected $runtimeInitialized = false; protected $extensionInitialized = false; protected $loadedTemplates; protected $strictVariables; protected $unaryOperators; protected $binaryOperators; protected $templateClassPrefix = '__TwigTemplate_'; protected $functionCallbacks = array(); protected $filterCallbacks = array(); protected $staging; private $originalCache; private $bcWriteCacheFile = false; private $bcGetCacheFilename = false; private $lastModifiedExtension = 0; private $extensionsByClass = array(); private $runtimeLoaders = array(); private $runtimes = array(); private $optionsHash; /** * Constructor. * * Available options: * * * debug: When set to true, it automatically set "auto_reload" to true as * well (default to false). * * * charset: The charset used by the templates (default to UTF-8). * * * base_template_class: The base template class to use for generated * templates (default to Twig_Template). * * * cache: An absolute path where to store the compiled templates, * a Twig_Cache_Interface implementation, * or false to disable compilation cache (default). * * * auto_reload: Whether to reload the template if the original source changed. * If you don't provide the auto_reload option, it will be * determined automatically based on the debug value. * * * strict_variables: Whether to ignore invalid variables in templates * (default to false). * * * autoescape: Whether to enable auto-escaping (default to html): * * false: disable auto-escaping * * true: equivalent to html * * html, js: set the autoescaping to one of the supported strategies * * name: set the autoescaping strategy based on the template name extension * * PHP callback: a PHP callback that returns an escaping strategy based on the template "name" * * * optimizations: A flag that indicates which optimizations to apply * (default to -1 which means that all optimizations are enabled; * set it to 0 to disable). * * @param Twig_LoaderInterface $loader * @param array $options An array of options */ public function __construct(Twig_LoaderInterface $loader = null, $options = array()) { if (null !== $loader) { $this->setLoader($loader); } else { @trigger_error('Not passing a Twig_LoaderInterface as the first constructor argument of Twig_Environment is deprecated since version 1.21.', E_USER_DEPRECATED); } $options = array_merge(array( 'debug' => false, 'charset' => 'UTF-8', 'base_template_class' => 'Twig_Template', 'strict_variables' => false, 'autoescape' => 'html', 'cache' => false, 'auto_reload' => null, 'optimizations' => -1, ), $options); $this->debug = (bool) $options['debug']; $this->charset = strtoupper($options['charset']); $this->baseTemplateClass = $options['base_template_class']; $this->autoReload = null === $options['auto_reload'] ? $this->debug : (bool) $options['auto_reload']; $this->strictVariables = (bool) $options['strict_variables']; $this->setCache($options['cache']); $this->addExtension(new Twig_Extension_Core()); $this->addExtension(new Twig_Extension_Escaper($options['autoescape'])); $this->addExtension(new Twig_Extension_Optimizer($options['optimizations'])); $this->staging = new Twig_Extension_Staging(); // For BC if (is_string($this->originalCache)) { $r = new ReflectionMethod($this, 'writeCacheFile'); if ($r->getDeclaringClass()->getName() !== __CLASS__) { @trigger_error('The Twig_Environment::writeCacheFile method is deprecated since version 1.22 and will be removed in Twig 2.0.', E_USER_DEPRECATED); $this->bcWriteCacheFile = true; } $r = new ReflectionMethod($this, 'getCacheFilename'); if ($r->getDeclaringClass()->getName() !== __CLASS__) { @trigger_error('The Twig_Environment::getCacheFilename method is deprecated since version 1.22 and will be removed in Twig 2.0.', E_USER_DEPRECATED); $this->bcGetCacheFilename = true; } } } /** * Gets the base template class for compiled templates. * * @return string The base template class name */ public function getBaseTemplateClass() { return $this->baseTemplateClass; } /** * Sets the base template class for compiled templates. * * @param string $class The base template class name */ public function setBaseTemplateClass($class) { $this->baseTemplateClass = $class; $this->updateOptionsHash(); } /** * Enables debugging mode. */ public function enableDebug() { $this->debug = true; $this->updateOptionsHash(); } /** * Disables debugging mode. */ public function disableDebug() { $this->debug = false; $this->updateOptionsHash(); } /** * Checks if debug mode is enabled. * * @return bool true if debug mode is enabled, false otherwise */ public function isDebug() { return $this->debug; } /** * Enables the auto_reload option. */ public function enableAutoReload() { $this->autoReload = true; } /** * Disables the auto_reload option. */ public function disableAutoReload() { $this->autoReload = false; } /** * Checks if the auto_reload option is enabled. * * @return bool true if auto_reload is enabled, false otherwise */ public function isAutoReload() { return $this->autoReload; } /** * Enables the strict_variables option. */ public function enableStrictVariables() { $this->strictVariables = true; $this->updateOptionsHash(); } /** * Disables the strict_variables option. */ public function disableStrictVariables() { $this->strictVariables = false; $this->updateOptionsHash(); } /** * Checks if the strict_variables option is enabled. * * @return bool true if strict_variables is enabled, false otherwise */ public function isStrictVariables() { return $this->strictVariables; } /** * Gets the current cache implementation. * * @param bool $original Whether to return the original cache option or the real cache instance * * @return Twig_CacheInterface|string|false A Twig_CacheInterface implementation, * an absolute path to the compiled templates, * or false to disable cache */ public function getCache($original = true) { return $original ? $this->originalCache : $this->cache; } /** * Sets the current cache implementation. * * @param Twig_CacheInterface|string|false $cache A Twig_CacheInterface implementation, * an absolute path to the compiled templates, * or false to disable cache */ public function setCache($cache) { if (is_string($cache)) { $this->originalCache = $cache; $this->cache = new Twig_Cache_Filesystem($cache); } elseif (false === $cache) { $this->originalCache = $cache; $this->cache = new Twig_Cache_Null(); } elseif (null === $cache) { @trigger_error('Using "null" as the cache strategy is deprecated since version 1.23 and will be removed in Twig 2.0.', E_USER_DEPRECATED); $this->originalCache = false; $this->cache = new Twig_Cache_Null(); } elseif ($cache instanceof Twig_CacheInterface) { $this->originalCache = $this->cache = $cache; } else { throw new LogicException(sprintf('Cache can only be a string, false, or a Twig_CacheInterface implementation.')); } } /** * Gets the cache filename for a given template. * * @param string $name The template name * * @return string|false The cache file name or false when caching is disabled * * @deprecated since 1.22 (to be removed in 2.0) */ public function getCacheFilename($name) { @trigger_error(sprintf('The %s method is deprecated since version 1.22 and will be removed in Twig 2.0.', __METHOD__), E_USER_DEPRECATED); $key = $this->cache->generateKey($name, $this->getTemplateClass($name)); return !$key ? false : $key; } /** * Gets the template class associated with the given string. * * The generated template class is based on the following parameters: * * * The cache key for the given template; * * The currently enabled extensions; * * Whether the Twig C extension is available or not; * * PHP version; * * Twig version; * * Options with what environment was created. * * @param string $name The name for which to calculate the template class name * @param int|null $index The index if it is an embedded template * * @return string The template class name */ public function getTemplateClass($name, $index = null) { $key = $this->getLoader()->getCacheKey($name).$this->optionsHash; return $this->templateClassPrefix.hash('sha256', $key).(null === $index ? '' : '_'.$index); } /** * Gets the template class prefix. * * @return string The template class prefix * * @deprecated since 1.22 (to be removed in 2.0) */ public function getTemplateClassPrefix() { @trigger_error(sprintf('The %s method is deprecated since version 1.22 and will be removed in Twig 2.0.', __METHOD__), E_USER_DEPRECATED); return $this->templateClassPrefix; } /** * Renders a template. * * @param string $name The template name * @param array $context An array of parameters to pass to the template * * @return string The rendered template * * @throws Twig_Error_Loader When the template cannot be found * @throws Twig_Error_Syntax When an error occurred during compilation * @throws Twig_Error_Runtime When an error occurred during rendering */ public function render($name, array $context = array()) { return $this->loadTemplate($name)->render($context); } /** * Displays a template. * * @param string $name The template name * @param array $context An array of parameters to pass to the template * * @throws Twig_Error_Loader When the template cannot be found * @throws Twig_Error_Syntax When an error occurred during compilation * @throws Twig_Error_Runtime When an error occurred during rendering */ public function display($name, array $context = array()) { $this->loadTemplate($name)->display($context); } /** * Loads a template. * * @param string|Twig_TemplateWrapper|Twig_Template $name The template name * * @return Twig_TemplateWrapper */ public function load($name) { if ($name instanceof Twig_TemplateWrapper) { return $name; } if ($name instanceof Twig_Template) { return new Twig_TemplateWrapper($this, $name); } return new Twig_TemplateWrapper($this, $this->loadTemplate($name)); } /** * Loads a template internal representation. * * This method is for internal use only and should never be called * directly. * * @param string $name The template name * @param int $index The index if it is an embedded template * * @return Twig_TemplateInterface A template instance representing the given template name * * @throws Twig_Error_Loader When the template cannot be found * @throws Twig_Error_Runtime When a previously generated cache is corrupted * @throws Twig_Error_Syntax When an error occurred during compilation * * @internal */ public function loadTemplate($name, $index = null) { $cls = $mainCls = $this->getTemplateClass($name); if (null !== $index) { $cls .= '_'.$index; } if (isset($this->loadedTemplates[$cls])) { return $this->loadedTemplates[$cls]; } if (!class_exists($cls, false)) { if ($this->bcGetCacheFilename) { $key = $this->getCacheFilename($name); } else { $key = $this->cache->generateKey($name, $mainCls); } if (!$this->isAutoReload() || $this->isTemplateFresh($name, $this->cache->getTimestamp($key))) { $this->cache->load($key); } if (!class_exists($cls, false)) { $loader = $this->getLoader(); if (!$loader instanceof Twig_SourceContextLoaderInterface) { $source = new Twig_Source($loader->getSource($name), $name); } else { $source = $loader->getSourceContext($name); } $content = $this->compileSource($source); if ($this->bcWriteCacheFile) { $this->writeCacheFile($key, $content); } else { $this->cache->write($key, $content); $this->cache->load($key); } if (!class_exists($mainCls, false)) { /* Last line of defense if either $this->bcWriteCacheFile was used, * $this->cache is implemented as a no-op or we have a race condition * where the cache was cleared between the above calls to write to and load from * the cache. */ eval('?>'.$content); } } if (!class_exists($cls, false)) { throw new Twig_Error_Runtime(sprintf('Failed to load Twig template "%s", index "%s": cache is corrupted.', $name, $index), -1, $source); } } if (!$this->runtimeInitialized) { $this->initRuntime(); } return $this->loadedTemplates[$cls] = new $cls($this); } /** * Creates a template from source. * * This method should not be used as a generic way to load templates. * * @param string $template The template name * * @return Twig_Template A template instance representing the given template name * * @throws Twig_Error_Loader When the template cannot be found * @throws Twig_Error_Syntax When an error occurred during compilation */ public function createTemplate($template) { $name = sprintf('__string_template__%s', hash('sha256', uniqid(mt_rand(), true), false)); $loader = new Twig_Loader_Chain(array( new Twig_Loader_Array(array($name => $template)), $current = $this->getLoader(), )); $this->setLoader($loader); try { $template = $this->loadTemplate($name); } catch (Exception $e) { $this->setLoader($current); throw $e; } catch (Throwable $e) { $this->setLoader($current); throw $e; } $this->setLoader($current); return $template; } /** * Returns true if the template is still fresh. * * Besides checking the loader for freshness information, * this method also checks if the enabled extensions have * not changed. * * @param string $name The template name * @param int $time The last modification time of the cached template * * @return bool true if the template is fresh, false otherwise */ public function isTemplateFresh($name, $time) { if (0 === $this->lastModifiedExtension) { foreach ($this->extensions as $extension) { $r = new ReflectionObject($extension); if (file_exists($r->getFileName()) && ($extensionTime = filemtime($r->getFileName())) > $this->lastModifiedExtension) { $this->lastModifiedExtension = $extensionTime; } } } return $this->lastModifiedExtension <= $time && $this->getLoader()->isFresh($name, $time); } /** * Tries to load a template consecutively from an array. * * Similar to loadTemplate() but it also accepts Twig_TemplateInterface instances and an array * of templates where each is tried to be loaded. * * @param string|Twig_Template|array $names A template or an array of templates to try consecutively * * @return Twig_Template * * @throws Twig_Error_Loader When none of the templates can be found * @throws Twig_Error_Syntax When an error occurred during compilation */ public function resolveTemplate($names) { if (!is_array($names)) { $names = array($names); } foreach ($names as $name) { if ($name instanceof Twig_Template) { return $name; } try { return $this->loadTemplate($name); } catch (Twig_Error_Loader $e) { } } if (1 === count($names)) { throw $e; } throw new Twig_Error_Loader(sprintf('Unable to find one of the following templates: "%s".', implode('", "', $names))); } /** * Clears the internal template cache. * * @deprecated since 1.18.3 (to be removed in 2.0) */ public function clearTemplateCache() { @trigger_error(sprintf('The %s method is deprecated since version 1.18.3 and will be removed in Twig 2.0.', __METHOD__), E_USER_DEPRECATED); $this->loadedTemplates = array(); } /** * Clears the template cache files on the filesystem. * * @deprecated since 1.22 (to be removed in 2.0) */ public function clearCacheFiles() { @trigger_error(sprintf('The %s method is deprecated since version 1.22 and will be removed in Twig 2.0.', __METHOD__), E_USER_DEPRECATED); if (is_string($this->originalCache)) { foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->originalCache), RecursiveIteratorIterator::LEAVES_ONLY) as $file) { if ($file->isFile()) { @unlink($file->getPathname()); } } } } /** * Gets the Lexer instance. * * @return Twig_LexerInterface * * @deprecated since 1.25 (to be removed in 2.0) */ public function getLexer() { @trigger_error(sprintf('The %s() method is deprecated since version 1.25 and will be removed in 2.0.', __FUNCTION__), E_USER_DEPRECATED); if (null === $this->lexer) { $this->lexer = new Twig_Lexer($this); } return $this->lexer; } public function setLexer(Twig_LexerInterface $lexer) { $this->lexer = $lexer; } /** * Tokenizes a source code. * * @param string|Twig_Source $source The template source code * @param string $name The template name (deprecated) * * @return Twig_TokenStream * * @throws Twig_Error_Syntax When the code is syntactically wrong */ public function tokenize($source, $name = null) { if (!$source instanceof Twig_Source) { @trigger_error(sprintf('Passing a string as the $source argument of %s() is deprecated since version 1.27. Pass a Twig_Source instance instead.', __METHOD__), E_USER_DEPRECATED); $source = new Twig_Source($source, $name); } if (null === $this->lexer) { $this->lexer = new Twig_Lexer($this); } return $this->lexer->tokenize($source); } /** * Gets the Parser instance. * * @return Twig_ParserInterface * * @deprecated since 1.25 (to be removed in 2.0) */ public function getParser() { @trigger_error(sprintf('The %s() method is deprecated since version 1.25 and will be removed in 2.0.', __FUNCTION__), E_USER_DEPRECATED); if (null === $this->parser) { $this->parser = new Twig_Parser($this); } return $this->parser; } public function setParser(Twig_ParserInterface $parser) { $this->parser = $parser; } /** * Converts a token stream to a node tree. * * @return Twig_Node_Module * * @throws Twig_Error_Syntax When the token stream is syntactically or semantically wrong */ public function parse(Twig_TokenStream $stream) { if (null === $this->parser) { $this->parser = new Twig_Parser($this); } return $this->parser->parse($stream); } /** * Gets the Compiler instance. * * @return Twig_CompilerInterface * * @deprecated since 1.25 (to be removed in 2.0) */ public function getCompiler() { @trigger_error(sprintf('The %s() method is deprecated since version 1.25 and will be removed in 2.0.', __FUNCTION__), E_USER_DEPRECATED); if (null === $this->compiler) { $this->compiler = new Twig_Compiler($this); } return $this->compiler; } public function setCompiler(Twig_CompilerInterface $compiler) { $this->compiler = $compiler; } /** * Compiles a node and returns the PHP code. * * @return string The compiled PHP source code */ public function compile(Twig_NodeInterface $node) { if (null === $this->compiler) { $this->compiler = new Twig_Compiler($this); } return $this->compiler->compile($node)->getSource(); } /** * Compiles a template source code. * * @param string|Twig_Source $source The template source code * @param string $name The template name (deprecated) * * @return string The compiled PHP source code * * @throws Twig_Error_Syntax When there was an error during tokenizing, parsing or compiling */ public function compileSource($source, $name = null) { if (!$source instanceof Twig_Source) { @trigger_error(sprintf('Passing a string as the $source argument of %s() is deprecated since version 1.27. Pass a Twig_Source instance instead.', __METHOD__), E_USER_DEPRECATED); $source = new Twig_Source($source, $name); } try { return $this->compile($this->parse($this->tokenize($source))); } catch (Twig_Error $e) { $e->setSourceContext($source); throw $e; } catch (Exception $e) { throw new Twig_Error_Syntax(sprintf('An exception has been thrown during the compilation of a template ("%s").', $e->getMessage()), -1, $source, $e); } } public function setLoader(Twig_LoaderInterface $loader) { if (!$loader instanceof Twig_SourceContextLoaderInterface && 0 !== strpos(get_class($loader), 'Mock_Twig_LoaderInterface')) { @trigger_error(sprintf('Twig loader "%s" should implement Twig_SourceContextLoaderInterface since version 1.27.', get_class($loader)), E_USER_DEPRECATED); } $this->loader = $loader; } /** * Gets the Loader instance. * * @return Twig_LoaderInterface */ public function getLoader() { if (null === $this->loader) { throw new LogicException('You must set a loader first.'); } return $this->loader; } /** * Sets the default template charset. * * @param string $charset The default charset */ public function setCharset($charset) { $this->charset = strtoupper($charset); } /** * Gets the default template charset. * * @return string The default charset */ public function getCharset() { return $this->charset; } /** * Initializes the runtime environment. * * @deprecated since 1.23 (to be removed in 2.0) */ public function initRuntime() { $this->runtimeInitialized = true; foreach ($this->getExtensions() as $name => $extension) { if (!$extension instanceof Twig_Extension_InitRuntimeInterface) { $m = new ReflectionMethod($extension, 'initRuntime'); if ('Twig_Extension' !== $m->getDeclaringClass()->getName()) { @trigger_error(sprintf('Defining the initRuntime() method in the "%s" extension is deprecated since version 1.23. Use the `needs_environment` option to get the Twig_Environment instance in filters, functions, or tests; or explicitly implement Twig_Extension_InitRuntimeInterface if needed (not recommended).', $name), E_USER_DEPRECATED); } } $extension->initRuntime($this); } } /** * Returns true if the given extension is registered. * * @param string $class The extension class name * * @return bool Whether the extension is registered or not */ public function hasExtension($class) { $class = ltrim($class, '\\'); if (isset($this->extensions[$class])) { if ($class !== get_class($this->extensions[$class])) { @trigger_error(sprintf('Referencing the "%s" extension by its name (defined by getName()) is deprecated since 1.26 and will be removed in Twig 2.0. Use the Fully Qualified Extension Class Name instead.', $class), E_USER_DEPRECATED); } return true; } return isset($this->extensionsByClass[$class]); } /** * Adds a runtime loader. */ public function addRuntimeLoader(Twig_RuntimeLoaderInterface $loader) { $this->runtimeLoaders[] = $loader; } /** * Gets an extension by class name. * * @param string $class The extension class name * * @return Twig_ExtensionInterface */ public function getExtension($class) { $class = ltrim($class, '\\'); if (isset($this->extensions[$class])) { if ($class !== get_class($this->extensions[$class])) { @trigger_error(sprintf('Referencing the "%s" extension by its name (defined by getName()) is deprecated since 1.26 and will be removed in Twig 2.0. Use the Fully Qualified Extension Class Name instead.', $class), E_USER_DEPRECATED); } return $this->extensions[$class]; } if (!isset($this->extensionsByClass[$class])) { throw new Twig_Error_Runtime(sprintf('The "%s" extension is not enabled.', $class)); } return $this->extensionsByClass[$class]; } /** * Returns the runtime implementation of a Twig element (filter/function/test). * * @param string $class A runtime class name * * @return object The runtime implementation * * @throws Twig_Error_Runtime When the template cannot be found */ public function getRuntime($class) { if (isset($this->runtimes[$class])) { return $this->runtimes[$class]; } foreach ($this->runtimeLoaders as $loader) { if (null !== $runtime = $loader->load($class)) { return $this->runtimes[$class] = $runtime; } } throw new Twig_Error_Runtime(sprintf('Unable to load the "%s" runtime.', $class)); } public function addExtension(Twig_ExtensionInterface $extension) { if ($this->extensionInitialized) { throw new LogicException(sprintf('Unable to register extension "%s" as extensions have already been initialized.', $extension->getName())); } $class = get_class($extension); if ($class !== $extension->getName()) { if (isset($this->extensions[$extension->getName()])) { unset($this->extensions[$extension->getName()], $this->extensionsByClass[$class]); @trigger_error(sprintf('The possibility to register the same extension twice ("%s") is deprecated since version 1.23 and will be removed in Twig 2.0. Use proper PHP inheritance instead.', $extension->getName()), E_USER_DEPRECATED); } } $this->lastModifiedExtension = 0; $this->extensionsByClass[$class] = $extension; $this->extensions[$extension->getName()] = $extension; $this->updateOptionsHash(); } /** * Removes an extension by name. * * This method is deprecated and you should not use it. * * @param string $name The extension name * * @deprecated since 1.12 (to be removed in 2.0) */ public function removeExtension($name) { @trigger_error(sprintf('The %s method is deprecated since version 1.12 and will be removed in Twig 2.0.', __METHOD__), E_USER_DEPRECATED); if ($this->extensionInitialized) { throw new LogicException(sprintf('Unable to remove extension "%s" as extensions have already been initialized.', $name)); } $class = ltrim($name, '\\'); if (isset($this->extensions[$class])) { if ($class !== get_class($this->extensions[$class])) { @trigger_error(sprintf('Referencing the "%s" extension by its name (defined by getName()) is deprecated since 1.26 and will be removed in Twig 2.0. Use the Fully Qualified Extension Class Name instead.', $class), E_USER_DEPRECATED); } unset($this->extensions[$class]); } unset($this->extensions[$class]); $this->updateOptionsHash(); } /** * Registers an array of extensions. * * @param array $extensions An array of extensions */ public function setExtensions(array $extensions) { foreach ($extensions as $extension) { $this->addExtension($extension); } } /** * Returns all registered extensions. * * @return Twig_ExtensionInterface[] An array of extensions (keys are for internal usage only and should not be relied on) */ public function getExtensions() { return $this->extensions; } public function addTokenParser(Twig_TokenParserInterface $parser) { if ($this->extensionInitialized) { throw new LogicException('Unable to add a token parser as extensions have already been initialized.'); } $this->staging->addTokenParser($parser); } /** * Gets the registered Token Parsers. * * @return Twig_TokenParserBrokerInterface * * @internal */ public function getTokenParsers() { if (!$this->extensionInitialized) { $this->initExtensions(); } return $this->parsers; } /** * Gets registered tags. * * Be warned that this method cannot return tags defined by Twig_TokenParserBrokerInterface classes. * * @return Twig_TokenParserInterface[] * * @internal */ public function getTags() { $tags = array(); foreach ($this->getTokenParsers()->getParsers() as $parser) { if ($parser instanceof Twig_TokenParserInterface) { $tags[$parser->getTag()] = $parser; } } return $tags; } public function addNodeVisitor(Twig_NodeVisitorInterface $visitor) { if ($this->extensionInitialized) { throw new LogicException('Unable to add a node visitor as extensions have already been initialized.'); } $this->staging->addNodeVisitor($visitor); } /** * Gets the registered Node Visitors. * * @return Twig_NodeVisitorInterface[] * * @internal */ public function getNodeVisitors() { if (!$this->extensionInitialized) { $this->initExtensions(); } return $this->visitors; } /** * Registers a Filter. * * @param string|Twig_SimpleFilter $name The filter name or a Twig_SimpleFilter instance * @param Twig_FilterInterface|Twig_SimpleFilter $filter */ public function addFilter($name, $filter = null) { if (!$name instanceof Twig_SimpleFilter && !($filter instanceof Twig_SimpleFilter || $filter instanceof Twig_FilterInterface)) { throw new LogicException('A filter must be an instance of Twig_FilterInterface or Twig_SimpleFilter.'); } if ($name instanceof Twig_SimpleFilter) { $filter = $name; $name = $filter->getName(); } else { @trigger_error(sprintf('Passing a name as a first argument to the %s method is deprecated since version 1.21. Pass an instance of "Twig_SimpleFilter" instead when defining filter "%s".', __METHOD__, $name), E_USER_DEPRECATED); } if ($this->extensionInitialized) { throw new LogicException(sprintf('Unable to add filter "%s" as extensions have already been initialized.', $name)); } $this->staging->addFilter($name, $filter); } /** * Get a filter by name. * * Subclasses may override this method and load filters differently; * so no list of filters is available. * * @param string $name The filter name * * @return Twig_Filter|false A Twig_Filter instance or false if the filter does not exist * * @internal */ public function getFilter($name) { if (!$this->extensionInitialized) { $this->initExtensions(); } if (isset($this->filters[$name])) { return $this->filters[$name]; } foreach ($this->filters as $pattern => $filter) { $pattern = str_replace('\\*', '(.*?)', preg_quote($pattern, '#'), $count); if ($count) { if (preg_match('#^'.$pattern.'$#', $name, $matches)) { array_shift($matches); $filter->setArguments($matches); return $filter; } } } foreach ($this->filterCallbacks as $callback) { if (false !== $filter = call_user_func($callback, $name)) { return $filter; } } return false; } public function registerUndefinedFilterCallback($callable) { $this->filterCallbacks[] = $callable; } /** * Gets the registered Filters. * * Be warned that this method cannot return filters defined with registerUndefinedFilterCallback. * * @return Twig_FilterInterface[] * * @see registerUndefinedFilterCallback * * @internal */ public function getFilters() { if (!$this->extensionInitialized) { $this->initExtensions(); } return $this->filters; } /** * Registers a Test. * * @param string|Twig_SimpleTest $name The test name or a Twig_SimpleTest instance * @param Twig_TestInterface|Twig_SimpleTest $test A Twig_TestInterface instance or a Twig_SimpleTest instance */ public function addTest($name, $test = null) { if (!$name instanceof Twig_SimpleTest && !($test instanceof Twig_SimpleTest || $test instanceof Twig_TestInterface)) { throw new LogicException('A test must be an instance of Twig_TestInterface or Twig_SimpleTest.'); } if ($name instanceof Twig_SimpleTest) { $test = $name; $name = $test->getName(); } else { @trigger_error(sprintf('Passing a name as a first argument to the %s method is deprecated since version 1.21. Pass an instance of "Twig_SimpleTest" instead when defining test "%s".', __METHOD__, $name), E_USER_DEPRECATED); } if ($this->extensionInitialized) { throw new LogicException(sprintf('Unable to add test "%s" as extensions have already been initialized.', $name)); } $this->staging->addTest($name, $test); } /** * Gets the registered Tests. * * @return Twig_TestInterface[] * * @internal */ public function getTests() { if (!$this->extensionInitialized) { $this->initExtensions(); } return $this->tests; } /** * Gets a test by name. * * @param string $name The test name * * @return Twig_Test|false A Twig_Test instance or false if the test does not exist * * @internal */ public function getTest($name) { if (!$this->extensionInitialized) { $this->initExtensions(); } if (isset($this->tests[$name])) { return $this->tests[$name]; } return false; } /** * Registers a Function. * * @param string|Twig_SimpleFunction $name The function name or a Twig_SimpleFunction instance * @param Twig_FunctionInterface|Twig_SimpleFunction $function */ public function addFunction($name, $function = null) { if (!$name instanceof Twig_SimpleFunction && !($function instanceof Twig_SimpleFunction || $function instanceof Twig_FunctionInterface)) { throw new LogicException('A function must be an instance of Twig_FunctionInterface or Twig_SimpleFunction.'); } if ($name instanceof Twig_SimpleFunction) { $function = $name; $name = $function->getName(); } else { @trigger_error(sprintf('Passing a name as a first argument to the %s method is deprecated since version 1.21. Pass an instance of "Twig_SimpleFunction" instead when defining function "%s".', __METHOD__, $name), E_USER_DEPRECATED); } if ($this->extensionInitialized) { throw new LogicException(sprintf('Unable to add function "%s" as extensions have already been initialized.', $name)); } $this->staging->addFunction($name, $function); } /** * Get a function by name. * * Subclasses may override this method and load functions differently; * so no list of functions is available. * * @param string $name function name * * @return Twig_Function|false A Twig_Function instance or false if the function does not exist * * @internal */ public function getFunction($name) { if (!$this->extensionInitialized) { $this->initExtensions(); } if (isset($this->functions[$name])) { return $this->functions[$name]; } foreach ($this->functions as $pattern => $function) { $pattern = str_replace('\\*', '(.*?)', preg_quote($pattern, '#'), $count); if ($count) { if (preg_match('#^'.$pattern.'$#', $name, $matches)) { array_shift($matches); $function->setArguments($matches); return $function; } } } foreach ($this->functionCallbacks as $callback) { if (false !== $function = call_user_func($callback, $name)) { return $function; } } return false; } public function registerUndefinedFunctionCallback($callable) { $this->functionCallbacks[] = $callable; } /** * Gets registered functions. * * Be warned that this method cannot return functions defined with registerUndefinedFunctionCallback. * * @return Twig_FunctionInterface[] * * @see registerUndefinedFunctionCallback * * @internal */ public function getFunctions() { if (!$this->extensionInitialized) { $this->initExtensions(); } return $this->functions; } /** * Registers a Global. * * New globals can be added before compiling or rendering a template; * but after, you can only update existing globals. * * @param string $name The global name * @param mixed $value The global value */ public function addGlobal($name, $value) { if ($this->extensionInitialized || $this->runtimeInitialized) { if (null === $this->globals) { $this->globals = $this->initGlobals(); } if (!array_key_exists($name, $this->globals)) { // The deprecation notice must be turned into the following exception in Twig 2.0 @trigger_error(sprintf('Registering global variable "%s" at runtime or when the extensions have already been initialized is deprecated since version 1.21.', $name), E_USER_DEPRECATED); //throw new LogicException(sprintf('Unable to add global "%s" as the runtime or the extensions have already been initialized.', $name)); } } if ($this->extensionInitialized || $this->runtimeInitialized) { // update the value $this->globals[$name] = $value; } else { $this->staging->addGlobal($name, $value); } } /** * Gets the registered Globals. * * @return array An array of globals * * @internal */ public function getGlobals() { if (!$this->runtimeInitialized && !$this->extensionInitialized) { return $this->initGlobals(); } if (null === $this->globals) { $this->globals = $this->initGlobals(); } return $this->globals; } /** * Merges a context with the defined globals. * * @param array $context An array representing the context * * @return array The context merged with the globals */ public function mergeGlobals(array $context) { // we don't use array_merge as the context being generally // bigger than globals, this code is faster. foreach ($this->getGlobals() as $key => $value) { if (!array_key_exists($key, $context)) { $context[$key] = $value; } } return $context; } /** * Gets the registered unary Operators. * * @return array An array of unary operators * * @internal */ public function getUnaryOperators() { if (!$this->extensionInitialized) { $this->initExtensions(); } return $this->unaryOperators; } /** * Gets the registered binary Operators. * * @return array An array of binary operators * * @internal */ public function getBinaryOperators() { if (!$this->extensionInitialized) { $this->initExtensions(); } return $this->binaryOperators; } /** * @deprecated since 1.23 (to be removed in 2.0) */ public function computeAlternatives($name, $items) { @trigger_error(sprintf('The %s method is deprecated since version 1.23 and will be removed in Twig 2.0.', __METHOD__), E_USER_DEPRECATED); return Twig_Error_Syntax::computeAlternatives($name, $items); } /** * @internal */ protected function initGlobals() { $globals = array(); foreach ($this->extensions as $name => $extension) { if (!$extension instanceof Twig_Extension_GlobalsInterface) { $m = new ReflectionMethod($extension, 'getGlobals'); if ('Twig_Extension' !== $m->getDeclaringClass()->getName()) { @trigger_error(sprintf('Defining the getGlobals() method in the "%s" extension without explicitly implementing Twig_Extension_GlobalsInterface is deprecated since version 1.23.', $name), E_USER_DEPRECATED); } } $extGlob = $extension->getGlobals(); if (!is_array($extGlob)) { throw new UnexpectedValueException(sprintf('"%s::getGlobals()" must return an array of globals.', get_class($extension))); } $globals[] = $extGlob; } $globals[] = $this->staging->getGlobals(); return call_user_func_array('array_merge', $globals); } /** * @internal */ protected function initExtensions() { if ($this->extensionInitialized) { return; } $this->parsers = new Twig_TokenParserBroker(array(), array(), false); $this->filters = array(); $this->functions = array(); $this->tests = array(); $this->visitors = array(); $this->unaryOperators = array(); $this->binaryOperators = array(); foreach ($this->extensions as $extension) { $this->initExtension($extension); } $this->initExtension($this->staging); // Done at the end only, so that an exception during initialization does not mark the environment as initialized when catching the exception $this->extensionInitialized = true; } /** * @internal */ protected function initExtension(Twig_ExtensionInterface $extension) { // filters foreach ($extension->getFilters() as $name => $filter) { if ($filter instanceof Twig_SimpleFilter) { $name = $filter->getName(); } else { @trigger_error(sprintf('Using an instance of "%s" for filter "%s" is deprecated since version 1.21. Use Twig_SimpleFilter instead.', get_class($filter), $name), E_USER_DEPRECATED); } $this->filters[$name] = $filter; } // functions foreach ($extension->getFunctions() as $name => $function) { if ($function instanceof Twig_SimpleFunction) { $name = $function->getName(); } else { @trigger_error(sprintf('Using an instance of "%s" for function "%s" is deprecated since version 1.21. Use Twig_SimpleFunction instead.', get_class($function), $name), E_USER_DEPRECATED); } $this->functions[$name] = $function; } // tests foreach ($extension->getTests() as $name => $test) { if ($test instanceof Twig_SimpleTest) { $name = $test->getName(); } else { @trigger_error(sprintf('Using an instance of "%s" for test "%s" is deprecated since version 1.21. Use Twig_SimpleTest instead.', get_class($test), $name), E_USER_DEPRECATED); } $this->tests[$name] = $test; } // token parsers foreach ($extension->getTokenParsers() as $parser) { if ($parser instanceof Twig_TokenParserInterface) { $this->parsers->addTokenParser($parser); } elseif ($parser instanceof Twig_TokenParserBrokerInterface) { @trigger_error('Registering a Twig_TokenParserBrokerInterface instance is deprecated since version 1.21.', E_USER_DEPRECATED); $this->parsers->addTokenParserBroker($parser); } else { throw new LogicException('getTokenParsers() must return an array of Twig_TokenParserInterface or Twig_TokenParserBrokerInterface instances.'); } } // node visitors foreach ($extension->getNodeVisitors() as $visitor) { $this->visitors[] = $visitor; } // operators if ($operators = $extension->getOperators()) { if (!is_array($operators)) { throw new InvalidArgumentException(sprintf('"%s::getOperators()" must return an array with operators, got "%s".', get_class($extension), is_object($operators) ? get_class($operators) : gettype($operators).(is_resource($operators) ? '' : '#'.$operators))); } if (2 !== count($operators)) { throw new InvalidArgumentException(sprintf('"%s::getOperators()" must return an array of 2 elements, got %d.', get_class($extension), count($operators))); } $this->unaryOperators = array_merge($this->unaryOperators, $operators[0]); $this->binaryOperators = array_merge($this->binaryOperators, $operators[1]); } } /** * @deprecated since 1.22 (to be removed in 2.0) */ protected function writeCacheFile($file, $content) { $this->cache->write($file, $content); } private function updateOptionsHash() { $hashParts = array_merge( array_keys($this->extensions), array( (int) function_exists('twig_template_get_attributes'), PHP_MAJOR_VERSION, PHP_MINOR_VERSION, self::VERSION, (int) $this->debug, $this->baseTemplateClass, (int) $this->strictVariables, ) ); $this->optionsHash = implode(':', $hashParts); } }
{ "content_hash": "4aeb1651ab90c8383e8b257206f3e1e6", "timestamp": "", "source": "github", "line_count": 1554, "max_line_length": 357, "avg_line_length": 32.58301158301158, "alnum_prop": 0.573962159813564, "repo_name": "ljepojevic/Phactory-PHP-framework", "id": "8c7783c79eaf94b2d103c466d3c85266489fc6e5", "size": "50827", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vendor/Twig-1.x/lib/Twig/Environment.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5361" }, { "name": "HTML", "bytes": "5549" }, { "name": "PHP", "bytes": "26166" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <package xmlns="http://pear.php.net/dtd/package-2.0" xmlns:tasks="http://pear.php.net/dtd/tasks-1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" packagerversion="1.9.0" version="2.0" xsi:schemaLocation="http://pear.php.net/dtd/tasks-1.0 http://pear.php.net/dtd/tasks-1.0.xsd http://pear.php.net/dtd/package-2.0 http://pear.php.net/dtd/package-2.0.xsd"> <name>subscriptions_option</name> <channel>pear.roundcube.net</channel> <summary>Option to disable IMAP subscriptions</summary> <description> A plugin which can enable or disable the use of imap subscriptions. It includes a toggle on the settings page under "Server Settings". The preference can also be locked. </description> <lead> <name>Thomas Bruederli</name> <user>thomasb</user> <email>[email protected]</email> <active>yes</active> </lead> <developer> <name>Ziba Scott</name> <user>ziba</user> <email>[email protected]</email> <active>yes</active> </developer> <date>2012-05-21</date> <version> <release>1.3</release> <api>1.1</api> </version> <stability> <release>stable</release> <api>stable</api> </stability> <license uri="http://www.gnu.org/licenses/gpl-2.0.html">GNU GPLv2</license> <notes>-</notes> <contents> <dir baseinstalldir="/" name="/"> <file name="subscriptions_option.php" role="php"> <tasks:replace from="@name@" to="name" type="package-info"/> <tasks:replace from="@package_version@" to="version" type="package-info"/> </file> <file name="localization/cs_CZ.inc" role="data"></file> <file name="localization/de_CH.inc" role="data"></file> <file name="localization/de_DE.inc" role="data"></file> <file name="localization/en_US.inc" role="data"></file> <file name="localization/es_ES.inc" role="data"></file> <file name="localization/et_EE.inc" role="data"></file> <file name="localization/gl_ES.inc" role="data"></file> <file name="localization/ja_JP.inc" role="data"></file> <file name="localization/pl_PL.inc" role="data"></file> <file name="localization/ru_RU.inc" role="data"></file> <file name="localization/sv_SE.inc" role="data"></file> <file name="localization/zh_TW.inc" role="data"></file> </dir> <!-- / --> </contents> <dependencies> <required> <php> <min>5.2.1</min> </php> <pearinstaller> <min>1.7.0</min> </pearinstaller> </required> </dependencies> <phprelease/> </package>
{ "content_hash": "8b536a1a2e0ecbcc99491e4bee0db324", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 246, "avg_line_length": 36, "alnum_prop": 0.6602254428341385, "repo_name": "exhibia/exhibia", "id": "79d44f8c259c30f48a90d0b06c0a9ca3f8200ebc", "size": "2484", "binary": false, "copies": "11", "ref": "refs/heads/master", "path": "roundcube/plugins/subscriptions_option/package.xml", "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": "" }
require('babel-register'); require('./server.js');
{ "content_hash": "6569f97307244b08ce2150b291c7b107", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 26, "avg_line_length": 25, "alnum_prop": 0.7, "repo_name": "garrettgraber/galaxy-map", "id": "d04e2a6ab16c5a2018d4a3ab7b7c190b71e1676e", "size": "50", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "docker-react-web-app/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3105" }, { "name": "HTML", "bytes": "4737" }, { "name": "JavaScript", "bytes": "65572" }, { "name": "Shell", "bytes": "1945" } ], "symlink_target": "" }
<?php return [ /* |-------------------------------------------------------------------------- | Password Reset Language Lines |-------------------------------------------------------------------------- | | The following language lines are the default lines which match reasons | that are given by the password broker for a password update attempt | has failed, such as for an invalid token or invalid new password. | */ 'reset' => 'Your password has been reset!', 'sent' => 'We have emailed your password reset link!', 'throttled' => 'Please wait before retrying.', 'token' => 'This password reset token is invalid.', 'user' => "We can't find a user with that email address.", ];
{ "content_hash": "bd691c24b1a5e42e2c7fef1799358fd7", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 79, "avg_line_length": 37.1, "alnum_prop": 0.5094339622641509, "repo_name": "laravelio/portal", "id": "b56e2067c4b4d6f6223ab14c24024cb8f05aa793", "size": "742", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "resources/lang/en/passwords.php", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "115744" }, { "name": "JavaScript", "bytes": "4829" }, { "name": "PHP", "bytes": "278018" } ], "symlink_target": "" }
/** @file VersionInfo.h @author Lime Microsystems @brief API for querying version and build information. */ #ifndef LIMESUITE_VERSION_INFO_H #define LIMESUITE_VERSION_INFO_H #include "LimeSuiteConfig.h" #include <string> /*! * API version number which can be used as a preprocessor check. * The format of the version number is encoded as follows: * <b>(major << 16) | (minor << 8) | (8 bit increment)</b>. * Where the increment can be used to indicate implementation * changes, fixes, or API additions within a minor release series. * * The macro is typically used in an application as follows: * \code * #if defined(LIME_SUITE_API_VERSION) && (LIME_SUITE_API_VERSION >= 0x20161200) * // Use a newer feature from the LimeSuite library API * #endif * \endcode */ #define LIME_SUITE_API_VERSION 0x20201000 namespace lime { /*! * Get the library version as a dotted string. * The format is major.minor.patch.build-extra. */ LIME_API std::string GetLibraryVersion(void); /*! * Get the date of the build in "%Y-%M-%d" format. */ LIME_API std::string GetBuildTimestamp(void); /*! * Get the LimeSuite library API version as a string. * The format of the version string is <b>major.minor.increment</b>, * where the digits are taken directly from <b>LIME_SUITE_API_VERSION</b>. */ LIME_API std::string GetAPIVersion(void); /*! * Get the ABI/so version of the library. */ LIME_API std::string GetABIVersion(void); } #endif //LIMESUITE_VERSION_INFO_H
{ "content_hash": "c387279b6783ca4f94818ed88911c062", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 80, "avg_line_length": 27.660714285714285, "alnum_prop": 0.6785022595222724, "repo_name": "limemicro/lms7suite", "id": "e0a8337d4f6a95e872a468c7ffa19c8d133558b3", "size": "1549", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/VersionInfo.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "10132449" }, { "name": "C++", "bytes": "2634407" }, { "name": "CMake", "bytes": "70115" }, { "name": "MATLAB", "bytes": "5623" }, { "name": "Python", "bytes": "8739" }, { "name": "Rich Text Format", "bytes": "84475" }, { "name": "Shell", "bytes": "2498" } ], "symlink_target": "" }
@protocol JavaLangIterable; @protocol JavaUtilList; @protocol JavaUtilMap; #define ComGoogleCommonCollectMultimap_RESTRICT 1 #define ComGoogleCommonCollectMultimap_INCLUDE 1 #include "com/google/common/collect/Multimap.h" @protocol ComGoogleCommonCollectListMultimap < ComGoogleCommonCollectMultimap, NSObject, JavaObject > - (id<JavaUtilList>)getWithId:(id)key; - (id<JavaUtilList>)removeAllWithId:(id)key; - (id<JavaUtilList>)replaceValuesWithId:(id)key withJavaLangIterable:(id<JavaLangIterable>)values; - (id<JavaUtilMap>)asMap; - (jboolean)isEqual:(id)obj; @end J2OBJC_EMPTY_STATIC_INIT(ComGoogleCommonCollectListMultimap) #endif J2OBJC_TYPE_LITERAL_HEADER(ComGoogleCommonCollectListMultimap)
{ "content_hash": "705564006d8996221b5c3afc5bc1df54", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 101, "avg_line_length": 26.925925925925927, "alnum_prop": 0.8005502063273727, "repo_name": "hambroperks/pollexor", "id": "a9c5f51d85aea8b7d3c8c63f06b1ea1e00c0fac9", "size": "1270", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Pods/J2ObjC/dist/include/com/google/common/collect/ListMultimap.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1040" }, { "name": "HTML", "bytes": "4169" }, { "name": "Java", "bytes": "59016" }, { "name": "Objective-C", "bytes": "87524" }, { "name": "Ruby", "bytes": "1420" }, { "name": "Shell", "bytes": "2482" } ], "symlink_target": "" }
.. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Getting Started With Heat on Fedora =================================== .. This file is a ReStructuredText document, but can be converted to a script using the accompanying rst2script.sed script. Any blocks that are indented by 4 spaces (including comment blocks) will appear in the script. To document code that should not appear in the script, use an indent of less than 4 spaces. (Using a Quoted instead of Indented Literal block also works.) To include code in the script that should not appear in the output, make it a comment block. Installing OpenStack and Heat on Fedora --------------------------------------- Either the Grizzly, or Havana release of OpenStack is required. If you are using Grizzly, you should use the stable/grizzly branch of Heat. Instructions for installing the RDO OpenStack distribution on Fedora are available at ``http://openstack.redhat.com/Quickstart`` Instructions for installing Heat on RDO are also available at ``http://openstack.redhat.com/Docs`` Alternatively, if you require a development environment not a package-based install, the suggested method is devstack, see instructions at :doc:`on_devstack` Example Templates ----------------- Check out the example templates at ``https://github.com/openstack/heat-templates``. Here you can view example templates which will work with several Fedora versions.
{ "content_hash": "31622284c4cbb649e59c7bb9ecad86a2", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 166, "avg_line_length": 50.05128205128205, "alnum_prop": 0.7300204918032787, "repo_name": "rickerc/heat_audit", "id": "f768ec48b6084ce191d5b13304ad15f3eb5e0350", "size": "1952", "binary": false, "copies": "7", "ref": "refs/heads/cis-havana-staging", "path": "doc/source/getting_started/on_fedora.rst", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "2811491" }, { "name": "Shell", "bytes": "21618" } ], "symlink_target": "" }
// ---------------------------------------------------------------------------- #include "dcmtk/config/osconfig.h" // specific configuration for operating system #include "dcmtk/dcmnet/dicom.h" // for DIC_NODENAME etc. used in "wltypdef.h" #include "dcmtk/dcmwlm/wltypdef.h" // for type definitions #include "dcmtk/ofstd/oftypes.h" // for OFBool #include "dcmtk/dcmdata/dcdatset.h" // for DcmDataset #include "dcmtk/dcmdata/dcvrat.h" // for DcmAttributTag #include "dcmtk/dcmdata/dcvrlo.h" // for DcmLongString #include "dcmtk/dcmdata/dcvrae.h" #include "dcmtk/dcmdata/dcvrda.h" #include "dcmtk/dcmdata/dcvrcs.h" #include "dcmtk/dcmdata/dcvrpn.h" #include "dcmtk/dcmdata/dcvrtm.h" #include "dcmtk/dcmdata/dcvrsh.h" #include "dcmtk/dcmdata/dcvrui.h" #include "dcmtk/dcmdata/dcdict.h" // for global variable dcmDataDict #include "dcmtk/dcmdata/dcdeftag.h" // for DCM_OffendingElement, ... #include "dcmtk/dcmdata/dcsequen.h" // for DcmSequenceOfItems #include "dcmtk/dcmdata/dcdicent.h" // needed by MSVC5 with STL #include "dcmtk/dcmwlm/wlds.h" OFLogger DCM_dcmwlmLogger = OFLog::getLogger("dcmtk.dcmwlm"); // ---------------------------------------------------------------------------- WlmDataSource::WlmDataSource() // Date : December 10, 2001 // Author : Thomas Wilkens // Task : Constructor. // Parameters : none. // Return Value : none. : failOnInvalidQuery( OFTrue ), calledApplicationEntityTitle(""), identifiers( NULL ), errorElements( NULL ), offendingElements( NULL ), errorComment( NULL ), foundUnsupportedOptionalKey( OFFalse ), readLockSetOnDataSource( OFFalse ), noSequenceExpansion( OFFalse ), returnedCharacterSet( RETURN_NO_CHARACTER_SET ), matchingDatasets(), specificCharacterSet( "" ), superiorSequenceArray( NULL ), numOfSuperiorSequences( 0 ) { // Make sure data dictionary is loaded. if( !dcmDataDict.isDictionaryLoaded() ) { DCMWLM_WARN("No data dictionary loaded, check environment variable: " << DCM_DICT_ENVIRONMENT_VARIABLE); } // Initialize member variables. identifiers = new DcmDataset(); offendingElements = new DcmAttributeTag( DCM_OffendingElement, 0 ); errorElements = new DcmAttributeTag( DCM_OffendingElement, 0 ); errorComment = new DcmLongString( DCM_ErrorComment, 0 ); } // ---------------------------------------------------------------------------- WlmDataSource::~WlmDataSource() // Date : December 10, 2001 // Author : Thomas Wilkens // Task : Destructor. // Parameters : none. // Return Value : none. { // free memory ClearDataset(identifiers); delete identifiers; delete offendingElements; delete errorElements; delete errorComment; } // ---------------------------------------------------------------------------- void WlmDataSource::SetCalledApplicationEntityTitle( const OFString& value ) // Date : December 10, 2001 // Author : Thomas Wilkens // Task : Sets the member variable that specifies called application entity title. // Parameters : value - Value for calledApplicationEntityTitle. // Return Value : none. { calledApplicationEntityTitle = value; } // ---------------------------------------------------------------------------- void WlmDataSource::SetFailOnInvalidQuery( OFBool value ) // Date : December 10, 2001 // Author : Thomas Wilkens // Task : Set member variable that determines if a call should fail on an invalid query. // Parameters : value - Value for failOnInvalidQuery. // Return Value : none. { failOnInvalidQuery = value; } // ---------------------------------------------------------------------------- void WlmDataSource::SetNoSequenceExpansion( OFBool value ) // Date : May 8, 2002 // Author : Thomas Wilkens // Task : Set member variable. // Parameters : value - Value for member variable. // Return Value : none. { noSequenceExpansion = value; } // ---------------------------------------------------------------------------- void WlmDataSource::SetReturnedCharacterSet( WlmReturnedCharacterSetType value ) // Date : March 21, 2002 // Author : Thomas Wilkens // Task : Set member variable. // Parameters : value - Value for member variable. // Return Value : none. { returnedCharacterSet = value; } // ---------------------------------------------------------------------------- OFBool WlmDataSource::CheckSearchMask( DcmDataset *searchMask ) // Date : March 18, 2001 // Author : Thomas Wilkens // Task : This function checks if the search mask has a correct format. It returns OFTrue if this // is the case, OFFalse if this is not the case. // Parameters : searchMask - [in] Contains the search mask. // Return Value : OFTrue - The search mask has a correct format. // OFFalse - The search mask does not have a correct format. { // Initialize counter that counts invalid elements in the search mask. This // variable will later be used to determine the return value for this function. int invalidMatchingKeyAttributeCount = 0; // remember the number of data elements in the search mask unsigned long numOfElementsInSearchMask = searchMask->card(); // remember potentially specified specific character set searchMask->findAndGetOFString( DCM_SpecificCharacterSet, specificCharacterSet ); // dump some information if required DCMWLM_INFO("Checking the search mask"); // this member variable indicates if we encountered an unsupported // optional key attribute in the search mask; initialize it with false. foundUnsupportedOptionalKey = OFFalse; // start a loop; go through all data elements in the search mask, for each element, do some checking unsigned long i = 0; while( i < numOfElementsInSearchMask ) { // determine current element DcmElement *element = searchMask->getElement(i); // Depending on if the current element is a sequence or not, process this element. if( element->ident() != EVR_SQ ) CheckNonSequenceElementInSearchMask( searchMask, invalidMatchingKeyAttributeCount, element ); else CheckSequenceElementInSearchMask( searchMask, invalidMatchingKeyAttributeCount, element ); // Depending on if the number of elements in the search mask has changed, the current element was // deleted in the above called function or not. In case the current element was deleted, we do not // need to increase counter i, we only need to update numOfElementsInSearchMask. If the current // element was not deleted, we need to increase i but don't have to update numOfElementsInSearchMask. unsigned long currentNumOfElementsInSearchMask = searchMask->card(); if( currentNumOfElementsInSearchMask != numOfElementsInSearchMask ) numOfElementsInSearchMask = currentNumOfElementsInSearchMask; else i++; } // if there was more than 1 error, override the error comment if( invalidMatchingKeyAttributeCount > 1 ) errorComment->putString("Syntax error in 1 or more matching keys"); // return OFTrue or OFFalse depending on the number of invalid matching attributes return( invalidMatchingKeyAttributeCount == 0 ); } // ---------------------------------------------------------------------------- void WlmDataSource::CheckNonSequenceElementInSearchMask( DcmDataset *searchMask, int &invalidMatchingKeyAttributeCount, DcmElement *element, DcmSequenceOfItems *supSequenceElement ) // Date : March 8, 2002 // Author : Thomas Wilkens // Task : This function checks if a non-sequence element in the search mask has a correct format. // Note that if the current element is an unsupported element, the entire element will be re- // moved from the search mask, since unsupported elements shall not be returned to the caller. // Parameters : searchMask - [in] Pointer to the search mask. // invalidMatchingKeyAttributeCount - [inout] Counter that counts invalid elements in the search mask. // element - [in] Pointer to the currently processed element. // supSequenceElement - [in] Pointer to the superordinate sequence element of which // the currently processed element is an attribute. // Return Value : none. { DcmElement *elem = NULL; // determine current element's tag DcmTag tag( element->getTag() ); // determine if the current element is a supported matching key attribute if( IsSupportedMatchingKeyAttribute( element, supSequenceElement ) ) { // if the current element is a supported matching key attribute, check if the current element meets // certain conditions (at the moment we only check if the element's data type and value go together) if( !CheckMatchingKey( element ) ) { // if there is a problem with the current element, increase the corresponding counter and dump an error message. invalidMatchingKeyAttributeCount++; DCMWLM_WARN("Matching key attribute (" << tag.getTagName() << ") with invalid value encountered in the search mask"); } } // if current element is not a supported matching key attribute, determine // if the current element is a supported return key attribute. else if( IsSupportedReturnKeyAttribute( element, supSequenceElement ) ) { // we need to check if the current element (a supported return key attribute) does not contain a value. // According to the DICOM standard part 4, section K.2.2.1.2. a return key attribute which is NOT a // a matching key attribute must not contain a value. If one such attribute does contain a value, // i.e. if the current element's length does not equal 0, we want to dump a warning message. if( element->getLength() != 0 ) { DCMWLM_INFO(" - Non-empty return key attribute (" << tag.getTagName() << ") encountered in the search mask." << OFendl << " The specified value will be overridden."); } } // if current element is neither a supported matching key attribute nor a supported return key // attribute we've found an unsupported optional attribute; we want to delete this element from // the search mask, dump a warning and remember this attribute's tag in the list of error elements. else { // delete element from the search mask // in case there is a superordinate sequence element in whose first item this element occurs, // we need to delete this element from this particular item in the superordinate sequence element if( supSequenceElement != NULL ) { elem = supSequenceElement->getItem(0)->remove( element ); delete elem; } // in case there is NO superordinate sequence element in whose first item this element occurs, // we need to delete this element from the search mask itself. else { elem = searchMask->remove( element ); delete elem; } // handle special case of "Specific Character Set" if( tag == DCM_SpecificCharacterSet ) { DCMWLM_WARN("Attribute " << tag.getTagName() << " found in the search mask, value is neither checked nor used for matching"); } else { // dump a warning DCMWLM_INFO(" - Unsupported (non-sequence) attribute (" << tag.getTagName() << ") encountered in the search mask." << OFendl << " This attribute will not be existent in any result dataset."); // remember this attribute's tag in the list of error elements foundUnsupportedOptionalKey = OFTrue; PutErrorElements( tag ); } } } // ---------------------------------------------------------------------------- void WlmDataSource::CheckSequenceElementInSearchMask( DcmDataset *searchMask, int &invalidMatchingKeyAttributeCount, DcmElement *element, DcmSequenceOfItems *supSequenceElement ) // Date : March 8, 2002 // Author : Thomas Wilkens // Task : This function checks if a sequence element in the search mask has a correct format. // Note that if the current element is an unsupported element, the entire element will be re- // moved from the search mask, since unsupported elements shall not be returned to the caller. // Moreover, in case the sequence element in the search mask is supported but empty, this // function will expand the sequence element by inserting all required attributes into that sequence. // Parameters : searchMask - [in] Pointer to the search mask. // invalidMatchingKeyAttributeCount - [inout] Counter that counts invalid elements in the search mask. // element - [in] Pointer to the currently processed element. // supSequenceElement - [in] Pointer to the superordinate sequence element of which // the currently processed element is an attribute. // Return Value : none. { // Be aware of the following remark: the DICOM standard specifies in part 4, section C.2.2.2.6 // that if a search mask contains a sequence attribute which contains a single empty item, all // attributes from that particular sequence are in fact queried and shall be returned by the SCP. // This implementation accounts for this specification by expanding the search mask correspondingly. DcmElement *elem = NULL; // determine current element's tag DcmTag tag( element->getTag() ); // remember that the current element is a sequence of items DcmSequenceOfItems *sequenceElement = OFstatic_cast(DcmSequenceOfItems *, element); // determine if the current sequence element is a supported matching or return key attribute if( IsSupportedMatchingKeyAttribute( element, supSequenceElement ) || IsSupportedReturnKeyAttribute( element, supSequenceElement ) ) { // if the sequence attribute is supported, check if the length of the sequence equals 0, or if the sequence // contains exactly one empty item if( element->getLength() == 0 || ( sequenceElement->card() == 1 && sequenceElement->getItem(0)->card() == 0 ) ) { // an empty sequence is not allowed in a C-FIND request if (element->getLength() == 0) { DCMWLM_WARN("Empty sequence (" << tag.getTagName() << ") encountered within the query, " << "treating as if an empty item within the sequence has been sent"); } // if this is the case, we need to check the value of a variable // which pertains to a certain command line option if( noSequenceExpansion == OFFalse ) { // if the user did not explicitely disable the expansion of empty sequences in C-FIND request // messages go ahead and expand this sequence according to the remark above ExpandEmptySequenceInSearchMask( element ); } } else { // if this is not the case we want to check the cardinality of the sequence; note that there should // always be exactly one item in a sequence within the search mask. if( sequenceElement->card() != 1 ) { // if there is not exactly one item in the sequence of items, we want to remember this // attribute in the list of offending elements, we want to set the error comment correspondingly, // we want to dump an error message and we want to increase the corresponding counter. PutOffendingElements(tag); errorComment->putString("More than 1 item in sequence."); DCMWLM_ERROR("More than one item in sequence (" << tag.getTagName() << ") within the query encountered, " << "discarding all items except for the first one"); invalidMatchingKeyAttributeCount++; // also, we want to delete all items except the first one unsigned long numOfItems = sequenceElement->card(); for( unsigned long i=1 ; i<numOfItems ; i++ ) { delete sequenceElement->remove( i ); } } // (now, even though we might have encountered an error, we go on scrutinizing the search mask) // get the first (and only) item in the sequence of items DcmItem *item = sequenceElement->getItem(0); // determine the cardinality of this item unsigned long numOfElementsInItem = item->card(); unsigned long k = 0; // go through all elements of this item while( k < numOfElementsInItem ) { // determine the current element DcmElement *elementseq = item->getElement(k); // Depending on if the current element is a sequence or not, process this element. if( elementseq->ident() != EVR_SQ ) CheckNonSequenceElementInSearchMask( searchMask, invalidMatchingKeyAttributeCount, elementseq, sequenceElement ); else CheckSequenceElementInSearchMask( searchMask, invalidMatchingKeyAttributeCount, elementseq, sequenceElement ); // Depending on if the number of elements in the item has changed, the current element was // deleted in the above called function or not. In case the current element was deleted, we do not // need to increase counter k, we only need to update numOfElementsInItem. If the current // element was not deleted, we need to increase k but don't have to update numOfElementsInItem. unsigned long currentNumOfElementsInItem = item->card(); if( currentNumOfElementsInItem != numOfElementsInItem ) numOfElementsInItem = currentNumOfElementsInItem; else k++; } } } // if current element is neither a supported matching key attribute sequence nor a supported return key // attribute sequence we've found an unsupported sequence attribute; we want to delete this element from // the search mask, dump a warning message (only in verbose mode) remember this attribute in the list of // error elements. else { // delete element from the search mask // in case there is a superordinate sequence element in whose first item this element occurs, // we need to delete this element from this particular item in the superordinate sequence element if( supSequenceElement != NULL ) { elem = supSequenceElement->getItem(0)->remove( element ); delete elem; } // in case there is NO superordinate sequence element in whose first item this element occurs, // we need to delete this element from the search mask itself. else { elem = searchMask->remove( element ); delete elem; } // dump a warning DCMWLM_INFO(" - Unsupported (sequence) attribute (" << tag.getTagName() << ") encountered in the search mask." << OFendl << " This attribute will not be existent in any result dataset."); // remember this attribute's tag in the list of error elements foundUnsupportedOptionalKey = OFTrue; PutErrorElements( tag ); } } // ---------------------------------------------------------------------------- void WlmDataSource::ExpandEmptySequenceInSearchMask( DcmElement *&element ) // Date : March 8, 2002 // Author : Thomas Wilkens // Task : According to the DICOM standard (part 4, section C.2.2.2.6), if a search mask // contains a sequence attribute which contains no item or a single empty item, all // attributes from that particular sequence are in fact queried and shall be returned // by the SCP. This implementation accounts for this specification by inserting a // corresponding single item with all required attributes into such emtpy sequences. // This function performs the insertion of the required item and attributes. // Parameters : element - [inout] Pointer to the currently processed element. // Return Value : none. { DcmItem *item = NULL; DcmElement *newElement = NULL; // remember that the current element is a sequence of items DcmSequenceOfItems *sequenceElement = OFstatic_cast(DcmSequenceOfItems *, element); // determine if the length of the sequence equals 0 if( element->getLength() == 0 ) { // if the length of the sequence attribute equals 0, we have to insert a single item item = new DcmItem(); if( sequenceElement->insert( item ) != EC_Normal ) { delete item; item = NULL; } } else { // if the length of the sequence attribute does not equal 0, we have to determine the // one and only item in the sequence item = sequenceElement->getItem(0); } // check if item does not equal NULL, only if this is the case, we can insert attributes // into that item. In general, this should always be the case. if( item != NULL ) { // at this point, the current element contains exactly one item, which is empty, i.e. does not // contain any attributes. Now we have to insert the required attributes into this item. // depending on what kind of supported sequence attribute // was passed, we have to insert different attributes DcmTagKey key = element->getTag().getXTag(); if( key == DCM_ScheduledProcedureStepSequence ) { newElement = new DcmApplicationEntity( DcmTag( DCM_ScheduledStationAETitle ) ); if( item->insert( newElement ) != EC_Normal ) delete newElement; newElement = new DcmDate( DcmTag( DCM_ScheduledProcedureStepStartDate ) ); if( item->insert( newElement ) != EC_Normal ) delete newElement; newElement = new DcmTime( DcmTag( DCM_ScheduledProcedureStepStartTime ) ); if( item->insert( newElement ) != EC_Normal ) delete newElement; newElement = new DcmCodeString( DcmTag( DCM_Modality ) ); if( item->insert( newElement ) != EC_Normal ) delete newElement; newElement = new DcmPersonName( DcmTag( DCM_ScheduledPerformingPhysicianName ) ); if( item->insert( newElement ) != EC_Normal ) delete newElement; newElement = new DcmLongString( DcmTag( DCM_ScheduledProcedureStepDescription ) ); if( item->insert( newElement ) != EC_Normal ) delete newElement; newElement = new DcmShortString( DcmTag( DCM_ScheduledStationName ) ); if( item->insert( newElement ) != EC_Normal ) delete newElement; newElement = new DcmShortString( DcmTag( DCM_ScheduledProcedureStepLocation ) ); if( item->insert( newElement ) != EC_Normal ) delete newElement; newElement = new DcmLongString( DcmTag( DCM_PreMedication ) ); if( item->insert( newElement ) != EC_Normal ) delete newElement; newElement = new DcmShortString( DcmTag( DCM_ScheduledProcedureStepID ) ); if( item->insert( newElement ) != EC_Normal ) delete newElement; newElement = new DcmLongString( DcmTag( DCM_RequestedContrastAgent ) ); if( item->insert( newElement ) != EC_Normal ) delete newElement; newElement = new DcmLongString( DcmTag( DCM_CommentsOnTheScheduledProcedureStep ) ); if( item->insert( newElement ) != EC_Normal ) delete newElement; newElement = new DcmCodeString( DcmTag( DCM_ScheduledProcedureStepStatus ) ); if( item->insert( newElement ) != EC_Normal ) delete newElement; newElement = new DcmDate( DcmTag( DCM_ScheduledProcedureStepEndDate ) ); if( item->insert( newElement ) != EC_Normal ) delete newElement; newElement = new DcmTime( DcmTag( DCM_ScheduledProcedureStepEndTime ) ); if( item->insert( newElement ) != EC_Normal ) delete newElement; newElement = new DcmSequenceOfItems( DcmTag( DCM_ScheduledProtocolCodeSequence ) ); if( item->insert( newElement ) != EC_Normal ) delete newElement; else { DcmItem *item2 = new DcmItem(); if( OFstatic_cast(DcmSequenceOfItems*, newElement)->insert( item2 ) != EC_Normal ) { delete item2; item2 = NULL; } else { DcmElement *newElement2 = NULL; newElement2 = new DcmShortString( DcmTag( DCM_CodeValue ) ); if( item2->insert( newElement2 ) != EC_Normal ) delete newElement2; newElement2 = new DcmShortString( DcmTag( DCM_CodingSchemeVersion ) ); if( item2->insert( newElement2 ) != EC_Normal ) delete newElement2; newElement2 = new DcmShortString( DcmTag( DCM_CodingSchemeDesignator ) ); if( item2->insert( newElement2 ) != EC_Normal ) delete newElement2; newElement2 = new DcmLongString( DcmTag( DCM_CodeMeaning ) ); if( item2->insert( newElement2 ) != EC_Normal ) delete newElement2; } } } else if( key == DCM_ScheduledProtocolCodeSequence || key == DCM_RequestedProcedureCodeSequence ) { newElement = new DcmShortString( DcmTag( DCM_CodeValue ) ); if( item->insert( newElement ) != EC_Normal ) delete newElement; newElement = new DcmShortString( DcmTag( DCM_CodingSchemeVersion ) ); if( item->insert( newElement ) != EC_Normal ) delete newElement; newElement = new DcmShortString( DcmTag( DCM_CodingSchemeDesignator ) ); if( item->insert( newElement ) != EC_Normal ) delete newElement; newElement = new DcmLongString( DcmTag( DCM_CodeMeaning ) ); if( item->insert( newElement ) != EC_Normal ) delete newElement; } else if( key == DCM_ReferencedStudySequence || key == DCM_ReferencedPatientSequence ) { newElement = new DcmUniqueIdentifier( DcmTag( DCM_ReferencedSOPClassUID ) ); if( item->insert( newElement ) != EC_Normal ) delete newElement; newElement = new DcmUniqueIdentifier( DcmTag( DCM_ReferencedSOPInstanceUID ) ); if( item->insert( newElement ) != EC_Normal ) delete newElement; } else { // this code should never be executed; if it is, there is a logical error // in the source code and we want to dump a warning message DCMWLM_ERROR("WlmDataSource::ExpandEmptySequenceInSearchMask: Unsupported sequence attribute encountered"); } } else { // this code should never be executed. if it is, we want to dump a warning message DCMWLM_ERROR("WlmDataSource::ExpandEmptySequenceInSearchMask: Unable to find item in sequence"); } } // ---------------------------------------------------------------------------- void WlmDataSource::ClearDataset( DcmDataset *idents ) // Date : December 10, 2001 // Author : Thomas Wilkens // Task : This function removes all elements from the given DcmDataset object. // Parameters : idents - [in] pointer to object which shall be cleared. // Return Value : none. { // If the given pointer is valid and refers to a non-empty structure if( idents && (idents->card()>0) ) { // clear structure idents->clear(); } } // ---------------------------------------------------------------------------- void WlmDataSource::PutOffendingElements( const DcmTagKey &tag ) // Date : December 10, 2001 // Author : Thomas Wilkens // Task : This function inserts the tag of an offending element into the // corresponding member variable, unless this tag is already con- // tained in this variable. // Parameters : tag - [in] The tag that shall be inserted. // Return Value : none. { DcmTagKey errortag; // determine how many offending elements there have been so far unsigned long d = offendingElements->getVM(); // if this is the first one, insert it at position 0 if( d==0 ) { offendingElements->putTagVal(tag, 0); } // if this is not the first one, insert it at the end // but only if it is not yet contained. else { OFBool tagFound = OFFalse; for( unsigned long j=0 ; j<d && !tagFound ; j++ ) { offendingElements->getTagVal( errortag, j ); if( errortag == tag ) tagFound = OFTrue; } if( !tagFound ) offendingElements->putTagVal( tag, d ); } } // ---------------------------------------------------------------------------- void WlmDataSource::PutErrorElements( const DcmTagKey &tag ) // Date : December 10, 2001 // Author : Thomas Wilkens // Task : This function inserts the tag of an error element into the // corresponding member variable, without checking if it is already // contained in this variable. // Parameters : tag - [in] The tag that shall be inserted. // Return Value : none. { // insert tag errorElements->putTagVal( tag, errorElements->getVM() ); } // ---------------------------------------------------------------------------- OFBool WlmDataSource::CheckMatchingKey( const DcmElement *elem ) // Date : March 18, 2002 // Author : Thomas Wilkens // Task : This function checks if the passed matching key's value only uses characters // which are part of its data type's character repertoire. Note that at the moment // this application supports the following matching key attributes: // DCM_ScheduledProcedureStepSequence (0040,0100) SQ R 1 // > DCM_ScheduledStationAETitle (0040,0001) AE R 1 // > DCM_ScheduledProcedureStepStartDate (0040,0002) DA R 1 // > DCM_ScheduledProcedureStepStartTime (0040,0003) TM R 1 // > DCM_Modality (0008,0060) CS R 1 // > DCM_ScheduledPerformingPhysicianName (0040,0006) PN R 2 // DCM_PatientName (0010,0010) PN R 1 // DCM_PatientID (0010,0020) LO R 1 // DCM_AccessionNumber (0008,0050) SH O 2 // DCM_RequestedProcedureID (0040,1001) SH O 1 // DCM_ReferringPhysicianName (0008,0090) PN O 2 // DCM_PatientSex (0010,0040) CS O 2 // DCM_RequestingPhysician (0032,1032) PN O 2 // DCM_AdmissionID (0038,0010) LO O 2 // DCM_RequestedProcedurePriority (0040,1003) SH O 2 // DCM_PatientBirthDate (0010,0030) DA O 2 // As a result, the following data types have to be supported in this function: // AE, DA, TM, CS, PN, LO and SH. For the correct specification of these datatypes // 2003 DICOM standard, part 5, section 6.2, table 6.2-1. // Parameters : elem - [in] Element which shall be checked. // Return Value : OFTrue - The given element's value only uses characters which are part of // the element's data type's character repertoire. // OFFalse - The given element's value does not only use characters which are part of // the element's data type's character repertoire. { OFBool ok = OFTrue; OFString val; switch( elem->ident() ) { case EVR_DA: // get string value ok = GetStringValue( elem, val ); // if there is a value and if the value is not a date or a date range, return invalid value if( ok && !IsValidDateOrDateRange( val ) ) { DcmTag tag( elem->getTag() ); PutOffendingElements( tag ); errorComment->putString("Invalid value for an attribute of datatype DA"); ok = OFFalse; } else return OFTrue; case EVR_TM: // get string value ok = GetStringValue( elem, val ); // if there is a value and if the value is not a time or a time range, return invalid value if( ok && !IsValidTimeOrTimeRange( val ) ) { DcmTag tag( elem->getTag() ); PutOffendingElements( tag ); errorComment->putString("Invalid value for an attribute of datatype TM"); ok = OFFalse; } else return OFTrue; case EVR_CS: // get string value ok = GetStringValue( elem, val ); // check if value contains only valid characters if( ok && !ContainsOnlyValidCharacters( val.c_str(), "*?ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 _" ) ) { DcmTag tag( elem->getTag() ); PutOffendingElements( tag ); errorComment->putString("Invalid Character Repertoire for datatype CS"); ok = OFFalse; } else return OFTrue; case EVR_AE: // get string value ok = GetStringValue( elem, val ); // check if value contains only valid characters if( ok && !ContainsOnlyValidCharacters( val.c_str(), " !\"#$%%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~" ) ) { DcmTag tag( elem->getTag() ); PutOffendingElements( tag ); errorComment->putString("Invalid Character Repertoire for datatype AE"); ok = OFFalse; } else return OFTrue; case EVR_PN: // get string value ok = GetStringValue( elem, val ); // check if value contains only valid characters if( ok && !ContainsOnlyValidCharacters( val.c_str(), "*? !\"#$%%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\033" ) && specificCharacterSet == "" ) // ESC=\033 { DcmTag tag( elem->getTag() ); PutOffendingElements( tag ); errorComment->putString("Invalid Character Repertoire for datatype PN"); ok = OFFalse; } else return OFTrue; case EVR_LO: // get string value ok = GetStringValue( elem, val ); // check if value contains only valid characters if( ok && !ContainsOnlyValidCharacters( val.c_str(), "*? !\"#$%%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\033\012\014\015" ) && specificCharacterSet == "" ) // ESC=\033, LF=\012, FF=\014, CR=\015 { DcmTag tag( elem->getTag() ); PutOffendingElements( tag ); errorComment->putString("Invalid Character Repertoire for datatype LO"); ok = OFFalse; } else return OFTrue; case EVR_SH: // get string value ok = GetStringValue( elem, val ); // check if value contains only valid characters if( ok && !ContainsOnlyValidCharacters( val.c_str(), "*? !\"#$%%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\033\012\014\015" ) && specificCharacterSet == "" ) // ESC=\033, LF=\012, FF=\014, CR=\015 { DcmTag tag( elem->getTag() ); PutOffendingElements( tag ); errorComment->putString("Invalid Character Repertoire for datatype SH"); ok = OFFalse; } else return OFTrue; default: break; } return( ok ); } // ---------------------------------------------------------------------------- OFBool WlmDataSource::IsValidDateOrDateRange( const OFString& value ) // Date : March 19, 2002 // Author : Thomas Wilkens // Task : This function checks if the given value is a valid date or date range. // Parameters : value - [in] The value which shall be checked. // Return Value : OFTrue - The given value is a valid date or date range. // OFFalse - The given value is not a valid date or date range. { // create new string without leading or trailing blanks OFString dateRange = DeleteLeadingAndTrailingBlanks( value ); if (dateRange.length() == 0) return OFFalse; // check if only allowed characters occur in the string if( !ContainsOnlyValidCharacters( dateRange.c_str(), "0123456789.-" ) ) return( OFFalse ); // initialize return value OFBool isValidDateRange = OFFalse; // Determine if a hyphen occurs in the date range size_t hyphen = dateRange.find('-'); if( hyphen != OFString_npos ) { // determine if two date values are given or not if( dateRange[0] == '-' ) { // if the hyphen occurs at the beginning, there is just one date value which has to be checked for validity isValidDateRange = IsValidDate( dateRange.substr(1) ); } else if( dateRange[ dateRange.length() - 1 ] == '-' ) { // if the hyphen occurs at the end, there is just one date value which has to be checked for validity isValidDateRange = IsValidDate( dateRange.substr(0, dateRange.length() -1 )); } else { // in this case the hyphen occurs somewhere in between beginning and end; hence there are two date values // which have to be checked for validity. Determine where the hyphen occurs exactly // check both dates for validity if( IsValidDate( dateRange.substr(0, dateRange.length()-hyphen-1 )) && IsValidDate( dateRange.substr( hyphen + 1 )) ) { isValidDateRange = OFTrue; } } } else { // if there is no hyphen, there is just one date value which has to be checked for validity isValidDateRange = IsValidDate( dateRange ); } // return result return( isValidDateRange ); } // ---------------------------------------------------------------------------- OFBool WlmDataSource::IsValidDate( const OFString& value ) // Date : March 19, 2002 // Author : Thomas Wilkens // Task : This function checks if the given date value is valid. // According to the 2001 DICOM standard, part 5, Table 6.2-1, a date // value is either in format "yyyymmdd" or in format "yyyy.mm.dd", // so that e.g. "19840822" represents August 22, 1984. // Parameters : value - [in] The value which shall be checked. // Return Value : OFTrue - Date is valid. // OFFalse - Date is not valid. { int year=0, month=0, day=0; // create new string without leading or trailing blanks OFString date = DeleteLeadingAndTrailingBlanks( value ); // check parameter if( value.length() == 0 ) return( OFFalse ); // check if only allowed characters occur in the string if( !ContainsOnlyValidCharacters( date.c_str(), "0123456789." ) ) return( OFFalse ); // initialize return value OFBool isValidDate = OFFalse; // check which of the two formats applies to the given string if( date.length() == 8 ) { // scan given date string sscanf( date.c_str(), "%4d%2d%2d", &year, &month, &day ); if( year > 0 && month >= 1 && month <= 12 && day >= 1 && day <= 31 ) isValidDate = OFTrue; } else if( date.length() == 10 ) { // scan given date string sscanf( date.c_str(), "%4d.%2d.%2d", &year, &month, &day ); if( year > 0 && month >= 1 && month <= 12 && day >= 1 && day <= 31 ) isValidDate = OFTrue; } // return result return( isValidDate ); } // ---------------------------------------------------------------------------- OFBool WlmDataSource::IsValidTimeOrTimeRange( const OFString& value ) // Date : March 19, 2002 // Author : Thomas Wilkens // Task : This function checks if the given value is a valid time or time range. // Parameters : timeRange - [in] The value which shall be checked. // Return Value : OFTrue - The given value is a valid time or time range. // OFFalse - The given value is not a valid time or time range. { // create new string without leading or trailing blanks OFString timeRange = DeleteLeadingAndTrailingBlanks( value ); // check if string is empty now if( timeRange.length() == 0 ) return( OFFalse ); // check if only allowed characters occur in the string if( !ContainsOnlyValidCharacters( timeRange.c_str(), "0123456789.:-" ) ) return( OFFalse ); // Determine if a hyphen occurs in the time range size_t hyphen = timeRange.find('-'); if( hyphen != OFString_npos ) { // determine if two time values are given or not if( timeRange[0] == '-' ) { // if the hyphen occurs at the beginning, there is just one time value which has to be checked for validity return IsValidTime( timeRange.substr(1) ); } else if( timeRange[ timeRange.length() - 1 ] == '-' ) { // if the hyphen occurs at the end, there is just one time value which has to be checked for validity return IsValidTime( timeRange.substr(0, timeRange.length()-1) ); } else { // in this case the hyphen occurs somewhere in between beginning and end; hence there are two time values // which have to be checked for validity. // check both times for validity if( IsValidTime( timeRange.substr(0, timeRange.length() - hyphen -1 )) && IsValidTime( timeRange.substr( hyphen + 1 ) )) return OFTrue; } } else { // if there is no hyphen, there is just one date value which has to be checked for validity return IsValidTime( timeRange ); } return OFFalse; } // ---------------------------------------------------------------------------- OFBool WlmDataSource::IsValidTime( const OFString& value ) // Date : March 19, 2002 // Author : Thomas Wilkens // Task : This function checks if the given time value is valid. // According to the 2001 DICOM standard, part 5, Table 6.2-1, a time // value is either in format "hhmmss.fracxx" or "hh:mm:ss.fracxx" where // - hh represents the hour (0-23) // - mm represents the minutes (0-59) // - ss represents the seconds (0-59) // - fracxx represents the fraction of a second in millionths of seconds (000000-999999) // Note that one or more of the components mm, ss, or fracxx may be missing as // long as every component to the right of a missing component is also missing. // If fracxx is missing, the "." character in front of fracxx is also missing. // Parameters : value - [in] The value which shall be checked. // Return Value : OFTrue - Time is valid. // OFFalse - Time is not valid. { int hour=0, min=0, sec=0, frac=0, fieldsRead=0; // create new string without leading or trailing blanks OFString timevalue = DeleteLeadingAndTrailingBlanks( value ); // check if string is empty now if( timevalue.length() == 0) return( OFFalse ); // check if only allowed characters occur in the string if( !ContainsOnlyValidCharacters( timevalue.c_str(), "0123456789.:" ) ) return( OFFalse ); // check which of the two formats applies to the given string size_t colon = timevalue.find(':'); if( colon != OFString_npos ) { // time format is "hh:mm:ss.fracxx" // check which components are missing if( timevalue.length() == 5 ) { // scan given time string "hh:mm" fieldsRead = sscanf( timevalue.c_str(), "%2d:%2d", &hour, &min ); if( fieldsRead == 2 && hour >= 0 && hour <= 23 && min >= 0 && min <= 59 ) return OFTrue; } else if( timevalue.length() == 8 ) { // scan given time string "hh:mm:ss" fieldsRead = sscanf( timevalue.c_str(), "%2d:%2d:%2d", &hour, &min, &sec ); if( fieldsRead == 3 && hour >= 0 && hour <= 23 && min >= 0 && min <= 59 && sec >= 0 && sec <= 59 ) return OFTrue; } else if( timevalue.length() > 8 && timevalue.length() < 16 ) { // scan given time string "hh:mm:ss.fracxx" fieldsRead = sscanf( timevalue.c_str(), "%2d:%2d:%2d.%6d", &hour, &min, &sec, &frac ); if( fieldsRead == 4 && hour >= 0 && hour <= 23 && min >= 0 && min <= 59 && sec >= 0 && sec <= 59 && frac >= 0 && frac <= 999999 ) return OFTrue; } } else { // time format is "hhmmss.fracxx" // check which components are missing if( timevalue.length() == 4 ) { // scan given time string "hhmm" fieldsRead = sscanf( timevalue.c_str(), "%2d%2d", &hour, &min ); if( fieldsRead == 2 && hour >= 0 && hour <= 23 && min >= 0 && min <= 59 ) return OFTrue; } else if( timevalue.length() == 6 ) { // scan given time string "hhmmss" fieldsRead = sscanf( timevalue.c_str(), "%2d%2d%2d", &hour, &min, &sec ); if( fieldsRead == 3 && hour >= 0 && hour <= 23 && min >= 0 && min <= 59 && sec >= 0 && sec <= 59 ) return OFTrue; } else if( timevalue.length() > 6 && timevalue.length() < 14 ) { // scan given time string "hhmmss.fracxx" fieldsRead = sscanf( timevalue.c_str(), "%2d%2d%2d.%6d", &hour, &min, &sec, &frac ); if( fieldsRead == 4 && hour >= 0 && hour <= 23 && min >= 0 && min <= 59 && sec >= 0 && sec <= 59 && frac >= 0 && frac <= 999999 ) return OFTrue; } } return OFFalse; } // ---------------------------------------------------------------------------- OFBool WlmDataSource::ContainsOnlyValidCharacters( const char *s, const char *charset ) // Date : December 10, 2001 // Author : Thomas Wilkens // Task : This function returns OFTrue if all the characters of s can be found // in the string charset. // Parameters : s - [in] String which shall be checked. // charset - [in] Possible character set for s. (valid pointer expected.) // Return Value : This function returns OFTrue if all the characters of s can be found // in the string charset. If s equals NULL, OFTrue will be returned. { OFBool result = OFTrue; // check parameter if( s == NULL ) { return OFTrue; } // return OFTrue if all the characters of s can be found in the string charset. int s_len = strlen( s ); int charset_len = strlen( charset ); for( int i=0 ; i<s_len && result ; i++ ) { OFBool isSetMember = OFFalse; for( int j=0 ; !isSetMember && j<charset_len ; j++ ) { if( s[i] == charset[j] ) isSetMember = OFTrue; } if( !isSetMember ) result = OFFalse; } return( result ); } // ---------------------------------------------------------------------------- OFString WlmDataSource::DeleteLeadingAndTrailingBlanks( const OFString& value ) // Date : March 19, 2002 // Author : Thomas Wilkens // Task : This function makes a copy of value without leading and trailing blanks. // Parameters : value - [in] The source string. // Return Value : A copy of the given string without leading and trailing blanks. { OFString returnValue = value; size_t pos = 0; // delete leading blanks while ( (returnValue.length() > 0) && (returnValue[pos] == ' ') ) pos++; // count blanks if (pos > 0) returnValue.erase(0, pos); // delete trailing blanks, start from end of string pos = returnValue.length() - 1; while ( (returnValue.length() > 0) && (returnValue[pos] == ' ') ) pos--; if (pos < returnValue.length() -1) returnValue.erase(pos); return returnValue; } // ---------------------------------------------------------------------------- OFBool WlmDataSource::GetStringValue( const DcmElement *elem, OFString& resultVal ) // Date : December 10, 2001 // Author : Thomas Wilkens // Task : This function returns the value of the given DICOM string element (attribute) // in the parameter resultVal and returns OFTrue if successful. // If the element does not refer to a string attribute or contains no value, // OFFalse is returned. // Parameters : elem - [in] The DICOM element. // resultVal - [out] The resulting string value // Return Value : OFTrue if string value could be accessed, OFFalse else { DcmElement *elemNonConst = OFconst_cast(DcmElement*, elem); OFCondition result = elemNonConst->getOFStringArray( resultVal ); if (result.bad() || resultVal.length() == 0) return OFFalse; return OFTrue; } // ---------------------------------------------------------------------------- DcmAttributeTag *WlmDataSource::GetOffendingElements() // Date : December 10, 2001 // Author : Thomas Wilkens // Task : This function returns offending elements from member variable offendingElements // if there are any. // Parameters : none. // Return Value : Pointer to offending elements or NULL if there are none. { if( offendingElements->getLength() == 0 ) return NULL; else return offendingElements; } // ---------------------------------------------------------------------------- DcmLongString *WlmDataSource::GetErrorComments() // Date : December 10, 2001 // Author : Thomas Wilkens // Task : This function returns error comments from member variable errorComment // if there are any. // Parameters : none. // Return Value : Pointer to error comments or NULL if there are none. { if( errorComment->getLength() == 0 ) return NULL; else return errorComment; } // ---------------------------------------------------------------------------- WlmDataSourceStatusType WlmDataSource::CancelFindRequest() // Date : December 10, 2001 // Author : Thomas Wilkens // Task : This function handles a C-CANCEL Request during the processing of a C-FIND Request. // In detail, in case there are still matching datasets captured in member variable // matchingDatasets, memory for these datasets (and the array itself) is freed and // all pointers are set to NULL. // Parameters : none. // Return Value : WLM_CANCEL. { // remove all remaining datasets from result list while (!matchingDatasets.empty()) { DcmDataset *dset = matchingDatasets.front(); delete dset; dset = NULL; matchingDatasets.pop_front(); } // return WLM_CANCEL return WLM_CANCEL; } // ---------------------------------------------------------------------------- OFBool WlmDataSource::IsSupportedMatchingKeyAttribute( DcmElement *element, DcmSequenceOfItems *supSequenceElement ) // Date : December 12, 2001 // Author : Thomas Wilkens // Task : This function checks if the given element refers to an attribute which is a supported // matching key attribute. If this is the case OFTrue is returned, else OFFalse. // Currently, the following attributes are supported as matching keys: // DCM_ScheduledProcedureStepSequence (0040,0100) SQ R 1 // > DCM_ScheduledStationAETitle (0040,0001) AE R 1 // > DCM_ScheduledProcedureStepStartDate (0040,0002) DA R 1 // > DCM_ScheduledProcedureStepStartTime (0040,0003) TM R 1 // > DCM_Modality (0008,0060) CS R 1 // > DCM_ScheduledPerformingPhysicianName (0040,0006) PN R 2 // DCM_PatientName (0010,0010) PN R 1 // DCM_PatientID (0010,0020) LO R 1 // DCM_AccessionNumber (0008,0050) SH O 2 // DCM_RequestedProcedureID (0040,1001) SH O 1 // DCM_ReferringPhysicianName (0008,0090) PN O 2 // DCM_PatientSex (0010,0040) CS O 2 // DCM_RequestingPhysician (0032,1032) PN O 2 // DCM_AdmissionID (0038,0010) LO O 2 // DCM_RequestedProcedurePriority (0040,1003) SH O 2 // DCM_PatientBirthDate (0010,0030) DA O 2 // Parameters : element - [in] Pointer to the element which shall be checked. // supSequenceElement - [in] Pointer to the superordinate sequence element of which // the currently processed element is an attribute, or NULL if // the currently processed element does not belong to any sequence. // Return Value : OFTrue - The given tag is a supported matching key attribute. // OFFalse - The given tag is not a supported matching key attribute. { DcmTagKey elementKey, supSequenceElementKey; // determine the current element's tag elementKey = element->getTag().getXTag(); // determine the sequence element's tag, if there is one if( supSequenceElement != NULL ) supSequenceElementKey = supSequenceElement->getTag().getXTag(); // initialize result variable OFBool isSupportedMatchingKeyAttribute = OFFalse; // perform check, depending on if a superordinate sequence element is given or not if( supSequenceElement != NULL ) { if( supSequenceElementKey == DCM_ScheduledProcedureStepSequence && ( elementKey == DCM_ScheduledStationAETitle || elementKey == DCM_ScheduledProcedureStepStartDate || elementKey == DCM_ScheduledProcedureStepStartTime || elementKey == DCM_Modality || elementKey == DCM_ScheduledPerformingPhysicianName ) ) isSupportedMatchingKeyAttribute = OFTrue; } else { if( elementKey == DCM_ScheduledProcedureStepSequence || elementKey == DCM_PatientName || elementKey == DCM_PatientID || elementKey == DCM_AccessionNumber || elementKey == DCM_RequestedProcedureID || elementKey == DCM_ReferringPhysicianName || elementKey == DCM_PatientSex || elementKey == DCM_RequestingPhysician || elementKey == DCM_AdmissionID || elementKey == DCM_RequestedProcedurePriority || elementKey == DCM_PatientBirthDate ) isSupportedMatchingKeyAttribute = OFTrue; } // return result return( isSupportedMatchingKeyAttribute ); } // ---------------------------------------------------------------------------- OFBool WlmDataSource::IsSupportedReturnKeyAttribute( DcmElement *element, DcmSequenceOfItems *supSequenceElement ) // Date : December 12, 2001 // Author : Thomas Wilkens // Task : This function checks if the given element refers to an attribute which is a supported // return key attribute. If this is the case OFTrue is returned, else OFFalse. // Currently, the following attributes are supported as return keys: // DCM_ScheduledProcedureStepSequence (0040,0100) SQ R 1 // > DCM_ScheduledStationAETitle (0040,0001) AE R 1 // > DCM_ScheduledProcedureStepStartDate (0040,0002) DA R 1 // > DCM_ScheduledProcedureStepStartTime (0040,0003) TM R 1 // > DCM_Modality (0008,0060) CS R 1 // > DCM_ScheduledPerformingPhysicianName (0040,0006) PN R 2 // > DCM_ScheduledProcedureStepDescription (0040,0007) LO O 1 // > DCM_ScheduledStationName (0040,0010) SH O 2 // > DCM_ScheduledProcedureStepLocation (0040,0011) SH O 2 // > DCM_PreMedication (0040,0012) LO O 2 // > DCM_ScheduledProcedureStepID (0040,0009) SH O 1 // > DCM_RequestedContrastAgent (0032,1070) LO O 2 // > DCM_CommentsOnTheScheduledProcedureStep (0040,0400) LT O 3 (from the Scheduled Procedure Step Module) // > DCM_ScheduledProcedureStepStatus (0040,0020) CS O 3 // > DCM_ScheduledProcedureStepEndDate (0040,0004) DA O 3 (from the Scheduled Procedure Step Module) // > DCM_ScheduledProcedureStepEndTime (0040,0005) TM O 3 (from the Scheduled Procedure Step Module) // > DCM_ScheduledProtocolCodeSequence (0040,0008) SQ O 1C // > > DCM_CodeValue (0008,0100) SH O 1C // > > DCM_CodingSchemeVersion (0008,0103) SH O 3 // > > DCM_CodingSchemeDesignator (0080,0102) SH O 1C // > > DCM_CodeMeaning (0080,0104) LO O 3 // DCM_RequestedProcedureID (0040,1001) SH O 1 // DCM_RequestedProcedureDescription (0032,1060) LO O 1 // DCM_StudyInstanceUID (0020,000d) UI O 1 // DCM_StudyDate (0008,0020) DA O 3 // DCM_StudyTime (0008,0030) TM O 3 // DCM_ReferencedStudySequence (0008,1110) SQ O 2 // > DCM_ReferencedSOPClassUID (0008,1150) UI O 1 // > DCM_ReferencedSOPInstanceUID (0008,1155) UI O 1 // DCM_RequestedProcedurePriority (0040,1003) SH O 2 // DCM_PatientTransportArrangements (0040,1004) LO O 2 // DCM_AccessionNumber (0008,0050) SH O 2 // DCM_RequestingPhysician (0032,1032) PN O 2 // DCM_ReferringPhysicianName (0008,0090) PN O 2 // DCM_AdmissionID (0038,0010) LO O 2 // DCM_CurrentPatientLocation (0038,0300) LO O 2 // DCM_ReferencedPatientSequence (0008,1120) SQ O 2 // > DCM_ReferencedSOPClassUID (0008,1150) UI O 2 // > DCM_ReferencedSOPInstanceUID (0008,1155) UI O 2 // DCM_PatientName (0010,0010) PN R 1 // DCM_PatientID (0010,0020) LO R 1 // DCM_IssuerOfPatientID (0010,0021) LO O 3 (from the Patient Identification Module) // DCM_PatientBirthDate (0010,0030) DA O 2 // DCM_PatientSex (0010,0040) CS O 2 // DCM_PatientWeight (0010,1030) DS O 2 // DCM_ConfidentialityConstraintOnPatientDataDescription (0040,3001) LO O 2 // DCM_PatientState (0038,0500) LO O 2 // DCM_PregnancyStatus (0010,21c0) US O 2 // DCM_MedicalAlerts (0010,2000) LO O 2 // DCM_ContrastAllergies (0010,2110) LO O 2 // DCM_SpecialNeeds (0038,0050) LO O 2 // DCM_NamesOfIntendedRecipientsOfResults (0040,1010) PN O 3 (from the Requested Procedure Module) // DCM_InstitutionName (0008,0080) LO O 3 (from the Visit Identification Module) // DCM_AdmittingDiagnosesDescription (0008,1080) LO O 3 (from the Visit Admission Module) // DCM_OtherPatientIDs (0010,1000) LO O 3 (from the Patient Identification Module) // DCM_PatientSize (0010,1020) DS O 3 (from the Patient Demographic Module) // DCM_EthnicGroup (0010,2160) SH O 3 (from the Patient Demographic Module) // DCM_PatientComments (0010,4000) LT O 3 (from the Patient Demographic Module) // DCM_AdditionalPatientHistory (0010,21b0) LT O 3 (from the Patient Medical Module) // DCM_LastMenstrualDate (0010,21d0) DA O 3 (from the Patient Medical Module) // DCM_InstitutionAddress (0008,0081) ST O 3 (from the Visit Identification Module) // DCM_OtherPatientNames (0010,1001) PN O 3 (from the Patient Identification Module) // DCM_PatientAddress (0010,1040) LO O 3 (from the Patient Demographic Module) // DCM_MilitaryRank (0010,1080) LO O 3 (from the Patient Demographic Module) // DCM_SmokingStatus (0010,21a0) CS O 3 (from the Patient Medical Module) // DCM_RequestingService (0032,1033) LO O 3 (from the Imaging Service Request Module) // DCM_RETIRED_IssuerOfAdmissionID (0038,0011) LO O 3 (from the Visit Identification Module) // DCM_ReasonForTheRequestedProcedure (0040,1002) LO O 3 (from the Requested Procedure Module) // DCM_RequestedProcedureLocation (0040,1005) LO O 3 (from the Requested Procedure Module) // DCM_ConfidentialityCode (0040,1008) LO O 3 (from the Requested Procedure Module) // DCM_ReportingPriority (0040,1009) SH O 3 (from the Requested Procedure Module) // DCM_RequestedProcedureComments (0040,1400) LT O 3 (from the Requested Procedure Module) // DCM_RETIRED_ReasonForTheImagingServiceRequest (0040,2001) LO O 3 (from the Imaging Service Request Module) // DCM_IssueDateOfImagingServiceRequest (0040,2004) DA O 3 (from the Imaging Service Request Module) // DCM_IssueTimeOfImagingServiceRequest (0040,2005) TM O 3 (from the Imaging Service Request Module) // DCM_OrderEnteredBy (0040,2008) PN O 3 (from the Imaging Service Request Module) // DCM_OrderEnterersLocation (0040,2009) SH O 3 (from the Imaging Service Request Module) // DCM_OrderCallbackPhoneNumber (0040,2010) SH O 3 (from the Imaging Service Request Module) // DCM_PlacerOrderNumberImagingServiceRequest (0040,2016) LO O 3 (from the Imaging Service Request Module) // DCM_FillerOrderNumberImagingServiceRequest (0040,2017) LO O 3 (from the Imaging Service Request Module) // DCM_ImagingServiceRequestComments (0040,2400) LT O 3 (from the Imaging Service Request Module) // DCM_RequestedProcedureCodeSequence (0032,1064) SQ O 3 (from the Requested Procedure Module) // > DCM_CodeValue (0008,0100) SH O 1C // > DCM_CodingSchemeVersion (0008,0103) SH O 3 // > DCM_CodingSchemeDesignator (0080,0102) SH O 1C // > DCM_CodeMeaning (0080,0104) LO O 3 // Parameters : element - [in] Pointer to the element which shall be checked. // supSequenceElement - [in] Pointer to the superordinate sequence element of which // the currently processed element is an attribute, or NULL if // the currently processed element does not belong to any sequence. // Return Value : OFTrue - The given tag is a supported return key attribute. // OFFalse - The given tag is not a supported return key attribute. { DcmTagKey elementKey, supSequenceElementKey; // determine the current element's tag elementKey = element->getTag().getXTag(); // determine the sequence element's tag, if there is one if( supSequenceElement != NULL ) supSequenceElementKey = supSequenceElement->getTag().getXTag(); // initialize result variable OFBool isSupportedReturnKeyAttribute = OFFalse; // perform check, depending on if a superordinate sequence element is given or not if( supSequenceElement != NULL ) { if( ( supSequenceElementKey == DCM_ScheduledProcedureStepSequence && ( elementKey == DCM_ScheduledStationAETitle || elementKey == DCM_ScheduledProcedureStepStartDate || elementKey == DCM_ScheduledProcedureStepStartTime || elementKey == DCM_Modality || elementKey == DCM_ScheduledPerformingPhysicianName || elementKey == DCM_ScheduledProcedureStepDescription || elementKey == DCM_ScheduledStationName || elementKey == DCM_ScheduledProcedureStepLocation || elementKey == DCM_PreMedication || elementKey == DCM_ScheduledProcedureStepID || elementKey == DCM_RequestedContrastAgent || elementKey == DCM_CommentsOnTheScheduledProcedureStep || elementKey == DCM_ScheduledProcedureStepStatus || elementKey == DCM_ScheduledProcedureStepEndDate || elementKey == DCM_ScheduledProcedureStepEndTime || elementKey == DCM_ScheduledProtocolCodeSequence ) ) || ( supSequenceElementKey == DCM_ReferencedStudySequence && ( elementKey == DCM_ReferencedSOPClassUID || elementKey == DCM_ReferencedSOPInstanceUID ) ) || ( supSequenceElementKey == DCM_ReferencedPatientSequence && ( elementKey == DCM_ReferencedSOPClassUID || elementKey == DCM_ReferencedSOPInstanceUID ) ) || ( supSequenceElementKey == DCM_ScheduledProtocolCodeSequence && ( elementKey == DCM_CodeValue || elementKey == DCM_CodingSchemeVersion || elementKey == DCM_CodingSchemeDesignator || elementKey == DCM_CodeMeaning ) ) || ( supSequenceElementKey == DCM_RequestedProcedureCodeSequence && ( elementKey == DCM_CodeValue || elementKey == DCM_CodingSchemeVersion || elementKey == DCM_CodingSchemeDesignator || elementKey == DCM_CodeMeaning ) ) ) isSupportedReturnKeyAttribute = OFTrue; } else { if( elementKey == DCM_ScheduledProcedureStepSequence || elementKey == DCM_RequestedProcedureID || elementKey == DCM_RequestedProcedureDescription || elementKey == DCM_StudyInstanceUID || elementKey == DCM_StudyDate || elementKey == DCM_StudyTime || elementKey == DCM_ReferencedStudySequence || elementKey == DCM_RequestedProcedurePriority || elementKey == DCM_PatientTransportArrangements || elementKey == DCM_AccessionNumber || elementKey == DCM_RequestingPhysician || elementKey == DCM_ReferringPhysicianName || elementKey == DCM_AdmissionID || elementKey == DCM_CurrentPatientLocation || elementKey == DCM_ReferencedPatientSequence || elementKey == DCM_PatientName || elementKey == DCM_PatientID || elementKey == DCM_IssuerOfPatientID || elementKey == DCM_PatientBirthDate || elementKey == DCM_PatientSex || elementKey == DCM_PatientWeight || elementKey == DCM_ConfidentialityConstraintOnPatientDataDescription || elementKey == DCM_PatientState || elementKey == DCM_PregnancyStatus || elementKey == DCM_MedicalAlerts || elementKey == DCM_Allergies || elementKey == DCM_SpecialNeeds || elementKey == DCM_NamesOfIntendedRecipientsOfResults || elementKey == DCM_InstitutionName || elementKey == DCM_AdmittingDiagnosesDescription || elementKey == DCM_OtherPatientIDs || elementKey == DCM_PatientSize || elementKey == DCM_EthnicGroup || elementKey == DCM_PatientComments || elementKey == DCM_AdditionalPatientHistory || elementKey == DCM_LastMenstrualDate || elementKey == DCM_InstitutionAddress || elementKey == DCM_OtherPatientNames || elementKey == DCM_PatientAddress || elementKey == DCM_MilitaryRank || elementKey == DCM_SmokingStatus || elementKey == DCM_RequestingService || elementKey == DCM_RETIRED_IssuerOfAdmissionID || elementKey == DCM_ReasonForTheRequestedProcedure || elementKey == DCM_RequestedProcedureLocation || elementKey == DCM_ConfidentialityCode || elementKey == DCM_ReportingPriority || elementKey == DCM_RequestedProcedureComments || elementKey == DCM_RETIRED_ReasonForTheImagingServiceRequest || elementKey == DCM_IssueDateOfImagingServiceRequest || elementKey == DCM_IssueTimeOfImagingServiceRequest || elementKey == DCM_OrderEnteredBy || elementKey == DCM_OrderEntererLocation || elementKey == DCM_OrderCallbackPhoneNumber || elementKey == DCM_PlacerOrderNumberImagingServiceRequest || elementKey == DCM_FillerOrderNumberImagingServiceRequest || elementKey == DCM_ImagingServiceRequestComments || elementKey == DCM_RequestedProcedureCodeSequence ) isSupportedReturnKeyAttribute = OFTrue; } // return result return( isSupportedReturnKeyAttribute ); }
{ "content_hash": "016767f262e269bb87814c1de0231431", "timestamp": "", "source": "github", "line_count": 1420, "max_line_length": 251, "avg_line_length": 51.40845070422535, "alnum_prop": 0.5736849315068493, "repo_name": "NCIP/annotation-and-image-markup", "id": "eeb4c8df474f608d2f0c8b4676aee46dcf4a6c46", "size": "73422", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AIMToolkit_v4.0.0_rv44/source/dcmtk-3.6.1_20121102/dcmwlm/libsrc/wlds.cc", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "31363450" }, { "name": "C#", "bytes": "5152916" }, { "name": "C++", "bytes": "148605530" }, { "name": "CSS", "bytes": "85406" }, { "name": "Java", "bytes": "2039090" }, { "name": "Objective-C", "bytes": "381107" }, { "name": "Perl", "bytes": "502054" }, { "name": "Shell", "bytes": "11832" }, { "name": "Tcl", "bytes": "30867" } ], "symlink_target": "" }
// type definitions on DefinitelyTyped are missing the w3cwebsocket definitions declare module 'websocket' { export class w3cwebsocket { // tslint:disable-line constructor(url: string); onopen(): void; onclose: (() => void) | null; onmessage(event: {data: string}): void; send(message: string): void; close(): void; CONNECTING: string; OPEN: string; readyState: string; } } import { w3cwebsocket as WebSocket } from 'websocket'; /** * Connection to the backend. * * The standard template is to create a connection first, then use it to * wire all UI elements, to add custom callback functions and at last to run * [[Connection.connect]] to create a WebSocket connection to the backend * server (see example below). * * The other two essential functions to know about are * [[Connection.on]] and [[Connection.emit]]. * * Logging across frontend and backend can be done by emitting `log`, * `warn` or `error`, e.g. `emit('log', 'Hello World')`. * * ```js * var databench = new Databench.Connection(); * Databench.ui.wire(databench); * * * // put custom databench.on() methods here * * * databench.connect(); * ``` */ export class Connection { wsUrl: string; requestArgs?: string; analysisId?: string; databenchBackendVersion?: string; analysesVersion?: string; errorCB: (message?: string) => void; private onCallbacks: {[field: string]: ((message: any, signal?: string) => void)[]}; private onProcessCallbacks: {[field: string]: ((status: any) => void)[]}; private preEmitCallbacks: {[field: string]: ((message: any) => any)[]}; private connectCallback: (connection: Connection) => void; private wsReconnectAttempt: number; private wsReconnectDelay: number; private socket?: WebSocket; private socketCheckOpen?: number; /** * @param wsUrl URL of WebSocket endpoint or undefined to guess it. * @param requestArgs `search` part of request url or undefined to take from * `window.location.search`. * @param analysisId Specify an analysis id or undefined to have one generated. * The connection will try to connect to a previously created * analysis with that id. */ constructor(wsUrl?: string, requestArgs?: string, analysisId?: string) { this.wsUrl = wsUrl || Connection.guessWSUrl(); this.requestArgs = (!requestArgs && (typeof window !== 'undefined')) ? window.location.search : requestArgs; this.analysisId = analysisId; this.errorCB = msg => (msg != null ? console.log(`connection error: ${msg}`) : null); this.onCallbacks = {}; this.onProcessCallbacks = {}; this.preEmitCallbacks = {}; this.connectCallback = connection => {}; this.wsReconnectAttempt = 0; this.wsReconnectDelay = 100.0; // wire log, warn, error messages into console outputs ['log', 'warn', 'error'].forEach(wireSignal => { this.on(wireSignal, message => console[wireSignal]('backend: ', message)); this.preEmit(wireSignal, message => { console[wireSignal]('frontend: ', message); return message; }); }); } static guessWSUrl(): string { if (typeof location === 'undefined') return ''; const WSProtocol = location.origin.indexOf('https://') === 0 ? 'wss' : 'ws'; const path = location.pathname.substring(0, location.pathname.lastIndexOf('/')); return `${WSProtocol}://${document.domain}:${location.port}${path}/ws`; } /** initialize connection */ connect(callback?: (connection: Connection) => void): Connection { if (!this.wsUrl) throw Error('Need a wsUrl.'); this.connectCallback = callback ? callback : () => this; this.socket = new WebSocket(this.wsUrl); this.socketCheckOpen = setInterval(this.wsCheckOpen.bind(this), 2000); this.socket.onopen = this.wsOnOpen.bind(this); this.socket.onclose = this.wsOnClose.bind(this); this.socket.onmessage = this.wsOnMessage.bind(this); return this; } /** close connection */ disconnect() { if (this.socketCheckOpen) { clearInterval(this.socketCheckOpen); this.socketCheckOpen = undefined; } if (this.socket) { this.socket.onclose = null; this.socket.close(); this.socket = undefined; } } wsCheckOpen() { if (!this.socket) return; if (this.socket.readyState === this.socket.CONNECTING) { return; } if (this.socket.readyState !== this.socket.OPEN) { this.errorCB( 'Connection could not be opened. ' + 'Please <a href="javascript:location.reload(true);" ' + 'class="alert-link">reload</a> this page to try again.' ); } if (this.socketCheckOpen) { clearInterval(this.socketCheckOpen); this.socketCheckOpen = undefined; } } wsOnOpen() { if (!this.socket) return; this.wsReconnectAttempt = 0; this.wsReconnectDelay = 100.0; this.errorCB(); // clear errors this.socket.send(JSON.stringify({ __connect: this.analysisId ? this.analysisId : null, __request_args: this.requestArgs, // eslint-disable-line camelcase })); } wsOnClose() { if (this.socketCheckOpen) { clearInterval(this.socketCheckOpen); this.socketCheckOpen = undefined; } this.wsReconnectAttempt += 1; this.wsReconnectDelay *= 2; if (this.wsReconnectAttempt > 5) { this.errorCB( 'Connection closed. ' + 'Please <a href="javascript:location.reload(true);" ' + 'class="alert-link">reload</a> this page to reconnect.' ); return; } const actualDelay = 0.7 * this.wsReconnectDelay + 0.3 * Math.random() * this.wsReconnectDelay; console.log(`WebSocket reconnect attempt ${this.wsReconnectAttempt} ` + `in ${actualDelay.toFixed(0)}ms.`); setTimeout(this.connect.bind(this), actualDelay); } /** * Trigger all callbacks for this signal with this message. * @param signal Name of the signal to trigger. * @param message Payload for the triggered signal. */ trigger(signal: string, message?: any) { this.onCallbacks[signal].forEach(cb => cb(message, signal)); } wsOnMessage(event: {data: string}) { const message = JSON.parse(event.data); // connect response if (message.signal === '__connect') { this.analysisId = message.load.analysis_id; this.databenchBackendVersion = message.load.databench_backend_version; const newVersion = message.load.analyses_version; if (this.analysesVersion && this.analysesVersion !== newVersion) { location.reload(); } this.analysesVersion = newVersion; this.connectCallback(this); } // processes if (message.signal === '__process') { const id = message.load.id; const status = message.load.status; this.onProcessCallbacks[id].forEach(cb => cb(status)); } // normal message if (message.signal in this.onCallbacks) { this.trigger(message.signal, message.load); } } /** * Register a callback that listens for a signal. * * The signal can be a simple string (the name for a signal/action), but it * can also be an Object of the form `{data: 'current_value'}` which would * trigger on `data` actions that are sending a JSON dictionary that contains * the key `current_value`. In this case, the value that is * given to the callback function is the value assigned to `current_value`. * * ~~~ * d.on('data', value => { console.log(value); }); * // If the backend sends an action called 'data' with a message * // {current_value: 3.0}, this function would log `{current_value: 3.0}`. * ~~~ * * ~~~ * d.on({data: 'current_value'}, value => { console.log(value); }); * // If the backend sends an action called 'data' with a * // message {current_value: 3.0}, this function would log `3.0`. * // This callback is not triggered when the message does not contain a * // `current_value` key. * ~~~ * * @param signal Signal name to listen for. * @param callback A callback function that takes the attached data. */ on(signal: string|{[field: string]: string}|{[field: string]: RegExp}, callback: (message: any, key?: string) => void): Connection { if (typeof signal === 'object') { this._on_object(signal, callback); return this; } if (!(signal in this.onCallbacks)) this.onCallbacks[signal] = []; this.onCallbacks[signal].push(callback); return this; } /** * Listen for a signal once. * * Similar to [on] but returns a `Promise` instead of taking a callback. * This is mostly useful for unit tests. * * @param signal Signal name to listen for. */ once(signal: string|{[field: string]: string}|{[field: string]: RegExp}): Promise<{message: any, key?: string}> { return new Promise(resolve => { this.on(signal, resolve); }); } _on_object(signal: {[field: string]: string}|{[field: string]: RegExp}, callback: (message: any, key?: string) => void): Connection { Object.keys(signal).forEach(signalName => { const entryName = signal[signalName]; const filteredCallback = (data: any, signalName: string) => { Object.keys(data).forEach(dataKey => { if (dataKey.match(entryName) === null) return; callback(data[dataKey], dataKey); }); }; this.on(signalName, filteredCallback); }); return this; } /** * Set a pre-emit hook. * @param signalName A signal name. * @param callback Callback function. */ preEmit(signalName: string, callback: (message: any) => any): Connection { if (!(signalName in this.preEmitCallbacks)) this.preEmitCallbacks[signalName] = []; this.preEmitCallbacks[signalName].push(callback); return this; } /** * Emit a signal/action to the backend. * @param signalName A signal name. Usually an action name. * @param message Payload attached to the action. */ emit(signalName: string, message?: any): Connection { // execute preEmit hooks before sending message to backend if (signalName in this.preEmitCallbacks) { this.preEmitCallbacks[signalName].forEach(cb => { message = cb(message); }); } // socket will never be open if (!this.socket) return this; // socket is not open yet if (this.socket.readyState !== this.socket.OPEN) { setTimeout(() => this.emit(signalName, message), 5); return this; } // send to backend this.socket.send(JSON.stringify({ signal: signalName, load: message })); return this; } onProcess(processID: number, callback: (message: any) => void): Connection { if (!(processID in this.onProcessCallbacks)) { this.onProcessCallbacks[processID] = []; } this.onProcessCallbacks[processID].push(callback); return this; } } /** * Create a Connection and immediately connect to it. * * This is a shorthand for * ~~~ * new Connection(wsUrl, requestArgs, analysisId).connect(); * ~~~ * * Use this function in tests where you know that `connect()` will not trigger * any callbacks that you should listen to. In regular code, it is better * to define all `on` callbacks before calling `connect()` and so this * shorthand should not be used. * * @param wsUrl URL of WebSocket endpoint or undefined to guess it. * @param requestArgs `search` part of request url or undefined to take from * `window.location.search`. * @param analysisId Specify an analysis id or undefined to have one generated. * The connection will try to connect to a previously created * analysis with that id. * @param callback Called when connection is established. */ export function connect(wsUrl?: string, requestArgs?: string, analysisId?: string, callback?: (connection: Connection) => void) { return new Connection(wsUrl, requestArgs, analysisId).connect(callback); } /** * Attach to a backend. * * Similar to [connect](globals.html#connect). Instead of a callback parameter, it * returns a Promise that resolves to a [[Connection]] instance once the connection is * established. * * @param wsUrl URL of WebSocket endpoint or undefined to guess it. * @param requestArgs `search` part of request url or undefined to take from * `window.location.search`. * @param analysisId Specify an analysis id or undefined to have one generated. * The connection will try to connect to a previously created * analysis with that id. */ export function attach(wsUrl?: string, requestArgs?: string, analysisId?: string): Promise<Connection> { const connection = new Connection(wsUrl, requestArgs, analysisId); return new Promise((resolve) => connection.connect(resolve)); }
{ "content_hash": "38e7dc9106e94132d018c4e0b1a9d33b", "timestamp": "", "source": "github", "line_count": 383, "max_line_length": 129, "avg_line_length": 33.87467362924282, "alnum_prop": 0.6428241097579775, "repo_name": "svenkreiss/databench", "id": "9dde867afad0c93ca193896ae2426dceebfb52e5", "size": "12974", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "js/src/connection.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2636" }, { "name": "HTML", "bytes": "9991" }, { "name": "JavaScript", "bytes": "2842" }, { "name": "Python", "bytes": "110972" }, { "name": "TypeScript", "bytes": "46737" } ], "symlink_target": "" }
using System; using System.Linq; using Hudl.FFmpeg.Attributes; using Hudl.FFmpeg.Enums; using Hudl.FFmpeg.Settings.Interfaces; using Hudl.FFmpeg.Settings.Utility; namespace Hudl.FFmpeg.Common { /// <summary> /// helper class that helps with validation of objects in a ffmpeg project /// </summary> public class Validate { /// <summary> /// returns a boolean indicating if <cref name="objectType"/> is applicable to <cref name="restrictedType"/> /// </summary> public static bool ContainsStream(Type objectType, Type streamType) { var matchingAttributes = AttributeRetrieval.GetAttributes<ContainsStreamAttribute>(objectType); if (matchingAttributes.Count == 0) { return false; } return matchingAttributes.Any(attribute => (attribute.Type == streamType || attribute.Type.IsAssignableFrom(streamType))); } public static bool IsSettingFor<TSetting>(TSetting item, SettingsCollectionResourceType type) where TSetting : ISetting { return item.GetResourceType() == SettingsCollectionResourceType.Any || type == item.GetResourceType(); } } }
{ "content_hash": "909d5fddc8865bfe1d70fe32686fed8d", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 117, "avg_line_length": 34.44736842105263, "alnum_prop": 0.6172650878533231, "repo_name": "hudl/HudlFfmpeg", "id": "007f075fb2af0ed7ea2d53976f66d36bbe6e8709", "size": "1311", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Hudl.FFmpeg/Common/Validate.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "471695" }, { "name": "Smalltalk", "bytes": "469" } ], "symlink_target": "" }
namespace umath { vector3::vector3() : x(0), y(0),z(0) {} vector3::vector3(const vector3& vec3) : x(vec3.x), y(vec3.y), z(vec3.z) {} vector3::vector3(float X, float Y, float Z) : x(X), y(Y), z(Z) {} vector3::~vector3(){} float vector3::getLengthSquared() const { return pow(x,2) + pow(y,2) + pow(z,2); } float vector3::getLength() const { return sqrt(getLengthSquared()); } const float& vector3::operator [](const unsigned int& index) const { return (&x)[index]; } float& vector3::operator [](const unsigned int& index) { return (&x)[index]; } vector3 operator -(const vector3& RightVal) { return vector3(-RightVal.x, -RightVal.y,-RightVal.z); } vector3 operator +(const vector3& LeftVal,const vector3& RightVal) { return vector3(LeftVal.x+RightVal.x,LeftVal.y+RightVal.y,LeftVal.z+RightVal.z); } vector3 operator -(const vector3& LeftVal,const vector3& RightVal) { return vector3(LeftVal.x-RightVal.x,LeftVal.y-RightVal.y,LeftVal.z-RightVal.z); } const vector3& operator +=(vector3& LeftVal,const vector3& RightVal) { LeftVal.x += RightVal.x; LeftVal.y += RightVal.y; LeftVal.z += RightVal.z; return LeftVal; } const vector3& operator -=(vector3& LeftVal,const vector3& RightVal) { LeftVal.x -= RightVal.x; LeftVal.y -= RightVal.y; LeftVal.z -= RightVal.z; return LeftVal; } vector3 operator /(const vector3& LeftVal, const float& RightVal) { return vector3(LeftVal.x / RightVal,LeftVal.y / RightVal, LeftVal.z / RightVal); } const vector3& operator /=(vector3& LeftVal, const float& RightVal) { LeftVal.x /= (float)RightVal; LeftVal.y /= (float)RightVal; LeftVal.z /= (float)RightVal; return LeftVal; } bool operator ==(const vector3& LeftVal,const vector3& RightVal) { if (LeftVal.x == RightVal.x && LeftVal.y == RightVal.y && LeftVal.z == RightVal.z) return true; return false; } bool operator !=(const vector3& LeftVal,const vector3& RightVal) { return !(LeftVal == RightVal); } vector3 operator *(const vector3& LeftVal, const float& RightVal) { return vector3(LeftVal.x * RightVal,LeftVal.y * RightVal, LeftVal.z * RightVal); } vector3 operator *(const float& LeftVal, const vector3& RightVal) { return vector3(LeftVal * RightVal.x,LeftVal * RightVal.y, LeftVal * RightVal.z); } const vector3& operator *=(vector3& LeftVal,const float& RightVal) { LeftVal.x *= RightVal; LeftVal.y *= RightVal; LeftVal.z *= RightVal; return LeftVal; } }
{ "content_hash": "ac0a3175b3cded41d739ad53ffa9928e", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 84, "avg_line_length": 24.76, "alnum_prop": 0.678513731825525, "repo_name": "RafaOP/CastleOfValhalla", "id": "9049d3ce53f75c5f7bb09d353b14d2be82d62b88", "size": "2523", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Math/Vector3.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "3114448" }, { "name": "C++", "bytes": "855354" }, { "name": "Java", "bytes": "172" }, { "name": "Shell", "bytes": "254" } ], "symlink_target": "" }
define("dojox/widget/nls/da/FilePicker",{name:"Navn",path:"Sti",size:"St\u00f8rrelse (i byte)"}); //# sourceMappingURL=FilePicker.js.map
{ "content_hash": "d703a254372dfc14f17868ed459e26d6", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 97, "avg_line_length": 68, "alnum_prop": 0.7352941176470589, "repo_name": "Caspar12/zh.sw", "id": "fd7d3989bf176871f6d3c543d410326b17e6d502", "size": "146", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "zh.web.site.admin/src/main/resources/static/js/dojo/dojox/widget/nls/da/FilePicker.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ActionScript", "bytes": "19954" }, { "name": "Batchfile", "bytes": "1258" }, { "name": "CSS", "bytes": "6378085" }, { "name": "HTML", "bytes": "385499" }, { "name": "Java", "bytes": "152316" }, { "name": "JavaScript", "bytes": "35186401" }, { "name": "PHP", "bytes": "38104" }, { "name": "Shell", "bytes": "1026" }, { "name": "XSLT", "bytes": "47383" } ], "symlink_target": "" }
import unittest from SevenStories import game from SevenStories import parse class TestGame(unittest.TestCase): def setUp(self): """Set up for all the tests Creates a sample character and stores the GameMap object. Creates a sample load with 'health name' as sample input. """ self.sample_input = "health name" self.sample_name = "testcharacter" self.game_map = game.create_character(lambda x: "test") self.load = parse.parse_command(self.sample_input) def tearDown(self): import os os.remove(game.get_saves_dir() + self.game_map.player.name.lower() + ".dat") def test_play_game(self): """Testing play_game function Using 'save quit' as example input. Expecting play_game to not only run successfully, but in this case, it should also return 'quit', which will be stored as arg. If this test passes, then the execute function's arg return works. """ arg = game.play_game(self.game_map, input=lambda x: "save quit") self.assertEqual(arg, "quit", "Arg was not quit!") def test_execute(self): """Testing execute function Sample load uses 'health name' as example input Simply testing to ensure the function runs successfully. """ game.execute(self.game_map, self.load) def test_get_saves_dir(self): import os """Testing get_saves_dir function The project directory is expected to contain the saves directory, just as 'SevenStories/saves'. This test will check the returned absolute path from the get_saves_dir function and ensure that the ending is 'SevenStories/saves'. Test handles differences between how operating systems handle slashes in directory paths. """ saves_dir = game.get_saves_dir() if os.name == "posix": self.assertEqual(saves_dir[len(saves_dir) - 19:], "SevenStories/saves/", "Incorrect saves directory returned!") else: self.assertEqual(saves_dir[len(saves_dir) - 19:], "SevenStories\\saves\\", "Incorrect saves directory returned!") def test_get_simple_answer(self): """Testing get_simple_answer function Running the two most important sample answers, 'yes' and 'no'. """ answer1 = game.get_simple_answer("Test question.", input=lambda x: "yes") answer2 = game.get_simple_answer("Test question.", input=lambda x: "no") self.assertTrue(answer1, "First answer failed to return True!") self.assertFalse(answer2, "Second answer failed to return False!") def test_save_game(self): """Testing save_game function Simply testing to ensure the function runs successfully. """ game.save_game(self.game_map, echo=False) def test_load_game(self): """Testing load_game function Ensuring that load_game returns a GameMap object and ensuring that the correct game_map is loaded by checking the player's name within it. """ sample_game_map = game.load_game("test") self.assertIsInstance(sample_game_map, game.gamemap.GameMap, "Did not return a GameMap object!") self.assertEqual(sample_game_map.player.name, "test", "Failed to load the correct GameMap object!") def test_reset_character(self): """Testing reset_character function Simply testing to ensure the function runs successfully. """ game.reset_character("test", echo=False) def test_create_character(self): """Testing create_character function Creating a sample character with sample name. Ensuring that create_character returns the proper GameMap object Deletes the sample character after """ sample_game_map = game.create_character(input=lambda x: self.sample_name) self.assertIsInstance(sample_game_map, game.gamemap.GameMap, "Did not return a GameMap object!") self.assertEqual(sample_game_map.player.name, self.sample_name, "Failed to create the correct GameMap object!") game.delete_character(sample_game_map.player.name, echo=False) def test_delete_character(self): """Testing delete_character function Creating a sample character with sample name. Deleting that character after it's created. Checking directory to ensure that the character does not exist. """ sample_game_map = game.create_character(input=lambda x: self.sample_name) game.delete_character(sample_game_map.player.name.lower(), echo=False)
{ "content_hash": "aebd4565f5c7324a426369b2fe0d6443", "timestamp": "", "source": "github", "line_count": 130, "max_line_length": 84, "avg_line_length": 37.61538461538461, "alnum_prop": 0.62719836400818, "repo_name": "huntermalm/SevenStories", "id": "bfc9bc0c07c1ee8bc888c273d2f18b5bd9ec4b1b", "size": "4890", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/test_game.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "42007" } ], "symlink_target": "" }
package com.google.step.coffee.servlets; import com.google.api.client.auth.oauth2.AuthorizationCodeFlow; import com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.extensions.appengine.auth.oauth2.AbstractAppEngineAuthorizationCodeCallbackServlet; import com.google.step.coffee.OAuthService; import com.google.step.coffee.data.UserStore; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** Handle callback from OAuth 2.0 request by user. */ @WebServlet("/api/oauth2callback") public class OAuthCallbackServlet extends AbstractAppEngineAuthorizationCodeCallbackServlet { private UserStore userStore = new UserStore(); @Override protected void onSuccess(HttpServletRequest req, HttpServletResponse resp, Credential credential) throws ServletException, IOException { userStore.updateCurrentUserInfo(); resp.sendRedirect("/"); } @Override protected void onError(HttpServletRequest req, HttpServletResponse resp, AuthorizationCodeResponseUrl errorResponse) throws ServletException, IOException { super.onError(req, resp, errorResponse); } @Override protected AuthorizationCodeFlow initializeFlow() throws ServletException, IOException { return OAuthService.getAuthFlow(); } @Override protected String getRedirectUri(HttpServletRequest httpServletRequest) throws ServletException, IOException { return OAuthService.getRedirectUri(httpServletRequest); } }
{ "content_hash": "6997c22bdb55acf3e8649024756c0b96", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 112, "avg_line_length": 37.95454545454545, "alnum_prop": 0.8131736526946107, "repo_name": "googleinterns/step250-2020", "id": "faa9164191c172f18cb7dcb6238db629b6cd0a63", "size": "1670", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "coffee-chats/src/main/java/com/google/step/coffee/servlets/OAuthCallbackServlet.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "629" }, { "name": "HTML", "bytes": "1930" }, { "name": "Java", "bytes": "226235" }, { "name": "JavaScript", "bytes": "578" }, { "name": "TypeScript", "bytes": "86214" } ], "symlink_target": "" }
# # # Set environment variables here. # The java implementation to use. Java 1.6 required. # export JAVA_HOME=/usr/java/jdk1.6.0/ # Extra Java CLASSPATH elements. Optional. # export HBASE_CLASSPATH= # The maximum amount of heap to use, in MB. Default is 1000. # export HBASE_HEAPSIZE=1000 # Extra Java runtime options. # Below are what we set by default. May only work with SUN JVM. # For more on why as well as other possible settings, # see http://wiki.apache.org/hadoop/PerformanceTuning export HBASE_OPTS="$HBASE_OPTS -XX:+UseConcMarkSweepGC " #export HBASE_OPTS="$HBASE_OPTS -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:CMSInitiatingOccupancyFraction=70 " # Uncomment below to enable java garbage collection logging in the .out file. #export HBASE_OPTS="$HBASE_OPTS -verbose:gc -XX:+PrintGCDetails -XX:+PrintGCDateStamps $HBASE_GC_OPTS " # Uncomment below (along with above GC logging) to put GC information in its own logfile (will set HBASE_GC_OPTS) # export HBASE_USE_GC_LOGFILE=true # Uncomment below if you intend to use the EXPERIMENTAL off heap cache. # export HBASE_OPTS="$HBASE_OPTS -XX:MaxDirectMemorySize=" # Set hbase.offheapcache.percentage in hbase-site.xml to a nonzero value. # Uncomment and adjust to enable JMX exporting # See jmxremote.password and jmxremote.access in $JRE_HOME/lib/management to configure remote password access. # More details at: http://java.sun.com/javase/6/docs/technotes/guides/management/agent.html # # export HBASE_JMX_BASE="-Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false" # export HBASE_MASTER_OPTS="$HBASE_MASTER_OPTS $HBASE_JMX_BASE -Dcom.sun.management.jmxremote.port=10101" # export HBASE_REGIONSERVER_OPTS="$HBASE_REGIONSERVER_OPTS $HBASE_JMX_BASE -Dcom.sun.management.jmxremote.port=10102" # export HBASE_THRIFT_OPTS="$HBASE_THRIFT_OPTS $HBASE_JMX_BASE -Dcom.sun.management.jmxremote.port=10103" # export HBASE_ZOOKEEPER_OPTS="$HBASE_ZOOKEEPER_OPTS $HBASE_JMX_BASE -Dcom.sun.management.jmxremote.port=10104" # File naming hosts on which HRegionServers will run. $HBASE_HOME/conf/regionservers by default. # export HBASE_REGIONSERVERS=${HBASE_HOME}/conf/regionservers # File naming hosts on which backup HMaster will run. $HBASE_HOME/conf/backup-masters by default. # export HBASE_BACKUP_MASTERS=${HBASE_HOME}/conf/backup-masters # Extra ssh options. Empty by default. # export HBASE_SSH_OPTS="-o ConnectTimeout=1 -o SendEnv=HBASE_CONF_DIR" # Where log files are stored. $HBASE_HOME/logs by default. # export HBASE_LOG_DIR=${HBASE_HOME}/logs # Enable remote JDWP debugging of major HBase processes. Meant for Core Developers # export HBASE_MASTER_OPTS="$HBASE_MASTER_OPTS -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8070" # export HBASE_REGIONSERVER_OPTS="$HBASE_REGIONSERVER_OPTS -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8071" # export HBASE_THRIFT_OPTS="$HBASE_THRIFT_OPTS -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8072" # export HBASE_ZOOKEEPER_OPTS="$HBASE_ZOOKEEPER_OPTS -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8073" # A string representing this instance of hbase. $USER by default. # export HBASE_IDENT_STRING=$USER # The scheduling priority for daemon processes. See 'man nice'. # export HBASE_NICENESS=10 # The directory where pid files are stored. /tmp by default. # export HBASE_PID_DIR=/var/hadoop/pids # Seconds to sleep between slave commands. Unset by default. This # can be useful in large clusters, where, e.g., slave rsyncs can # otherwise arrive faster than the master can service them. # export HBASE_SLAVE_SLEEP=0.1 # Tell HBase whether it should manage it's own instance of Zookeeper or not. export HBASE_MANAGES_ZK=true
{ "content_hash": "677f6945c2456bf04fe5b12942534f9f", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 129, "avg_line_length": 48.30769230769231, "alnum_prop": 0.7733545647558386, "repo_name": "Lingcc/hadoop-lingccfs", "id": "097812adf31f5d40dfb0e6d5b9934fe254ad3aa3", "size": "4644", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lingccfs_conf/hbase-0.94.3/conf_leofs/hbase-env.sh", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "27344" }, { "name": "Shell", "bytes": "13762" }, { "name": "XML", "bytes": "1070" } ], "symlink_target": "" }
from pyquery import PyQuery as pq import calendar import urllib2 import codecs import time import re import os, os.path def shouldRetrieve(pseudoToCheck): try: if os.stat("datafiles/tweets_party_generales.csv").st_size == 0: print "return because file empty" return True except: print "return because file does not exist" return True tweets = codecs.open("datafiles/tweets_party_generales.csv", "r", "utf-8") for line in reversed(tweets.readlines()): line = line.strip() fields = line.split(',') pseudo = fields[1][1:-1] if pseudo.lower() == pseudoToCheck.lower(): halfDay = 60 * 60 * 12 timeElapsed = int(time.time()) - int(fields[6][1:-1]) tweets.close() return timeElapsed > halfDay tweets.close() return True def retrieveFromList(date_min = "", date_max = ""): parties = codecs.open("datafiles/pseudo_parties.txt", "r", "utf-8") # Parties + level + pseudos for party in parties: fields = party.strip().split(",") party_name = fields[0] level = fields[1] if fields[2][1:-1]: pseudo = fields[2] else: continue partyLine = '"' + party_name + '","' + level + '","' + pseudo + '"' print "Retrieving tweets for", pseudo if shouldRetrieve(pseudo): retrievePages(partyLine, party_name, pseudo, date_min, date_max) parties.close() def writeAccounts(page, partyLine, pseudo): with codecs.open("datafiles/parties_accounts.csv","a+","utf-8") as accounts: for line in accounts: foundPseudo = line.strip().split(',')[2][1:-1] if foundPseudo == pseudo: return location = cleanText(page(".ProfileHeaderCard-location").text()) biography = cleanText(page(".ProfileHeaderCard-bio").text()) subscription_ini = page(".ProfileHeaderCard-joinDateText").attr("title") subscription = "" if subscription_ini: subscription = strToTimestamp(subscription_ini.split(" - ")[1]) accounts.write('%s,"%s","%s","%s"\n' % (partyLine, location, subscription, biography)) def retrievePages(partyLine, party_name, pseudo, date_min = "", date_max = ""): data = codecs.open("datafiles/tweets_party_generales.csv", "a", "utf-8") # If no minimal date is specified, the program searches in the file the last tweets written if date_min == "": timestamp_min = findTimestampMax(pseudo) else: timestamp_min = strToTimestamp(date_min) # Max. date by default is the date at which the program is launched if date_max == "": timestamp_max = int(time.time()) else: timestamp_max = strToTimestamp(date_max) # Retrieve informations about the candidate page = pq("https://twitter.com/" + pseudo, headers={'Accept-Language': 'en-US,en;q=0.5'}) writeAccounts(page, partyLine, pseudo) ret = retrieveTweets(party_name, pseudo, page, timestamp_min, timestamp_max, 0) if len(ret) == 0: t = int(time.time()) ret = ((6 * '"%s",' + '"%d"\n') % (party_name, pseudo, "", "", t, "", t)) data.write(ret) data.close() def retrieveTweets(party_name, pseudo, page, timestamp_min, timestamp_max, timestamp_old, first_page = True, has_more_items = True): if first_page: css = "div.stream div.tweet" else: css = "div.tweet" tweets = page(css) params = "" tweet_id = "" # Retrieve information for each tweet for tweet in tweets: tweetdom = pq(tweet) content = cleanText(tweetdom("p.tweet-text").text()) tweet_author = cleanText(tweetdom("strong.fullname").eq(0).text()) tweet_pseudo = tweetdom("span.username").eq(0).text() if tweet_pseudo == "": continue # If tweet is a retweet, its timestamp is modified in order for the program to continue if tweet_pseudo.lower() != '@ ' + pseudo.lower(): timestamp = int(tweetdom("span._timestamp").attr("data-time")) else: timestamp = timestamp_old # Retrieve page's last tweet id to create next page's url later tweet_id = tweetdom.attr("data-item-id") # Do not take into account pinned tweets if tweetdom("span.js-pinned-text"): print "Pinned tweet found. Continue." continue # Skip tweets until date_max, and then retrieve them until date_min if timestamp == 0: continue if timestamp >= timestamp_max: continue if timestamp > 0 and timestamp <= timestamp_min: return params timestamp_old = timestamp params += ((6 * '"%s",' + '"%d"\n') % (party_name, pseudo, tweet_author, tweet_pseudo, timestamp, content, int(time.time()))) if not has_more_items: return params # Create next page's url and open it base = "https://twitter.com/i/profiles/show/" parameters = "/timeline?include_available_features=1&include_entities=1&max_position=" url = base + pseudo + parameters + tweet_id req = urllib2.urlopen(url) # Read code in utf-8 obj = unicode(req.read(), "utf-8") # Transform next page's json code (obtained using Live HTTP Headers) into html obj = obj.decode("unicode_escape").replace('\\/', '/') more_items = (obj.split("\"has_more_items\":")[1].split(',')[0] == "true") obj = obj.split("\"items_html\":\"")[1][:-2] if not obj.strip(): print "No tweets available" return params # Recall function with first page option set to "False" params += retrieveTweets(party_name, pseudo, pq(obj), timestamp_min, timestamp_max, timestamp_old, False, more_items) return params # Convert date to timestamp def strToTimestamp(date_min): time_struct = time.strptime(date_min, "%d %b %Y") timestamp = calendar.timegm(time_struct) return(timestamp) # Find last tweet retrieved's date def findTimestampMax(pseudo): try: csv = codecs.open("datafiles/tweets_generales.csv", "r", "utf-8") except: print "File not found" return 0 # Create a table containing timestampsOn crée un tableau contenant les timestamps (index 7) à chaque ligne du fichier csv en enlevant les guillemets. .strip() enlève les retours à la ligne tab = [int(line.strip().split(",")[7][1:-1]) if line.strip().split(",")[1][3:-1] == pseudo else 0 for line in csv] csv.close() # Returns greater timestamp (hence the more recent) return max(tab) # Remove quotes and \n in data def cleanText(text): if not text: return "" text = re.sub('[\s,"]', " ", text) return text retrieveFromList("04 Dec 2015", "20 Dec 2015")
{ "content_hash": "e0ddda0daec61d9139184a94d2501780", "timestamp": "", "source": "github", "line_count": 176, "max_line_length": 192, "avg_line_length": 38.75568181818182, "alnum_prop": 0.6091482187362557, "repo_name": "florence-nocca/spanish-elections", "id": "eeec1317c53b072c7df0686189f526ac20275af7", "size": "6868", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "retrieve-tweets/retrieve_party_tweets.py", "mode": "33261", "license": "mit", "language": [ { "name": "Python", "bytes": "38619" }, { "name": "R", "bytes": "12969" } ], "symlink_target": "" }
SET(CMAKE_RELATIVE_PATH_TOP_SOURCE "/home/bijanadmin/git/eye-tracker-offline") SET(CMAKE_RELATIVE_PATH_TOP_BINARY "/home/bijanadmin/git/eye-tracker-offline") # Force unix paths in dependencies. SET(CMAKE_FORCE_UNIX_PATHS 1) # The C and CXX include file search paths: SET(CMAKE_C_INCLUDE_PATH "/usr/local/include/opencv" "/usr/local/include" ) SET(CMAKE_CXX_INCLUDE_PATH ${CMAKE_C_INCLUDE_PATH}) SET(CMAKE_Fortran_INCLUDE_PATH ${CMAKE_C_INCLUDE_PATH}) SET(CMAKE_ASM_INCLUDE_PATH ${CMAKE_C_INCLUDE_PATH}) # The C and CXX include file regular expressions for this directory. SET(CMAKE_C_INCLUDE_REGEX_SCAN "^.*$") SET(CMAKE_C_INCLUDE_REGEX_COMPLAIN "^$") SET(CMAKE_CXX_INCLUDE_REGEX_SCAN ${CMAKE_C_INCLUDE_REGEX_SCAN}) SET(CMAKE_CXX_INCLUDE_REGEX_COMPLAIN ${CMAKE_C_INCLUDE_REGEX_COMPLAIN})
{ "content_hash": "fbb9d39941047a8052b2887ecbd054fe", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 78, "avg_line_length": 39.85, "alnum_prop": 0.7540777917189461, "repo_name": "justanotherbrain/eye-tracker-offline", "id": "2c874d936bf7a03a5402f3b8fdb8a460fd0ec013", "size": "940", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CMakeFiles/CMakeDirectoryInformation.cmake", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "17908" }, { "name": "C++", "bytes": "25941" }, { "name": "Makefile", "bytes": "5118" } ], "symlink_target": "" }
#ifndef MK_EXTRACT_PROC_H_ #define MK_EXTRACT_PROC_H_ #include"ast.h" #include"bv_decl_plugin.h" class mk_extract_proc { bv_util & m_util; unsigned m_high; unsigned m_low; sort * m_domain; func_decl * m_f_cached; public: mk_extract_proc(bv_util & u); ~mk_extract_proc(); app * operator()(unsigned high, unsigned low, expr * arg); ast_manager & m() { return m_util.get_manager(); } bv_util & bvutil() { return m_util; } }; #endif /* MK_EXTRACT_PROC_H_ */
{ "content_hash": "342560d1abb54bffd6f4d0239d6aef33", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 62, "avg_line_length": 27.31578947368421, "alnum_prop": 0.5895953757225434, "repo_name": "kyledewey/z3", "id": "2b242d0f535e71da36a8165b1f2844074c508a9e", "size": "683", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "src/ast/rewriter/mk_extract_proc.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "335825" }, { "name": "C#", "bytes": "499026" }, { "name": "C++", "bytes": "15420572" }, { "name": "CMake", "bytes": "77898" }, { "name": "Java", "bytes": "371711" }, { "name": "OCaml", "bytes": "278706" }, { "name": "Objective-C", "bytes": "3615" }, { "name": "Python", "bytes": "624641" }, { "name": "SMT", "bytes": "30220" }, { "name": "Shell", "bytes": "353" } ], "symlink_target": "" }
casper.test.begin('Background-image test', 55, function suite(test) { var currentURL = params.url + '/background-image.html'; casper.start(currentURL, function() { test.assertTitle('background-image test', "page title is okay"); }); casper.then(function() { casper.checkImage(test, 319, 480, 'tiny', 'background'); casper.checkImage(test, 320, 480, 'tiny', 'background'); casper.checkImage(test, 321, 480, 'small', 'background'); casper.checkImage(test, 479, 480, 'small', 'background'); casper.checkImage(test, 480, 480, 'small', 'background'); casper.checkImage(test, 481, 480, 'medium', 'background'); casper.checkImage(test, 599, 480, 'medium', 'background'); casper.checkImage(test, 600, 480, 'medium', 'background'); casper.checkImage(test, 601, 480, 'regular', 'background'); casper.checkImage(test, 767, 600, 'regular', 'background'); casper.checkImage(test, 768, 600, 'regular', 'background'); casper.checkImage(test, 769, 600, 'large', 'background'); casper.checkImage(test, 1023, 768, 'large', 'background'); casper.checkImage(test, 1024, 768, 'large', 'background'); casper.checkImage(test, 1025, 768, 'huge', 'background'); casper.checkImage(test, 1199, 768, 'huge', 'background'); casper.checkImage(test, 1200, 1024, 'huge', 'background'); casper.checkImage(test, 1201, 1024, 'huge', 'background'); test.comment('done'); }); //start casper.run(function(){ test.done(); }); });
{ "content_hash": "353d465077e5f6735a79ecc762e5b9e6", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 72, "avg_line_length": 48.24242424242424, "alnum_prop": 0.6180904522613065, "repo_name": "joeyvandijk/rimg", "id": "8ba8e61e1f7e66a88359f31c7558151cdbdfedd9", "size": "1592", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/examples/background-image.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "76336" }, { "name": "JavaScript", "bytes": "71618" } ], "symlink_target": "" }
package br.edu.ifrn.helppet.dominio; import java.io.Serializable; import java.util.Set; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.SequenceGenerator; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; /** * * @author anne */ @Getter @Setter @ToString @EqualsAndHashCode @Builder @AllArgsConstructor(access = AccessLevel.PUBLIC) @NoArgsConstructor(access = AccessLevel.PUBLIC) @Entity @SequenceGenerator(sequenceName = "seq_pessoafisica", name = "ID_SEQUENCE", allocationSize = 1) public class PessoaFisica implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "ID_SEQUENCE") private Long id; private String cpf; @OneToOne private Usuario usuario; @OneToMany(mappedBy = "adotante") private Set<Encontro> encontros; }
{ "content_hash": "63f686e03649b93dc2696e4e36342255", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 95, "avg_line_length": 24.254901960784313, "alnum_prop": 0.7720291026677445, "repo_name": "AnneGoncalo/helppettest", "id": "670866964d5c10aac7c11852b29cbb4c699a4294", "size": "1829", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/br/edu/ifrn/helppet/dominio/PessoaFisica.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "5186" }, { "name": "CSS", "bytes": "4113" }, { "name": "HTML", "bytes": "65092" }, { "name": "Java", "bytes": "106888" }, { "name": "JavaScript", "bytes": "14786" }, { "name": "Shell", "bytes": "7112" } ], "symlink_target": "" }
/******************************** *** Multiplexer for Go *** *** Bone is under MIT license *** *** Code by CodingFerret *** *** github.com/go-zoo *** *********************************/ package bone import ( "net/http" "net/url" "strings" ) func (m *Mux) parse(rw http.ResponseWriter, req *http.Request) bool { for _, r := range m.Routes[req.Method] { ok := r.parse(rw, req) if ok { return true } } // If no HEAD method, default to GET if req.Method == "HEAD" { for _, r := range m.Routes["GET"] { ok := r.parse(rw, req) if ok { return true } } } return false } // StaticRoute check if the request path is for Static route func (m *Mux) staticRoute(rw http.ResponseWriter, req *http.Request) bool { for _, s := range m.Routes[static] { if len(req.URL.Path) >= s.Size { if req.URL.Path[:s.Size] == s.Path { s.Handler.ServeHTTP(rw, req) return true } } } return false } // HandleNotFound handle when a request does not match a registered handler. func (m *Mux) HandleNotFound(rw http.ResponseWriter, req *http.Request) { if m.notFound != nil { m.notFound.ServeHTTP(rw, req) } else { http.NotFound(rw, req) } } // Check if the path don't end with a / func (m *Mux) validate(rw http.ResponseWriter, req *http.Request) bool { plen := len(req.URL.Path) if plen > 1 && req.URL.Path[plen-1:] == "/" { cleanURL(&req.URL.Path) rw.Header().Set("Location", req.URL.String()) rw.WriteHeader(http.StatusFound) return true } // Retry to find a route that match return m.parse(rw, req) } func valid(path string) bool { plen := len(path) if plen > 1 && path[plen-1:] == "/" { return false } return true } // Clean url path func cleanURL(url *string) { ulen := len((*url)) if ulen > 1 { if (*url)[ulen-1:] == "/" { *url = (*url)[:ulen-1] cleanURL(url) } } } // GetValue return the key value, of the current *http.Request func GetValue(req *http.Request, key string) string { return GetAllValues(req)[key] } // GetRequestRoute returns the route of given Request func (m *Mux) GetRequestRoute(req *http.Request) string { cleanURL(&req.URL.Path) for _, r := range m.Routes[req.Method] { if r.Atts != 0 { if r.Atts&SUB != 0 { if len(req.URL.Path) >= r.Size { if req.URL.Path[:r.Size] == r.Path { return r.Path } } } if r.Match(req) { return r.Path } } if req.URL.Path == r.Path { return r.Path } } for _, s := range m.Routes[static] { if len(req.URL.Path) >= s.Size { if req.URL.Path[:s.Size] == s.Path { return s.Path } } } return "NotFound" } // GetQuery return the key value, of the current *http.Request query func GetQuery(req *http.Request, key string) []string { if ok, value := extractQueries(req); ok { return value[key] } return nil } // GetAllQueries return all queries of the current *http.Request func GetAllQueries(req *http.Request) map[string][]string { if ok, values := extractQueries(req); ok { return values } return nil } func extractQueries(req *http.Request) (bool, map[string][]string) { if q, err := url.ParseQuery(req.URL.RawQuery); err == nil { var queries = make(map[string][]string) for k, v := range q { for _, item := range v { values := strings.Split(item, ",") queries[k] = append(queries[k], values...) } } return true, queries } return false, nil }
{ "content_hash": "7c71fffc6cb9a80e62000bb0530e5cb9", "timestamp": "", "source": "github", "line_count": 154, "max_line_length": 76, "avg_line_length": 22.058441558441558, "alnum_prop": 0.608772446276126, "repo_name": "go-box/brochure", "id": "c42800409b0b320381ab42372ea81860b5b29a48", "size": "3397", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "vendor/github.com/go-zoo/bone/helper.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "11925" }, { "name": "HTML", "bytes": "1080" }, { "name": "Makefile", "bytes": "357" }, { "name": "Shell", "bytes": "262" } ], "symlink_target": "" }
// ****************************************************************** // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THE CODE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH // THE CODE OR THE USE OR OTHER DEALINGS IN THE CODE. // ****************************************************************** using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Windows.Foundation; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Markup; using Windows.UI.Xaml.Media; namespace Microsoft.Toolkit.Uwp.UI.Controls { /// <summary> /// Control that implements support for transformations as if applied by LayoutTransform. /// </summary> [ContentProperty(Name = "Child")] public partial class LayoutTransformControl : Control { /// <summary> /// Value used to work around double arithmetic rounding issues. /// </summary> private const double AcceptableDelta = 0.0001; /// <summary> /// Value used to work around double arithmetic rounding issues. /// </summary> private const int DecimalsAfterRound = 4; /// <summary> /// List of property change event sources for events when properties of the Transform tree change /// </summary> private readonly Dictionary<Transform, List<PropertyChangeEventSource<double>>> _transformPropertyChangeEventSources = new Dictionary <Transform, List<PropertyChangeEventSource<double>>>(); /// <summary> /// Host panel for Child element. /// </summary> private Panel _layoutRoot; /// <summary> /// RenderTransform/MatrixTransform applied to layout root. /// </summary> private MatrixTransform _matrixTransform; /// <summary> /// Transformation matrix corresponding to matrix transform. /// </summary> private Matrix _transformation; /// <summary> /// Actual DesiredSize of Child element. /// </summary> private Size _childActualSize = Size.Empty; /// <summary> /// Initializes a new instance of the <see cref="LayoutTransformControl"/> class. /// </summary> public LayoutTransformControl() { DefaultStyleKey = typeof(LayoutTransformControl); // Can't tab to LayoutTransformControl IsTabStop = false; // Disable layout rounding because its rounding of values confuses things. UseLayoutRounding = false; } /// <summary> /// Called whenever the control's template changes. /// </summary> protected override void OnApplyTemplate() { // Save existing content and remove it from the visual tree FrameworkElement savedContent = Child; Child = null; // Apply new template base.OnApplyTemplate(); // Find template parts _layoutRoot = GetTemplateChild("LayoutRoot") as Panel; _matrixTransform = GetTemplateChild("MatrixTransform") as MatrixTransform; // RestoreAsync saved content Child = savedContent; // Apply the current transform TransformUpdated(); } /// <summary> /// Notifies the LayoutTransformControl that some aspect of its Transform property has changed. /// </summary> /// <remarks> /// Call this to update the LayoutTransform in cases where /// LayoutTransformControl wouldn't otherwise know to do so. /// </remarks> public void TransformUpdated() { ProcessTransform(); } /// <summary> /// Return true if Size a is smaller than Size b in either dimension. /// </summary> /// <param name="a">The left size.</param> /// <param name="b">The right size.</param> /// <returns>A value indicating whether the left size is smaller than /// the right.</returns> private static bool IsSizeSmaller(Size a, Size b) { // WPF equivalent of following code: // return ((a.Width < b.Width) || (a.Height < b.Height)); return (a.Width + AcceptableDelta < b.Width) || (a.Height + AcceptableDelta < b.Height); } /// <summary> /// Rounds the non-offset elements of a matrix to avoid issues due to floating point imprecision. /// </summary> /// <param name="matrix">The matrix to round.</param> /// <param name="decimalsAfterRound">The number of decimals after the round.</param> /// <returns>The rounded matrix.</returns> private static Matrix RoundMatrix(Matrix matrix, int decimalsAfterRound) { return new Matrix( Math.Round(matrix.M11, decimalsAfterRound), Math.Round(matrix.M12, decimalsAfterRound), Math.Round(matrix.M21, decimalsAfterRound), Math.Round(matrix.M22, decimalsAfterRound), matrix.OffsetX, matrix.OffsetY); } /// <summary> /// Implement WPF's Rect.Transform. /// </summary> /// <param name="rectangle">The rectangle to transform.</param> /// <param name="matrix">The matrix to use to transform the rectangle. /// </param> /// <returns>The transformed rectangle.</returns> private static Rect RectTransform(Rect rectangle, Matrix matrix) { // WPF equivalent of following code: // var rectTransformed = Rect.Transform(rect, matrix); Point leftTop = matrix.Transform(new Point(rectangle.Left, rectangle.Top)); Point rightTop = matrix.Transform(new Point(rectangle.Right, rectangle.Top)); Point leftBottom = matrix.Transform(new Point(rectangle.Left, rectangle.Bottom)); Point rightBottom = matrix.Transform(new Point(rectangle.Right, rectangle.Bottom)); double left = Math.Min(Math.Min(leftTop.X, rightTop.X), Math.Min(leftBottom.X, rightBottom.X)); double top = Math.Min(Math.Min(leftTop.Y, rightTop.Y), Math.Min(leftBottom.Y, rightBottom.Y)); double right = Math.Max(Math.Max(leftTop.X, rightTop.X), Math.Max(leftBottom.X, rightBottom.X)); double bottom = Math.Max(Math.Max(leftTop.Y, rightTop.Y), Math.Max(leftBottom.Y, rightBottom.Y)); Rect rectTransformed = new Rect(left, top, right - left, bottom - top); return rectTransformed; } /// <summary> /// Implements WPF's Matrix.Multiply. /// </summary> /// <param name="matrix1">The left matrix.</param> /// <param name="matrix2">The right matrix.</param> /// <returns>The product of the two matrices.</returns> private static Matrix MatrixMultiply(Matrix matrix1, Matrix matrix2) { // WPF equivalent of following code: // return Matrix.Multiply(matrix1, matrix2); return new Matrix( (matrix1.M11 * matrix2.M11) + (matrix1.M12 * matrix2.M21), (matrix1.M11 * matrix2.M12) + (matrix1.M12 * matrix2.M22), (matrix1.M21 * matrix2.M11) + (matrix1.M22 * matrix2.M21), (matrix1.M21 * matrix2.M12) + (matrix1.M22 * matrix2.M22), ((matrix1.OffsetX * matrix2.M11) + (matrix1.OffsetY * matrix2.M21)) + matrix2.OffsetX, ((matrix1.OffsetX * matrix2.M12) + (matrix1.OffsetY * matrix2.M22)) + matrix2.OffsetY); } /// <summary> /// Implements WPF's Matrix.HasInverse. /// </summary> /// <param name="matrix">The matrix.</param> /// <returns>True if matrix has an inverse.</returns> private static bool MatrixHasInverse(Matrix matrix) { // WPF equivalent of following code: // return matrix.HasInverse; return ((matrix.M11 * matrix.M22) - (matrix.M12 * matrix.M21)) != 0; } /// <summary> /// Processes the current transform to determine the corresponding /// matrix. /// </summary> private void ProcessTransform() { // Get the transform matrix and apply it _transformation = RoundMatrix(GetTransformMatrix(Transform), DecimalsAfterRound); if (_matrixTransform != null) { _matrixTransform.Matrix = _transformation; } // New transform means re-layout is necessary InvalidateMeasure(); } /// <summary> /// Walks the Transform and returns the corresponding matrix. /// </summary> /// <param name="transform">The transform to create a matrix for. /// </param> /// <returns>The matrix calculated from the transform.</returns> private Matrix GetTransformMatrix(Transform transform) { if (transform != null) { // WPF equivalent of this entire method (why oh why only WPF...): // return transform.Value; // Process the TransformGroup var transformGroup = transform as TransformGroup; if (transformGroup != null) { var groupMatrix = Matrix.Identity; foreach (var child in transformGroup.Children) { groupMatrix = MatrixMultiply(groupMatrix, GetTransformMatrix(child)); } return groupMatrix; } // Process the RotateTransform var rotateTransform = transform as RotateTransform; if (rotateTransform != null) { var angle = rotateTransform.Angle; var angleRadians = (2 * Math.PI * angle) / 360; var sine = Math.Sin(angleRadians); var cosine = Math.Cos(angleRadians); return new Matrix(cosine, sine, -sine, cosine, 0, 0); } // Process the ScaleTransform var scaleTransform = transform as ScaleTransform; if (scaleTransform != null) { var scaleX = scaleTransform.ScaleX; var scaleY = scaleTransform.ScaleY; return new Matrix(scaleX, 0, 0, scaleY, 0, 0); } // Process the SkewTransform var skewTransform = transform as SkewTransform; if (skewTransform != null) { var angleX = skewTransform.AngleX; var angleY = skewTransform.AngleY; var angleXRadians = (2 * Math.PI * angleX) / 360; var angleYRadians = (2 * Math.PI * angleY) / 360; return new Matrix(1, angleYRadians, angleXRadians, 1, 0, 0); } // Process the MatrixTransform var matrixTransform = transform as MatrixTransform; if (matrixTransform != null) { return matrixTransform.Matrix; } if (transform is CompositeTransform) { throw new NotSupportedException("CompositeTransforms are not supported (yet) by the LayoutTransformControl."); } // TranslateTransform has no effect in LayoutTransform } // Fall back to no-op transformation return Matrix.Identity; } /// <summary> /// Provides the behavior for the "Measure" pass of layout. /// </summary> /// <param name="availableSize">The available size that this element can /// give to child elements. Infinity can be specified as a value to /// indicate that the element will size to whatever content is available.</param> /// <returns>The size that this element determines it needs during /// layout, based on its calculations of child element sizes.</returns> protected override Size MeasureOverride(Size availableSize) { FrameworkElement child = Child; if (_layoutRoot == null || child == null) { // No content, no size return Size.Empty; } Size measureSize; if (_childActualSize == Size.Empty) { // Determine the largest size after the transformation measureSize = ComputeLargestTransformedSize(availableSize); } else { // Previous measure/arrange pass determined that Child.DesiredSize was larger than believed. measureSize = _childActualSize; } // Perform a mesaure on the _layoutRoot (containing Child) _layoutRoot.Measure(measureSize); // Transform DesiredSize to find its width/height Rect transformedDesiredRect = RectTransform(new Rect(0, 0, _layoutRoot.DesiredSize.Width, _layoutRoot.DesiredSize.Height), _transformation); Size transformedDesiredSize = new Size(transformedDesiredRect.Width, transformedDesiredRect.Height); // Return result to allocate enough space for the transformation return transformedDesiredSize; } /// <summary> /// Provides the behavior for the "Arrange" pass of layout. /// </summary> /// <param name="finalSize">The final area within the parent that this /// element should use to arrange itself and its children.</param> /// <returns>The actual size used.</returns> protected override Size ArrangeOverride(Size finalSize) { FrameworkElement child = Child; if (_layoutRoot == null || child == null) { // No child, use whatever was given return finalSize; } // Determine the largest available size after the transformation Size finalSizeTransformed = ComputeLargestTransformedSize(finalSize); if (IsSizeSmaller(finalSizeTransformed, _layoutRoot.DesiredSize)) { // Some elements do not like being given less space than they asked for (ex: TextBlock) // Bump the working size up to do the right thing by them finalSizeTransformed = _layoutRoot.DesiredSize; } // Transform the working size to find its width/height Rect transformedRect = RectTransform(new Rect(0, 0, finalSizeTransformed.Width, finalSizeTransformed.Height), _transformation); // Create the Arrange rect to center the transformed content Rect finalRect = new Rect( -transformedRect.Left + ((finalSize.Width - transformedRect.Width) / 2), -transformedRect.Top + ((finalSize.Height - transformedRect.Height) / 2), finalSizeTransformed.Width, finalSizeTransformed.Height); // Perform an Arrange on _layoutRoot (containing Child) _layoutRoot.Arrange(finalRect); // This is the first opportunity to find out the Child's true DesiredSize if (IsSizeSmaller(finalSizeTransformed, child.RenderSize) && (Size.Empty == _childActualSize)) { // Unfortunately, all the work so far is invalid because the wrong DesiredSize was used // Make a note of the actual DesiredSize _childActualSize = new Size(child.ActualWidth, child.ActualHeight); // Force a new measure/arrange pass InvalidateMeasure(); } else { // Clear the "need to measure/arrange again" flag _childActualSize = Size.Empty; } // Return result to perform the transformation return finalSize; } /// <summary> /// Computes the largest usable size after applying the transformation to the specified bounds. /// </summary> /// <param name="arrangeBounds">The size to arrange within.</param> /// <returns>The size required.</returns> [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Closely corresponds to WPF's FrameworkElement.FindMaximalAreaLocalSpaceRect.")] private Size ComputeLargestTransformedSize(Size arrangeBounds) { // Computed largest transformed size Size computedSize = Size.Empty; // Detect infinite bounds and constrain the scenario bool infiniteWidth = double.IsInfinity(arrangeBounds.Width); if (infiniteWidth) { arrangeBounds.Width = arrangeBounds.Height; } bool infiniteHeight = double.IsInfinity(arrangeBounds.Height); if (infiniteHeight) { arrangeBounds.Height = arrangeBounds.Width; } // Capture the matrix parameters double a = _transformation.M11; double b = _transformation.M12; double c = _transformation.M21; double d = _transformation.M22; // Compute maximum possible transformed width/height based on starting width/height // These constraints define two lines in the positive x/y quadrant double maxWidthFromWidth = Math.Abs(arrangeBounds.Width / a); double maxHeightFromWidth = Math.Abs(arrangeBounds.Width / c); double maxWidthFromHeight = Math.Abs(arrangeBounds.Height / b); double maxHeightFromHeight = Math.Abs(arrangeBounds.Height / d); // The transformed width/height that maximize the area under each segment is its midpoint // At most one of the two midpoints will satisfy both constraints double idealWidthFromWidth = maxWidthFromWidth / 2; double idealHeightFromWidth = maxHeightFromWidth / 2; double idealWidthFromHeight = maxWidthFromHeight / 2; double idealHeightFromHeight = maxHeightFromHeight / 2; // Compute slope of both constraint lines double slopeFromWidth = -(maxHeightFromWidth / maxWidthFromWidth); double slopeFromHeight = -(maxHeightFromHeight / maxWidthFromHeight); if (arrangeBounds.Width == 0 || arrangeBounds.Height == 0) { // Check for empty bounds computedSize = new Size(0, 0); } else if (infiniteWidth && infiniteHeight) { // Check for completely unbound scenario computedSize = new Size(double.PositiveInfinity, double.PositiveInfinity); } else if (!MatrixHasInverse(_transformation)) { // Check for singular matrix computedSize = new Size(0, 0); } else if (b == 0 || c == 0) { // Check for 0/180 degree special cases double maxHeight = infiniteHeight ? double.PositiveInfinity : maxHeightFromHeight; double maxWidth = infiniteWidth ? double.PositiveInfinity : maxWidthFromWidth; if (b == 0 && c == 0) { // No constraints computedSize = new Size(maxWidth, maxHeight); } else if (b == 0) { // Constrained by width double computedHeight = Math.Min(idealHeightFromWidth, maxHeight); computedSize = new Size( maxWidth - Math.Abs((c * computedHeight) / a), computedHeight); } else if (c == 0) { // Constrained by height double computedWidth = Math.Min(idealWidthFromHeight, maxWidth); computedSize = new Size( computedWidth, maxHeight - Math.Abs((b * computedWidth) / d)); } } else if (a == 0 || d == 0) { // Check for 90/270 degree special cases double maxWidth = infiniteHeight ? double.PositiveInfinity : maxWidthFromHeight; double maxHeight = infiniteWidth ? double.PositiveInfinity : maxHeightFromWidth; if (a == 0 && d == 0) { // No constraints computedSize = new Size(maxWidth, maxHeight); } else if (a == 0) { // Constrained by width double computedHeight = Math.Min(idealHeightFromHeight, maxHeight); computedSize = new Size( maxWidth - Math.Abs((d * computedHeight) / b), computedHeight); } else if (d == 0) { // Constrained by height. double computedWidth = Math.Min(idealWidthFromWidth, maxWidth); computedSize = new Size( computedWidth, maxHeight - Math.Abs((a * computedWidth) / c)); } } else if (idealHeightFromWidth <= ((slopeFromHeight * idealWidthFromWidth) + maxHeightFromHeight)) { // Check the width midpoint for viability (by being below the height constraint line). computedSize = new Size(idealWidthFromWidth, idealHeightFromWidth); } else if (idealHeightFromHeight <= ((slopeFromWidth * idealWidthFromHeight) + maxHeightFromWidth)) { // Check the height midpoint for viability (by being below the width constraint line). computedSize = new Size(idealWidthFromHeight, idealHeightFromHeight); } else { // Neither midpoint is viable; use the intersection of the two constraint lines instead. // Compute width by setting heights equal (m1*x+c1=m2*x+c2). double computedWidth = (maxHeightFromHeight - maxHeightFromWidth) / (slopeFromWidth - slopeFromHeight); // Compute height from width constraint line (y=m*x+c; using height would give same result). computedSize = new Size( computedWidth, (slopeFromWidth * computedWidth) + maxHeightFromWidth); } return computedSize; } } }
{ "content_hash": "fe600fb9e044b728d4cb02981f708095", "timestamp": "", "source": "github", "line_count": 547, "max_line_length": 185, "avg_line_length": 42.79890310786106, "alnum_prop": 0.567681858955192, "repo_name": "bkaankose/UWPCommunityToolkit", "id": "4691b2406b1337f12f6b6349da917685bbc0ec24", "size": "23417", "binary": false, "copies": "2", "ref": "refs/heads/dev", "path": "Microsoft.Toolkit.Uwp.UI.Controls/LayoutTransformControl/LayoutTransformControl.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "2389" }, { "name": "C#", "bytes": "3952789" }, { "name": "HTML", "bytes": "2326" }, { "name": "PowerShell", "bytes": "41001" } ], "symlink_target": "" }