Dataset Preview
Duplicate
The full dataset viewer is not available (click to read why). Only showing a preview of the rows.
The dataset generation failed
Error code:   DatasetGenerationError
Exception:    ArrowInvalid
Message:      JSON parse error: Missing a closing quotation mark in string. in row 541
Traceback:    Traceback (most recent call last):
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/packaged_modules/json/json.py", line 145, in _generate_tables
                  dataset = json.load(f)
                File "/usr/local/lib/python3.9/json/__init__.py", line 293, in load
                  return loads(fp.read(),
                File "/usr/local/lib/python3.9/json/__init__.py", line 346, in loads
                  return _default_decoder.decode(s)
                File "/usr/local/lib/python3.9/json/decoder.py", line 340, in decode
                  raise JSONDecodeError("Extra data", s, end)
              json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 2003)
              
              During handling of the above exception, another exception occurred:
              
              Traceback (most recent call last):
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1995, in _prepare_split_single
                  for _, table in generator:
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/packaged_modules/json/json.py", line 148, in _generate_tables
                  raise e
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/packaged_modules/json/json.py", line 122, in _generate_tables
                  pa_table = paj.read_json(
                File "pyarrow/_json.pyx", line 308, in pyarrow._json.read_json
                File "pyarrow/error.pxi", line 154, in pyarrow.lib.pyarrow_internal_check_status
                File "pyarrow/error.pxi", line 91, in pyarrow.lib.check_status
              pyarrow.lib.ArrowInvalid: JSON parse error: Missing a closing quotation mark in string. in row 541
              
              The above exception was the direct cause of the following exception:
              
              Traceback (most recent call last):
                File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1529, in compute_config_parquet_and_info_response
                  parquet_operations = convert_to_parquet(builder)
                File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1154, in convert_to_parquet
                  builder.download_and_prepare(
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1027, in download_and_prepare
                  self._download_and_prepare(
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1122, in _download_and_prepare
                  self._prepare_split(split_generator, **prepare_split_kwargs)
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1882, in _prepare_split
                  for job_id, done, content in self._prepare_split_single(
                File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 2038, in _prepare_split_single
                  raise DatasetGenerationError("An error occurred while generating the dataset") from e
              datasets.exceptions.DatasetGenerationError: An error occurred while generating the dataset

Need help to make the dataset viewer work? Make sure to review how to configure the dataset viewer, and open a discussion for direct support.

text
string
meta
dict
<?php namespace Google\AdsApi\Dfp\v201705; /** * This file was generated from WSDL. DO NOT EDIT. */ class PublisherQueryLanguageSyntaxError extends \Google\AdsApi\Dfp\v201705\ApiError { /** * @var string $reason */ protected $reason = null; /** * @param string $fieldPath * @param \Google\AdsApi\Dfp\v201705\FieldPathElement[] $fieldPathElements * @param string $trigger * @param string $errorString * @param string $reason */ public function __construct($fieldPath = null, array $fieldPathElements = null, $trigger = null, $errorString = null, $reason = null) { parent::__construct($fieldPath, $fieldPathElements, $trigger, $errorString); $this->reason = $reason; } /** * @return string */ public function getReason() { return $this->reason; } /** * @param string $reason * @return \Google\AdsApi\Dfp\v201705\PublisherQueryLanguageSyntaxError */ public function setReason($reason) { $this->reason = $reason; return $this; } }
{ "content_hash": "641850bec6d5a8807ad70e6fdf0976bc", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 137, "avg_line_length": 22.666666666666668, "alnum_prop": 0.6194852941176471, "repo_name": "jeraldfeller/jbenterprises", "id": "ba2f9901aa84fa4d7620ccc6e69d0cf84cd619d7", "size": "1088", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "google-adwords/vendor/googleads/googleads-php-lib/src/Google/AdsApi/Dfp/v201705/PublisherQueryLanguageSyntaxError.php", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "137" }, { "name": "CSS", "bytes": "4465774" }, { "name": "CoffeeScript", "bytes": "83631" }, { "name": "HTML", "bytes": "2549782" }, { "name": "JavaScript", "bytes": "17552996" }, { "name": "PHP", "bytes": "3092947" }, { "name": "Shell", "bytes": "444" } ] }
package com.cloud.consoleproxy.util; import java.awt.Rectangle; import java.util.ArrayList; import java.util.List; public class RegionClassifier { private List<Region> regionList; public RegionClassifier() { regionList = new ArrayList<Region>(); } public void add(Rectangle rect) { boolean newRegion = true; Rectangle rcInflated = new Rectangle(rect.x - 1, rect.y - 1, rect.width + 2, rect.height + 2); for(Region region : regionList) { if(region.getBound().intersects(rcInflated)) { newRegion = false; break; } } if(newRegion) { regionList.add(new Region(rect)); } else { for(Region region : regionList) { if(region.add(rect)) return; } regionList.add(new Region(rect)); } } public List<Region> getRegionList() { return regionList; } public void clear() { regionList.clear(); } }
{ "content_hash": "ea41245e04c51cd92bb2058f375b65d1", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 96, "avg_line_length": 21.428571428571427, "alnum_prop": 0.64, "repo_name": "argv0/cloudstack", "id": "c4d9b82eb4e5a7b3fdfe36d4f47858f174233880", "size": "1701", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "console-proxy/src/com/cloud/consoleproxy/util/RegionClassifier.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "52484672" }, { "name": "JavaScript", "bytes": "1913801" }, { "name": "Perl", "bytes": "824212" }, { "name": "Python", "bytes": "2076246" }, { "name": "Ruby", "bytes": "2166" }, { "name": "Shell", "bytes": "445096" } ] }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `SA_NOCLDWAIT` constant in crate `libc`."> <meta name="keywords" content="rust, rustlang, rust-lang, SA_NOCLDWAIT"> <title>libc::SA_NOCLDWAIT - Rust</title> <link rel="stylesheet" type="text/css" href="../normalize.css"> <link rel="stylesheet" type="text/css" href="../rustdoc.css"> <link rel="stylesheet" type="text/css" href="../main.css"> <link rel="shortcut icon" href="https://doc.rust-lang.org/favicon.ico"> </head> <body class="rustdoc constant"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <nav class="sidebar"> <a href='../libc/index.html'><img src='https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png' alt='logo' width='100'></a> <p class='location'><a href='index.html'>libc</a></p><script>window.sidebarCurrent = {name: 'SA_NOCLDWAIT', ty: 'constant', relpath: ''};</script><script defer src="sidebar-items.js"></script> </nav> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"> </div> </form> </nav> <section id='main' class="content"> <h1 class='fqn'><span class='in-band'>Constant <a href='index.html'>libc</a>::<wbr><a class="constant" href=''>SA_NOCLDWAIT</a></span><span class='out-of-band'><span id='render-detail'> <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs"> [<span class='inner'>&#x2212;</span>] </a> </span><a class='srclink' href='../src/libc/unix/notbsd/linux/other/b64/x86_64.rs.html#281' title='goto source code'>[src]</a></span></h1> <pre class='rust const'>pub const SA_NOCLDWAIT: <a class="type" href="../libc/type.c_int.html" title="type libc::c_int">c_int</a><code> = </code><code>2</code></pre></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <aside id="help" class="hidden"> <div> <h1 class="hidden">Help</h1> <div class="shortcuts"> <h2>Keyboard Shortcuts</h2> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> <dt>+</dt> <dd>Collapse/expand all sections</dd> </dl> </div> <div class="infos"> <h2>Search Tricks</h2> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>. </p> <p> Search functions by type signature (e.g. <code>vec -> usize</code> or <code>* -> vec</code>) </p> </div> </div> </aside> <script> window.rootPath = "../"; window.currentCrate = "libc"; </script> <script src="../jquery.js"></script> <script src="../main.js"></script> <script defer src="../search-index.js"></script> </body> </html>
{ "content_hash": "71a67261e4a2019edec7129325a2940a", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 200, "avg_line_length": 38.30088495575221, "alnum_prop": 0.5122458410351202, "repo_name": "nitro-devs/nitro-game-engine", "id": "ba977eb69f2a758df3b3a40638c80741595cf4f5", "size": "4338", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/libc/constant.SA_NOCLDWAIT.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CMake", "bytes": "1032" }, { "name": "Rust", "bytes": "59380" } ] }
package net.sf.qualitytest.blueprint.strategy.creation; import org.junit.Assert; import org.junit.Test; public class RandomCharValueCreationStrategyTest { @Test public void testCreationStrategy() { Assert.assertNotNull(new RandomCharValueCreationStrategy().createValue(Character.class)); } }
{ "content_hash": "b02bdc68d39a9e97a2f3bb18e31aa790", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 91, "avg_line_length": 23.153846153846153, "alnum_prop": 0.8106312292358804, "repo_name": "before/quality-check", "id": "b4ec6c577b842575c48cfa47fd683ed2f5faa77e", "size": "1074", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/quality-test/src/test/java/net/sf/qualitytest/blueprint/strategy/creation/RandomCharValueCreationStrategyTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2514" }, { "name": "Java", "bytes": "1175447" } ] }
/** * SharedCriterionErrorReason.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter. */ package com.google.api.ads.adwords.axis.v201601.cm; public class SharedCriterionErrorReason implements java.io.Serializable { private java.lang.String _value_; private static java.util.HashMap _table_ = new java.util.HashMap(); // Constructor protected SharedCriterionErrorReason(java.lang.String value) { _value_ = value; _table_.put(_value_,this); } public static final java.lang.String _EXCEEDS_CRITERIA_LIMIT = "EXCEEDS_CRITERIA_LIMIT"; public static final java.lang.String _INCORRECT_CRITERION_TYPE = "INCORRECT_CRITERION_TYPE"; public static final java.lang.String _CANNOT_TARGET_AND_EXCLUDE = "CANNOT_TARGET_AND_EXCLUDE"; public static final java.lang.String _NEGATIVE_CRITERION_REQUIRED = "NEGATIVE_CRITERION_REQUIRED"; public static final java.lang.String _UNKNOWN = "UNKNOWN"; public static final SharedCriterionErrorReason EXCEEDS_CRITERIA_LIMIT = new SharedCriterionErrorReason(_EXCEEDS_CRITERIA_LIMIT); public static final SharedCriterionErrorReason INCORRECT_CRITERION_TYPE = new SharedCriterionErrorReason(_INCORRECT_CRITERION_TYPE); public static final SharedCriterionErrorReason CANNOT_TARGET_AND_EXCLUDE = new SharedCriterionErrorReason(_CANNOT_TARGET_AND_EXCLUDE); public static final SharedCriterionErrorReason NEGATIVE_CRITERION_REQUIRED = new SharedCriterionErrorReason(_NEGATIVE_CRITERION_REQUIRED); public static final SharedCriterionErrorReason UNKNOWN = new SharedCriterionErrorReason(_UNKNOWN); public java.lang.String getValue() { return _value_;} public static SharedCriterionErrorReason fromValue(java.lang.String value) throws java.lang.IllegalArgumentException { SharedCriterionErrorReason enumeration = (SharedCriterionErrorReason) _table_.get(value); if (enumeration==null) throw new java.lang.IllegalArgumentException(); return enumeration; } public static SharedCriterionErrorReason fromString(java.lang.String value) throws java.lang.IllegalArgumentException { return fromValue(value); } public boolean equals(java.lang.Object obj) {return (obj == this);} public int hashCode() { return toString().hashCode();} public java.lang.String toString() { return _value_;} public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);} public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.EnumSerializer( _javaType, _xmlType); } public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.EnumDeserializer( _javaType, _xmlType); } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(SharedCriterionErrorReason.class); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://adwords.google.com/api/adwords/cm/v201601", "SharedCriterionError.Reason")); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } }
{ "content_hash": "0f421c4cda9f0c29002b6a7a568e8ba0", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 143, "avg_line_length": 48.28947368421053, "alnum_prop": 0.7198910081743869, "repo_name": "gawkermedia/googleads-java-lib", "id": "ea24b7a1325185b59343ca7d02c0b26f9bd169ae", "size": "3670", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/adwords_axis/src/main/java/com/google/api/ads/adwords/axis/v201601/cm/SharedCriterionErrorReason.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "107468648" } ] }
package org.apache.hadoop.yarn.nodelabels; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.Path; import org.apache.hadoop.yarn.api.records.NodeId; import org.apache.hadoop.yarn.api.records.NodeLabel; import org.apache.hadoop.yarn.exceptions.YarnException; import org.apache.hadoop.yarn.nodelabels.store.FSStoreOpHandler; import org.apache.hadoop.yarn.nodelabels.store.StoreOp; import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * Store implementation for Non Appendable File Store. */ public class NonAppendableFSNodeLabelStore extends FileSystemNodeLabelsStore { protected static final Logger LOG = LoggerFactory.getLogger(NonAppendableFSNodeLabelStore.class); @Override public void close() throws IOException { } @Override public void recover() throws YarnException, IOException { Path newMirrorPath = new Path(fsWorkingPath, MIRROR_FILENAME + ".new"); Path oldMirrorPath = new Path(fsWorkingPath, MIRROR_FILENAME); loadFromMirror(newMirrorPath, oldMirrorPath); // if new mirror exists, remove old mirror and rename new mirror if (fs.exists(newMirrorPath)) { // remove old mirror try { fs.delete(oldMirrorPath, false); } catch (IOException e) { // do nothing LOG.debug("Exception while removing old mirror", e); } // rename new to old fs.rename(newMirrorPath, oldMirrorPath); } LOG.info("Node label store recover is completed"); } @Override public void updateNodeToLabelsMappings( Map<NodeId, Set<String>> nodeToLabels) throws IOException { writeNewMirror(); } @Override public void storeNewClusterNodeLabels(List<NodeLabel> labels) throws IOException { writeNewMirror(); } @Override public void removeClusterNodeLabels(Collection<String> labels) throws IOException { writeNewMirror(); } private void writeNewMirror() throws IOException { ReentrantReadWriteLock.ReadLock readLock = manager.readLock; // Acquire readlock to make sure we get cluster node labels and // node-to-labels mapping atomically. readLock.lock(); try { // Write mirror to mirror.new.tmp file Path newTmpPath = new Path(fsWorkingPath, MIRROR_FILENAME + ".new.tmp"); try (FSDataOutputStream os = fs.create(newTmpPath, true)) { StoreOp op = FSStoreOpHandler.getMirrorOp(getStoreType()); op.write(os, manager); } // Rename mirror.new.tmp to mirror.new (will remove .new if it's existed) Path newPath = new Path(fsWorkingPath, MIRROR_FILENAME + ".new"); fs.delete(newPath, false); fs.rename(newTmpPath, newPath); // Remove existing mirror and rename mirror.new to mirror Path mirrorPath = new Path(fsWorkingPath, MIRROR_FILENAME); fs.delete(mirrorPath, false); fs.rename(newPath, mirrorPath); } finally { readLock.unlock(); } } }
{ "content_hash": "61eb4cdc4abc7c75ed286ac8f6e6f297", "timestamp": "", "source": "github", "line_count": 102, "max_line_length": 79, "avg_line_length": 30.852941176470587, "alnum_prop": 0.7089291388624086, "repo_name": "apurtell/hadoop", "id": "0686f122cd72d6fa4c1f2c7956bac46f2bf2c6ea", "size": "3953", "binary": false, "copies": "10", "ref": "refs/heads/trunk", "path": "hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/nodelabels/NonAppendableFSNodeLabelStore.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "78445" }, { "name": "C", "bytes": "2023750" }, { "name": "C++", "bytes": "2873786" }, { "name": "CMake", "bytes": "120569" }, { "name": "CSS", "bytes": "94990" }, { "name": "Dockerfile", "bytes": "4613" }, { "name": "HTML", "bytes": "221057" }, { "name": "Handlebars", "bytes": "207062" }, { "name": "Java", "bytes": "97177756" }, { "name": "JavaScript", "bytes": "1273196" }, { "name": "Python", "bytes": "14938" }, { "name": "SCSS", "bytes": "23607" }, { "name": "Shell", "bytes": "517782" }, { "name": "TLA", "bytes": "14997" }, { "name": "TSQL", "bytes": "17801" }, { "name": "TeX", "bytes": "19322" }, { "name": "XSLT", "bytes": "18026" } ] }
<?php namespace Anomaly\FilesModule\Http\Controller\Admin; use Anomaly\FilesModule\File\Contract\FileInterface; use Anomaly\FilesModule\File\Contract\FileRepositoryInterface; use Anomaly\FilesModule\File\Form\EntryFormBuilder; use Anomaly\FilesModule\File\Form\FileEntryFormBuilder; use Anomaly\FilesModule\File\Form\FileFormBuilder; use Anomaly\FilesModule\File\Table\FileTableBuilder; use Anomaly\FilesModule\Folder\Command\GetFolder; use Anomaly\FilesModule\Folder\Contract\FolderInterface; use Anomaly\FilesModule\Folder\Contract\FolderRepositoryInterface; use Anomaly\Streams\Platform\Http\Controller\AdminController; /** * Class FilesController * * @link http://pyrocms.com/ * @author PyroCMS, Inc. <support@pyrocms.com> * @author Ryan Thompson <ryan@pyrocms.com> */ class FilesController extends AdminController { /** * Display an index of existing entries. * * @param FileTableBuilder $table * @return \Symfony\Component\HttpFoundation\Response */ public function index(FileTableBuilder $table) { return $table->render(); } /** * Return an ajax modal to choose the folder * to use for uploading files. * * @param FolderRepositoryInterface * @return \Illuminate\View\View */ public function choose(FolderRepositoryInterface $folders) { return $this->view->make( 'module::ajax/choose_folder', [ 'folders' => $folders->all(), ] ); } /** * Return the form for editing an existing file. * * @param FileRepositoryInterface $files * @param FileEntryFormBuilder $form * @param $id * @return \Symfony\Component\HttpFoundation\Response */ public function edit( FileRepositoryInterface $files, FileFormBuilder $fileForm, EntryFormBuilder $entryForm, FileEntryFormBuilder $form, $id ) { /* @var FileInterface $file */ $file = $files->find($id); $form->addForm( 'entry', $entryForm ->setFormMode('edit') ->setModel($file->getFolder()->getEntryModelName())->setEntry($file->getEntry()) ); $form->addForm('file', $fileForm->setEntry($file)); return $form->render($id); } /** * Redirect to a file's URL. * * @param FileRepositoryInterface $files * @return \Illuminate\Http\RedirectResponse */ public function view(FileRepositoryInterface $files) { /* @var FileInterface $file */ if (!$file = $files->find($this->route->getParameter('id'))) { abort(404); } return $this->redirect->to($file->route('view')); } /** * Return if a file exists or not. * * @param FileRepositoryInterface $files * @param $folder * @param $name * @return \Illuminate\Http\JsonResponse */ public function exists(FileRepositoryInterface $files, $folder, $name) { $success = true; $exists = false; /* @var FolderInterface|null $folder */ $folder = $this->dispatch(new GetFolder($folder)); if ($folder && $file = $files->findByNameAndFolder($name, $folder)) { $exists = true; } return $this->response->json(compact('success', 'exists')); } }
{ "content_hash": "06257ba975635a56776debee209aa298", "timestamp": "", "source": "github", "line_count": 120, "max_line_length": 96, "avg_line_length": 29.741666666666667, "alnum_prop": 0.5895208741944522, "repo_name": "vileopratama/portal-toyotadjakarta", "id": "8ccb6a49f6fd934a67d8abe9c8deb3bfec1ccd28", "size": "3569", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "core/anomaly/files-module/src/Http/Controller/Admin/FilesController.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "946" }, { "name": "Batchfile", "bytes": "731" }, { "name": "CSS", "bytes": "1331179" }, { "name": "HTML", "bytes": "2942360" }, { "name": "JavaScript", "bytes": "386767" }, { "name": "PHP", "bytes": "2361899" }, { "name": "Shell", "bytes": "4281" }, { "name": "Vue", "bytes": "559" } ] }
#include "curl_setup.h" #include <curl/curl.h> #include "urldata.h" #include "curl_base64.h" #include "curl_md5.h" #include "vauth/vauth.h" #include "vtls/vtls.h" #include "curl_hmac.h" #include "curl_sasl.h" #include "warnless.h" #include "strtok.h" #include "sendf.h" #include "non-ascii.h" /* included for Curl_convert_... prototypes */ /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" /* Supported mechanisms */ static const struct { const char *name; /* Name */ size_t len; /* Name length */ unsigned int bit; /* Flag bit */ } mechtable[] = { { "LOGIN", 5, SASL_MECH_LOGIN }, { "PLAIN", 5, SASL_MECH_PLAIN }, { "CRAM-MD5", 8, SASL_MECH_CRAM_MD5 }, { "DIGEST-MD5", 10, SASL_MECH_DIGEST_MD5 }, { "GSSAPI", 6, SASL_MECH_GSSAPI }, { "EXTERNAL", 8, SASL_MECH_EXTERNAL }, { "NTLM", 4, SASL_MECH_NTLM }, { "XOAUTH2", 7, SASL_MECH_XOAUTH2 }, { "OAUTHBEARER", 11, SASL_MECH_OAUTHBEARER }, { ZERO_NULL, 0, 0 } }; /* * Curl_sasl_cleanup() * * This is used to cleanup any libraries or curl modules used by the sasl * functions. * * Parameters: * * conn [in] - The connection data. * authused [in] - The authentication mechanism used. */ void Curl_sasl_cleanup(struct connectdata *conn, unsigned int authused) { #if defined(USE_KERBEROS5) /* Cleanup the gssapi structure */ if(authused == SASL_MECH_GSSAPI) { Curl_auth_gssapi_cleanup(&conn->krb5); } #endif #if defined(USE_NTLM) /* Cleanup the NTLM structure */ if(authused == SASL_MECH_NTLM) { Curl_auth_ntlm_cleanup(&conn->ntlm); } #endif #if !defined(USE_KERBEROS5) && !defined(USE_NTLM) /* Reserved for future use */ (void)conn; (void)authused; #endif } /* * Curl_sasl_decode_mech() * * Convert a SASL mechanism name into a token. * * Parameters: * * ptr [in] - The mechanism string. * maxlen [in] - Maximum mechanism string length. * len [out] - If not NULL, effective name length. * * Returns the SASL mechanism token or 0 if no match. */ unsigned int Curl_sasl_decode_mech(const char *ptr, size_t maxlen, size_t *len) { unsigned int i; char c; for(i = 0; mechtable[i].name; i++) { if(maxlen >= mechtable[i].len && !memcmp(ptr, mechtable[i].name, mechtable[i].len)) { if(len) *len = mechtable[i].len; if(maxlen == mechtable[i].len) return mechtable[i].bit; c = ptr[mechtable[i].len]; if(!ISUPPER(c) && !ISDIGIT(c) && c != '-' && c != '_') return mechtable[i].bit; } } return 0; } /* * Curl_sasl_parse_url_auth_option() * * Parse the URL login options. */ CURLcode Curl_sasl_parse_url_auth_option(struct SASL *sasl, const char *value, size_t len) { CURLcode result = CURLE_OK; unsigned int mechbit; size_t mechlen; if(!len) return CURLE_URL_MALFORMAT; if(sasl->resetprefs) { sasl->resetprefs = FALSE; sasl->prefmech = SASL_AUTH_NONE; } if(!strncmp(value, "*", len)) sasl->prefmech = SASL_AUTH_DEFAULT; else { mechbit = Curl_sasl_decode_mech(value, len, &mechlen); if(mechbit && mechlen == len) sasl->prefmech |= mechbit; else result = CURLE_URL_MALFORMAT; } return result; } /* * Curl_sasl_init() * * Initializes the SASL structure. */ void Curl_sasl_init(struct SASL *sasl, const struct SASLproto *params) { sasl->params = params; /* Set protocol dependent parameters */ sasl->state = SASL_STOP; /* Not yet running */ sasl->authmechs = SASL_AUTH_NONE; /* No known authentication mechanism yet */ sasl->prefmech = SASL_AUTH_DEFAULT; /* Prefer all mechanisms */ sasl->authused = SASL_AUTH_NONE; /* No the authentication mechanism used */ sasl->resetprefs = TRUE; /* Reset prefmech upon AUTH parsing. */ sasl->mutual_auth = FALSE; /* No mutual authentication (GSSAPI only) */ sasl->force_ir = FALSE; /* Respect external option */ } /* * state() * * This is the ONLY way to change SASL state! */ static void state(struct SASL *sasl, struct connectdata *conn, saslstate newstate) { #if defined(DEBUGBUILD) && !defined(CURL_DISABLE_VERBOSE_STRINGS) /* for debug purposes */ static const char * const names[]={ "STOP", "PLAIN", "LOGIN", "LOGIN_PASSWD", "EXTERNAL", "CRAMMD5", "DIGESTMD5", "DIGESTMD5_RESP", "NTLM", "NTLM_TYPE2MSG", "GSSAPI", "GSSAPI_TOKEN", "GSSAPI_NO_DATA", "OAUTH2", "OAUTH2_RESP", "CANCEL", "FINAL", /* LAST */ }; if(sasl->state != newstate) infof(conn->data, "SASL %p state change from %s to %s\n", (void *)sasl, names[sasl->state], names[newstate]); #else (void) conn; #endif sasl->state = newstate; } /* * Curl_sasl_can_authenticate() * * Check if we have enough auth data and capabilities to authenticate. */ bool Curl_sasl_can_authenticate(struct SASL *sasl, struct connectdata *conn) { /* Have credentials been provided? */ if(conn->bits.user_passwd) return TRUE; /* EXTERNAL can authenticate without a user name and/or password */ if(sasl->authmechs & sasl->prefmech & SASL_MECH_EXTERNAL) return TRUE; return FALSE; } /* * Curl_sasl_start() * * Calculate the required login details for SASL authentication. */ CURLcode Curl_sasl_start(struct SASL *sasl, struct connectdata *conn, bool force_ir, saslprogress *progress) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; unsigned int enabledmechs; const char *mech = NULL; char *resp = NULL; size_t len = 0; saslstate state1 = SASL_STOP; saslstate state2 = SASL_FINAL; const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name : conn->host.name; const long int port = SSL_IS_PROXY() ? conn->port : conn->remote_port; #if defined(USE_KERBEROS5) || defined(USE_NTLM) const char *service = data->set.str[STRING_SERVICE_NAME] ? data->set.str[STRING_SERVICE_NAME] : sasl->params->service; #endif sasl->force_ir = force_ir; /* Latch for future use */ sasl->authused = 0; /* No mechanism used yet */ enabledmechs = sasl->authmechs & sasl->prefmech; *progress = SASL_IDLE; /* Calculate the supported authentication mechanism, by decreasing order of security, as well as the initial response where appropriate */ if((enabledmechs & SASL_MECH_EXTERNAL) && !conn->passwd[0]) { mech = SASL_MECH_STRING_EXTERNAL; state1 = SASL_EXTERNAL; sasl->authused = SASL_MECH_EXTERNAL; if(force_ir || data->set.sasl_ir) result = Curl_auth_create_external_message(data, conn->user, &resp, &len); } else if(conn->bits.user_passwd) { #if defined(USE_KERBEROS5) if((enabledmechs & SASL_MECH_GSSAPI) && Curl_auth_is_gssapi_supported() && Curl_auth_user_contains_domain(conn->user)) { sasl->mutual_auth = FALSE; /* TODO: Calculate mutual authentication */ mech = SASL_MECH_STRING_GSSAPI; state1 = SASL_GSSAPI; state2 = SASL_GSSAPI_TOKEN; sasl->authused = SASL_MECH_GSSAPI; if(force_ir || data->set.sasl_ir) result = Curl_auth_create_gssapi_user_message(data, conn->user, conn->passwd, service, data->easy_conn-> host.name, sasl->mutual_auth, NULL, &conn->krb5, &resp, &len); } else #endif #ifndef CURL_DISABLE_CRYPTO_AUTH if((enabledmechs & SASL_MECH_DIGEST_MD5) && Curl_auth_is_digest_supported()) { mech = SASL_MECH_STRING_DIGEST_MD5; state1 = SASL_DIGESTMD5; sasl->authused = SASL_MECH_DIGEST_MD5; } else if(enabledmechs & SASL_MECH_CRAM_MD5) { mech = SASL_MECH_STRING_CRAM_MD5; state1 = SASL_CRAMMD5; sasl->authused = SASL_MECH_CRAM_MD5; } else #endif #ifdef USE_NTLM if((enabledmechs & SASL_MECH_NTLM) && Curl_auth_is_ntlm_supported()) { mech = SASL_MECH_STRING_NTLM; state1 = SASL_NTLM; state2 = SASL_NTLM_TYPE2MSG; sasl->authused = SASL_MECH_NTLM; if(force_ir || data->set.sasl_ir) result = Curl_auth_create_ntlm_type1_message(data, conn->user, conn->passwd, service, hostname, &conn->ntlm, &resp, &len); } else #endif if((enabledmechs & SASL_MECH_OAUTHBEARER) && conn->oauth_bearer) { mech = SASL_MECH_STRING_OAUTHBEARER; state1 = SASL_OAUTH2; state2 = SASL_OAUTH2_RESP; sasl->authused = SASL_MECH_OAUTHBEARER; if(force_ir || data->set.sasl_ir) result = Curl_auth_create_oauth_bearer_message(data, conn->user, hostname, port, conn->oauth_bearer, &resp, &len); } else if((enabledmechs & SASL_MECH_XOAUTH2) && conn->oauth_bearer) { mech = SASL_MECH_STRING_XOAUTH2; state1 = SASL_OAUTH2; sasl->authused = SASL_MECH_XOAUTH2; if(force_ir || data->set.sasl_ir) result = Curl_auth_create_oauth_bearer_message(data, conn->user, NULL, 0, conn->oauth_bearer, &resp, &len); } else if(enabledmechs & SASL_MECH_PLAIN) { mech = SASL_MECH_STRING_PLAIN; state1 = SASL_PLAIN; sasl->authused = SASL_MECH_PLAIN; if(force_ir || data->set.sasl_ir) result = Curl_auth_create_plain_message(data, conn->user, conn->passwd, &resp, &len); } else if(enabledmechs & SASL_MECH_LOGIN) { mech = SASL_MECH_STRING_LOGIN; state1 = SASL_LOGIN; state2 = SASL_LOGIN_PASSWD; sasl->authused = SASL_MECH_LOGIN; if(force_ir || data->set.sasl_ir) result = Curl_auth_create_login_message(data, conn->user, &resp, &len); } } if(!result && mech) { if(resp && sasl->params->maxirlen && strlen(mech) + len > sasl->params->maxirlen) { free(resp); resp = NULL; } result = sasl->params->sendauth(conn, mech, resp); if(!result) { *progress = SASL_INPROGRESS; state(sasl, conn, resp ? state2 : state1); } } free(resp); return result; } /* * Curl_sasl_continue() * * Continue the authentication. */ CURLcode Curl_sasl_continue(struct SASL *sasl, struct connectdata *conn, int code, saslprogress *progress) { CURLcode result = CURLE_OK; struct Curl_easy *data = conn->data; saslstate newstate = SASL_FINAL; char *resp = NULL; const char * const hostname = SSL_IS_PROXY() ? conn->http_proxy.host.name : conn->host.name; const long int port = SSL_IS_PROXY() ? conn->port : conn->remote_port; #if !defined(CURL_DISABLE_CRYPTO_AUTH) char *chlg = NULL; size_t chlglen = 0; #endif #if !defined(CURL_DISABLE_CRYPTO_AUTH) || defined(USE_KERBEROS5) || \ defined(USE_NTLM) const char *service = data->set.str[STRING_SERVICE_NAME] ? data->set.str[STRING_SERVICE_NAME] : sasl->params->service; char *serverdata; #endif size_t len = 0; *progress = SASL_INPROGRESS; if(sasl->state == SASL_FINAL) { if(code != sasl->params->finalcode) result = CURLE_LOGIN_DENIED; *progress = SASL_DONE; state(sasl, conn, SASL_STOP); return result; } if(sasl->state != SASL_CANCEL && sasl->state != SASL_OAUTH2_RESP && code != sasl->params->contcode) { *progress = SASL_DONE; state(sasl, conn, SASL_STOP); return CURLE_LOGIN_DENIED; } switch(sasl->state) { case SASL_STOP: *progress = SASL_DONE; return result; case SASL_PLAIN: result = Curl_auth_create_plain_message(data, conn->user, conn->passwd, &resp, &len); break; case SASL_LOGIN: result = Curl_auth_create_login_message(data, conn->user, &resp, &len); newstate = SASL_LOGIN_PASSWD; break; case SASL_LOGIN_PASSWD: result = Curl_auth_create_login_message(data, conn->passwd, &resp, &len); break; case SASL_EXTERNAL: result = Curl_auth_create_external_message(data, conn->user, &resp, &len); break; #ifndef CURL_DISABLE_CRYPTO_AUTH case SASL_CRAMMD5: sasl->params->getmessage(data->state.buffer, &serverdata); result = Curl_auth_decode_cram_md5_message(serverdata, &chlg, &chlglen); if(!result) result = Curl_auth_create_cram_md5_message(data, chlg, conn->user, conn->passwd, &resp, &len); free(chlg); break; case SASL_DIGESTMD5: sasl->params->getmessage(data->state.buffer, &serverdata); result = Curl_auth_create_digest_md5_message(data, serverdata, conn->user, conn->passwd, service, &resp, &len); newstate = SASL_DIGESTMD5_RESP; break; case SASL_DIGESTMD5_RESP: resp = strdup(""); if(!resp) result = CURLE_OUT_OF_MEMORY; break; #endif #ifdef USE_NTLM case SASL_NTLM: /* Create the type-1 message */ result = Curl_auth_create_ntlm_type1_message(data, conn->user, conn->passwd, service, hostname, &conn->ntlm, &resp, &len); newstate = SASL_NTLM_TYPE2MSG; break; case SASL_NTLM_TYPE2MSG: /* Decode the type-2 message */ sasl->params->getmessage(data->state.buffer, &serverdata); result = Curl_auth_decode_ntlm_type2_message(data, serverdata, &conn->ntlm); if(!result) result = Curl_auth_create_ntlm_type3_message(data, conn->user, conn->passwd, &conn->ntlm, &resp, &len); break; #endif #if defined(USE_KERBEROS5) case SASL_GSSAPI: result = Curl_auth_create_gssapi_user_message(data, conn->user, conn->passwd, service, data->easy_conn->host.name, sasl->mutual_auth, NULL, &conn->krb5, &resp, &len); newstate = SASL_GSSAPI_TOKEN; break; case SASL_GSSAPI_TOKEN: sasl->params->getmessage(data->state.buffer, &serverdata); if(sasl->mutual_auth) { /* Decode the user token challenge and create the optional response message */ result = Curl_auth_create_gssapi_user_message(data, NULL, NULL, NULL, NULL, sasl->mutual_auth, serverdata, &conn->krb5, &resp, &len); newstate = SASL_GSSAPI_NO_DATA; } else /* Decode the security challenge and create the response message */ result = Curl_auth_create_gssapi_security_message(data, serverdata, &conn->krb5, &resp, &len); break; case SASL_GSSAPI_NO_DATA: sasl->params->getmessage(data->state.buffer, &serverdata); /* Decode the security challenge and create the response message */ result = Curl_auth_create_gssapi_security_message(data, serverdata, &conn->krb5, &resp, &len); break; #endif case SASL_OAUTH2: /* Create the authorisation message */ if(sasl->authused == SASL_MECH_OAUTHBEARER) { result = Curl_auth_create_oauth_bearer_message(data, conn->user, hostname, port, conn->oauth_bearer, &resp, &len); /* Failures maybe sent by the server as continuations for OAUTHBEARER */ newstate = SASL_OAUTH2_RESP; } else result = Curl_auth_create_oauth_bearer_message(data, conn->user, NULL, 0, conn->oauth_bearer, &resp, &len); break; case SASL_OAUTH2_RESP: /* The continuation is optional so check the response code */ if(code == sasl->params->finalcode) { /* Final response was received so we are done */ *progress = SASL_DONE; state(sasl, conn, SASL_STOP); return result; } else if(code == sasl->params->contcode) { /* Acknowledge the continuation by sending a 0x01 response base64 encoded */ resp = strdup("AQ=="); if(!resp) result = CURLE_OUT_OF_MEMORY; break; } else { *progress = SASL_DONE; state(sasl, conn, SASL_STOP); return CURLE_LOGIN_DENIED; } case SASL_CANCEL: /* Remove the offending mechanism from the supported list */ sasl->authmechs ^= sasl->authused; /* Start an alternative SASL authentication */ result = Curl_sasl_start(sasl, conn, sasl->force_ir, progress); newstate = sasl->state; /* Use state from Curl_sasl_start() */ break; default: failf(data, "Unsupported SASL authentication mechanism"); result = CURLE_UNSUPPORTED_PROTOCOL; /* Should not happen */ break; } switch(result) { case CURLE_BAD_CONTENT_ENCODING: /* Cancel dialog */ result = sasl->params->sendcont(conn, "*"); newstate = SASL_CANCEL; break; case CURLE_OK: if(resp) result = sasl->params->sendcont(conn, resp); break; default: newstate = SASL_STOP; /* Stop on error */ *progress = SASL_DONE; break; } free(resp); state(sasl, conn, newstate); return result; }
{ "content_hash": "911b5ac3db645821a9c4b70fa01ac061", "timestamp": "", "source": "github", "line_count": 601, "max_line_length": 79, "avg_line_length": 31.943427620632278, "alnum_prop": 0.538441504323367, "repo_name": "draede/cx", "id": "e54e4875e2d9202afe5ec93bf51b8a4f8efd885c", "size": "20598", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Contrib/cURL/Src/curl_sasl.c", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "4691" }, { "name": "C", "bytes": "15739837" }, { "name": "C++", "bytes": "4586671" }, { "name": "Makefile", "bytes": "11584" } ] }
static CGFloat am_backgroundInset = 1.5; static CGFloat am_textGap = 1.5; static CGFloat am_bezierPathFlatness = 0.2; @interface AMButtonBarCell (Private) - (NSSize)lastFrameSize; - (void)setLastFrameSize:(NSSize)newLastFrameSize; - (CGFloat)calculateTextInsetForRadius:(CGFloat)radius font:(NSFont *)font; - (void)finishInit; @end @implementation AMButtonBarCell + (NSColor *)offControlColor { static NSColor *offControlColor = nil; if (!offControlColor) { offControlColor = [[NSColor clearColor] retain]; } return offControlColor; } + (NSColor *)offTextColor { static NSColor *offTextColor = nil; if (!offTextColor) { offTextColor = [[NSColor colorWithCalibratedWhite:0 alpha:1] retain]; } return offTextColor; } + (NSShadow *)offTextShadow { static NSShadow *offTextShadow = nil; if (!offTextShadow) { NSColor *color = [NSColor colorWithCalibratedWhite:1 alpha:1]; offTextShadow = [[NSShadow shadowWithColor:color blurRadius:1 offset:NSMakeSize(0, -1)] retain]; } return offTextShadow; } + (NSColor *)offMouseOverControlColor { static NSColor *offMouseOverControlColor = nil; if (!offMouseOverControlColor) { offMouseOverControlColor = [[NSColor colorWithCalibratedWhite:.5 alpha:.5] retain]; } return offMouseOverControlColor; } + (NSColor *)offMouseOverTextColor { static NSColor *offMouseOverTextColor = nil; if (!offMouseOverTextColor) { offMouseOverTextColor = [[NSColor colorWithCalibratedWhite:1 alpha:1] retain]; } return offMouseOverTextColor; } + (NSShadow *)offMouseOverTextShadow { static NSShadow *offMouseOverTextShadow = nil; // if (!offMouseOverTextShadow) { // NSColor *color = [NSColor colorWithCalibratedWhite:.2 alpha:1]; // offMouseOverTextShadow = [[NSShadow shadowWithColor:color blurRadius:1 offset:NSMakeSize(0, 1)] retain]; // } return offMouseOverTextShadow; } + (NSColor *)onControlColor { static NSColor *onControlColor = nil; if (!onControlColor) { onControlColor = [[NSColor colorWithCalibratedWhite:.6 alpha:1] retain]; } return onControlColor; } + (NSShadow *)onControlUpperShadow { static NSShadow *onControlUpperShadow = nil; if (!onControlUpperShadow) { NSColor *color = [NSColor colorWithCalibratedWhite:.0 alpha:.5]; onControlUpperShadow = [[NSShadow shadowWithColor:color blurRadius:1 offset:NSMakeSize(0, 1)] retain]; } return onControlUpperShadow; } + (NSShadow *)onControlLowerShadow { static NSShadow *onControlLowerShadow = nil; if (!onControlLowerShadow) { NSColor *color = [NSColor colorWithCalibratedWhite:1 alpha:.5]; onControlLowerShadow = [[NSShadow shadowWithColor:color blurRadius:1 offset:NSMakeSize(0, -1)] retain]; } return onControlLowerShadow; } + (NSColor *)onTextColor { static NSColor *onTextColor = nil; if (!onTextColor) { onTextColor = [[NSColor colorWithCalibratedWhite:1 alpha:1] retain]; } return onTextColor; } + (NSShadow *)onTextShadow { static NSShadow *onTextShadow = nil; if (!onTextShadow) { NSColor *color = [NSColor colorWithCalibratedWhite:.6 alpha:1]; onTextShadow = [[NSShadow shadowWithColor:color blurRadius:1 offset:NSMakeSize(0, 1)] retain]; } return onTextShadow; } + (NSColor *)onMouseOverControlColor { static NSColor *onMouseOverControlColor = nil; if (!onMouseOverControlColor) { onMouseOverControlColor = [[NSColor colorWithCalibratedWhite:.68 alpha:1] retain]; } return onMouseOverControlColor; } + (NSShadow *)onMouseOverControlUpperShadow { static NSShadow *onMouseOverControlUpperShadow = nil; if (!onMouseOverControlUpperShadow) { NSColor *color = [NSColor colorWithCalibratedWhite:0 alpha:.5]; onMouseOverControlUpperShadow = [[NSShadow shadowWithColor:color blurRadius:1 offset:NSMakeSize(0, 1)] retain]; } return onMouseOverControlUpperShadow; } + (NSShadow *)onMouseOverControlLowerShadow { static NSShadow *onMouseOverControlLowerShadow = nil; if (!onMouseOverControlLowerShadow) { NSColor *color = [NSColor colorWithCalibratedWhite:1 alpha:.5]; onMouseOverControlLowerShadow = [[NSShadow shadowWithColor:color blurRadius:1 offset:NSMakeSize(0, -1)] retain]; } return onMouseOverControlLowerShadow; } + (NSColor *)onMouseOverTextColor { static NSColor *onMouseOverTextColor = nil; if (!onMouseOverTextColor) { onMouseOverTextColor = [[NSColor colorWithCalibratedWhite:1 alpha:1] retain]; } return onMouseOverTextColor; } + (NSShadow *)onMouseOverTextShadow { static NSShadow *onMouseOverTextShadow = nil; // if (!onMouseOverTextShadow) { // NSColor *color = [NSColor colorWithCalibratedWhite:.7 alpha:1]; // onMouseOverTextShadow = [[NSShadow shadowWithColor:color blurRadius:1 offset:NSMakeSize(0, 1)] retain]; // } return onMouseOverTextShadow; } + (NSColor *)mouseDownControlColor { static NSColor *mouseDownControlColor = nil; if (!mouseDownControlColor) { mouseDownControlColor = [[NSColor colorWithCalibratedWhite:.5 alpha:1] retain]; } return mouseDownControlColor; } + (NSShadow *)mouseDownControlUpperShadow { static NSShadow *mouseDownControlUpperShadow = nil; if (!mouseDownControlUpperShadow) { NSColor *color = [NSColor colorWithCalibratedWhite:0 alpha:.4]; mouseDownControlUpperShadow = [[NSShadow shadowWithColor:color blurRadius:1 offset:NSMakeSize(0, 1)] retain]; } return mouseDownControlUpperShadow; } + (NSShadow *)mouseDownControlLowerShadow { static NSShadow *mouseDownControlLowerShadow = nil; if (!mouseDownControlLowerShadow) { NSColor *color = [NSColor colorWithCalibratedWhite:.9 alpha:.5]; mouseDownControlLowerShadow = [[NSShadow shadowWithColor:color blurRadius:1 offset:NSMakeSize(0, -1)] retain]; } return mouseDownControlLowerShadow; } + (NSColor *)mouseDownTextColor { static NSColor *mouseDownTextColor = nil; if (!mouseDownTextColor) { mouseDownTextColor = [[NSColor colorWithCalibratedWhite:1 alpha:1] retain]; } return mouseDownTextColor; } + (NSShadow *)mouseDownTextShadow { static NSShadow *mouseDownTextShadow = nil; if (!mouseDownTextShadow) { NSColor *color = [NSColor colorWithCalibratedWhite:.4 alpha:1]; mouseDownTextShadow = [[NSShadow shadowWithColor:color blurRadius:1 offset:NSMakeSize(0, 1)] retain]; } return mouseDownTextShadow; } - (id)initTextCell:(NSString *)aString { if (self = [super initTextCell:aString]) { [self finishInit]; } return self; } - (void)finishInit { [super setBezelStyle:NSShadowlessSquareBezelStyle]; [self setAlignment:NSCenterTextAlignment]; } - (id)initWithCoder:(NSCoder *)decoder { self = [super initWithCoder:decoder]; [self setAlignment:NSCenterTextAlignment]; return self; } - (void)encodeWithCoder:(NSCoder *)coder { [super encodeWithCoder:coder]; } - (void)dealloc { [am_controlPath release]; [am_innerControlPath release]; [super dealloc]; } - (NSBezierPath *)backgroundPath { return am_controlPath; } - (void)setControlPath:(NSBezierPath *)newControlPath { id old = nil; if (newControlPath != am_controlPath) { old = am_controlPath; am_controlPath = [newControlPath retain]; [old release]; } } - (NSBezierPath *)innerControlPath { return am_innerControlPath; } - (void)setInnerControlPath:(NSBezierPath *)newInnerControlPath { id old = nil; if (newInnerControlPath != am_innerControlPath) { old = am_innerControlPath; am_innerControlPath = [newInnerControlPath retain]; [old release]; } } - (NSSize)lastFrameSize { return am_lastFrameSize; } - (void)setLastFrameSize:(NSSize)newLastFrameSize { am_lastFrameSize = newLastFrameSize; } - (BOOL)mouseOver { return am_mouseOver; } - (void)setMouseOver:(BOOL)newMouseOver { am_mouseOver = newMouseOver; } - (BOOL)mouseDown { return am_mouseDown; } - (void)setMouseDown:(BOOL)value { am_mouseDown = value; } - (void)calculateLayoutForFrame:(NSRect)cellFrame inView:(NSView *)controlView { // bezier path for plate background [self setLastFrameSize:cellFrame.size]; NSRect innerRect = NSInsetRect(cellFrame, am_backgroundInset, am_backgroundInset); // text rect am_textRect = innerRect; NSFont *font = [self font]; NSDictionary *stringAttributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil]; NSAttributedString *string = [[[NSAttributedString alloc] initWithString:[self title] attributes:stringAttributes] autorelease]; NSSize size = [string size]; CGFloat radius = (am_lastFrameSize.height/2.0)-am_backgroundInset; // calculate minimum text inset CGFloat textInset; CGFloat h = [font ascender]/2.0; textInset = ceilf((float)(radius-sqrt(radius*radius - h*h))); am_textRect = NSInsetRect(am_textRect, textInset+am_textGap, 0); am_textRect.size.height = size.height; CGFloat capHeight = [font fixed_capHeight]; CGFloat ascender = [font ascender]; CGFloat yOrigin = innerRect.origin.y; CGFloat offset = ((innerRect.size.height-am_textRect.size.height) / 2.0); offset += (ascender-capHeight)-((am_textRect.size.height-capHeight) / 2.0); yOrigin += floorf((float)offset); am_textRect.origin.y = yOrigin; // bezier path for button background innerRect.origin.x = 0; innerRect.origin.y = 0; id returnValue; returnValue = [NSBezierPath bezierPathWithPlateInRect:innerRect]; [self setControlPath:returnValue]; // bezier path for pressed button (with gap for shadows) innerRect.size.height--; innerRect.origin.y++; returnValue = [NSBezierPath bezierPathWithPlateInRect:innerRect]; [self setInnerControlPath:returnValue]; } - (void)drawWithFrame:(NSRect)cellFrame inView:(NSView *)controlView { if ((am_lastFrameSize.width != cellFrame.size.width) || (am_lastFrameSize.height != cellFrame.size.height)) { [self calculateLayoutForFrame:cellFrame inView:controlView]; } [self drawInteriorWithFrame:cellFrame inView:controlView]; } - (void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView *)controlView { NSBezierPath *path; NSColor *controlColor; NSShadow *upperShadow = nil; NSShadow *lowerShadow = nil; NSColor *textColor; NSShadow *textShadow; NSAffineTransform *transformation = [NSAffineTransform transform]; [transformation translateXBy:cellFrame.origin.x+am_backgroundInset yBy:cellFrame.origin.y+am_backgroundInset]; if (![self isEnabled]) { // disabled if ([self state] == NSOnState) { // on controlColor = [AMButtonBarCell onControlColor]; upperShadow = [AMButtonBarCell onControlUpperShadow]; lowerShadow = [AMButtonBarCell onControlLowerShadow]; path = [[am_innerControlPath copy] autorelease]; textColor = [AMButtonBarCell onTextColor]; textShadow = [AMButtonBarCell onTextShadow]; } else { // off controlColor = [AMButtonBarCell offControlColor]; path = [[am_controlPath copy] autorelease]; textColor = [AMButtonBarCell offTextColor]; textShadow = [AMButtonBarCell offTextShadow]; } controlColor = [controlColor disabledColor]; textColor = [textColor disabledColor]; } else { // enabled if ([self isHighlighted]) { // mouse down controlColor = [AMButtonBarCell mouseDownControlColor]; upperShadow = [AMButtonBarCell mouseDownControlUpperShadow]; lowerShadow = [AMButtonBarCell mouseDownControlLowerShadow]; path = [[am_innerControlPath copy] autorelease]; textColor = [AMButtonBarCell mouseDownTextColor]; textShadow = [AMButtonBarCell mouseDownTextShadow]; } else if ([self state] == NSOnState) { // on if (am_mouseOver) { controlColor = [AMButtonBarCell onMouseOverControlColor]; upperShadow = [AMButtonBarCell onMouseOverControlUpperShadow]; lowerShadow = [AMButtonBarCell onMouseOverControlLowerShadow]; path = [[am_innerControlPath copy] autorelease]; textColor = [AMButtonBarCell onMouseOverTextColor]; textShadow = [AMButtonBarCell onMouseOverTextShadow]; } else { controlColor = [AMButtonBarCell onControlColor]; upperShadow = [AMButtonBarCell onControlUpperShadow]; lowerShadow = [AMButtonBarCell onControlLowerShadow]; path = [[am_innerControlPath copy] autorelease]; textColor = [AMButtonBarCell onTextColor]; textShadow = [AMButtonBarCell onTextShadow]; } } else { // off if (am_mouseOver) { controlColor = [AMButtonBarCell offMouseOverControlColor]; path = [[am_controlPath copy] autorelease]; textColor = [AMButtonBarCell offMouseOverTextColor]; textShadow = [AMButtonBarCell offMouseOverTextShadow]; } else { controlColor = [AMButtonBarCell offControlColor]; path = [[am_controlPath copy] autorelease]; textColor = [AMButtonBarCell offTextColor]; textShadow = [AMButtonBarCell offTextShadow]; } } } [NSGraphicsContext saveGraphicsState]; [path transformUsingAffineTransform:transformation]; [path setLineWidth:0.0]; [path setFlatness:am_bezierPathFlatness]; if (upperShadow) { // draw two halves with shadow [controlColor set]; [NSGraphicsContext saveGraphicsState]; // adjust clipping rectangle NSRect halfFrame = cellFrame; halfFrame.size.height = floorf((float)(halfFrame.size.height/2)); [NSBezierPath clipRect:halfFrame]; [upperShadow set]; [path fill]; [NSGraphicsContext restoreGraphicsState]; [NSGraphicsContext saveGraphicsState]; halfFrame.origin.y = cellFrame.origin.y+halfFrame.size.height; [NSBezierPath clipRect:halfFrame]; [lowerShadow set]; [path fill]; [NSGraphicsContext restoreGraphicsState]; // draw middle part without shadow halfFrame.origin.y = cellFrame.origin.y+floorf((float)(cellFrame.size.height/2))-1; halfFrame.size.height = 2; [NSBezierPath clipRect:halfFrame]; [path fill]; } else { // draw one path only [controlColor set]; [path fill]; } [NSGraphicsContext restoreGraphicsState]; [NSGraphicsContext saveGraphicsState]; [textShadow set]; // draw button title NSDictionary *stringAttributes; NSFont *font; NSMutableParagraphStyle *parapraphStyle = [[[NSMutableParagraphStyle alloc] init] autorelease]; [parapraphStyle setAlignment:[self alignment]]; font = [self font]; stringAttributes = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, textColor, NSForegroundColorAttributeName, parapraphStyle, NSParagraphStyleAttributeName, nil]; [[self title] drawInRect:am_textRect withAttributes:stringAttributes]; [NSGraphicsContext restoreGraphicsState]; } - (CGFloat)widthForFrame:(NSRect)frameRect { if ([self title] == nil) return 0.0; CGFloat result; NSFont *font = [self font]; NSDictionary *attrs = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil]; result = [[self title] sizeWithAttributes:attrs].width; CGFloat radius = (frameRect.size.height/2.0)-am_backgroundInset; CGFloat textInset; CGFloat h = [font ascender]/2.0; textInset = ceilf((float)(radius-sqrt(radius*radius - h*h)+(radius*0.25))); result += 2.0*(textInset+am_backgroundInset+am_textGap); if ([self menu] != nil) { CGFloat arrowWidth = [NSFont systemFontSizeForControlSize:[self controlSize]]*0.6; result += (radius*0.5)+arrowWidth; } return result; } - (BOOL)trackMouse:(NSEvent *)theEvent inRect:(NSRect)cellFrame ofView:(NSView *)controlView untilMouseUp:(BOOL)untilMouseUp { BOOL result = NO; //NSLog(@"trackMouse:inRect:ofView:untilMouseUp:"); NSDate *endDate; NSPoint currentPoint = [theEvent locationInWindow]; BOOL done = NO; BOOL trackContinously = [self startTrackingAt:currentPoint inView:controlView]; // catch next mouse-dragged or mouse-up event until timeout BOOL mouseIsUp = NO; NSEvent *event; while (!done) { // loop ... NSPoint lastPoint = currentPoint; endDate = [NSDate distantFuture]; event = [NSApp nextEventMatchingMask:(NSLeftMouseUpMask|NSLeftMouseDraggedMask) untilDate:endDate inMode:NSEventTrackingRunLoopMode dequeue:YES]; if (event) { // mouse event currentPoint = [event locationInWindow]; if (trackContinously) { // send continueTracking.../stopTracking... if (![self continueTracking:lastPoint at:currentPoint inView:controlView]) { done = YES; [self stopTracking:lastPoint at:currentPoint inView:controlView mouseIsUp:mouseIsUp]; } if ([self isContinuous]) { [NSApp sendAction:[self action] to:[self target] from:controlView]; } } mouseIsUp = ([event type] == NSLeftMouseUp); [self setMouseDown:mouseIsUp]; done = done || mouseIsUp; if (untilMouseUp) { result = mouseIsUp; } else { // check, if the mouse left our cell rect result = NSPointInRect([controlView convertPoint:currentPoint fromView:nil], cellFrame); if (!result) { done = YES; [self setMouseOver:NO]; } else { [self setMouseOver:YES]; } } if (done && result && ![self isContinuous]) { [NSApp sendAction:[self action] to:[self target] from:controlView]; } } else { // show menu done = YES; result = YES; // [self showMenuForEvent:theEvent controlView:controlView cellFrame:cellFrame]; } } // while (!done) return result; } @end
{ "content_hash": "f22f6afe7be3d7a8e38b51c37820f056", "timestamp": "", "source": "github", "line_count": 557, "max_line_length": 185, "avg_line_length": 30.210053859964095, "alnum_prop": 0.7452308789445534, "repo_name": "hsoft/ambuttonbar", "id": "4b9c7216e9d951acded9a1e2280a0c3730a06e52", "size": "17251", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AMButtonBarCell.m", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Objective-C", "bytes": "55947" } ] }
import {CompileReflector, ExternalReference, Identifiers, getUrlScheme, syntaxError} from '@angular/compiler'; import {ANALYZE_FOR_ENTRY_COMPONENTS, ChangeDetectionStrategy, ChangeDetectorRef, Component, ComponentFactory, ComponentFactoryResolver, ComponentRef, ElementRef, Injector, LOCALE_ID, NgModuleFactory, NgModuleRef, QueryList, Renderer, Renderer2, SecurityContext, TRANSLATIONS_FORMAT, TemplateRef, ViewContainerRef, ViewEncapsulation, ɵCodegenComponentFactoryResolver, ɵEMPTY_ARRAY, ɵEMPTY_MAP, ɵReflectionCapabilities as ReflectionCapabilities, ɵand, ɵccf, ɵcmf, ɵcrt, ɵdid, ɵeld, ɵinlineInterpolate, ɵinterpolate, ɵmod, ɵmpd, ɵncd, ɵnov, ɵpad, ɵpid, ɵpod, ɵppd, ɵprd, ɵqud, ɵregisterModuleFactory, ɵstringify as stringify, ɵted, ɵunv, ɵvid} from '@angular/core'; export const MODULE_SUFFIX = ''; const builtinExternalReferences = createBuiltinExternalReferencesMap(); export class JitReflector implements CompileReflector { private reflectionCapabilities = new ReflectionCapabilities(); componentModuleUrl(type: any, cmpMetadata: Component): string { const moduleId = cmpMetadata.moduleId; if (typeof moduleId === 'string') { const scheme = getUrlScheme(moduleId); return scheme ? moduleId : `package:${moduleId}${MODULE_SUFFIX}`; } else if (moduleId !== null && moduleId !== void 0) { throw syntaxError( `moduleId should be a string in "${stringify(type)}". See https://goo.gl/wIDDiL for more information.\n` + `If you're using Webpack you should inline the template and the styles, see https://goo.gl/X2J8zc.`); } return `./${stringify(type)}`; } parameters(typeOrFunc: /*Type*/ any): any[][] { return this.reflectionCapabilities.parameters(typeOrFunc); } tryAnnotations(typeOrFunc: /*Type*/ any): any[] { return this.annotations(typeOrFunc); } annotations(typeOrFunc: /*Type*/ any): any[] { return this.reflectionCapabilities.annotations(typeOrFunc); } shallowAnnotations(typeOrFunc: /*Type*/ any): any[] { throw new Error('Not supported in JIT mode'); } propMetadata(typeOrFunc: /*Type*/ any): {[key: string]: any[]} { return this.reflectionCapabilities.propMetadata(typeOrFunc); } hasLifecycleHook(type: any, lcProperty: string): boolean { return this.reflectionCapabilities.hasLifecycleHook(type, lcProperty); } guards(type: any): {[key: string]: any} { return this.reflectionCapabilities.guards(type); } resolveExternalReference(ref: ExternalReference): any { return builtinExternalReferences.get(ref) || ref.runtime; } } function createBuiltinExternalReferencesMap() { const map = new Map<ExternalReference, any>(); map.set(Identifiers.ANALYZE_FOR_ENTRY_COMPONENTS, ANALYZE_FOR_ENTRY_COMPONENTS); map.set(Identifiers.ElementRef, ElementRef); map.set(Identifiers.NgModuleRef, NgModuleRef); map.set(Identifiers.ViewContainerRef, ViewContainerRef); map.set(Identifiers.ChangeDetectorRef, ChangeDetectorRef); map.set(Identifiers.Renderer2, Renderer2); map.set(Identifiers.QueryList, QueryList); map.set(Identifiers.TemplateRef, TemplateRef); map.set(Identifiers.CodegenComponentFactoryResolver, ɵCodegenComponentFactoryResolver); map.set(Identifiers.ComponentFactoryResolver, ComponentFactoryResolver); map.set(Identifiers.ComponentFactory, ComponentFactory); map.set(Identifiers.ComponentRef, ComponentRef); map.set(Identifiers.NgModuleFactory, NgModuleFactory); map.set(Identifiers.createModuleFactory, ɵcmf); map.set(Identifiers.moduleDef, ɵmod); map.set(Identifiers.moduleProviderDef, ɵmpd); map.set(Identifiers.RegisterModuleFactoryFn, ɵregisterModuleFactory); map.set(Identifiers.Injector, Injector); map.set(Identifiers.ViewEncapsulation, ViewEncapsulation); map.set(Identifiers.ChangeDetectionStrategy, ChangeDetectionStrategy); map.set(Identifiers.SecurityContext, SecurityContext); map.set(Identifiers.LOCALE_ID, LOCALE_ID); map.set(Identifiers.TRANSLATIONS_FORMAT, TRANSLATIONS_FORMAT); map.set(Identifiers.inlineInterpolate, ɵinlineInterpolate); map.set(Identifiers.interpolate, ɵinterpolate); map.set(Identifiers.EMPTY_ARRAY, ɵEMPTY_ARRAY); map.set(Identifiers.EMPTY_MAP, ɵEMPTY_MAP); map.set(Identifiers.Renderer, Renderer); map.set(Identifiers.viewDef, ɵvid); map.set(Identifiers.elementDef, ɵeld); map.set(Identifiers.anchorDef, ɵand); map.set(Identifiers.textDef, ɵted); map.set(Identifiers.directiveDef, ɵdid); map.set(Identifiers.providerDef, ɵprd); map.set(Identifiers.queryDef, ɵqud); map.set(Identifiers.pureArrayDef, ɵpad); map.set(Identifiers.pureObjectDef, ɵpod); map.set(Identifiers.purePipeDef, ɵppd); map.set(Identifiers.pipeDef, ɵpid); map.set(Identifiers.nodeValue, ɵnov); map.set(Identifiers.ngContentDef, ɵncd); map.set(Identifiers.unwrapValue, ɵunv); map.set(Identifiers.createRendererType2, ɵcrt); map.set(Identifiers.createComponentFactory, ɵccf); return map; }
{ "content_hash": "58a687e93382f4b45b62d3b22414239c", "timestamp": "", "source": "github", "line_count": 96, "max_line_length": 663, "avg_line_length": 51.354166666666664, "alnum_prop": 0.7671399594320487, "repo_name": "juristr/angular", "id": "da2ec859d223c964a8ad83eae6541d9eb940c6cd", "size": "5184", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "packages/platform-browser-dynamic/src/compiler_reflector.ts", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "493" }, { "name": "CSS", "bytes": "338993" }, { "name": "Dockerfile", "bytes": "14627" }, { "name": "HTML", "bytes": "332398" }, { "name": "JSONiq", "bytes": "619" }, { "name": "JavaScript", "bytes": "803881" }, { "name": "PHP", "bytes": "7222" }, { "name": "PowerShell", "bytes": "4229" }, { "name": "Python", "bytes": "335391" }, { "name": "Shell", "bytes": "70124" }, { "name": "TypeScript", "bytes": "17551162" } ] }
#include "native_client/src/untrusted/irt/irt.h" #include "native_client/src/untrusted/nacl/syscall_bindings_trampoline.h" static int nacl_irt_open(const char *pathname, int oflag, mode_t cmode, int *newfd) { int rv = NACL_GC_WRAP_SYSCALL(NACL_SYSCALL(open)(pathname, oflag, cmode)); if (rv < 0) return -rv; *newfd = rv; return 0; } static int nacl_irt_stat(const char *pathname, struct stat *st) { return -NACL_SYSCALL(stat)(pathname, st); } const struct nacl_irt_filename nacl_irt_filename = { nacl_irt_open, nacl_irt_stat, };
{ "content_hash": "ac83296159b9697c4f8b670c18c6f396", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 76, "avg_line_length": 26.227272727272727, "alnum_prop": 0.6707105719237435, "repo_name": "leighpauls/k2cro4", "id": "c00942adde2759efca2abbf4132f16a87b9bddbd", "size": "757", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "native_client/src/untrusted/irt/irt_filename.c", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ASP", "bytes": "3062" }, { "name": "AppleScript", "bytes": "25392" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "68131038" }, { "name": "C", "bytes": "242794338" }, { "name": "C#", "bytes": "11024" }, { "name": "C++", "bytes": "353525184" }, { "name": "Common Lisp", "bytes": "3721" }, { "name": "D", "bytes": "1931" }, { "name": "Emacs Lisp", "bytes": "1639" }, { "name": "F#", "bytes": "4992" }, { "name": "FORTRAN", "bytes": "10404" }, { "name": "Java", "bytes": "3845159" }, { "name": "JavaScript", "bytes": "39146656" }, { "name": "Lua", "bytes": "13768" }, { "name": "Matlab", "bytes": "22373" }, { "name": "Objective-C", "bytes": "21887598" }, { "name": "PHP", "bytes": "2344144" }, { "name": "Perl", "bytes": "49033099" }, { "name": "Prolog", "bytes": "2926122" }, { "name": "Python", "bytes": "39863959" }, { "name": "R", "bytes": "262" }, { "name": "Racket", "bytes": "359" }, { "name": "Ruby", "bytes": "304063" }, { "name": "Scheme", "bytes": "14853" }, { "name": "Shell", "bytes": "9195117" }, { "name": "Tcl", "bytes": "1919771" }, { "name": "Verilog", "bytes": "3092" }, { "name": "Visual Basic", "bytes": "1430" }, { "name": "eC", "bytes": "5079" } ] }
package main import ( "bufio" "net" "strconv" "time" "github.com/osrg/gobgp/pkg/packet/bgp" "github.com/osrg/gobgp/pkg/packet/rtr" log "github.com/sirupsen/logrus" ) const rtrProtocolVersion uint8 = 0 type rtrConn struct { conn *net.TCPConn sessionId uint16 remoteAddr net.Addr } type rtrServer struct { connCh chan *rtrConn listenPort int } func newRTRServer(port int) *rtrServer { s := &rtrServer{ connCh: make(chan *rtrConn, 1), listenPort: port, } return s } func (s *rtrServer) run() { service := ":" + strconv.Itoa(s.listenPort) addr, _ := net.ResolveTCPAddr("tcp", service) l, err := net.ListenTCP("tcp", addr) checkError(err) for i := 0; ; { conn, err := l.AcceptTCP() if err != nil { continue } i++ c := &rtrConn{ conn: conn, sessionId: uint16(i), remoteAddr: conn.RemoteAddr(), } s.connCh <- c } } func (r *rtrConn) sendPDU(msg rtr.RTRMessage) error { pdu, _ := msg.Serialize() _, err := r.conn.Write(pdu) if err != nil { return err } return nil } func (r *rtrConn) cacheResponse(currentSN uint32, lists FakeROATable) error { if err := r.sendPDU(rtr.NewRTRCacheResponse(r.sessionId)); err != nil { return err } log.Infof("Sent Cache Response PDU to %v (ID: %v)", r.remoteAddr, r.sessionId) for _, rf := range []bgp.RouteFamily{bgp.RF_IPv4_UC, bgp.RF_IPv6_UC} { for _, flag := range []uint8{rtr.ANNOUNCEMENT, rtr.WITHDRAWAL} { for _, v := range lists[rf][flag] { if err := r.sendPDU(rtr.NewRTRIPPrefix(v.Prefix, v.PrefixLen, v.MaxLen, v.AS, flag)); err != nil { return err } log.Debugf("Sent %s Prefix PDU to %v (Prefix: %v/%v, Maxlen: %v, AS: %v, flags: %v)", RFToIPVer(rf), r.remoteAddr, v.Prefix, v.PrefixLen, v.MaxLen, v.AS, flag) } prefixes := len(lists[rf][flag]) if !commandOpts.Debug && prefixes != 0 { log.Infof("Sent %s Prefix PDU(s) to %v (%d ROA(s), flags: %v)", RFToIPVer(rf), r.remoteAddr, prefixes, flag) } } } if err := r.sendPDU(rtr.NewRTREndOfData(r.sessionId, currentSN)); err != nil { return err } log.Infof("Sent End of Data PDU to %v (ID: %v, SN: %v)", r.remoteAddr, r.sessionId, currentSN) return nil } func (r *rtrConn) noIncrementalUpdateAvailable() error { if err := r.sendPDU(rtr.NewRTRCacheReset()); err != nil { return err } log.Infof("Sent Cache Reset PDU to %v", r.remoteAddr) return nil } func (r *rtrConn) cacheHasNoDataAvailable() error { if err := r.sendPDU(rtr.NewRTRErrorReport(rtr.NO_DATA_AVAILABLE, nil, nil)); err != nil { return err } log.Infof("Sent Error Report PDU to %v (ID: %v, ErrorCode: %v)", r.remoteAddr, r.sessionId, rtr.NO_DATA_AVAILABLE) return nil } func RFToIPVer(rf bgp.RouteFamily) string { switch rf { case bgp.RF_IPv4_UC: return "IPv4" case bgp.RF_IPv6_UC: return "IPv6" default: return "Unsupported" } } type errMsg struct { code uint16 data []byte } type resourceResponse struct { sn uint32 list FakeROATable } func handleRTR(r *rtrConn, mgr *ResourceManager) { bcastReceiver := mgr.serialNotify.Join() scanner := bufio.NewScanner(bufio.NewReader(r.conn)) scanner.Split(rtr.SplitRTR) msgCh := make(chan rtr.RTRMessage, 1) errCh := make(chan *errMsg, 1) go func() { defer func() { log.Infof("Connection to %v was closed. (ID: %v)", r.remoteAddr, r.sessionId) r.conn.Close() }() for scanner.Scan() { buf := scanner.Bytes() if buf[0] != rtrProtocolVersion { errCh <- &errMsg{code: rtr.UNSUPPORTED_PROTOCOL_VERSION, data: buf} continue } m, err := rtr.ParseRTR(buf) if err != nil { errCh <- &errMsg{code: rtr.INVALID_REQUEST, data: buf} continue } msgCh <- m } }() LOOP: for { select { case <-bcastReceiver.In: currentSN := mgr.CurrentSerial() if err := r.sendPDU(rtr.NewRTRSerialNotify(r.sessionId, currentSN)); err != nil { break LOOP } log.Infof("Sent Serial Notify PDU to %v (ID: %v, SN: %v)", r.remoteAddr, r.sessionId, currentSN) case msg := <-errCh: r.sendPDU(rtr.NewRTRErrorReport(msg.code, msg.data, nil)) log.Infof("Sent Error Report PDU to %v (ID: %v, ErrorCode: %v)", r.remoteAddr, r.sessionId, msg.code) return case m := <-msgCh: switch msg := m.(type) { case *rtr.RTRSerialQuery: peerSN := msg.SerialNumber log.Infof("Received Serial Query PDU from %v (ID: %v, SN: %d)", r.remoteAddr, msg.SessionID, peerSN) timeoutCh := make(chan bool, 1) resourceResponseCh := make(chan *resourceResponse, 1) go func(tCh chan bool) { time.Sleep(10 * time.Second) tCh <- true }(timeoutCh) go func(rrCh chan *resourceResponse, peerSN uint32) { trans := mgr.BeginTransaction() defer trans.EndTransaction() if trans.HasKey(peerSN) { rrCh <- &resourceResponse{ sn: trans.CurrentSerial(), list: trans.DeltaList(peerSN), } } else { rrCh <- nil } }(resourceResponseCh, peerSN) select { case rr := <-resourceResponseCh: if rr != nil { if err := r.cacheResponse(rr.sn, rr.list); err == nil { continue } } else { if err := r.noIncrementalUpdateAvailable(); err == nil { continue } } case <-timeoutCh: if err := r.cacheHasNoDataAvailable(); err == nil { continue } } break LOOP case *rtr.RTRResetQuery: log.Infof("Received Reset Query PDU from %v", r.remoteAddr) timeoutCh := make(chan bool, 1) resourceResponseCh := make(chan *resourceResponse, 1) go func(tCh chan bool) { time.Sleep(10 * time.Second) tCh <- true }(timeoutCh) go func(rrCh chan *resourceResponse) { trans := mgr.BeginTransaction() defer trans.EndTransaction() rrCh <- &resourceResponse{ sn: trans.CurrentSerial(), list: trans.CurrentList(), } }(resourceResponseCh) select { case rr := <-resourceResponseCh: if err := r.cacheResponse(rr.sn, rr.list); err == nil { continue } case <-timeoutCh: if err := r.cacheHasNoDataAvailable(); err == nil { continue } } break LOOP case *rtr.RTRErrorReport: log.Warnf("Received Error Report PDU from %v (%#v)", r.remoteAddr, msg) return default: pdu, _ := msg.Serialize() log.Warnf("Received unsupported PDU (type %d) from %v (%#v)", pdu[1], r.remoteAddr, msg) r.sendPDU(rtr.NewRTRErrorReport(rtr.UNSUPPORTED_PDU_TYPE, pdu, nil)) return } } } r.sendPDU(rtr.NewRTRErrorReport(rtr.INTERNAL_ERROR, nil, nil)) return }
{ "content_hash": "c7601998985231da587fc44989180190", "timestamp": "", "source": "github", "line_count": 264, "max_line_length": 163, "avg_line_length": 24.700757575757574, "alnum_prop": 0.6313448857537187, "repo_name": "a16/fake-rtrd", "id": "97a11d35d92e3df89f499f067b36466bafa7ebc5", "size": "7122", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "rtr.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "36398" }, { "name": "Makefile", "bytes": "572" } ] }
<!DOCTYPE html> <html lang="en"> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/> <meta charset="utf-8"/> <title>API Documentation</title> <meta name="author" content=""/> <meta name="description" content=""/> <link href="../css/bootstrap-combined.no-icons.min.css" rel="stylesheet"> <link href="../css/font-awesome.min.css" rel="stylesheet"> <link href="../css/prism.css" rel="stylesheet" media="all"/> <link href="../css/template.css" rel="stylesheet" media="all"/> <!--[if lt IE 9]> <script src="../js/html5.js"></script> <![endif]--> <script src="../js/jquery-1.11.0.min.js"></script> <script src="../js/ui/1.10.4/jquery-ui.min.js"></script> <script src="../js/bootstrap.min.js"></script> <script src="../js/jquery.smooth-scroll.js"></script> <script src="../js/prism.min.js"></script> <!-- TODO: Add http://jscrollpane.kelvinluck.com/ to style the scrollbars for browsers not using webkit--> <script type="text/javascript"> function loadExternalCodeSnippets() { Array.prototype.slice.call(document.querySelectorAll('pre[data-src]')).forEach(function (pre) { var src = pre.getAttribute('data-src'); var extension = (src.match(/\.(\w+)$/) || [, ''])[1]; var language = 'php'; var code = document.createElement('code'); code.className = 'language-' + language; pre.textContent = ''; code.textContent = 'Loading…'; pre.appendChild(code); var xhr = new XMLHttpRequest(); xhr.open('GET', src, true); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { if (xhr.status < 400 && xhr.responseText) { code.textContent = xhr.responseText; Prism.highlightElement(code); } else if (xhr.status >= 400) { code.textContent = '✖ Error ' + xhr.status + ' while fetching file: ' + xhr.statusText; } else { code.textContent = '✖ Error: File does not exist or is empty'; } } }; xhr.send(null); }); } $(document).ready(function(){ loadExternalCodeSnippets(); }); $('#source-view').on('shown', function () { loadExternalCodeSnippets(); }) </script> <link rel="shortcut icon" href="../images/favicon.ico"/> <link rel="apple-touch-icon" href="../images/apple-touch-icon.png"/> <link rel="apple-touch-icon" sizes="72x72" href="../images/apple-touch-icon-72x72.png"/> <link rel="apple-touch-icon" sizes="114x114" href="../images/apple-touch-icon-114x114.png"/> </head> <body> <div class="navbar navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <i class="icon-ellipsis-vertical"></i> </a> <a class="brand" href="../index.html">API Documentation</a> <div class="nav-collapse"> <ul class="nav pull-right"> <li class="dropdown"> <a href="../index.html" class="dropdown-toggle" data-toggle="dropdown"> API Documentation <b class="caret"></b> </a> <ul class="dropdown-menu"> <li><a href="../namespaces/Events.html">\Events</a></li> <li><a href="../namespaces/Grav.html">\Grav</a></li> </ul> </li> <li class="dropdown" id="charts-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> Charts <b class="caret"></b> </a> <ul class="dropdown-menu"> <li> <a href="../graphs/class.html"> <i class="icon-list-alt"></i>&#160;Class hierarchy diagram </a> </li> </ul> </li> <li class="dropdown" id="reports-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> Reports <b class="caret"></b> </a> <ul class="dropdown-menu"> <li> <a href="../reports/errors.html"> <i class="icon-list-alt"></i>&#160;Errors <span class="label label-info pull-right">0</span> </a> </li> <li> <a href="../reports/markers.html"> <i class="icon-list-alt"></i>&#160;Markers <span class="label label-info pull-right">3</span> </a> </li> <li> <a href="../reports/deprecated.html"> <i class="icon-list-alt"></i>&#160;Deprecated <span class="label label-info pull-right">0</span> </a> </li> </ul> </li> </ul> </div> </div> </div> <!--<div class="go_to_top">--> <!--<a href="#___" style="color: inherit">Back to top&#160;&#160;<i class="icon-upload icon-white"></i></a>--> <!--</div>--> </div> <div id="___" class="container-fluid"> <section class="row-fluid"> <div class="span2 sidebar"> <div class="accordion" style="margin-bottom: 0"> <div class="accordion-group"> <div class="accordion-heading"> <a class="accordion-toggle " data-toggle="collapse" data-target="#namespace-2134000915"></a> <a href="../namespaces/default.html" style="margin-left: 30px; padding-left: 0">\</a> </div> <div id="namespace-2134000915" class="accordion-body collapse in"> <div class="accordion-inner"> <div class="accordion" style="margin-bottom: 0"> <div class="accordion-group"> <div class="accordion-heading"> <a class="accordion-toggle collapsed" data-toggle="collapse" data-target="#namespace-1005019502"></a> <a href="../namespaces/Events.html" style="margin-left: 30px; padding-left: 0">Events</a> </div> <div id="namespace-1005019502" class="accordion-body collapse "> <div class="accordion-inner"> <ul> <li class="class"><a href="../classes/Events.Calendar.html">Calendar</a></li> <li class="class"><a href="../classes/Events.Events.html">Events</a></li> </ul> </div> </div> </div> </div> <div class="accordion" style="margin-bottom: 0"> <div class="accordion-group"> <div class="accordion-heading"> <a class="accordion-toggle collapsed" data-toggle="collapse" data-target="#namespace-1219488088"></a> <a href="../namespaces/Grav.html" style="margin-left: 30px; padding-left: 0">Grav</a> </div> <div id="namespace-1219488088" class="accordion-body collapse "> <div class="accordion-inner"> <div class="accordion" style="margin-bottom: 0"> <div class="accordion-group"> <div class="accordion-heading"> <a class="accordion-toggle collapsed" data-toggle="collapse" data-target="#namespace-522524926"></a> <a href="../namespaces/Grav.Plugin.html" style="margin-left: 30px; padding-left: 0">Plugin</a> </div> <div id="namespace-522524926" class="accordion-body collapse "> <div class="accordion-inner"> <ul> <li class="class"><a href="../classes/Grav.Plugin.EventsPlugin.html">EventsPlugin</a></li> </ul> </div> </div> </div> </div> <ul> </ul> </div> </div> </div> </div> <ul> </ul> </div> </div> </div> </div> </div> </section> <section class="row-fluid"> <div class="span10 offset2"> <div class="row-fluid"> <div class="span8 content file"> <nav> </nav> <a href="#source-view" role="button" class="pull-right btn" data-toggle="modal"><i class="icon-code"></i></a> <h1><small></small>events.php</h1> <p><em>__ _ _ _ _ _ / _| | | | | | | | | ___ _ __ __ _| |_| |_ ___ __| | |__ _ _| | _| |__ / __| &#039;__/ _` | _| __/ _ \/ _` | &#039;_ \| | | | |/ / &#039;_ \ | (__| | | (_| | | | || __/ (_| | |_) | |_| | &lt;| | | | \___|_| \__,_|_| \__\___|\__,_|_.__/ \__, |_|\_\_| |_| __/ | Designed + Developed by Kaleb Heitzman |___/ (c) 2016</em></p> <h2>Classes</h2> <table class="table table-hover"> <tr> <td><a href="../classes/Grav.Plugin.EventsPlugin.html">EventsPlugin</a></td> <td><em>Grav Events</em></td> </tr> </table> </div> <aside class="span4 detailsbar"> <dl> <dt>Package</dt> <dd><div class="namespace-wrapper">\Default</div></dd> </dl> <h2>Tags</h2> <table class="table table-condensed"> <tr><td colspan="2"><em>None found</em></td></tr> </table> </aside> </div> </div> </section> <div id="source-view" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="source-view-label" aria-hidden="true"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h3 id="source-view-label"></h3> </div> <div class="modal-body"> <pre data-src="../files/events.php.txt" class="language-php line-numbers"></pre> </div> </div> <footer class="row-fluid"> <section class="span10 offset2"> <section class="row-fluid"> <section class="span10 offset1"> <section class="row-fluid footer-sections"> <section class="span4"> <h1><i class="icon-code"></i></h1> <div> <ul> <li><a href="../namespaces/Events.html">\Events</a></li> <li><a href="../namespaces/Grav.html">\Grav</a></li> </ul> </div> </section> <section class="span4"> <h1><i class="icon-bar-chart"></i></h1> <div> <ul> <li><a href="../graphs/class.html">Class Hierarchy Diagram</a></li> </ul> </div> </section> <section class="span4"> <h1><i class="icon-pushpin"></i></h1> <div> <ul> <li><a href="../reports/errors.html">Errors</a></li> <li><a href="../reports/markers.html">Markers</a></li> </ul> </div> </section> </section> </section> </section> <section class="row-fluid"> <section class="span10 offset1"> <hr /> Documentation is powered by <a href="http://www.phpdoc.org/">phpDocumentor </a> and authored on October 2nd, 2016 at 21:54. </section> </section> </section> </footer> </div> </body> </html>
{ "content_hash": "93640c29cacb8fd3deb7942d007b90fa", "timestamp": "", "source": "github", "line_count": 325, "max_line_length": 429, "avg_line_length": 47.26769230769231, "alnum_prop": 0.36635854706418436, "repo_name": "ottramst/TamaraIntranet", "id": "dbea810e08f4fbf318cb97bfc93f384270bc6f5f", "size": "15369", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "user/plugins/events/docs/files/events.html", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "2919" }, { "name": "CSS", "bytes": "607337" }, { "name": "CoffeeScript", "bytes": "1615" }, { "name": "HTML", "bytes": "502293" }, { "name": "JavaScript", "bytes": "639523" }, { "name": "Nginx", "bytes": "1430" }, { "name": "PHP", "bytes": "1221855" }, { "name": "Shell", "bytes": "240" } ] }
import datetime from django.db import models from django.utils import timezone from .object_source import ObjectSource from .product import Product class TestRun(models.Model): STATUS_CHOICES = ((-1, 'Pending'), (0, 'Passed'), (1, 'Failed'), (2, 'Analyzed'), (3, 'Abandoned')) STATE_CHOICES = ((-1, 'Not Ready'), (0, 'Starting'), (1, 'Running'), (2, 'Aborted'), (3, 'Completed')) name = models.CharField(max_length=200) owner = models.CharField(max_length=50) start_time = models.DateTimeField(default=timezone.now) end_time = models.DateTimeField(null=True, blank=True) start_by = models.CharField(max_length=50) state = models.IntegerField(choices=STATE_CHOICES, default=-1) status = models.IntegerField(choices=STATUS_CHOICES, default=-1) product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='runs') source = models.OneToOneField(ObjectSource, on_delete=models.SET_NULL, default=None, null=True) def team_name(self): return self.product.team.name def product_name(self): return self.product.name def result_total(self): return self.results.count() def result_passed(self): return self.results.filter(outcome=0).count() def result_failed(self): return self.results.filter(outcome=1).count() def result_skipped(self): return self.results.filter(outcome=2).count() def result_error(self): return self.results.filter(outcome=3).count() def duration(self): if isinstance(self.end_time, datetime.datetime): return str((self.end_time - self.start_time)) class Meta: ordering = ['-id'] def __str__(self): return '{}'.format(self.id)
{ "content_hash": "710f0453188070611a6a5021ddefd613", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 106, "avg_line_length": 32.27777777777778, "alnum_prop": 0.6655192197360872, "repo_name": "tobyqin/testcube", "id": "7edfcea64f6943f4a96a8dcec78844d5efbcf923", "size": "1743", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "testcube/core/models/test_run.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "262" }, { "name": "CSS", "bytes": "180930" }, { "name": "Dockerfile", "bytes": "302" }, { "name": "HTML", "bytes": "30516" }, { "name": "JavaScript", "bytes": "328876" }, { "name": "Python", "bytes": "126583" }, { "name": "Shell", "bytes": "78" } ] }
#include "extensions/filters/network/dubbo_proxy/router/config.h" #include "envoy/registry/registry.h" #include "extensions/filters/network/dubbo_proxy/router/router_impl.h" namespace Envoy { namespace Extensions { namespace NetworkFilters { namespace DubboProxy { namespace Router { DubboFilters::FilterFactoryCb RouterFilterConfig::createFilterFactoryFromProtoTyped( const envoy::config::filter::dubbo::router::v2alpha1::Router&, const std::string&, Server::Configuration::FactoryContext& context) { return [&context](DubboFilters::FilterChainFactoryCallbacks& callbacks) -> void { callbacks.addDecoderFilter(std::make_shared<Router>(context.clusterManager())); }; } /** * Static registration for the router filter. @see RegisterFactory. */ static Registry::RegisterFactory<RouterFilterConfig, DubboFilters::NamedDubboFilterConfigFactory> register_; } // namespace Router } // namespace DubboProxy } // namespace NetworkFilters } // namespace Extensions } // namespace Envoy
{ "content_hash": "cb7a17c1ecc40479673bb7cead79a40f", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 97, "avg_line_length": 32.41935483870968, "alnum_prop": 0.7761194029850746, "repo_name": "dnoe/envoy", "id": "4e4382a61bc3f2eb3b2385c198a7b0efb629f6d0", "size": "1005", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "source/extensions/filters/network/dubbo_proxy/router/config.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "9173" }, { "name": "C++", "bytes": "12933900" }, { "name": "Dockerfile", "bytes": "245" }, { "name": "Emacs Lisp", "bytes": "966" }, { "name": "Go", "bytes": "836" }, { "name": "PowerShell", "bytes": "4285" }, { "name": "PureBasic", "bytes": "472" }, { "name": "Python", "bytes": "946275" }, { "name": "Shell", "bytes": "98909" }, { "name": "Thrift", "bytes": "748" } ] }
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { Router, Redirect, browserHistory } from 'react-router'; import injectTapEventPlugin from 'react-tap-event-plugin'; import { syncHistoryWithStore } from 'react-router-redux'; import configureStore from './store/configureStore'; import routes from './routes'; injectTapEventPlugin(); const store = configureStore(); const history = syncHistoryWithStore(browserHistory, store); ReactDOM.render( <Provider store={store}> <Router history={history}> <Redirect from="/" to="main" /> {routes} </Router> </Provider>, document.getElementById('root') );
{ "content_hash": "a8eebd1d645ff9c5822e2de71ed8ff50", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 64, "avg_line_length": 25.884615384615383, "alnum_prop": 0.7340267459138187, "repo_name": "morrishopkins/test_spa", "id": "50f52649e510c11da2b5681439ef1c4b4dc2e7c7", "size": "673", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "497" }, { "name": "HTML", "bytes": "6541" }, { "name": "JavaScript", "bytes": "87047" } ] }
<div ng-include="'components/navbar/navbar.html'"></div> <div class="container"> <div class="row"> <div class="col-sm-12"> <h1>Login</h1> <p>Default account is <code>test@test.com</code> / <code>test</code></p> </div> <div class="col-sm-12"> <form class="form" name="form" ng-submit="login(form)" novalidate> <div class="form-group"> <label>Email</label> <input type="email" name="email" class="form-control" ng-model="user.email" required> </div> <div class="form-group"> <label>Password</label> <input type="password" name="password" class="form-control" ng-model="user.password" required> </div> <div class="form-group has-error"> <p class="help-block" ng-show="form.email.$error.required && form.password.$error.required && submitted"> Please enter your email and password. </p> <p class="help-block" ng-show="form.email.$error.email && submitted"> Please enter a valid email. </p> <p class="help-block">{{ errors.other }}</p> </div> <div> <md-button style="padding: 10px;" class="md-primary" type="submit"> Login </md-button> <md-button style="color: #727272; text-decoration: none; padding: 10px;" href="/signup"> Register </md-button> </div> <hr> <div> <a class="btn btn-facebook" href="" ng-click="loginOauth('facebook')"> <i class="fa fa-facebook"></i> Connect with Facebook </a> <a class="btn btn-google-plus" href="" ng-click="loginOauth('google')"> <i class="fa fa-google-plus"></i> Connect with Google+ </a> <a class="btn btn-twitter" href="" ng-click="loginOauth('twitter')"> <i class="fa fa-twitter"></i> Connect with Twitter </a> </div> </form> </div> </div> <hr> </div>
{ "content_hash": "080fb20d9e46b1b5296293b125de8f86", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 114, "avg_line_length": 38.328125, "alnum_prop": 0.4406848756624541, "repo_name": "Awk34/hackshare", "id": "81d456472b07f086f144385848afc272cd59df66", "size": "2453", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "client/app/account/login/login.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "7942" }, { "name": "JavaScript", "bytes": "122663" } ] }
EllipseFloat FitEllipse_float(int32_t *x, int32_t *y, int16_t numberOfPoints); void calculateMatricesMAndT_float(int64_t *scatterMatrix, float *T, float *M); void matrixInverseSymmetric3by3_float(int64_t *matrix, float *inverse); void calculateTMatrix_float(int64_t *sm, float *s3i, float *T); void calculateSecondTermOfM_float(int64_t *sm, float *T, float *M); void calculateCompleteM_float(int64_t *sm, float *M); void conicToGeneralForm_float(float *cc, EllipseFloat *results); #endif // ELLIPSEFIT_FLOAT_H
{ "content_hash": "39c87c0418d603bd7a8bb5125c778fae", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 78, "avg_line_length": 32.4375, "alnum_prop": 0.7610789980732178, "repo_name": "hbldh/b2ac", "id": "031fb1bede6afb0324a501d8ea8bd9e2709699ac", "size": "631", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "b2ac/ext/src/EllipseFit_float.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "81780" }, { "name": "C++", "bytes": "15169" }, { "name": "Python", "bytes": "118161" } ] }
package com.gs.fw.common.mithra.attribute.calculator.aggregateFunction; import com.gs.fw.common.mithra.attribute.Attribute; import com.gs.fw.common.mithra.attribute.DateAttribute; import com.gs.fw.common.mithra.attribute.calculator.procedure.DateProcedure; import com.gs.fw.common.mithra.util.*; import java.util.Date; import java.io.ObjectOutput; import java.io.IOException; import java.io.ObjectInput; public class MinCalculatorDate extends AbstractAggregateAttributeCalculator implements DateProcedure { private static final long serialVersionUID = -7414558010917457361L; DateAttribute attribute; public MinCalculatorDate(DateAttribute attribute) { super("min"); this.attribute = attribute; } public MinCalculatorDate() { } public Attribute getAttribute() { return this.attribute; } public Object aggregate(Object previousValue, Object newValue) { if(previousValue == null) { previousValue = new MutableComparableReference<Date>(); } this.attribute.forEach(this, newValue, previousValue); return previousValue; } public boolean execute(Date object, Object context) { MutableComparableReference<Date> result = (MutableComparableReference<Date>) context; if(result.isNull() || object.compareTo(result.getValue()) < 0) { result.replace(object); } return false; } @Override public void writeExternal(ObjectOutput out) throws IOException { super.writeExternal(out); out.writeObject(attribute); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { super.readExternal(in); attribute = (DateAttribute)in.readObject(); } public Nullable getDefaultValueForEmptyGroup() { return new MutableComparableReference<Date>(); } @Override public int hashCode() { return this.attribute.hashCode() ^ 0xEB10AF98; } @Override public Class valueType() { return Date.class; } public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof MinCalculatorDate)) return false; MinCalculatorDate that = (MinCalculatorDate) o; if (!attribute.equals(that.attribute)) return false; return true; } }
{ "content_hash": "53416f3a7363c4e07ee5e064988966e3", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 100, "avg_line_length": 25.34, "alnum_prop": 0.6424625098658248, "repo_name": "itohro/reladomo", "id": "3d99b5a4a16ca912eb0261ce31cef3c1c1650b4f", "size": "3118", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "reladomo/src/main/java/com/gs/fw/common/mithra/attribute/calculator/aggregateFunction/MinCalculatorDate.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "4970" }, { "name": "CSS", "bytes": "13402" }, { "name": "HTML", "bytes": "64206" }, { "name": "Java", "bytes": "16956343" }, { "name": "JavaScript", "bytes": "18247" }, { "name": "Ruby", "bytes": "745" }, { "name": "Shell", "bytes": "7436" }, { "name": "XSLT", "bytes": "383852" } ] }
// // Created by Adrian Castillejos on 5/24/14. // Copyright (c) 2014 Adrian Castillejos. All rights reserved. // #import <UIKit/UIKit.h> #import "NSLayoutConstraint+LinearEquationFormat.h" @interface ZIOLayoutConstraintManager : NSObject @property(nonatomic, strong) NSString *string; @property(nonatomic, strong) NSMutableArray *constraints; @property(nonatomic, strong) NSMutableDictionary *constraintPriorityDict; @property(nonatomic, strong) NSDictionary *metricDict; @property(nonatomic, strong) NSDictionary *viewDict; - (instancetype)initWithString:(NSString *)string metrics:(NSDictionary *)metricDict views:(NSDictionary *)viewDict; - (instancetype)initWithString:(NSString *)string metrics:(NSDictionary *)metricDict views:(NSDictionary *)viewDict priorities:(NSDictionary *)priorityDict; - (NSLayoutConstraint *)constraintWithString:(NSString *)string metrics:(NSDictionary *)metricDict views:(NSDictionary *)viewDict; - (NSArray *)constraintsWithStrings:(NSArray *)strings metrics:(NSDictionary *)metricDict views:(NSDictionary *)viewDict; @end @implementation ZIOLayoutConstraintManager #pragma mark Initialization - (instancetype)init { self = [super init]; if (self) { [self initialize]; } return self; } - (void)initialize { self.constraintPriorityDict = [NSMutableDictionary dictionary]; self.constraints = [NSMutableArray array]; } - (void)setMetrics:(NSDictionary *)metrics views:(NSDictionary *)views { self.metricDict = metrics; self.viewDict = views; } - (instancetype)initWithString:(NSString *)string metrics:(NSDictionary *)metricDict views:(NSDictionary *)viewDict { return nil; } - (instancetype)initWithString:(NSString *)string metrics:(NSDictionary *)metricDict views:(NSDictionary *)viewDict priorities:(NSDictionary *)priorityDict { return nil; } - (NSLayoutConstraint *)constraintWithString:(NSString *)string metrics:(NSDictionary *)metricDict views:(NSDictionary *)viewDict { NSParameterAssert(string); NSParameterAssert(viewDict); // check if we have the metric dict and the viewDict UIView *view1, *view2; NSNumber *attribute1, *attribute2, *relation, *multiplier, *constant; NSString *name; // First we ensure that the string is vaguely properly formatted NSTextCheckingResult *leftSide = [self stringContainsLeftSide:string]; if (leftSide) { NSString *withRange = [string substringWithRange:leftSide.range]; view1 = [self view1FromString:withRange]; attribute1 = [self attributeFromString:withRange]; } NSTextCheckingResult *rightSide = [self stringContainsRightSide:string]; if (rightSide) { NSString *rightSideString = [string substringWithRange:rightSide.range]; view2 = [self view2FromString:rightSideString]; attribute2 = [self attributeFromString:rightSideString]; } return nil; } - (NSArray *)constraintsWithStrings:(NSArray *)strings metrics:(NSDictionary *)metricDict views:(NSDictionary *)viewDict { [self setMetrics:metricDict views:viewDict]; NSMutableArray *ret = [NSMutableArray array]; for (NSString *string in strings) { [ret addObject:[self constraintWithString:string metrics:metricDict views:viewDict]]; } return ret; } #pragma mark Parsing - (NSTextCheckingResult *)stringContainsLeftSide:(NSString *)string { NSError *error; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[\\w]+.[\\w]+\\s*[=|>=|<=]{1}" options:0 error:&error]; NSArray *matches = [regex matchesInString:string options:0 range:NSMakeRange(0, string.length)]; if (matches.count == 1) { // We can continue because there is exactly one attribute being set in this string. return matches.firstObject; } else { return nil; } return nil; } /** * Input string is of format 'viewName.attribute =' (aka [\w]+.[\w]+\s*[=|>=|<=]{1}). From this, we want to extract the view name * and match it to a view in our viewDict. */ - (UIView *)view1FromString:(NSString *)string { NSError *error; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[\\w]+\\." options:0 error:&error]; NSArray *matches = [regex matchesInString:string options:0 range:NSMakeRange(0, string.length)]; if (error) { NSLog(@"Could not parse view from string %@. Error:%@", string, error.localizedDescription); NSAssert(NO, @"View could not be parsed"); } if (matches.count == 1) { NSTextCheckingResult *result = matches.firstObject; NSString *viewKey = [string substringWithRange:NSMakeRange(result.range.location, result.range.length - 1)]; UIView *ret = self.viewDict[viewKey]; if (ret) { return ret; } } return nil; } /** * Input string is of format '=viewName.attribute...' (aka [=|<=|>=]{1}.*). From this, we want to extract the view name and * match it to a view in our viewDict. */ - (UIView *)view2FromString:(NSString *)string { NSError *error; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[\\w]+\\." options:0 error:&error]; NSArray *matches = [regex matchesInString:string options:0 range:NSMakeRange(0, string.length)]; if (error) { NSAssert(NO, @"Could not parse view from string '%@'. Error:%@", string, error.localizedDescription); } if (matches.count == 1) { NSTextCheckingResult *result = matches.firstObject; NSString *viewKey = [string substringWithRange:NSMakeRange(result.range.location, result.range.length - 1)]; UIView *ret = self.viewDict[viewKey]; if (ret) { return ret; } } return nil; } /** * Input string is of format 'viewName.attribute =' (aka [\w]+.[\w]+\s*[=|>=|<=]{1}). From this, we want to extract the attribute name * and match it to a layout attribute, wrapped in an NSNumber. */ - (NSNumber *)attributeFromString:(NSString *)string { NSError *error; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\.[\\w]+" options:0 error:&error]; NSArray *matches = [regex matchesInString:string options:0 range:NSMakeRange(0, string.length)]; if (error) { NSAssert(NO, @"Attribute could not be parsed"); } if (matches.count == 1) { NSTextCheckingResult *results = matches.firstObject; NSString *attributeKey = [string substringWithRange:NSMakeRange(results.range.location + 1, results.range.length - 1)]; NSNumber *ret = [ZIOLayoutConstraintManager attributes][attributeKey]; if (ret) { return ret; } } return nil; } - (NSTextCheckingResult *)stringContainsRightSide:(NSString *)string { NSError *error; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[=|<=|>=]{1}.*" options:0 error:&error]; NSArray *matches = [regex matchesInString:string options:0 range:NSMakeRange(0, string.length)]; if (matches.count == 1) { // We can continue because there is exactly one attribute being set in this string. return matches.firstObject; } else { return nil; } return nil; } #pragma mark Store-Bought (Pre-Baked?) + (NSDictionary *)attributes { return @{@"left" : @(NSLayoutAttributeLeft), @"right" : @(NSLayoutAttributeRight), @"top" : @(NSLayoutAttributeTop), @"bottom" : @(NSLayoutAttributeBottom), @"leading" : @(NSLayoutAttributeLeading), @"trailing" : @(NSLayoutAttributeTrailing), @"width" : @(NSLayoutAttributeWidth), @"height" : @(NSLayoutAttributeHeight), @"centerX" : @(NSLayoutAttributeCenterX), @"centerY" : @(NSLayoutAttributeCenterY), @"baseline" : @(NSLayoutAttributeBaseline) }; } + (NSDictionary *)relations { return @{@"=" : @(NSLayoutRelationEqual), @">=" : @(NSLayoutRelationGreaterThanOrEqual), @"<=" : @(NSLayoutRelationLessThanOrEqual) }; } @end @interface NSLayoutConstraint () @end @implementation NSLayoutConstraint (LinearEquationFormat) + (NSArray *)constraintsWithLinearEquationFormat:(NSArray *)linearEquations metrics:(NSDictionary *)metricDict views:(NSDictionary *)viewDict { ZIOLayoutConstraintManager *manager = [[ZIOLayoutConstraintManager alloc] init]; return [manager constraintsWithStrings:linearEquations metrics:metricDict views:viewDict]; } + (NSLayoutConstraint *)constraintWithLinearEquationFormat:(NSString *)linearEquation metrics:(NSDictionary *)metricDict views:(NSDictionary *)viewDict { ZIOLayoutConstraintManager *manager = [[ZIOLayoutConstraintManager alloc] init]; return [manager constraintWithString:linearEquation metrics:metricDict views:viewDict]; } @end
{ "content_hash": "49e7c6facbb08a92d2807b80790a45da", "timestamp": "", "source": "github", "line_count": 277, "max_line_length": 156, "avg_line_length": 33.51263537906137, "alnum_prop": 0.6632554131207584, "repo_name": "zioyero/NSLayoutConstraint-LinearEquationFormat", "id": "61caa96e5c73c26fe0e62d65c40e0235c66b5e4a", "size": "9283", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Classes/ios/NSLayoutConstraint+LinearEquationFormat.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "2422" }, { "name": "Ruby", "bytes": "5922" } ] }
[![Build Status](https://secure.travis-ci.org/dockyard/ember-validations.svg?branch=master)](http://travis-ci.org/dockyard/ember-validations) ## Building yourself ## ```bash npm install bower install ember build ``` The builds will be in the `dist/` directory. ## Installing ## #### With Ember-CLI #### If you are using [`ember-cli`](https://github.com/stefanpenner/ember-cli) you can add `ember-validations` to your `package.json`: ```javascript "devDependencies": { ... "ember-validations": "~ 2.0.0" } ``` You may want to be more precise with your version locking. #### Without Ember-CLI #### We will continue to build `EmberValidations` to the DockYard build server until `ember-cli` is officially recommended by Ember. You can select a build version from: [http://builds.dockyard.com](http://builds.dockyard.com) for use in Bower. ## Looking for help? ## If it is a bug [please open an issue on GitHub](https://github.com/dockyard/ember-validations/issues). ## Usage ## You need to mixin `EmberValidations` into any `Ember.Object` you want to add validations to: ```javascript import Ember from 'ember'; import EmberValidations from 'ember-validations'; export default Ember.ObjectController.extend(EmberValidations); ``` You define your validations as a JSON object. They should be added to the controller that represents the model in question. The keys in the object should map to properties. If you pass a JSON object as the value this will be seen as validation rules to apply to the property. If you pass `true` then the property itself will be seen as a validatable object. ```javascript import Ember from 'ember'; export default Ember.ObjectController.extend({ validations: { firstName: { presence: true, length: { minimum: 5 } }, age: { numericality: true }, profile: true } }); ``` Though not yet explicitly part of the API, you can also add validators to nested objects: ```javascript import Ember from 'ember'; export default Ember.Component.extend({ validations: { 'user.firstName': { presence: true, length: { minimum: 5 } } } }); ``` This is useful for things like Components which don't act as proxies, but again, until this is officially built into the project, YMMV. **Note: If you override the init function, you must call _super()** ```javascript import Ember from 'ember'; export default Ember.ObjectController.extend({ init: function() { // this call is necessary, don't forget it! this._super.apply(this, arguments); // Your init code... } }); ``` ## Validators ## ### Absence ### Validates the property has a value that is `null`, `undefined`, or `''` #### Options #### * `true` - Passing just `true` will activate validation and use default message * `message` - Any string you wish to be the error message. Overrides `i18n`. ```javascript // Examples absence: true absence: { message: 'must be blank' } ``` ### Acceptance ### By default the values `'1'`, `1`, and `true` are the acceptable values #### Options #### * `true` - Passing just `true` will activate validation and use default message * `message` - Any string you wish to be the error message. Overrides `i18n`. * `accept` - the value for acceptance ```javascript // Examples acceptance: true acceptance: { message: 'you must accept', accept: 'yes' } ``` ### Confirmation ### Expects a `propertyConfirmation` to have the same value as `property`. The validation must be applied to the `property`, not the `propertyConfirmation` (otherwise it would expect a `propertyConfirmationConfirmation`). #### Options #### * `true` - Passing just `true` will activate validation and use default message * `message` - Any string you wish to be the error message. Overrides `i18n`. ```javascript // Examples confirmation: true confirmation: { message: 'you must confirm' } ``` ### Exclusion ### A list of values that are not allowed #### Options #### * `message` - Any string you wish to be the error message. Overrides `i18n`. * `allowBlank` - If `true` skips validation if value is empty * `in` - An array of values that are excluded * `range` - an array with the first element as the lower bound the and second element as the upper bound. Any value that falls within the range will be considered excluded ```javascript // Examples exclusion: { in: ['Yellow', 'Black', 'Red'] } exclusion: { range: [5, 10], allowBlank: true, message: 'cannot be between 5 and 10' } ``` ### Format ### A regular expression to test with the value #### Options #### * `message` - Any string you wish to be the error message. Overrides `i18n`. * `allowBlank` - If `true` skips validation if value is empty * `with` - The regular expression to test with ```javascript // Examples format: { with: /^([a-zA-Z]|\d)+$/, allowBlank: true, message: 'must be letters and numbers only' } ``` ### Inclusion ### A list of the only values allowed #### Options #### * `message` - Any string you wish to be the error message. Overrides `i18n`. * `allowBlank` - If `true` skips validation if value is empty * `in` - An array of values that are allowed * `range` - an array with the first element as the lower bound the and second element as the upper bound. Only values that fall within the range will be considered allowed ```javascript // Examples inclusion: { in: ['Yellow', 'Black', 'Red'] } inclusion: { range: [5, 10], allowBlank: true, message: 'must be between 5 and 10' } ``` ### Length ### Define the lengths that are allowed #### Options #### * `number` - Alias for `is` * `array` - Will expand to `minimum` and `maximum`. First element is the lower bound, second element is the upper bound. * `allowBlank` - If `true` skips validation if value is empty * `minimum` - The minimum length of the value allowed * `maximum` - The maximum length of the value allowed * `is` - The exact length of the value allowed * `tokenizer` - A function that should return a object that responds to `length` ##### Messages ##### * `tooShort` - the message used when the `minimum` validation fails. Overrides `i18n` * `tooLong` - the message used when the `maximum` validation fails. Overrides `i18n` * `wrongLength` - the message used when the `is` validation fails. Overrides `i18n` ```javascript // Examples length: 5 length: [3, 5] length: { is: 10, allowBlank: true } length: { minimum: 3, maximum: 5, messages: { tooShort: 'should be more than 3 characters', tooLong: 'should be less than 5 characters' } } length: { is: 5, tokenizer: function(value) { return value.split(''); } } ``` ### Numericality ### Will ensure the value is a number #### Options #### * `true` - Passing just `true` will activate validation and use default message * `allowBlank` - If `true` skips validation if value is empty * `onlyInteger` - Will only allow integers * `greaterThan` - Ensures the value is greater than * `greaterThanOrEqualTo` - Ensures the value is greater than or equal to * `equalTo` - Ensures the value is equal to * `lessThan` - Ensures the value is less than * `lessThanOrEqualTo` - Ensures the value is less than or equal to * `odd` - Ensures the value is odd * `even` - Ensures the value is even ##### Messages ##### * `greaterThan` - Message used when value failes to be greater than. Overrides `i18n` * `greaterThanOrEqualTo` - Message used when value failes to be greater than or equal to. Overrides `i18n` * `equalTo` - Message used when value failes to be equal to. Overrides `i18n` * `lessThan` - Message used when value failes to be less than. Overrides `i18n` * `lessThanOrEqualTo` - Message used when value failes to be less than or equal to. Overrides `i18n` * `odd` - Message used when value failes to be odd. Overrides `i18n` * `even` - Message used when value failes to be even. Overrides `i18n` ```javascript // Examples numericality: true numericality: { odd: true, messages: { odd: 'must be an odd number' } } numericality: { onlyInteger: true, greaterThan: 5, lessThanOrEqualTo : 10 } ``` ### Presence ### Validates the property has a value that is not `null`, `undefined`, or `''` #### Options #### * `true` - Passing just `true` will activate validation and use default message * `message` - Any string you wish to be the error message. Overrides `i18n`. ```javascript // Examples presence: true presence: { message: 'must not be blank' } ``` ### Uniqueness ### *Not yet implemented.* ### Conditional Validators ## Each validator can take an `if` or an `unless` in its `options` hash. The value of the conditional can be an inline function, a string that represents a property on the object, or a string that represents a function on the object. The result should be a boolean. **note that `if` is considered a keyword in IE8 and so you should put it in quotes** ```javascript // function form firstName: { presence: { 'if': function(object, validator) { return true; } } } // string form // if 'canValidate' is a function on the object it will be called // if 'canValidate' is a property object.get('canValidate') will be called firstName: { presence: { unless: 'canValidate' } } ``` ### Custom Validators ### ### With Ember-CLI ### You can place your custom validators into `my-app/app/validators/{local,remote}/<name>`: ```javascript import Base from 'ember-validations/validators/base'; export default Base.extend({ // ... }); ``` It is recommended that you separate between `local` and `remote` validators. However, if you wish you can place your validator into `my-app/app/validators/<name>`. However, any similarly named validator in `local/` or `remote/` has a higher lookup presedence over those in `validators/`. The "native" validators that come with `ember-validations` have the lowest lookup priority. ### Without Ember-CLI ### You can add your validators to the global object: ```javascript EmberValidations.validators.local.<ClassName> = EmberValidations.validators.Base.extend({ // ... }); ``` ### Creating ### To create a new validator you need to override the `call` function. When the validator is run its `call` function is what handles determining if the validator is valid or not. Call has access to `this.model`, `this.property`. If the validation fails you **must** push the failing message onto the validator's `this.errors` array. A simple example of a validator could be: ```javascript import Base from 'ember-validations/validators/base'; import Ember from 'ember'; export default Base.extend({ call: function() { if (Ember.isBlank(this.model.get(this.property))) { this.errors.pushObject("cannot be blank"); } } }); ``` You may want to create a more complex validator that can observer for changes on multiple properties. You should override the `init` function to accomplish this: ```javascript import Base from 'ember-validations/validators/base'; import Ember from 'ember'; export default Base.extend({ init: function() { // this call is necessary, don't forget it! this._super(); this.dependentValidationKeys.pushObject(this.options.alsoWatch); }, call: function() { if (Ember.isBlank(this.model.get(this.property))) { this.errors.pushObject("cannot be blank"); } } }); ``` The `init` function is given access to the `this.options` wich is simply a POJO of the options passed to the validator. `dependentValidationKeys` is the collection of paths relative to `this.model` that will be observed for changes. If any changes occur on any given path the validator will automatically trigger. #### Inline Validators #### If you want to create validators inline you can use the `validator` function that is part of the `ember-validations` export: ```javascript import EmberValidations, { validator } from 'ember-validations'; User.create({ validations: { name: { inline: validator(function() { if (this.model.get('canNotDoSomething')) { return "you can't do this!" } }) } } }); ``` Inside the `validator` function you have access to `this.model` which is a reference to the model. You **must** return an error message that will be attached to the errors array for the property it is created on. Return nothing for the validator to pass. Alternatively if the property doesn't have any additional validations you can use a more concise syntax: ```javascript User.create({ validations: { name: EmberValidations.validator(function() { if (this.model.get('canNotDoSomething')) { return "you can't do this!" } }) } }); ``` ## Running Validations Validations will automatically run when the object is created and when each property changes. `isValid` states bubble up and help define the direct parent's validation state. `isInvalid` is also available for convenience. If you want to force all validations to run simply call `.validate()` on the object. `isValid` will be set to `true` or `false`. All validations are run as deferred objects, so the validations will not be completed when `validate` is done. So `validate` returns a promise, call `then` with a function containing the code you want to run after the validations have successfully completed. ```javascript user.validate().then(function() { // all validations pass user.get('isValid'); // true }).catch(function() { // any validations fail user.get('isValid'); // false }).finally(function() { // all validations complete // regardless of isValid state user.get('isValid'); // true || false }); ``` ## Inspecting Errors ## After mixing in `EmberValidations` into your object it will now have a `.errors` object. All validation error messages will be placed in there for the corresponding property. Errors messages will always be an array. ```javascript import Ember from 'ember'; import EmberValidations from 'ember-validations'; export default Ember.Object.extend(EmberValidations, { validations: { firstName: { presence: true } } }); ``` ```javascript import User from 'my-app/models/user'; user = User.create(); user.validate().then(null, function() { user.get('isValid'); // false user.get('errors.firstName'); // ["can't be blank"] user.set('firstName', 'Brian'); user.validate().then(function() { user.get('isValid'); // true user.get('errors.firstName'); // [] }) }) ``` ## Testing ## #### With Ember QUnit #### For Ember Validations to work with [Ember QUnit](https://github.com/rwjblue/ember-qunit), you must define all your validations in the `needs` property of the `moduleFor` call. This will ensure Ember QUnit's isolated container will be able to locate the validations during testing. ```javascript import { test, moduleFor } from 'ember-qunit'; moduleFor('controller:user/edit', 'UserEditController', { needs: ['service:validations', 'ember-validations@validator:local/presence', 'ember-validations@validator:local/length', 'validator:local/name', 'validator:local/email' ] }); test('Controller Test', function() { ... }); ``` Where `UserEditController` uses the built-in `presence` and `length` validators, and the locally defined `name` and `email` validators. #### Test Helpers #### To test whether your Ember validations are working correctly, you can use the test helpers: **`testValidPropertyValues(propertyName, values [, context ])`** **`testInvalidPropertyValues(propertyName, values [, context ])`** * `propertyName` (String): the property that you are validating. * `values` (Array): an array of property values to check. * `context` (function) _optional_: if specified, this function will be called with the object under test as an argument. See example below. ```javascript import { test, moduleFor } from 'ember-qunit'; import { testValidPropertyValues, testInvalidPropertyValues } from '../../helpers/validate-properties'; moduleFor('controller:user', 'UserController', { needs: ['ember-validations@validator:local/presence', 'ember-validations@validator:local/length' ] }); testValidPropertyValues('firstName', ['Winston', '12345']); testInvalidPropertyValues('firstName', ['abc', '', null, undefined]); ``` If a property's validation relies on another property, you can pass a context to the test helper: ```javascript testValidPropertyValues('lastName', ['Dog', '12345'], function(subject) { subject.set('firstName', 'Boomer'); }); testValidPropertyValues('lastName', ['', null, undefined], function(subject) { subject.set('firstName', null); }); ``` ## i18n ## When you use [ember-i18n](https://github.com/jamesarosen/ember-i18n) your `Ember.I18n.translations` object should contain the following keys under the `errors` key: ```javascript Ember.I18n.translations = { errors: { inclusion: "is not included in the list", exclusion: "is reserved", invalid: "is invalid", confirmation: "doesn't match {{attribute}}", accepted: "must be accepted", empty: "can't be empty", blank: "can't be blank", present: "must be blank", tooLong: "is too long (maximum is {{count}} characters)", tooShort: "is too short (minimum is {{count}} characters)", wrongLength: "is the wrong length (should be {{count}} characters)", notANumber: "is not a number", notAnInteger: "must be an integer", greaterThan: "must be greater than {{count}}", greaterThanOrEqualTo: "must be greater than or equal to {{count}}", equalTo: "must be equal to {{count}}", lessThan: "must be less than {{count}}", lessThanOrEqualTo: "must be less than or equal to {{count}}", otherThan: "must be other than {{count}}", odd: "must be odd", even: "must be even" } } ```` ## Authors ## * [Brian Cardarella](http://twitter.com/bcardarella) [We are very thankful for the many contributors](https://github.com/dockyard/ember-validations/graphs/contributors) ## Versioning ## This library follows [Semantic Versioning](http://semver.org) ## Want to help? ## Please do! We are always looking to improve this library. Please see our [Contribution Guidelines](https://github.com/dockyard/ember-validations/blob/master/CONTRIBUTING.md) on how to properly submit issues and pull requests. ## Legal ## [DockYard](http://dockyard.com/ember-consulting), LLC &copy; 2013 [@dockyard](http://twitter.com/dockyard) [Licensed under the MIT license](http://www.opensource.org/licenses/mit-license.php)
{ "content_hash": "a8514920cd1769847405a197416a54ab", "timestamp": "", "source": "github", "line_count": 614, "max_line_length": 173, "avg_line_length": 30.136807817589577, "alnum_prop": 0.7008754863813229, "repo_name": "indirect/ember-validations", "id": "300f0ce54b31e4acc32883c4661520b22d65da38", "size": "18527", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "31" }, { "name": "HTML", "bytes": "1574" }, { "name": "Handlebars", "bytes": "52" }, { "name": "JavaScript", "bytes": "100642" } ] }
package gmodlab object GmodLab extends swing.SimpleSwingApplication with ul.GetTextable { val app = this def top = new swing.MainFrame { //load configuration and localization Config.props.loadConf(Config.confFile) ul.GetText.load(Config.localeDir, "messages", "MESSAGES", Config.lang, "en") //set Look&Feel javax.swing.UIManager.setLookAndFeel(Config.laf) title = Config.project menuBar = Menu contents = new swing.BoxPanel(swing.Orientation.Vertical) { contents += Tabs } // restore window geometry minimumSize = new swing.Dimension( 800, 600 ); bounds = new swing.Rectangle( Config.x, Config.y, Config.width, Config.height ); preferredSize = new swing.Dimension( Config.width, Config.height ) if (Config.maximized) maximize // load tabs configuration Tabs.fromConf(Config.tabs) if (Tabs.pages.length > 0) Tabs.selection.index = Config.tab // save configuration on close override def closeOperation() { Config.x = bounds.x; Config.y = bounds.y; Config.width = bounds.width; Config.height = bounds.height; Config.tabs = Tabs.toConf; Config.tab = Tabs.selection.index Config.maximized = maximized Config.props.saveConf(Config.confFile) super.closeOperation(); } } }
{ "content_hash": "b5bd250c0d751514bd9638f737abbae0", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 95, "avg_line_length": 36.825, "alnum_prop": 0.6116768499660556, "repo_name": "tardigrade888/gmodlab", "id": "61bcd63f3c1651c1bcdf8cbb6814de45a5a1fa4e", "size": "1473", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "repo/src/gmodlab/GmodLab.scala", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "67228" }, { "name": "Python", "bytes": "80" }, { "name": "Scala", "bytes": "76007" }, { "name": "Shell", "bytes": "432" } ] }
import React from 'react'; import BForm from 'react-bootstrap/lib/Form'; import FormGroup from './FormGroup'; import FormControl from './FormControl'; export default class Form extends React.Component { static propTypes = { allowAutoComplete: React.PropTypes.bool, }; static defaultProps = { allowAutoComplete: false, }; render() { let props = { ...this.props }; delete props.allowAutoComplete; if (!props.allowAutoComplete) { return ( <BForm {...props} autoComplete="off"> <div style={{height: 0, visibility: 'hidden'}}> <FormGroup> <FormControl type='text' /> </FormGroup> <FormGroup> <FormControl type='email' /> </FormGroup> <FormGroup> <FormControl type='password' /> </FormGroup> </div> {this.props.children} </BForm> ); } return <BForm {...props} />; } }
{ "content_hash": "6e49adc7f65ae89bd083d4f468d62ba9", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 57, "avg_line_length": 23.902439024390244, "alnum_prop": 0.5540816326530612, "repo_name": "jeffthemaximum/jeffline", "id": "198fca72d43ecc4d9eca286c2f2f733251a6e9df", "size": "980", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "templates/rubix/rubix-bootstrap/src/Form.js", "mode": "33261", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "1648" }, { "name": "CSS", "bytes": "4646506" }, { "name": "CoffeeScript", "bytes": "211" }, { "name": "HTML", "bytes": "369118" }, { "name": "JavaScript", "bytes": "21256634" }, { "name": "PHP", "bytes": "192464" }, { "name": "Ruby", "bytes": "172800" }, { "name": "Shell", "bytes": "4961" } ] }
package edu.pdx.cs410J.airline; import edu.pdx.cs410J.AbstractAirline; import java.util.Collection; public class Airline extends AbstractAirline<Flight> { private final String name; public Airline(String name) { this.name = name; } @Override public String getName() { return this.name; } @Override public void addFlight(Flight flight) { throw new UnsupportedOperationException("This method is not implemented yet"); } @Override public Collection<Flight> getFlights() { throw new UnsupportedOperationException("This method is not implemented yet"); } }
{ "content_hash": "fbdf87975018a65f6b31cee1d38972a9", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 82, "avg_line_length": 21.392857142857142, "alnum_prop": 0.7312186978297162, "repo_name": "DavidWhitlock/PortlandStateJava", "id": "bdd8ab886006cd6ce7186b15b9753b85e0acff4a", "size": "599", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "projects-parent/originals-parent/airline/src/main/java/edu/pdx/cs410J/airline/Airline.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "11316" }, { "name": "HTML", "bytes": "22112" }, { "name": "Java", "bytes": "1308183" } ] }
<!-- Copyright (C) 2015 The Android Open Source Project 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. --> <set xmlns:android="http://schemas.android.com/apk/res/android" > <objectAnimator android:duration="200" android:interpolator="@interpolator/ic_volume_expand_animation_interpolator_0" android:propertyName="rotation" android:valueFrom="-45.0" android:valueTo="45.0" android:valueType="floatType" /> </set>
{ "content_hash": "509a4060922cc2d9c8450b2c453c93cd", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 86, "avg_line_length": 38.23076923076923, "alnum_prop": 0.7002012072434608, "repo_name": "Ant-Droid/android_frameworks_base_OLD", "id": "6ae0fefa9bef90e9fa83db539181e644885f0c88", "size": "994", "binary": false, "copies": "4", "ref": "refs/heads/mm600", "path": "packages/SystemUI/res/anim/ic_volume_expand_rectangle_4_animation.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "167132" }, { "name": "C++", "bytes": "7099875" }, { "name": "GLSL", "bytes": "20654" }, { "name": "HTML", "bytes": "224185" }, { "name": "Java", "bytes": "79415679" }, { "name": "Makefile", "bytes": "419370" }, { "name": "Python", "bytes": "42309" }, { "name": "RenderScript", "bytes": "153826" }, { "name": "Shell", "bytes": "21079" } ] }
package io.protostuff.jetbrains.plugin.view.structure; import com.intellij.ide.util.treeView.smartTree.ActionPresentation; import com.intellij.ide.util.treeView.smartTree.Sorter; import java.util.Comparator; import org.jetbrains.annotations.NotNull; final class KindSorter implements Sorter { public static final Sorter INSTANCE = new KindSorter(); private static final String ID = "KIND"; private static final Comparator COMPARATOR = new Comparator() { @Override public int compare(final Object o1, final Object o2) { return getWeight(o1) - getWeight(o2); } private int getWeight(final Object value) { if (value instanceof ServiceTreeElement) { return 0; } if (value instanceof MessageFieldTreeElement) { return 10; } if (value instanceof EnumConstantTreeElement) { return 10; } if (value instanceof ServiceMethodTreeElement) { return 10; } if (value instanceof MessageTreeElement) { return 20; } if (value instanceof EnumTreeElement) { return 20; } return 0; } }; @Override @NotNull public Comparator getComparator() { return COMPARATOR; } @Override public boolean isVisible() { return false; } @Override @NotNull public ActionPresentation getPresentation() { throw new IllegalStateException(); } @Override @NotNull public String getName() { return ID; } }
{ "content_hash": "f42c4605983d64f776eb4ccaa6f8f5f9", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 67, "avg_line_length": 25.484848484848484, "alnum_prop": 0.5885850178359097, "repo_name": "protostuff/protobuf-jetbrains-plugin", "id": "360c27319b0256fd704a7e60464cce1187df9c55", "size": "1682", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/io/protostuff/jetbrains/plugin/view/structure/KindSorter.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "332566" }, { "name": "Shell", "bytes": "821" } ] }
package net.sf.jasperreports.engine.design; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import net.sf.jasperreports.engine.JRConstants; import net.sf.jasperreports.engine.JRDefaultStyleProvider; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JRExpression; import net.sf.jasperreports.engine.JRExpressionCollector; import net.sf.jasperreports.engine.JRSubreport; import net.sf.jasperreports.engine.JRSubreportParameter; import net.sf.jasperreports.engine.JRSubreportReturnValue; import net.sf.jasperreports.engine.JRVisitor; import net.sf.jasperreports.engine.base.JRBaseSubreport; import net.sf.jasperreports.engine.type.ModeEnum; import net.sf.jasperreports.engine.type.OverflowType; import net.sf.jasperreports.engine.util.JRCloneUtils; import net.sf.jasperreports.engine.util.JRStyleResolver; /** * @author Teodor Danciu (teodord@users.sourceforge.net) * @version $Id: JRDesignSubreport.java 7199 2014-08-27 13:58:10Z teodord $ */ public class JRDesignSubreport extends JRDesignElement implements JRSubreport { /** * */ private static final long serialVersionUID = JRConstants.SERIAL_VERSION_UID; public static final String PROPERTY_CONNECTION_EXPRESSION = "connectionExpression"; public static final String PROPERTY_DATASOURCE_EXPRESSION = "dataSourceExpression"; public static final String PROPERTY_EXPRESSION = "expression"; public static final String PROPERTY_PARAMETERS_MAP_EXPRESSION = "parametersMapExpression"; public static final String PROPERTY_PARAMETERS = "parameters"; public static final String PROPERTY_RETURN_VALUES = "returnValues"; /** * */ protected Boolean isUsingCache; private Boolean runToBottom; private OverflowType overflowType; /** * */ protected Map<String, JRSubreportParameter> parametersMap = new LinkedHashMap<String, JRSubreportParameter>(); /** * Values to be copied from the subreport into the master report. */ protected List<JRSubreportReturnValue> returnValues = new ArrayList<JRSubreportReturnValue>(); /** * */ protected JRExpression parametersMapExpression; protected JRExpression connectionExpression; protected JRExpression dataSourceExpression; protected JRExpression expression; /** * */ public JRDesignSubreport(JRDefaultStyleProvider defaultStyleProvider) { super(defaultStyleProvider); } /** * */ public ModeEnum getModeValue() { return JRStyleResolver.getMode(this, ModeEnum.TRANSPARENT); } /** * @deprecated Replaced by {@link #getUsingCache()}. */ public boolean isUsingCache() { if (isUsingCache == null) { JRExpression subreportExpression = getExpression(); if (subreportExpression != null) { return String.class.getName().equals(subreportExpression.getValueClassName()); } return true; } return isUsingCache.booleanValue(); } /** * */ public JRExpression getParametersMapExpression() { return this.parametersMapExpression; } /** * */ public void setParametersMapExpression(JRExpression parametersMapExpression) { Object old = this.parametersMapExpression; this.parametersMapExpression = parametersMapExpression; getEventSupport().firePropertyChange(PROPERTY_PARAMETERS_MAP_EXPRESSION, old, this.parametersMapExpression); } /** * */ public JRSubreportParameter[] getParameters() { JRSubreportParameter[] parametersArray = new JRSubreportParameter[parametersMap.size()]; parametersMap.values().toArray(parametersArray); return parametersArray; } /** * */ public Map<String, JRSubreportParameter> getParametersMap() { return this.parametersMap; } /** * */ public void addParameter(JRSubreportParameter subreportParameter) throws JRException { if (this.parametersMap.containsKey(subreportParameter.getName())) { throw new JRException("Duplicate declaration of subreport parameter : " + subreportParameter.getName()); } this.parametersMap.put(subreportParameter.getName(), subreportParameter); getEventSupport().fireCollectionElementAddedEvent(PROPERTY_PARAMETERS, subreportParameter, parametersMap.size() - 1); } /** * */ public JRSubreportParameter removeParameter(String name) { JRSubreportParameter removed = this.parametersMap.remove(name); if (removed != null) { getEventSupport().fireCollectionElementRemovedEvent(PROPERTY_PARAMETERS, removed, -1); } return removed; } /** * */ public JRExpression getConnectionExpression() { return this.connectionExpression; } /** * */ public void setConnectionExpression(JRExpression connectionExpression) { Object old = this.connectionExpression; this.connectionExpression = connectionExpression; if (this.connectionExpression != null) { setDataSourceExpression(null); } getEventSupport().firePropertyChange(PROPERTY_CONNECTION_EXPRESSION, old, this.connectionExpression); } /** * */ public JRExpression getDataSourceExpression() { return this.dataSourceExpression; } /** * */ public void setDataSourceExpression(JRExpression dataSourceExpression) { Object old = this.dataSourceExpression; this.dataSourceExpression = dataSourceExpression; if (this.dataSourceExpression != null) { setConnectionExpression(null); } getEventSupport().firePropertyChange(PROPERTY_DATASOURCE_EXPRESSION, old, this.dataSourceExpression); } /** * */ public JRExpression getExpression() { return this.expression; } /** * */ public void setExpression(JRExpression expression) { Object old = this.expression; this.expression = expression; getEventSupport().firePropertyChange(PROPERTY_EXPRESSION, old, this.expression); } /** * */ public void collectExpressions(JRExpressionCollector collector) { collector.collect(this); } /** * */ public void visit(JRVisitor visitor) { visitor.visitSubreport(this); } /** * Adds a return value to the subreport. * * @param returnValue the return value to be added. */ public void addReturnValue(JRSubreportReturnValue returnValue) { this.returnValues.add(returnValue); getEventSupport().fireCollectionElementAddedEvent(PROPERTY_RETURN_VALUES, returnValue, returnValues.size() - 1); } /** * Returns the list of values to be copied from the subreport into the master. * * @return the list of values to be copied from the subreport into the master. */ public JRSubreportReturnValue[] getReturnValues() { JRSubreportReturnValue[] returnValuesArray = new JRSubreportReturnValue[returnValues.size()]; returnValues.toArray(returnValuesArray); return returnValuesArray; } /** * Returns the list of values to be copied from the subreport into the master. * * @return list of {@link JRSubreportReturnValue JRSubreportReturnValue} objects */ public List<JRSubreportReturnValue> getReturnValuesList() { return returnValues; } /** * Removes a return value from the subreport. * * @param returnValue the return value to be removed * @return <code>true</code> if the return value was found and removed */ public boolean removeReturnValue(JRSubreportReturnValue returnValue) { int idx = this.returnValues.indexOf(returnValue); if (idx >= 0) { this.returnValues.remove(idx); getEventSupport().fireCollectionElementRemovedEvent(PROPERTY_RETURN_VALUES, returnValue, idx); return true; } return false; } /** * @deprecated Replaced by {@link #getUsingCache()}. */ public Boolean isOwnUsingCache() { return isUsingCache; } /** * */ public Boolean getUsingCache() { return isUsingCache; } public void setUsingCache(Boolean isUsingCache) { Object old = this.isUsingCache; this.isUsingCache = isUsingCache; getEventSupport().firePropertyChange(JRBaseSubreport.PROPERTY_USING_CACHE, old, this.isUsingCache); } public Boolean isRunToBottom() { return runToBottom; } public void setRunToBottom(Boolean runToBottom) { Object old = this.runToBottom; this.runToBottom = runToBottom; getEventSupport().firePropertyChange(JRBaseSubreport.PROPERTY_RUN_TO_BOTTOM, old, this.runToBottom); } @Override public OverflowType getOverflowType() { return overflowType; } @Override public void setOverflowType(OverflowType overflowType) { Object old = this.overflowType; this.overflowType = overflowType; getEventSupport().firePropertyChange(JRBaseSubreport.PROPERTY_OVERFLOW_TYPE, old, this.overflowType); } /** * */ public Object clone() { JRDesignSubreport clone = (JRDesignSubreport)super.clone(); if (parametersMap != null) { clone.parametersMap = new LinkedHashMap<String, JRSubreportParameter>(); for(Iterator<String> it = parametersMap.keySet().iterator(); it.hasNext();) { String name = it.next(); clone.parametersMap.put(name, JRCloneUtils.nullSafeClone(parametersMap.get(name))); } } clone.returnValues = JRCloneUtils.cloneList(returnValues); clone.parametersMapExpression = JRCloneUtils.nullSafeClone(parametersMapExpression); clone.connectionExpression = JRCloneUtils.nullSafeClone(connectionExpression); clone.dataSourceExpression = JRCloneUtils.nullSafeClone(dataSourceExpression); clone.expression = JRCloneUtils.nullSafeClone(expression); return clone; } }
{ "content_hash": "2b4136881e5b1f36cc0a2c8fff2fbd6b", "timestamp": "", "source": "github", "line_count": 395, "max_line_length": 111, "avg_line_length": 23.68860759493671, "alnum_prop": 0.7501335898257989, "repo_name": "juniormesquitadandao/report4all", "id": "d9890c166ffc8e0802388293f1602d1116d908bd", "size": "10344", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/src/net/sf/jasperreports/engine/design/JRDesignSubreport.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "21402" }, { "name": "GAP", "bytes": "7307" }, { "name": "HTML", "bytes": "30715" }, { "name": "Java", "bytes": "12194927" }, { "name": "JavaScript", "bytes": "231788" } ] }
import { InjectionToken } from "../static.injector/injection_token"; /** * @hidden */ export const REFLECT_HAS = new InjectionToken<typeof Reflect.has>("Reflect has");
{ "content_hash": "478ec7cfec5605332a8779b2753fca93", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 81, "avg_line_length": 28.5, "alnum_prop": 0.7134502923976608, "repo_name": "dvabuzyarov/moq.ts", "id": "5e77734c0c98e10e47b3fc738f0bdd605fa0dea6", "size": "171", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "projects/moq/src/lib/explorers/reflect-has.injection-token.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Shell", "bytes": "168" }, { "name": "TypeScript", "bytes": "671367" } ] }
#ifndef __UIPAGEVIEW_H__ #define __UIPAGEVIEW_H__ #include "ui/UIListView.h" #include "ui/GUIExport.h" /** * @addtogroup ui * @{ */ NS_CC_BEGIN namespace ui { class PageViewIndicator; /** *PageView page turn event type. *@deprecated Use `PageView::EventType` instead. */ typedef enum { PAGEVIEW_EVENT_TURNING, }PageViewEventType; /** *A callback which would be called when a PageView turning event is happening. *@deprecated Use `PageView::ccPageViewCallback` instead. */ typedef void (Ref::*SEL_PageViewEvent)(Ref*, PageViewEventType); #define pagevieweventselector(_SELECTOR)(SEL_PageViewEvent)(&_SELECTOR) /** *@brief Layout manager that allows the user to flip left & right and up & down through pages of data. * */ class CC_GUI_DLL PageView : public ListView { DECLARE_CLASS_GUI_INFO public: /** * Page turn event type. */ enum class EventType { TURNING }; /** * Touch direction type. */ enum class TouchDirection { LEFT, RIGHT, UP, DOWN }; /** * PageView page turn event callback. */ typedef std::function<void(Ref*, EventType)> ccPageViewCallback; /** * Default constructor * @js ctor * @lua new */ PageView(); /** * Default destructor * @js NA * @lua NA */ virtual ~PageView(); /** * Create an empty PageView. *@return A PageView instance. */ static PageView* create(); /** * Changes direction * Direction Direction::VERTICAL means vertical scroll, Direction::HORIZONTAL means horizontal scroll. * @param direction Set the page view's scroll direction. */ virtual void setDirection(Direction direction) override; /** * Add a widget as a page of PageView in a given index. * * @param widget Widget to be added to pageview. * @param pageIdx A given index. * @param forceCreate If `forceCreate` is true and `widget` isn't exists, pageview would create a default page and add it. * * Since v3.9, this is deprecated. Use `insertPage(Widget* page, int idx)` instead. */ CC_DEPRECATED_ATTRIBUTE void addWidgetToPage(Widget* widget, ssize_t pageIdx, bool forceCreate); /** * Insert a page into the end of PageView. * * @param page Page to be inserted. */ void addPage(Widget* page); /** * Insert a page into PageView at a given index. * * @param page Page to be inserted. * @param idx A given index. */ void insertPage(Widget* page, int idx); /** * Remove a page of PageView. * * @param page Page to be removed. */ void removePage(Widget* page); /** * Remove a page at a given index of PageView. * * @param index A given index. */ void removePageAtIndex(ssize_t index); /** * @brief Remove all pages of the PageView. */ void removeAllPages(); /** * Scroll to a page with a given index. * * @param idx A given index in the PageView. Index start from 0 to pageCount -1. */ void scrollToPage(ssize_t idx); /** * Scroll to a page with a given index and with a given scroll time. * * @param idx A given index in the PageView. Index start from 0 to pageCount -1. * @param time Scroll time must be >= 0. Otherwise last set scroll time will be used. */ void scrollToPage(ssize_t idx, float time); /** * Scroll to a page with a given index. * * @param itemIndex A given index in the PageView. Index start from 0 to pageCount -1. */ void scrollToItem(ssize_t itemIndex); /** * Scroll to a item with a given index and with a given scroll time. * * @param idx A given index in the PageView. Index start from 0 to pageCount -1. * @param time Scroll time must be >= 0. Otherwise last set scrolltime will be used. */ void scrollToItem(ssize_t idx, float time); /** * Gets current displayed page index. * @return current page index. * * Since v3.9, this is deprecated. Use `getCurrentPageIndex()` instead. */ CC_DEPRECATED_ATTRIBUTE ssize_t getCurPageIndex() const; /** * Gets current displayed page index. * @return current page index. */ ssize_t getCurrentPageIndex(); /** * Jump to a page with a given index without scrolling. * This is the different between scrollToPage. * * @param index A given index in PageView. Index start from 0 to pageCount -1. * * Since v3.9, this is deprecated. Use `setCurrentPageIndex()` instead. */ CC_DEPRECATED_ATTRIBUTE void setCurPageIndex(ssize_t index); /** * Jump to a page with a given index without scrolling. * This is the different between scrollToPage. * * @param index A given index in PageView. Index start from 0 to pageCount -1. */ void setCurrentPageIndex(ssize_t index); /** * @brief Get all the pages in the PageView. * @return A vector of Layout pointers. * * Since v3.9, this is obsolete. Use `Vector<Widget*>& ListView::getItems()` instead. */ CC_DEPRECATED_ATTRIBUTE Vector<Layout*>& getPages(); /** * @brief Get a page at a given index * * @param index A given index. * @return A layout pointer in PageView container. * * Since v3.9, this is obsolete. Use `Widget* ListView::getItem(index)` instead. */ CC_DEPRECATED_ATTRIBUTE Layout* getPage(ssize_t index); /** * Add a page turn callback to PageView, then when one page is turning, the callback will be called. *@deprecated Use `PageView::addEventListener` instead. *@param target A pointer of `Ref*` type. *@param selector A member function pointer with signature of `SEL_PageViewEvent`. */ CC_DEPRECATED_ATTRIBUTE void addEventListenerPageView(Ref *target, SEL_PageViewEvent selector); /** * @brief Add a page turn callback to PageView, then when one page is turning, the callback will be called. * * @param callback A page turning callback. */ void addEventListener(const ccPageViewCallback& callback); using ScrollView::addEventListener; //override methods virtual std::string getDescription() const override; /** * @brief Toggle page indicator enabled. * * @param enabled True if enable page indicator, false otherwise. */ void setIndicatorEnabled(bool enabled); /** * @brief Query page indicator state. * * @return True if page indicator is enabled, false otherwise. */ bool getIndicatorEnabled() const { return _indicator != nullptr; } /** * @brief Set the page indicator's position using anchor point. * * @param positionAsAnchorPoint The position as anchor point. */ void setIndicatorPositionAsAnchorPoint(const Vec2& positionAsAnchorPoint); /** * @brief Get the page indicator's position as anchor point. * * @return positionAsAnchorPoint */ const Vec2& getIndicatorPositionAsAnchorPoint() const; /** * @brief Set the page indicator's position in page view. * * @param position The position in page view */ void setIndicatorPosition(const Vec2& position); /** * @brief Get the page indicator's position. * * @return positionAsAnchorPoint */ const Vec2& getIndicatorPosition() const; /** * @brief Set space between page indicator's index nodes. * * @param spaceBetweenIndexNodes Space between nodes in pixel. */ void setIndicatorSpaceBetweenIndexNodes(float spaceBetweenIndexNodes); /** * @brief Get the space between page indicator's index nodes. * * @return spaceBetweenIndexNodes */ float getIndicatorSpaceBetweenIndexNodes() const; /** * @brief Set color of page indicator's selected index. * * @param color New color for selected (current) index. */ void setIndicatorSelectedIndexColor(const Color3B& color); /** * @brief Get the color of page indicator's selected index. * * @return color */ const Color3B& getIndicatorSelectedIndexColor() const; /** * @brief Set color of page indicator's index nodes. * * @param color New indicator node color. */ void setIndicatorIndexNodesColor(const Color3B& color); /** * @brief Get the color of page indicator's index nodes. * * @return color */ const Color3B& getIndicatorIndexNodesColor() const; /** * @brief Set opacity of page indicator's selected index. * * @param color New opacity for selected (current) index. */ void setIndicatorSelectedIndexOpacity(GLubyte opacity); /** * @brief Get the opacity of page indicator's selected index. * * @return opacity */ GLubyte getIndicatorSelectedIndexOpacity() const; /** * @brief Set opacity of page indicator's index nodes. * * @param opacity New indicator node opacity. */ void setIndicatorIndexNodesOpacity(GLubyte opacity); /** * @brief Get the opacity of page indicator's index nodes. * * @return opacity */ GLubyte getIndicatorIndexNodesOpacity() const; /** * @brief Set scale of page indicator's index nodes. * * @param indexNodesScale Scale of index nodes. */ void setIndicatorIndexNodesScale(float indexNodesScale); /** * sets texture for index nodes. * * @param fileName File name of texture. * @param resType @see TextureResType . */ void setIndicatorIndexNodesTexture(const std::string& texName,Widget::TextureResType texType = Widget::TextureResType::LOCAL); /** * @brief Get scale of page indicator's index nodes. * * @return indexNodesScale */ float getIndicatorIndexNodesScale() const; /** *@brief If you don't specify the value, the pageView will turn page when scrolling at the half width of a page. *@param threshold A threshold in float. *@deprecated Since v3.9, this method has no effect. */ CC_DEPRECATED_ATTRIBUTE void setCustomScrollThreshold(float threshold); /** *@brief Query the custom scroll threshold of the PageView. *@return Custom scroll threshold in float. *@deprecated Since v3.9, this method always returns 0. */ CC_DEPRECATED_ATTRIBUTE float getCustomScrollThreshold()const; /** *@brief Set using user defined scroll page threshold or not. * If you set it to false, then the default scroll threshold is pageView.width / 2 *@param flag True if using custom scroll threshold, false otherwise. *@deprecated Since v3.9, this method has no effect. */ CC_DEPRECATED_ATTRIBUTE void setUsingCustomScrollThreshold(bool flag); /** *@brief Query whether use user defined scroll page threshold or not. *@return True if using custom scroll threshold, false otherwise. *@deprecated Since v3.9, this method always returns false. */ CC_DEPRECATED_ATTRIBUTE bool isUsingCustomScrollThreshold()const; void setAutoScrollStopEpsilon(float epsilon); CC_CONSTRUCTOR_ACCESS: virtual bool init() override; //override methods virtual void doLayout() override; protected: void pageTurningEvent(); virtual float getAutoScrollStopEpsilon() const override; virtual void remedyLayoutParameter(Widget* item)override; virtual void moveInnerContainer(const Vec2& deltaMove, bool canStartBounceBack) override; virtual void onItemListChanged() override; virtual void onSizeChanged() override; virtual void handleReleaseLogic(Touch *touch) override; virtual void handlePressLogic(Touch *touch) override; virtual Widget* createCloneInstance() override; virtual void copySpecialProperties(Widget* model) override; void refreshIndicatorPosition(); protected: PageViewIndicator* _indicator; Vec2 _indicatorPositionAsAnchorPoint; ssize_t _currentPageIndex; float _childFocusCancelOffset; Ref* _pageViewEventListener; #if defined(__GNUC__) && ((__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1))) #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #elif _MSC_VER >= 1400 //vs 2005 or higher #pragma warning (push) #pragma warning (disable: 4996) #endif SEL_PageViewEvent _pageViewEventSelector; #if defined(__GNUC__) && ((__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1))) #pragma GCC diagnostic warning "-Wdeprecated-declarations" #elif _MSC_VER >= 1400 //vs 2005 or higher #pragma warning (pop) #endif ccPageViewCallback _eventCallback; float _autoScrollStopEpsilon; ssize_t _previousPageIndex; bool _isTouchBegin; }; } NS_CC_END // end of ui group /// @} #endif /* defined(__PageView__) */
{ "content_hash": "8191303a6959fb793d351ed76dbbf447", "timestamp": "", "source": "github", "line_count": 458, "max_line_length": 130, "avg_line_length": 28.53711790393013, "alnum_prop": 0.6466717674062739, "repo_name": "ecmas/cocos2d", "id": "e3f1062b58596e17d84b70f59a0d6ea240d65ec3", "size": "14380", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cocos/ui/UIPageView.h", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "120" }, { "name": "C", "bytes": "1366096" }, { "name": "C++", "bytes": "12227916" }, { "name": "CMake", "bytes": "243785" }, { "name": "GLSL", "bytes": "67202" }, { "name": "Java", "bytes": "378817" }, { "name": "JavaScript", "bytes": "14719" }, { "name": "Lua", "bytes": "15057" }, { "name": "Makefile", "bytes": "31752" }, { "name": "Objective-C", "bytes": "423269" }, { "name": "Objective-C++", "bytes": "439915" }, { "name": "Python", "bytes": "41173" }, { "name": "Shell", "bytes": "24062" } ] }
{% extends "layout.html" %} {% block page_title %} GOV.UK prototype kit {% endblock %} {% block service_name %} <nav id="proposition-menu"> <a href="/" id="proposition-name">Bob Thomas Arctor (Tester)</a> <ul id="proposition-links"> <li><a href="#">Home</a></li> <li><a href="#">Your profile</a></li> <li><a href="#">Sign out</a></li> </ul> </nav> {% endblock %} {% block content %} <style type="text/css"> .inline-element { clear: right; padding-right: 45px; } .inline-element:last-child { padding-right: initial; } .key-value-list__header { font-family: "nta", Arial, sans-serif; font-size: 24px; line-height: 1.1111111111; font-weight: 700; text-transform: none; margin-top: 1.04167em } @media (max-width: 640px) { .key-value-list__header { font-size: 24px; line-height: 1.0416666667; } } @media (min-width: 641px) { .key-value-list__header { margin-top: 1.25em; } } .key-value-list { margin-top: 30px } .key-value-list__key, .key-value-list__value, .key-value-list__value--numeric, .key-value-list__value--muted { width: 50% } .key-value-list__value { font-family: "nta", Arial, sans-serif; font-size: 19px; line-height: 1.3157894737; font-weight: 700; text-transform: none; padding-left: 15px } @media (max-width: 640px) { .key-value-list__value { font-size: 16px; line-height: 1.25; } } .key-value-list__item-action { padding-left: 15px } .key-value-list__value--numeric { font-family: "ntatabularnumbers", "nta", Arial, sans-serif; font-size: 19px; line-height: 1.3157894737; font-weight: 700; text-transform: none; padding-left: 15px; letter-spacing: 0.03em } @media (max-width: 640px) { .key-value-list__value--numeric { font-size: 16px; line-height: 1.25; } } .key-value-list__value--muted { color: #6f777b; padding-left: 15px } .key-value-list__meta { font-family: "nta", Arial, sans-serif; font-size: 16px; line-height: 1.25; font-weight: 400; text-transform: none; color: #6f777b; display: block } @media (max-width: 640px) { .key-value-list__meta { font-size: 14px; line-height: 1.1428571429; } } .result-table__meta { font-family: "nta", Arial, sans-serif; font-size: 16px; line-height: 1.25; font-weight: 400; text-transform: none; color: #6f777b; display: block } .table-caption { text-align: left; } .content-navigation { margin-top: 30px; } .object-svg { display: block; margin-bottom: 30px; } .data-wrapper { margin-top: 30px; margin-bottom: 15px; } .data-item.bold-large { padding-bottom: 8px; } .line-break { display: block; } .text-center { text-align: center; margin-top: 60px; margin-bottom: 90px; padding-top: 30px; padding-bottom: 60px; } .download-block { margin-bottom: 60px; } .column-one-quarter.column-one-fifth { width: 20%; } </style> <main id="content"> <div class="phase-banner"> <p> <strong class="phase-tag">BETA</strong> <span>This is a new service – your <a href="#">feedback</a> will help us to improve it.</span> </p> </div> <div class="breadcrumbs"> <ol> <li><a href="#">Home</a></li> <li><a href="#">Your profile</a></li> <li>Change your password</li> </ol> </div> <h1 class="heading-xlarge"> <span class="heading-secondary">Your profile</span> Change your password </h1> <form> <div class="error-summary" role="alert" aria-labelledby="error-summary-heading-example-2" tabindex="-1"> <h2 class="heading-medium error-summary-heading" id="error-summary-heading-example-2"> There was a problem with the information you entered: </h2> <ul class="error-summary-list"> <li><a href="#oldPassword">Current password - enter your current password</a></li> <li><a href="#password">New password - enter a password</a></li> <li><a href="#confirm_password">Re-type your new password - re-type your password</a></li> </ul> </div> <fieldset> <legend class="heading-large">Current password</legend> <div class="form-group form-group-error"> <label for="oldPassword" class="form-label ">Current password <span class="error-message">Enter your current password</span> </label> <input type="password" id="oldPassword" name="oldPassword" autocomplete="off" value="" class="form-control"> </div> </fieldset> <fieldset> <legend class="heading-large">New password</legend> <div> <span> Your new password must have: </span> <ul class="list list-bullet"> <li>8 or more characters</li> <li>1 or more numbers</li> <li>upper and lower case letters</li> </ul> <p>It can't be a password you have used before.</p> </div> </fieldset> <fieldset> <legend class="form-title heading-large" id=""></legend> <div class="form-group form-group-error"> <label for="password" class="form-label">New password <span class="error-message">Enter new password</span> </label> <input type="password" name="password" id="password" class="form-control" value=""> </div> <div class="form-group form-group-error"> <label for="confirm_password" class="form-label">Confirm new password <span class="error-message">Re-type your password</span> </label> <input type="password" name="confirm_password" id="confirm_password" class="form-control" value=""> </div> </fieldset> <nav class="content-navigation"> <a href="success.html" class="button">Change password</a> </nav> <br> <a href="#">Cancel and return to your profile</a> </form> </main> {% endblock %}
{ "content_hash": "d8151a2d7578a87845142daa47e28f50", "timestamp": "", "source": "github", "line_count": 243, "max_line_length": 132, "avg_line_length": 28.267489711934157, "alnum_prop": 0.5214732857766778, "repo_name": "dvsa/mot-prototypes", "id": "0514f7b172f87574cca358be647765835b12019c", "size": "6871", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/views/2FA/Password/empty/error-page.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "161034" }, { "name": "HTML", "bytes": "4215177" }, { "name": "JavaScript", "bytes": "173034" }, { "name": "Shell", "bytes": "1260" } ] }
package com.snowplowanalytics package snowplow package enrich package stream package sources // NSQ import com.snowplowanalytics.client.nsq.NSQConsumer import com.snowplowanalytics.client.nsq.lookup.DefaultNSQLookup import com.snowplowanalytics.client.nsq.NSQMessage import com.snowplowanalytics.client.nsq.NSQConfig import com.snowplowanalytics.client.nsq.callbacks.NSQMessageCallback import com.snowplowanalytics.client.nsq.callbacks.NSQErrorCallback import com.snowplowanalytics.client.nsq.exceptions.NSQException // Iglu import iglu.client.Resolver // Snowplow import common.enrichments.EnrichmentRegistry // Tracker import com.snowplowanalytics.snowplow.scalatracker.Tracker // Logging import org.slf4j.LoggerFactory // This project import model._ /** * Source to read raw events from NSQ. * * @param config Configuration for NSQ * @param igluResolver Instance of resolver for iglu * @param enrichmentRegistry EnrichmentRegistry instance * @param tracker Tracker instance */ class NsqSource( config: EnrichConfig, igluResolver: Resolver, enrichmentRegistry: EnrichmentRegistry, tracker: Option[Tracker] ) extends AbstractSource(config, igluResolver, enrichmentRegistry, tracker) { lazy val log = LoggerFactory.getLogger(getClass()) /** * Consumer will be started to wait new message. */ override def run(): Unit = { val nsqCallback = new NSQMessageCallback { override def message(msg: NSQMessage): Unit = { val bytes = msg.getMessage() enrichAndStoreEvents(List(bytes)) match { case true => msg.finished() case false => log.error(s"Error while enriching the event") } } } val errorCallback = new NSQErrorCallback { override def error(e: NSQException): Unit = log.error(s"Exception while consuming topic $config.streams.in.raw", e) } // use NSQLookupd val lookup = new DefaultNSQLookup lookup.addLookupAddress(config.streams.nsq.host, config.streams.nsq.lookupPort) val consumer = new NSQConsumer(lookup, config.streams.in.raw, config.streams.nsq.rawChannel, nsqCallback, new NSQConfig(), errorCallback) consumer.start() } }
{ "content_hash": "80dfe45e4c524daa690efd6e0151f819", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 83, "avg_line_length": 29.160493827160494, "alnum_prop": 0.6934801016088061, "repo_name": "aldemirenes/snowplow", "id": "44c4da08866367aeb90665d909ade0d6f25a70e6", "size": "3067", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "3-enrich/stream-enrich/src/main/scala/com.snowplowanalytics.snowplow.enrich.stream/sources/NsqSource.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "119" }, { "name": "Clojure", "bytes": "18945" }, { "name": "HTML", "bytes": "3654" }, { "name": "Java", "bytes": "38516" }, { "name": "JavaScript", "bytes": "7677" }, { "name": "LookML", "bytes": "153378" }, { "name": "PLpgSQL", "bytes": "60098" }, { "name": "Python", "bytes": "10880" }, { "name": "Ruby", "bytes": "195096" }, { "name": "Scala", "bytes": "1494177" }, { "name": "Shell", "bytes": "10735" }, { "name": "Thrift", "bytes": "3707" } ] }
End of preview.

No dataset card yet

Downloads last month
2