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 1444
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 10086)
              
              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 1444
              
              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
package net.sf.mmm.ui.toolkit.impl.swt.view.sync; import net.sf.mmm.ui.toolkit.api.UiDisplay; import net.sf.mmm.ui.toolkit.api.event.UiEventType; import net.sf.mmm.ui.toolkit.api.view.UiNode; import net.sf.mmm.ui.toolkit.base.view.AbstractUiNodeAdapter; import net.sf.mmm.ui.toolkit.impl.swt.UiFactorySwt; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; /** * This is the abstract base class used for synchronous access on a SWT object * (e.g. a {@link org.eclipse.swt.widgets.Widget}). SWT is designed in a way * that enforces a strict programming-model. This includes a specific threading * with an event-queue based main loop. Further it requires top-down UI * composition as every node of the UI can only be created after its parent. All * these aspects are unsuitable for an abstraction layer that also allows to run * the same code as a web-application. The idea of this framework is to free the * user of such constraints and make it easier to write cross-technology * user-interfaces. * * @author Joerg Hohwiller (hohwille at users.sourceforge.net) * @param <DELEGATE> is the generic type of the {@link #getDelegate() delegate}. * @since 1.0.0 */ public abstract class AbstractSyncObjectAccess<DELEGATE> extends AbstractUiNodeAdapter<DELEGATE> implements Runnable, Listener { /** * operation to * {@link org.eclipse.swt.widgets.Widget#Widget(org.eclipse.swt.widgets.Widget, int) * create} the object. This operation will be implemented in the according * sub-class. */ private static final String OPERATION_CREATE = "create"; /** * operation to {@link org.eclipse.swt.widgets.Widget#dispose() dispose} to * widget. */ private static final String OPERATION_DISPOSE = "dispose"; /** * operation to determine if the widget is * {@link org.eclipse.swt.widgets.Widget#isDisposed() disposed}. */ private static final String OPERATION_IS_DISPOSED = "isDisposed"; /** the ui display */ private final UiDisplay display; /** the operation to perform in {@link #run()} */ private String op; /** the {@link org.eclipse.swt.SWT} style of this widget */ private int style; /** <code>true</code> if the widget is disposed */ private boolean disposed; /** * The constructor. * * @param uiFactory is used to do the synchronization. * @param node is the owning {@link #getNode() node}. * @param swtStyle is the {@link org.eclipse.swt.widgets.Widget#getStyle() * style} of the widget. */ public AbstractSyncObjectAccess(UiFactorySwt uiFactory, UiNode node, int swtStyle) { super(node); this.display = uiFactory.getDisplay(); this.op = null; this.disposed = false; this.style = swtStyle; } /** * {@inheritDoc} */ public final void run() { Object widget = getDelegate(); if (widget == null) { if (this.op == OPERATION_CREATE) { doCreateSynchron(); } } else { if (isDisposedSynchron()) { handleDisposed(); } else { performSynchron(this.op); } } this.op = null; } /** * This method is called from {@link #run()} if the widget has been disposed. */ protected void handleDisposed() { this.disposed = true; } /** * This method is called from {@link #run()}. It does the actual job for the * given operation. * * @param operation is the actual operation to perform. */ protected void performSynchron(String operation) { if (operation == OPERATION_DISPOSE) { disposeSynchron(); } else if (operation == OPERATION_IS_DISPOSED) { // this.disposed = isDisposedSynchron(); } else if (operation == OPERATION_CREATE) { throw new UnsupportedOperationException("Duplicate operation: " + operation); } else { throw new UnsupportedOperationException("Unknown operation: " + operation); } } /** * This method is called for the create operation. */ protected void doCreateSynchron() { createSynchron(); } /** * This method is called for {@link #doCreateSynchron()}. */ protected abstract void createSynchron(); /** * This method is called for the isDisposed operation. * * @return <code>true</code> if the widget is disposed false otherwise. */ protected boolean isDisposedSynchron() { return this.disposed; } /** * This method is called for the dispose operation. */ protected void disposeSynchron() { this.disposed = true; } /** * This method creates the actual widget. The {@link #getDelegate() widget} * should not yet exist and the parent must be available. */ protected void create() { assert (checkReady()); assert (getDelegate() == null); invoke(OPERATION_CREATE); assert (getDelegate() != null); } /** * This method {@link org.eclipse.swt.widgets.Widget#dispose() disposes} the * widget. */ public void dispose() { assert (checkReady()); invoke(OPERATION_DISPOSE); this.disposed = true; } /** * This method determines if the widget is * {@link org.eclipse.swt.widgets.Widget#isDisposed() disposed}. * * @return <code>true</code> if the widget is disposed. */ @Override public boolean isDisposed() { if (!this.disposed) { assert (checkReady()); invoke(OPERATION_IS_DISPOSED); } return this.disposed; } /** * This method checks if previous operations are completed. It is used only * for assertions in development. * * @return <code>true</code> if all previous operations are completed. */ protected boolean checkReady() { String operation = this.op; if (operation == null) { return true; } else { System.out.println("Synchronization bug: the operation '" + operation + "' was NOT completed!"); return false; } } /** * This method gets the {@link org.eclipse.swt.widgets.Widget#getStyle() * style} of this widget. * * @return the style of the widget. */ public int getStyle() { return this.style; } /** * This method checks if the given <code>styleMask</code> is contained in the * {@link #getStyle() style} of the widget.<br> * E.g. use the following to check if the HORIZONTAL flag is set. * * <pre> * {@link #hasStyle(int) hasStyle}({@link org.eclipse.swt.SWT#HORIZONTAL}) * </pre> * * @param styleMask is the style mask to check. * @return <code>true</code> if all bits in the given styleMask are set in the * {@link #getStyle() style}, <code>false</code> otherwise. */ public boolean hasStyle(int styleMask) { return ((this.style & styleMask) == styleMask); } /** * This method sets the flag(s) given in <code>styleMask</code> in the * {@link #getStyle() style} of the widget. * * @param styleMask is the style mask to set. */ protected void setFlag(int styleMask) { this.style = (this.style | styleMask); } /** * This method clears the flag(s) given by <code>styleMask</code> in the * {@link #getStyle() style} of the widget. * * @param styleMask is the style mask to unset. */ protected void unsetFlag(int styleMask) { this.style = (this.style & ~styleMask); } /** * This method inverts (XORs) the flag(s) given by <code>styleMask</code> in * the {@link #getStyle() style} of the widget. * * @param styleMask is the style mask to invert. */ protected void invertFlag(int styleMask) { this.style = (this.style ^ styleMask); } /** * This method invokes the given operation synchronous. * * @param operation is the operation to perform. */ protected void invoke(String operation) { assert (checkReady()); this.op = operation; this.display.invokeSynchron(this); } /** * This method gets the display. * * @return the display. */ public UiDisplay getDisplay() { return this.display; } /** * {@inheritDoc} */ public String getId() { // not supported by SWT return null; } /** * {@inheritDoc} */ public void setId(String newId) { // not supported by SWT } /** * {@inheritDoc} */ public void handleEvent(Event event) { switch (event.type) { case SWT.Selection: getNode().sendEvent(UiEventType.CLICK); break; case SWT.Hide: getNode().sendEvent(UiEventType.HIDE); break; case SWT.Show: getNode().sendEvent(UiEventType.SHOW); break; case SWT.Iconify: getNode().sendEvent(UiEventType.ICONIFY); break; case SWT.Deiconify: getNode().sendEvent(UiEventType.DEICONIFY); break; case SWT.Activate: getNode().sendEvent(UiEventType.ACTIVATE); break; case SWT.Deactivate: getNode().sendEvent(UiEventType.DEACTIVATE); break; case SWT.Dispose: getNode().sendEvent(UiEventType.DISPOSE); break; default : return; } } }
{ "content_hash": "5aeafd50318bf601e4e4a0299bf7c524", "timestamp": "", "source": "github", "line_count": 352, "max_line_length": 96, "avg_line_length": 25.81534090909091, "alnum_prop": 0.6433366347529438, "repo_name": "m-m-m/multimedia", "id": "4540a22b0ea9c2558f916104ec2bb9dcce982da2", "size": "9215", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "mmm-uit/mmm-uit-impl-swt/src/main/java/net/sf/mmm/ui/toolkit/impl/swt/view/sync/AbstractSyncObjectAccess.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "237" }, { "name": "Java", "bytes": "1366298" } ] }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Description; using WebApiControllers.Models; namespace WebApiControllers.Controllers { [RoutePrefix("api")] public class WA2ProductsController : ApiController { private WACDBContext db = new WACDBContext(); [HttpGet] [Route("w2Products")] public IQueryable<Product> m1() { return db.Products; } [HttpGet] [Route("w2Products/{id}")] [ResponseType(typeof(Product))] public IHttpActionResult m2(int id) { Product product = db.Products.Find(id); if (product == null) { return NotFound(); } return Ok(product); } [HttpPut] [Route("w2Products/{id}")] [ResponseType(typeof(void))] public IHttpActionResult m3(int id, Product product) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != product.Id) { return BadRequest(); } db.Entry(product).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!ProductExists(id)) { return NotFound(); } else { throw; } } return StatusCode(HttpStatusCode.NoContent); } [HttpPost] [Route("w2Products")] [ResponseType(typeof(Product))] public IHttpActionResult PostProduct(Product product) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.Products.Add(product); db.SaveChanges(); return CreatedAtRoute("DefaultApi", new { id = product.Id }, product); } [HttpDelete] [Route("w2Products/{id}")] [ResponseType(typeof(Product))] public IHttpActionResult DeleteProduct(int id) { Product product = db.Products.Find(id); if (product == null) { return NotFound(); } db.Products.Remove(product); db.SaveChanges(); return Ok(product); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } private bool ProductExists(int id) { return db.Products.Count(e => e.Id == id) > 0; } } }
{ "content_hash": "8d641bd3a83040d355d2484144a89697", "timestamp": "", "source": "github", "line_count": 125, "max_line_length": 82, "avg_line_length": 23.984, "alnum_prop": 0.49132755170113407, "repo_name": "pusgs/materijali", "id": "0af2d09d0eaf53954ef92162ab140fc59e3c6b4e", "size": "3000", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "WebApiControllers/WebApiControllers/Controllers/WA2ProductsController.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "316" }, { "name": "C#", "bytes": "502591" }, { "name": "CSS", "bytes": "9092" }, { "name": "HTML", "bytes": "22592" }, { "name": "JavaScript", "bytes": "557466" }, { "name": "Shell", "bytes": "735" }, { "name": "TypeScript", "bytes": "51681" } ] }
module.exports = require('./birect-client')
{ "content_hash": "67f25a483e7aec6f5055ae149eb36e35", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 43, "avg_line_length": 43, "alnum_prop": 0.7441860465116279, "repo_name": "marcuswestin/js-birect", "id": "84476ad5989afab5fcc4b4cb5e122ba9d52d2c2b", "size": "43", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "client.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "10567" }, { "name": "Makefile", "bytes": "28" }, { "name": "Protocol Buffer", "bytes": "537" } ] }
package cn.edu.gdut.zaoying.Option.series.lines.label.normal; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface PositionString { String value() default ""; }
{ "content_hash": "d1ce3fc8187c2e50bdc271afc76f8d8d", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 61, "avg_line_length": 32.18181818181818, "alnum_prop": 0.8135593220338984, "repo_name": "zaoying/EChartsAnnotation", "id": "a7703afc98ac9f82c0017d74ced59f88e0f1960f", "size": "354", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/cn/edu/gdut/zaoying/Option/series/lines/label/normal/PositionString.java", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "97" }, { "name": "Java", "bytes": "1345279" } ] }
package com.google.cloud.bigquery; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import com.google.common.collect.ImmutableList; import org.junit.Test; import java.util.List; public class QueryResponseTest { private static final String ETAG = "etag"; private static final Field FIELD_SCHEMA1 = Field.builder("StringField", Field.Type.string()) .mode(Field.Mode.NULLABLE) .description("FieldDescription1") .build(); private static final Schema SCHEMA = Schema.of(FIELD_SCHEMA1); private static final JobId JOB_ID = JobId.of("project", "job"); private static final Long TOTAL_ROWS = 42L; private static final QueryResult.QueryResultsPageFetcher FETCHER = new QueryResult.QueryResultsPageFetcher() { @Override public QueryResult nextPage() { return null; } }; private static final Long TOTAL_BYTES_PROCESSED = 4200L; private static final Boolean JOB_COMPLETE = true; private static final List<BigQueryError> ERRORS = ImmutableList.of( new BigQueryError("reason1", "location1", "message1", "debugInfo1"), new BigQueryError("reason2", "location2", "message2", "debugInfo2") ); private static final Boolean CACHE_HIT = false; private static final QueryResult QUERY_RESULT = QueryResult.builder() .schema(SCHEMA) .totalRows(TOTAL_ROWS) .totalBytesProcessed(TOTAL_BYTES_PROCESSED) .cursor("cursor") .pageFetcher(FETCHER) .results(ImmutableList.<List<FieldValue>>of()) .cacheHit(CACHE_HIT) .build(); private static final QueryResponse QUERY_RESPONSE = QueryResponse.builder() .etag(ETAG) .jobId(JOB_ID) .jobCompleted(JOB_COMPLETE) .executionErrors(ERRORS) .result(QUERY_RESULT) .build(); @Test public void testBuilder() { assertEquals(ETAG, QUERY_RESPONSE.etag()); assertEquals(QUERY_RESULT, QUERY_RESPONSE.result()); assertEquals(JOB_ID, QUERY_RESPONSE.jobId()); assertEquals(JOB_COMPLETE, QUERY_RESPONSE.jobCompleted()); assertEquals(ERRORS, QUERY_RESPONSE.executionErrors()); assertTrue(QUERY_RESPONSE.hasErrors()); } @Test public void testBuilderIncomplete() { QueryResponse queryResponse = QueryResponse.builder().jobCompleted(false).build(); assertNull(queryResponse.etag()); assertNull(queryResponse.result()); assertNull(queryResponse.jobId()); assertFalse(queryResponse.jobCompleted()); assertEquals(ImmutableList.<BigQueryError>of(), queryResponse.executionErrors()); assertFalse(queryResponse.hasErrors()); } @Test public void testEquals() { compareQueryResponse(QUERY_RESPONSE, QUERY_RESPONSE); } private void compareQueryResponse(QueryResponse expected, QueryResponse value) { assertEquals(expected, value); assertEquals(expected.etag(), value.etag()); assertEquals(expected.result(), value.result()); assertEquals(expected.jobId(), value.jobId()); assertEquals(expected.jobCompleted(), value.jobCompleted()); assertEquals(expected.executionErrors(), value.executionErrors()); assertEquals(expected.hasErrors(), value.hasErrors()); } }
{ "content_hash": "da5a400952f0d4649baee51c0cffe9ec", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 86, "avg_line_length": 35.38709677419355, "alnum_prop": 0.7143725311455484, "repo_name": "aozarov/gcloud-java", "id": "8eae6a9e03e31541ab438e861d608ed6c7db4906", "size": "3908", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "gcloud-java-bigquery/src/test/java/com/google/cloud/bigquery/QueryResponseTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "23012" }, { "name": "HTML", "bytes": "11681" }, { "name": "Java", "bytes": "2029406" }, { "name": "JavaScript", "bytes": "989" }, { "name": "Shell", "bytes": "6228" } ] }
function api_get_children(loc_uuid, callback) { var params = (loc_uuid ? {parent_id: loc_uuid} : {}); $('#loc_ajax').show(); $.getJSON(LOAD_LOCS_URL, params, function(allData) { $('#loc_ajax').hide(); callback(allData.objects); }); } function LocationSelectViewModel(hierarchy, default_caption, auto_drill, loc_filter, func) { var model = this; this.default_caption = default_caption || 'All'; this.auto_drill = (auto_drill == null ? true : auto_drill); this.loc_filter = loc_filter || function(loc) { return true; }; this.func = typeof func !== 'undefined' ? func : LocationModel; this.root = ko.observable(); this.selected_path = ko.observableArray(); this.location_types = $.map(hierarchy, function(e) { return {type: e[0], allowed_parents: e[1]}; }); // currently selected location in the tree (or null) this.selected_location = ko.computed(function() { for (var i = this.selected_path().length - 1; i >= 0; i--) { var loc = this.selected_path()[i]; if (loc.selected_is_valid()) { return loc.selected_child(); } } return null; }, this); // uuid of currently selected location (or null) this.selected_locid = ko.computed(function() { return this.selected_location() ? this.selected_location().uuid() : null; }, this); // add a new level of drill-down to the tree this.path_push = function(loc) { if (this.selected_path().length != this.location_types.length) { this.selected_path.push(loc); if (this.auto_drill && loc.num_children() == 1) { loc.selected_child(loc.get_child(0)); } } } // search for a location within the tree by uuid; return path to location if found this.find_loc = function(uuid, loc) { loc = loc || this.root(); if (loc.uuid() == uuid) { return [loc]; } else { var path = null; $.each(loc.children(), function(i, e) { var subpath = model.find_loc(uuid, e); if (subpath) { path = subpath; path.splice(0, 0, loc); return false; } }); return path; } } // load location hierarchy and set initial path this.load = function(locs, selected, restriction) { this.root(new model.func({name: '_root', children: locs, 'restriction': restriction}, this)); this.path_push(this.root()); if (selected) { // this relies on the hierarchy of the selected location being pre-populated // in the initial locations set from the server (i.e., no location of the // pre-selected location's lineage is loaded asynchronously var sel_path = this.find_loc(selected); if (sel_path) { for (var i = 1; i < sel_path.length; i++) { sel_path[i - 1].selected_child(sel_path[i]); } } } } } function LocationModel(data, root, depth, func, withAllOption) { var loc = this; this.name = ko.observable(); this.type = ko.observable(); this.uuid = ko.observable(); this.location_restriction = ko.observable(); this.children = ko.observableArray(); this.depth = depth || 0; this.children_loaded = false; this.func = typeof func !== 'undefined' ? func : LocationModel; this.withAllOption = typeof withAllOption !== 'undefined' ? withAllOption : true; this.display_name = ko.computed(function() { return this.name() == '_all' ? root.default_caption : this.name(); }, this); this.selected_child = ko.observable(); // when a location is selected, update the drill-down tree this.selected_child.subscribe(function(val) { if (val == null) { return; } var removed = root.selected_path.splice(val.depth, 99); $.each(removed, function(i, e) { // reset so dropdown for loc will default to 'all' if shown again e.selected_child(null); }); var post_children_loaded = function(parent) { if (parent.num_children()) { root.path_push(parent); } }; if (val.uuid() != null && !val.children_loaded) { val.load_children_async(post_children_loaded); } else { post_children_loaded(val); } }, this); this.selected_is_valid = ko.computed(function() { return this.selected_child() && this.selected_child().name() != '_all'; }, this); // helpers to account for the 'all' meta-entry this.num_children = ko.computed(function() { return (this.children().length == 0 ? 0 : this.children().length - 1); }, this); this.get_child = function(i) { return this.children()[i + 1]; } this.load = function(data) { this.name(data.name); this.type(data.location_type); this.uuid(data.uuid); this.location_restriction(data.restriction); if (data.children != null) { $.map(data.children, function(e) { e.restriction = data.restriction }); this.set_children(data.children); } } this.set_children = function(data) { var children = []; if (data) { children = _.sortBy(data, function(e) { return e.name; }); //'all choices' meta-entry; annoying that we have to stuff this in //the children list, but all my attempts to make computed observables //based of children() caused infinite loops. if(loc.withAllOption || (!loc.withAllOption && loc.depth > REQUIRED)) children.splice(0, 0, {name: '_all'}); } this.children($.map(children, function(e) { var child = new loc.func(e, root, loc.depth + 1); return (child.filter() ? child : null); })); this.children_loaded = true; } this.load_children_async = function(callback) { api_get_children(this.uuid(), function(resp) { loc.set_children(resp); callback(loc); }); } //warning: duplicate code with location_tree.async.js this.allowed_child_types = ko.computed(function() { var loc = this; var types = []; $.each(root.location_types, function(i, loc_type) { $.each(loc_type.allowed_parents, function(i, parent_type) { if (loc.type() == parent_type) { types.push(loc_type.type); } }); }); return types; }, this); this.can_have_children = ko.computed(function() { return (this.allowed_child_types().length > 0); }, this); this.filter = function() { return this.name() == '_all' || root.loc_filter(this); } this.load(data); }
{ "content_hash": "d3bb04ae1c8942d8b6787f83a4e62e53", "timestamp": "", "source": "github", "line_count": 206, "max_line_length": 97, "avg_line_length": 32.077669902912625, "alnum_prop": 0.5856537530266344, "repo_name": "SEL-Columbia/commcare-hq", "id": "574123e519e1aceb1081c7a6165f0bb720b0d5d7", "size": "6609", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "corehq/apps/locations/static/locations/ko/location_drilldown.async.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ActionScript", "bytes": "15950" }, { "name": "CSS", "bytes": "768322" }, { "name": "JavaScript", "bytes": "2647080" }, { "name": "Python", "bytes": "7806659" }, { "name": "Shell", "bytes": "28569" } ] }
<?php /** * Options for the styled map. * @author Ianaré Sévi */ class EGmap3StyledMapOptions extends EGmap3OptionBase { /** * @var string Name shown for the map. */ public $name; }
{ "content_hash": "f3e03e8e66210ed911fe84b4533d4217", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 53, "avg_line_length": 12.933333333333334, "alnum_prop": 0.6597938144329897, "repo_name": "illibejiep/YiiBoilerplate", "id": "c97d2728d1e35b83a5bcb50f7f21dc45e803547c", "size": "443", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "common/extensions/jquery-gmap/EGmap3StyledMapOptions.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "49212" }, { "name": "Batchfile", "bytes": "1263" }, { "name": "CSS", "bytes": "111863" }, { "name": "Gherkin", "bytes": "514" }, { "name": "HTML", "bytes": "4160678" }, { "name": "JavaScript", "bytes": "1744248" }, { "name": "PHP", "bytes": "33269841" }, { "name": "Shell", "bytes": "273" } ] }
// A basic integration test for the service. // Assumes that there is a pre-existing etcd server running on localhost. package main import ( "fmt" "io/ioutil" "net" "net/http" "net/http/httptest" "os" "reflect" gruntime "runtime" "strconv" "strings" "sync" "time" kubeletapp "k8s.io/kubernetes/cmd/kubelet/app" "k8s.io/kubernetes/pkg/api" apierrors "k8s.io/kubernetes/pkg/api/errors" "k8s.io/kubernetes/pkg/api/testapi" "k8s.io/kubernetes/pkg/api/unversioned" "k8s.io/kubernetes/pkg/api/v1" clientset "k8s.io/kubernetes/pkg/client/clientset_generated/release_1_2" "k8s.io/kubernetes/pkg/client/record" client "k8s.io/kubernetes/pkg/client/unversioned" "k8s.io/kubernetes/pkg/controller" endpointcontroller "k8s.io/kubernetes/pkg/controller/endpoint" nodecontroller "k8s.io/kubernetes/pkg/controller/node" replicationcontroller "k8s.io/kubernetes/pkg/controller/replication" "k8s.io/kubernetes/pkg/kubelet/cadvisor" "k8s.io/kubernetes/pkg/kubelet/cm" kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" "k8s.io/kubernetes/pkg/kubelet/dockertools" kubetypes "k8s.io/kubernetes/pkg/kubelet/types" "k8s.io/kubernetes/pkg/labels" "k8s.io/kubernetes/pkg/master" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/util" utilnet "k8s.io/kubernetes/pkg/util/net" utilruntime "k8s.io/kubernetes/pkg/util/runtime" "k8s.io/kubernetes/pkg/util/sets" "k8s.io/kubernetes/pkg/util/wait" "k8s.io/kubernetes/pkg/volume/empty_dir" "k8s.io/kubernetes/plugin/pkg/scheduler" _ "k8s.io/kubernetes/plugin/pkg/scheduler/algorithmprovider" "k8s.io/kubernetes/plugin/pkg/scheduler/factory" "k8s.io/kubernetes/test/e2e" "k8s.io/kubernetes/test/integration" "k8s.io/kubernetes/test/integration/framework" etcd "github.com/coreos/etcd/client" "github.com/golang/glog" "github.com/spf13/pflag" "golang.org/x/net/context" ) var ( fakeDocker1 = dockertools.NewFakeDockerClient() fakeDocker2 = dockertools.NewFakeDockerClient() // Limit the number of concurrent tests. maxConcurrency int longTestTimeout = time.Second * 500 maxTestTimeout = time.Minute * 15 ) type delegateHandler struct { delegate http.Handler } func (h *delegateHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { if h.delegate != nil { h.delegate.ServeHTTP(w, req) return } w.WriteHeader(http.StatusNotFound) } func startComponents(firstManifestURL, secondManifestURL string) (string, string) { // Setup handler := delegateHandler{} apiServer := httptest.NewServer(&handler) cfg := etcd.Config{ Endpoints: []string{"http://127.0.0.1:4001"}, } etcdClient, err := etcd.New(cfg) if err != nil { glog.Fatalf("Error creating etcd client: %v", err) } glog.Infof("Creating etcd client pointing to %v", cfg.Endpoints) keysAPI := etcd.NewKeysAPI(etcdClient) sleep := 4 * time.Second ok := false for i := 0; i < 3; i++ { keys, err := keysAPI.Get(context.TODO(), "/", nil) if err != nil { glog.Warningf("Unable to list root etcd keys: %v", err) if i < 2 { time.Sleep(sleep) sleep = sleep * sleep } continue } for _, node := range keys.Node.Nodes { if _, err := keysAPI.Delete(context.TODO(), node.Key, &etcd.DeleteOptions{Recursive: true}); err != nil { glog.Fatalf("Unable delete key: %v", err) } } ok = true break } if !ok { glog.Fatalf("Failed to connect to etcd") } cl := client.NewOrDie(&client.Config{Host: apiServer.URL, ContentConfig: client.ContentConfig{GroupVersion: testapi.Default.GroupVersion()}}) clientset := clientset.NewForConfigOrDie(&client.Config{Host: apiServer.URL, ContentConfig: client.ContentConfig{GroupVersion: testapi.Default.GroupVersion()}}) // TODO: caesarxuchao: hacky way to specify version of Experimental client. // We will fix this by supporting multiple group versions in Config cl.ExtensionsClient = client.NewExtensionsOrDie(&client.Config{Host: apiServer.URL, ContentConfig: client.ContentConfig{GroupVersion: testapi.Extensions.GroupVersion()}}) // Master host, port, err := net.SplitHostPort(strings.TrimLeft(apiServer.URL, "http://")) if err != nil { glog.Fatalf("Unable to parse URL '%v': %v", apiServer.URL, err) } portNumber, err := strconv.Atoi(port) if err != nil { glog.Fatalf("Nonnumeric port? %v", err) } publicAddress := net.ParseIP(host) if publicAddress == nil { glog.Fatalf("No public address for %s", host) } // The caller of master.New should guarantee pulicAddress is properly set hostIP, err := utilnet.ChooseBindAddress(publicAddress) if err != nil { glog.Fatalf("Unable to find suitable network address.error='%v' . "+ "Fail to get a valid public address for master.", err) } masterConfig := framework.NewMasterConfig() masterConfig.EnableCoreControllers = true masterConfig.EnableProfiling = true masterConfig.ReadWritePort = portNumber masterConfig.PublicAddress = hostIP masterConfig.CacheTimeout = 2 * time.Second // Create a master and install handlers into mux. m := master.New(masterConfig) handler.delegate = m.Handler // Scheduler schedulerConfigFactory := factory.NewConfigFactory(cl, api.DefaultSchedulerName) schedulerConfig, err := schedulerConfigFactory.Create() if err != nil { glog.Fatalf("Couldn't create scheduler config: %v", err) } eventBroadcaster := record.NewBroadcaster() schedulerConfig.Recorder = eventBroadcaster.NewRecorder(api.EventSource{Component: api.DefaultSchedulerName}) eventBroadcaster.StartLogging(glog.Infof) eventBroadcaster.StartRecordingToSink(cl.Events("")) scheduler.New(schedulerConfig).Run() // ensure the service endpoints are sync'd several times within the window that the integration tests wait go endpointcontroller.NewEndpointController(clientset, controller.NoResyncPeriodFunc). Run(3, util.NeverStop) // TODO: Write an integration test for the replication controllers watch. go replicationcontroller.NewReplicationManager(clientset, controller.NoResyncPeriodFunc, replicationcontroller.BurstReplicas). Run(3, util.NeverStop) nodeController := nodecontroller.NewNodeController(nil, clientset, 5*time.Minute, util.NewFakeRateLimiter(), util.NewFakeRateLimiter(), 40*time.Second, 60*time.Second, 5*time.Second, nil, false) nodeController.Run(5 * time.Second) cadvisorInterface := new(cadvisor.Fake) // Kubelet (localhost) testRootDir := integration.MakeTempDirOrDie("kubelet_integ_1.", "") configFilePath := integration.MakeTempDirOrDie("config", testRootDir) glog.Infof("Using %s as root dir for kubelet #1", testRootDir) cm := cm.NewStubContainerManager() kcfg := kubeletapp.SimpleKubelet( clientset, fakeDocker1, "localhost", testRootDir, firstManifestURL, "127.0.0.1", 10250, /* KubeletPort */ 0, /* ReadOnlyPort */ api.NamespaceDefault, empty_dir.ProbeVolumePlugins(), nil, cadvisorInterface, configFilePath, nil, kubecontainer.FakeOS{}, 1*time.Second, /* FileCheckFrequency */ 1*time.Second, /* HTTPCheckFrequency */ 10*time.Second, /* MinimumGCAge */ 3*time.Second, /* NodeStatusUpdateFrequency */ 10*time.Second, /* SyncFrequency */ 10*time.Second, /* OutOfDiskTransitionFrequency */ 40, /* MaxPods */ cm, net.ParseIP("127.0.0.1")) kubeletapp.RunKubelet(kcfg) // Kubelet (machine) // Create a second kubelet so that the guestbook example's two redis slaves both // have a place they can schedule. testRootDir = integration.MakeTempDirOrDie("kubelet_integ_2.", "") glog.Infof("Using %s as root dir for kubelet #2", testRootDir) kcfg = kubeletapp.SimpleKubelet( clientset, fakeDocker2, "127.0.0.1", testRootDir, secondManifestURL, "127.0.0.1", 10251, /* KubeletPort */ 0, /* ReadOnlyPort */ api.NamespaceDefault, empty_dir.ProbeVolumePlugins(), nil, cadvisorInterface, "", nil, kubecontainer.FakeOS{}, 1*time.Second, /* FileCheckFrequency */ 1*time.Second, /* HTTPCheckFrequency */ 10*time.Second, /* MinimumGCAge */ 3*time.Second, /* NodeStatusUpdateFrequency */ 10*time.Second, /* SyncFrequency */ 10*time.Second, /* OutOfDiskTransitionFrequency */ 40, /* MaxPods */ cm, net.ParseIP("127.0.0.1")) kubeletapp.RunKubelet(kcfg) return apiServer.URL, configFilePath } func makeTempDirOrDie(prefix string, baseDir string) string { if baseDir == "" { baseDir = "/tmp" } tempDir, err := ioutil.TempDir(baseDir, prefix) if err != nil { glog.Fatalf("Can't make a temp rootdir: %v", err) } if err = os.MkdirAll(tempDir, 0750); err != nil { glog.Fatalf("Can't mkdir(%q): %v", tempDir, err) } return tempDir } // podsOnNodes returns true when all of the selected pods exist on a node. func podsOnNodes(c *client.Client, podNamespace string, labelSelector labels.Selector) wait.ConditionFunc { // Wait until all pods are running on the node. return func() (bool, error) { options := api.ListOptions{LabelSelector: labelSelector} pods, err := c.Pods(podNamespace).List(options) if err != nil { glog.Infof("Unable to get pods to list: %v", err) return false, nil } for i := range pods.Items { pod := pods.Items[i] podString := fmt.Sprintf("%s/%s", pod.Namespace, pod.Name) glog.Infof("Check whether pod %q exists on node %q", podString, pod.Spec.NodeName) if len(pod.Spec.NodeName) == 0 { glog.Infof("Pod %q is not bound to a host yet", podString) return false, nil } if pod.Status.Phase != api.PodRunning { glog.Infof("Pod %q is not running, status: %v", podString, pod.Status.Phase) return false, nil } } return true, nil } } func endpointsSet(c *client.Client, serviceNamespace, serviceID string, endpointCount int) wait.ConditionFunc { return func() (bool, error) { endpoints, err := c.Endpoints(serviceNamespace).Get(serviceID) if err != nil { glog.Infof("Error getting endpoints: %v", err) return false, nil } count := 0 for _, ss := range endpoints.Subsets { for _, addr := range ss.Addresses { for _, port := range ss.Ports { count++ glog.Infof("%s/%s endpoint: %s:%d %#v", serviceNamespace, serviceID, addr.IP, port.Port, addr.TargetRef) } } } return count == endpointCount, nil } } func countEndpoints(eps *api.Endpoints) int { count := 0 for i := range eps.Subsets { count += len(eps.Subsets[i].Addresses) * len(eps.Subsets[i].Ports) } return count } func podExists(c *client.Client, podNamespace string, podName string) wait.ConditionFunc { return func() (bool, error) { _, err := c.Pods(podNamespace).Get(podName) return err == nil, nil } } func podNotFound(c *client.Client, podNamespace string, podName string) wait.ConditionFunc { return func() (bool, error) { _, err := c.Pods(podNamespace).Get(podName) return apierrors.IsNotFound(err), nil } } func podRunning(c *client.Client, podNamespace string, podName string) wait.ConditionFunc { return func() (bool, error) { pod, err := c.Pods(podNamespace).Get(podName) if apierrors.IsNotFound(err) { glog.V(2).Infof("Pod %s/%s was not found", podNamespace, podName) return false, nil } if err != nil { // This could be a connection error so we want to retry, but log the error. glog.Errorf("Error when reading pod %q: %v", podName, err) return false, nil } if pod.Status.Phase != api.PodRunning { glog.V(2).Infof("Pod %s/%s is not running. In phase %q", podNamespace, podName, pod.Status.Phase) return false, nil } return true, nil } } // runStaticPodTest is disabled until #6651 is resolved. func runStaticPodTest(c *client.Client, configFilePath string) { var testCases = []struct { desc string fileContents string }{ { desc: "static-pod-from-manifest", fileContents: `version: v1beta2 id: static-pod-from-manifest containers: - name: static-container image: kubernetes/pause`, }, { desc: "static-pod-from-spec", fileContents: `{ "kind": "Pod", "apiVersion": "v1", "metadata": { "name": "static-pod-from-spec" }, "spec": { "containers": [{ "name": "static-container", "image": "kubernetes/pause" }] } }`, }, } for _, testCase := range testCases { func() { desc := testCase.desc manifestFile, err := ioutil.TempFile(configFilePath, "") defer os.Remove(manifestFile.Name()) ioutil.WriteFile(manifestFile.Name(), []byte(testCase.fileContents), 0600) // Wait for the mirror pod to be created. podName := fmt.Sprintf("%s-localhost", desc) namespace := kubetypes.NamespaceDefault if err := wait.Poll(time.Second, longTestTimeout, podRunning(c, namespace, podName)); err != nil { if pods, err := c.Pods(namespace).List(api.ListOptions{}); err == nil { for _, pod := range pods.Items { glog.Infof("pod found: %s/%s", namespace, pod.Name) } } glog.Fatalf("%s FAILED: mirror pod has not been created or is not running: %v", desc, err) } // Delete the mirror pod, and wait for it to be recreated. c.Pods(namespace).Delete(podName, nil) if err = wait.Poll(time.Second, longTestTimeout, podRunning(c, namespace, podName)); err != nil { glog.Fatalf("%s FAILED: mirror pod has not been re-created or is not running: %v", desc, err) } // Remove the manifest file, and wait for the mirror pod to be deleted. os.Remove(manifestFile.Name()) if err = wait.Poll(time.Second, longTestTimeout, podNotFound(c, namespace, podName)); err != nil { glog.Fatalf("%s FAILED: mirror pod has not been deleted: %v", desc, err) } }() } } func runReplicationControllerTest(c *client.Client) { t := time.Now() clientAPIVersion := c.APIVersion().String() data, err := ioutil.ReadFile("cmd/integration/" + clientAPIVersion + "-controller.json") if err != nil { glog.Fatalf("Unexpected error: %v", err) } glog.Infof("Done reading config file, took %v", time.Since(t)) t = time.Now() var controller api.ReplicationController if err := runtime.DecodeInto(testapi.Default.Codec(), data, &controller); err != nil { glog.Fatalf("Unexpected error: %v", err) } glog.Infof("Creating replication controllers") updated, err := c.ReplicationControllers("test").Create(&controller) if err != nil { glog.Fatalf("Unexpected error: %v", err) } glog.Infof("Done creating replication controllers, took %v", time.Since(t)) t = time.Now() // In practice the controller doesn't need 60s to create a handful of pods, but network latencies on CI // systems have been observed to vary unpredictably, so give the controller enough time to create pods. // Our e2e scalability tests will catch controllers that are *actually* slow. if err := wait.Poll(time.Second, longTestTimeout, client.ControllerHasDesiredReplicas(c, updated)); err != nil { glog.Fatalf("FAILED: pods never created %v", err) } glog.Infof("Done creating replicas, took %v", time.Since(t)) t = time.Now() // Poll till we can retrieve the status of all pods matching the given label selector from their nodes. // This involves 3 operations: // - The scheduler must assign all pods to a node // - The assignment must reflect in a `List` operation against the apiserver, for labels matching the selector // - We need to be able to query the kubelet on that node for information about the pod if err := wait.Poll( time.Second, longTestTimeout, podsOnNodes(c, "test", labels.Set(updated.Spec.Selector).AsSelector())); err != nil { glog.Fatalf("FAILED: pods never started running %v", err) } glog.Infof("Pods verified on nodes, took %v", time.Since(t)) } func runAPIVersionsTest(c *client.Client) { g, err := c.ServerGroups() clientVersion := c.APIVersion().String() if err != nil { glog.Fatalf("Failed to get api versions: %v", err) } versions := client.ExtractGroupVersions(g) // Verify that the server supports the API version used by the client. for _, version := range versions { if version == clientVersion { glog.Infof("Version test passed") return } } glog.Fatalf("Server does not support APIVersion used by client. Server supported APIVersions: '%v', client APIVersion: '%v'", versions, clientVersion) } func runSelfLinkTestOnNamespace(c *client.Client, namespace string) { svcBody := api.Service{ ObjectMeta: api.ObjectMeta{ Name: "selflinktest", Namespace: namespace, Labels: map[string]string{ "name": "selflinktest", }, }, Spec: api.ServiceSpec{ // This is here because validation requires it. Selector: map[string]string{ "foo": "bar", }, Ports: []api.ServicePort{{ Port: 12345, Protocol: "TCP", }}, SessionAffinity: "None", }, } services := c.Services(namespace) svc, err := services.Create(&svcBody) if err != nil { glog.Fatalf("Failed creating selflinktest service: %v", err) } err = c.Get().RequestURI(svc.SelfLink).Do().Into(svc) if err != nil { glog.Fatalf("Failed listing service with supplied self link '%v': %v", svc.SelfLink, err) } svcList, err := services.List(api.ListOptions{}) if err != nil { glog.Fatalf("Failed listing services: %v", err) } err = c.Get().RequestURI(svcList.SelfLink).Do().Into(svcList) if err != nil { glog.Fatalf("Failed listing services with supplied self link '%v': %v", svcList.SelfLink, err) } found := false for i := range svcList.Items { item := &svcList.Items[i] if item.Name != "selflinktest" { continue } found = true err = c.Get().RequestURI(item.SelfLink).Do().Into(svc) if err != nil { glog.Fatalf("Failed listing service with supplied self link '%v': %v", item.SelfLink, err) } break } if !found { glog.Fatalf("never found selflinktest service in namespace %s", namespace) } glog.Infof("Self link test passed in namespace %s", namespace) // TODO: Should test PUT at some point, too. } func runAtomicPutTest(c *client.Client) { svcBody := api.Service{ TypeMeta: unversioned.TypeMeta{ APIVersion: c.APIVersion().String(), }, ObjectMeta: api.ObjectMeta{ Name: "atomicservice", Labels: map[string]string{ "name": "atomicService", }, }, Spec: api.ServiceSpec{ // This is here because validation requires it. Selector: map[string]string{ "foo": "bar", }, Ports: []api.ServicePort{{ Port: 12345, Protocol: "TCP", }}, SessionAffinity: "None", }, } services := c.Services(api.NamespaceDefault) svc, err := services.Create(&svcBody) if err != nil { glog.Fatalf("Failed creating atomicService: %v", err) } glog.Info("Created atomicService") testLabels := labels.Set{ "foo": "bar", } for i := 0; i < 5; i++ { // a: z, b: y, etc... testLabels[string([]byte{byte('a' + i)})] = string([]byte{byte('z' - i)}) } var wg sync.WaitGroup wg.Add(len(testLabels)) for label, value := range testLabels { go func(l, v string) { for { glog.Infof("Starting to update (%s, %s)", l, v) tmpSvc, err := services.Get(svc.Name) if err != nil { glog.Errorf("Error getting atomicService: %v", err) continue } if tmpSvc.Spec.Selector == nil { tmpSvc.Spec.Selector = map[string]string{l: v} } else { tmpSvc.Spec.Selector[l] = v } glog.Infof("Posting update (%s, %s)", l, v) tmpSvc, err = services.Update(tmpSvc) if err != nil { if apierrors.IsConflict(err) { glog.Infof("Conflict: (%s, %s)", l, v) // This is what we expect. continue } glog.Errorf("Unexpected error putting atomicService: %v", err) continue } break } glog.Infof("Done update (%s, %s)", l, v) wg.Done() }(label, value) } wg.Wait() svc, err = services.Get(svc.Name) if err != nil { glog.Fatalf("Failed getting atomicService after writers are complete: %v", err) } if !reflect.DeepEqual(testLabels, labels.Set(svc.Spec.Selector)) { glog.Fatalf("Selector PUTs were not atomic: wanted %v, got %v", testLabels, svc.Spec.Selector) } glog.Info("Atomic PUTs work.") } func runPatchTest(c *client.Client) { name := "patchservice" resource := "services" svcBody := api.Service{ TypeMeta: unversioned.TypeMeta{ APIVersion: c.APIVersion().String(), }, ObjectMeta: api.ObjectMeta{ Name: name, Labels: map[string]string{}, }, Spec: api.ServiceSpec{ // This is here because validation requires it. Selector: map[string]string{ "foo": "bar", }, Ports: []api.ServicePort{{ Port: 12345, Protocol: "TCP", }}, SessionAffinity: "None", }, } services := c.Services(api.NamespaceDefault) svc, err := services.Create(&svcBody) if err != nil { glog.Fatalf("Failed creating patchservice: %v", err) } patchBodies := map[unversioned.GroupVersion]map[api.PatchType]struct { AddLabelBody []byte RemoveLabelBody []byte RemoveAllLabelsBody []byte }{ v1.SchemeGroupVersion: { api.JSONPatchType: { []byte(`[{"op":"add","path":"/metadata/labels","value":{"foo":"bar","baz":"qux"}}]`), []byte(`[{"op":"remove","path":"/metadata/labels/foo"}]`), []byte(`[{"op":"remove","path":"/metadata/labels"}]`), }, api.MergePatchType: { []byte(`{"metadata":{"labels":{"foo":"bar","baz":"qux"}}}`), []byte(`{"metadata":{"labels":{"foo":null}}}`), []byte(`{"metadata":{"labels":null}}`), }, api.StrategicMergePatchType: { []byte(`{"metadata":{"labels":{"foo":"bar","baz":"qux"}}}`), []byte(`{"metadata":{"labels":{"foo":null}}}`), []byte(`{"metadata":{"labels":{"$patch":"replace"}}}`), }, }, } pb := patchBodies[c.APIVersion()] execPatch := func(pt api.PatchType, body []byte) error { return c.Patch(pt). Resource(resource). Namespace(api.NamespaceDefault). Name(name). Body(body). Do(). Error() } for k, v := range pb { // add label err := execPatch(k, v.AddLabelBody) if err != nil { glog.Fatalf("Failed updating patchservice with patch type %s: %v", k, err) } svc, err = services.Get(name) if err != nil { glog.Fatalf("Failed getting patchservice: %v", err) } if len(svc.Labels) != 2 || svc.Labels["foo"] != "bar" || svc.Labels["baz"] != "qux" { glog.Fatalf("Failed updating patchservice with patch type %s: labels are: %v", k, svc.Labels) } // remove one label err = execPatch(k, v.RemoveLabelBody) if err != nil { glog.Fatalf("Failed updating patchservice with patch type %s: %v", k, err) } svc, err = services.Get(name) if err != nil { glog.Fatalf("Failed getting patchservice: %v", err) } if len(svc.Labels) != 1 || svc.Labels["baz"] != "qux" { glog.Fatalf("Failed updating patchservice with patch type %s: labels are: %v", k, svc.Labels) } // remove all labels err = execPatch(k, v.RemoveAllLabelsBody) if err != nil { glog.Fatalf("Failed updating patchservice with patch type %s: %v", k, err) } svc, err = services.Get(name) if err != nil { glog.Fatalf("Failed getting patchservice: %v", err) } if svc.Labels != nil { glog.Fatalf("Failed remove all labels from patchservice with patch type %s: %v", k, svc.Labels) } } glog.Info("PATCHs work.") } func runMasterServiceTest(client *client.Client) { time.Sleep(12 * time.Second) svcList, err := client.Services(api.NamespaceDefault).List(api.ListOptions{}) if err != nil { glog.Fatalf("Unexpected error listing services: %v", err) } var foundRW bool found := sets.String{} for i := range svcList.Items { found.Insert(svcList.Items[i].Name) if svcList.Items[i].Name == "kubernetes" { foundRW = true } } if foundRW { ep, err := client.Endpoints(api.NamespaceDefault).Get("kubernetes") if err != nil { glog.Fatalf("Unexpected error listing endpoints for kubernetes service: %v", err) } if countEndpoints(ep) == 0 { glog.Fatalf("No endpoints for kubernetes service: %v", ep) } } else { glog.Errorf("No RW service found: %v", found) glog.Fatal("Kubernetes service test failed") } glog.Infof("Master service test passed.") } func runServiceTest(client *client.Client) { pod := &api.Pod{ ObjectMeta: api.ObjectMeta{ Name: "foo", Labels: map[string]string{ "name": "thisisalonglabel", }, }, Spec: api.PodSpec{ Containers: []api.Container{ { Name: "c1", Image: "foo", Ports: []api.ContainerPort{ {ContainerPort: 1234}, }, ImagePullPolicy: api.PullIfNotPresent, }, }, RestartPolicy: api.RestartPolicyAlways, DNSPolicy: api.DNSClusterFirst, }, Status: api.PodStatus{ PodIP: "1.2.3.4", }, } pod, err := client.Pods(api.NamespaceDefault).Create(pod) if err != nil { glog.Fatalf("Failed to create pod: %v, %v", pod, err) } if err := wait.Poll(time.Second, longTestTimeout, podExists(client, pod.Namespace, pod.Name)); err != nil { glog.Fatalf("FAILED: pod never started running %v", err) } svc1 := &api.Service{ ObjectMeta: api.ObjectMeta{Name: "service1"}, Spec: api.ServiceSpec{ Selector: map[string]string{ "name": "thisisalonglabel", }, Ports: []api.ServicePort{{ Port: 8080, Protocol: "TCP", }}, SessionAffinity: "None", }, } svc1, err = client.Services(api.NamespaceDefault).Create(svc1) if err != nil { glog.Fatalf("Failed to create service: %v, %v", svc1, err) } // create an identical service in the non-default namespace svc3 := &api.Service{ ObjectMeta: api.ObjectMeta{Name: "service1"}, Spec: api.ServiceSpec{ Selector: map[string]string{ "name": "thisisalonglabel", }, Ports: []api.ServicePort{{ Port: 8080, Protocol: "TCP", }}, SessionAffinity: "None", }, } svc3, err = client.Services("other").Create(svc3) if err != nil { glog.Fatalf("Failed to create service: %v, %v", svc3, err) } // TODO Reduce the timeouts in this test when endpoints controller is sped up. See #6045. if err := wait.Poll(time.Second, longTestTimeout, endpointsSet(client, svc1.Namespace, svc1.Name, 1)); err != nil { glog.Fatalf("FAILED: unexpected endpoints: %v", err) } // A second service with the same port. svc2 := &api.Service{ ObjectMeta: api.ObjectMeta{Name: "service2"}, Spec: api.ServiceSpec{ Selector: map[string]string{ "name": "thisisalonglabel", }, Ports: []api.ServicePort{{ Port: 8080, Protocol: "TCP", }}, SessionAffinity: "None", }, } svc2, err = client.Services(api.NamespaceDefault).Create(svc2) if err != nil { glog.Fatalf("Failed to create service: %v, %v", svc2, err) } if err := wait.Poll(time.Second, longTestTimeout, endpointsSet(client, svc2.Namespace, svc2.Name, 1)); err != nil { glog.Fatalf("FAILED: unexpected endpoints: %v", err) } if err := wait.Poll(time.Second, longTestTimeout, endpointsSet(client, svc3.Namespace, svc3.Name, 0)); err != nil { glog.Fatalf("FAILED: service in other namespace should have no endpoints: %v", err) } svcList, err := client.Services(api.NamespaceAll).List(api.ListOptions{}) if err != nil { glog.Fatalf("Failed to list services across namespaces: %v", err) } names := sets.NewString() for _, svc := range svcList.Items { names.Insert(fmt.Sprintf("%s/%s", svc.Namespace, svc.Name)) } if !names.HasAll("default/kubernetes", "default/service1", "default/service2", "other/service1") { glog.Fatalf("Unexpected service list: %#v", names) } glog.Info("Service test passed.") } func runSchedulerNoPhantomPodsTest(client *client.Client) { pod := &api.Pod{ Spec: api.PodSpec{ Containers: []api.Container{ { Name: "c1", Image: "kubernetes/pause", Ports: []api.ContainerPort{ {ContainerPort: 1234, HostPort: 9999}, }, ImagePullPolicy: api.PullIfNotPresent, }, }, }, } // Assuming we only have two kublets, the third pod here won't schedule // if the scheduler doesn't correctly handle the delete for the second // pod. pod.ObjectMeta.Name = "phantom.foo" foo, err := client.Pods(api.NamespaceDefault).Create(pod) if err != nil { glog.Fatalf("Failed to create pod: %v, %v", pod, err) } if err := wait.Poll(time.Second, longTestTimeout, podRunning(client, foo.Namespace, foo.Name)); err != nil { glog.Fatalf("FAILED: pod never started running %v", err) } pod.ObjectMeta.Name = "phantom.bar" bar, err := client.Pods(api.NamespaceDefault).Create(pod) if err != nil { glog.Fatalf("Failed to create pod: %v, %v", pod, err) } if err := wait.Poll(time.Second, longTestTimeout, podRunning(client, bar.Namespace, bar.Name)); err != nil { glog.Fatalf("FAILED: pod never started running %v", err) } // Delete a pod to free up room. glog.Infof("Deleting pod %v", bar.Name) err = client.Pods(api.NamespaceDefault).Delete(bar.Name, api.NewDeleteOptions(0)) if err != nil { glog.Fatalf("FAILED: couldn't delete pod %q: %v", bar.Name, err) } pod.ObjectMeta.Name = "phantom.baz" baz, err := client.Pods(api.NamespaceDefault).Create(pod) if err != nil { glog.Fatalf("Failed to create pod: %v, %v", pod, err) } if err := wait.Poll(time.Second, longTestTimeout, podRunning(client, baz.Namespace, baz.Name)); err != nil { if pod, perr := client.Pods(api.NamespaceDefault).Get("phantom.bar"); perr == nil { glog.Fatalf("FAILED: 'phantom.bar' was never deleted: %#v, err: %v", pod, err) } else { glog.Fatalf("FAILED: (Scheduler probably didn't process deletion of 'phantom.bar') Pod never started running: err: %v, perr: %v", err, perr) } } glog.Info("Scheduler doesn't make phantom pods: test passed.") } type testFunc func(*client.Client) func addFlags(fs *pflag.FlagSet) { fs.IntVar( &maxConcurrency, "max-concurrency", -1, "Maximum number of tests to be run simultaneously. Unlimited if set to negative.") } func main() { gruntime.GOMAXPROCS(gruntime.NumCPU()) addFlags(pflag.CommandLine) util.InitFlags() utilruntime.ReallyCrash = true util.InitLogs() defer util.FlushLogs() go func() { defer util.FlushLogs() time.Sleep(maxTestTimeout) glog.Fatalf("This test has timed out.") }() glog.Infof("Running tests for APIVersion: %s", os.Getenv("KUBE_TEST_API")) firstManifestURL := ServeCachedManifestFile(testPodSpecFile) secondManifestURL := ServeCachedManifestFile(testPodSpecFile) apiServerURL, _ := startComponents(firstManifestURL, secondManifestURL) // Ok. we're good to go. glog.Infof("API Server started on %s", apiServerURL) // Wait for the synchronization threads to come up. time.Sleep(time.Second * 10) kubeClient := client.NewOrDie(&client.Config{Host: apiServerURL, ContentConfig: client.ContentConfig{GroupVersion: testapi.Default.GroupVersion()}}) // TODO: caesarxuchao: hacky way to specify version of Experimental client. // We will fix this by supporting multiple group versions in Config kubeClient.ExtensionsClient = client.NewExtensionsOrDie(&client.Config{Host: apiServerURL, ContentConfig: client.ContentConfig{GroupVersion: testapi.Extensions.GroupVersion()}}) // Run tests in parallel testFuncs := []testFunc{ runReplicationControllerTest, runAtomicPutTest, runPatchTest, runServiceTest, runAPIVersionsTest, runMasterServiceTest, func(c *client.Client) { runSelfLinkTestOnNamespace(c, api.NamespaceDefault) runSelfLinkTestOnNamespace(c, "other") }, } // Only run at most maxConcurrency tests in parallel. if maxConcurrency <= 0 { maxConcurrency = len(testFuncs) } glog.Infof("Running %d tests in parallel.", maxConcurrency) ch := make(chan struct{}, maxConcurrency) var wg sync.WaitGroup wg.Add(len(testFuncs)) for i := range testFuncs { f := testFuncs[i] go func() { ch <- struct{}{} f(kubeClient) <-ch wg.Done() }() } wg.Wait() close(ch) // Check that kubelet tried to make the containers. // Using a set to list unique creation attempts. Our fake is // really stupid, so kubelet tries to create these multiple times. createdConts := sets.String{} for _, p := range fakeDocker1.Created { // The last 8 characters are random, so slice them off. if n := len(p); n > 8 { createdConts.Insert(p[:n-8]) } } for _, p := range fakeDocker2.Created { // The last 8 characters are random, so slice them off. if n := len(p); n > 8 { createdConts.Insert(p[:n-8]) } } // We expect 12: 2 pod infra containers + 2 containers from the replication controller + // 1 pod infra container + 2 containers from the URL on first Kubelet + // 1 pod infra container + 2 containers from the URL on second Kubelet + // 1 pod infra container + 1 container from the service test. // The total number of container created is 12 if len(createdConts) != 12 { glog.Fatalf("Expected 12 containers; got %v\n\nlist of created containers:\n\n%#v\n\nDocker 1 Created:\n\n%#v\n\nDocker 2 Created:\n\n%#v\n\n", len(createdConts), createdConts.List(), fakeDocker1.Created, fakeDocker2.Created) } glog.Infof("OK - found created containers: %#v", createdConts.List()) // This test doesn't run with the others because it can't run in // parallel and also it schedules extra pods which would change the // above pod counting logic. runSchedulerNoPhantomPodsTest(kubeClient) glog.Infof("\n\nLogging high latency metrics from the 10250 kubelet") e2e.HighLatencyKubeletOperations(nil, 1*time.Second, "localhost:10250") glog.Infof("\n\nLogging high latency metrics from the 10251 kubelet") e2e.HighLatencyKubeletOperations(nil, 1*time.Second, "localhost:10251") } // ServeCachedManifestFile serves a file for kubelet to read. func ServeCachedManifestFile(contents string) (servingAddress string) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/manifest" { w.Write([]byte(contents)) return } glog.Fatalf("Got request: %#v\n", r) http.NotFound(w, r) })) return server.URL + "/manifest" } const ( testPodSpecFile = `{ "kind": "Pod", "apiVersion": "v1", "metadata": { "name": "container-vm-guestbook-pod-spec" }, "spec": { "containers": [ { "name": "redis", "image": "redis", "volumeMounts": [{ "name": "redis-data", "mountPath": "/data" }] }, { "name": "guestbook", "image": "google/guestbook-python-redis", "ports": [{ "name": "www", "hostPort": 80, "containerPort": 80 }] }], "volumes": [{ "name": "redis-data" }] } }` )
{ "content_hash": "8beb56f863044d8f1342cbee4eb9d8eb", "timestamp": "", "source": "github", "line_count": 1095, "max_line_length": 227, "avg_line_length": 31.160730593607305, "alnum_prop": 0.6795521819407403, "repo_name": "dcbw/kubernetes", "id": "c875b055f228465f8fe892be6da1d239b57dc9d8", "size": "34710", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cmd/integration/integration.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "18484218" }, { "name": "HTML", "bytes": "1193991" }, { "name": "Makefile", "bytes": "46385" }, { "name": "Nginx", "bytes": "1013" }, { "name": "Python", "bytes": "68276" }, { "name": "SaltStack", "bytes": "44807" }, { "name": "Shell", "bytes": "1163008" } ] }
/** * Classes and API methods for the Relationships service (not ready yet) * @module relationships */ // Classes import * as relationships from '../relationships' // Exports export { relationships }
{ "content_hash": "5fb1760a6caa94cf4af0c2d7ac9362d8", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 72, "avg_line_length": 20.5, "alnum_prop": 0.7170731707317073, "repo_name": "amaas-fintech/amaas-core-sdk-js", "id": "76a6397291206dd783c6a5610efe28dba65b91b9", "size": "205", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/exports/relationships.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "640082" } ] }
<?php namespace System\Validation\Rules; use System\Validation\Nullable_Rule; class Presence_Of extends Nullable_Rule { /** * Evaluate the validity of an attribute. * * @param string $attribute * @param array $attributes * @return bool */ public function check($attribute, $attributes) { if ( ! is_null($nullable = parent::check($attribute, $attributes))) { return $nullable; } // --------------------------------------------------------- // The Nullable_Rule check method essentially is a check for // the presence of an attribute, so there is no further // checking that needs to be done. // --------------------------------------------------------- return true; } }
{ "content_hash": "13a05d237b5fd1f417c027af721c5c4d", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 69, "avg_line_length": 24.655172413793103, "alnum_prop": 0.5636363636363636, "repo_name": "Jamongkad/s36-beta", "id": "8926e967d0ff3d22f8aa434be8073cf956f2dda0", "size": "715", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "system/validation/rules/presence_of.php", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "480204" }, { "name": "JavaScript", "bytes": "988448" }, { "name": "PHP", "bytes": "5379937" }, { "name": "Perl", "bytes": "96" }, { "name": "Ruby", "bytes": "380" } ] }
this_file := $(lastword $(MAKEFILE_LIST)) # Determine the absolute path of the Makefile (see http://blog.jgc.org/2007/01/what-makefile-am-i-in.html): this_dir := $(dir $(CURDIR)/$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST))) # Remove the trailing slash: this_dir := $(patsubst %/,%,$(this_dir)) # Define the root project directory: ROOT_DIR ?= $(this_dir) # Define the root tools directory: TOOLS_DIR ?= $(ROOT_DIR)/tools # Define the directory containing the entry point for Makefile dependencies: TOOLS_MAKE_DIR ?= $(TOOLS_DIR)/make # Define the subdirectory containing Makefile dependencies: TOOLS_MAKE_LIB_DIR ?= $(TOOLS_MAKE_DIR)/lib # Define the root build directory: BUILD_DIR ?= $(ROOT_DIR)/build # Define the directory for writing reports: REPORTS_DIR ?= $(ROOT_DIR)/reports # Define the root directory for storing temporary files: TMP_DIR ?= $(ROOT_DIR)/tmp # Define the root configuration directory: CONFIG_DIR ?= $(ROOT_DIR)/etc # Define the root directory for documentation: DOCS_DIR ?= $(ROOT_DIR)/docs # Define the directory for public WWW assets: WWW_DIR ?= $(ROOT_DIR)/public # Define the top-level directory containing executables: LOCAL_BIN_DIR ?= $(ROOT_DIR)/bin # Define the top-level directory containing node module dependencies: NODE_MODULES ?= $(ROOT_DIR)/node_modules # Define the top-level directory containing node module executables: BIN_DIR ?= $(NODE_MODULES)/.bin # Define the folder name convention for executables: BIN_FOLDER ?= bin # Define the folder name convention for documentation files: DOCUMENTATION_FOLDER ?= docs # Define the folder name convention for configuration files: CONFIG_FOLDER ?= etc # Define the folder name convention for build artifacts: BUILD_FOLDER ?= build # Define the folder name convention for temporary files: TMP_FOLDER ?= tmp # Define filename extension conventions (keep in alphabetical order): CSS_FILENAME_EXT ?= css HTML_FILENAME_EXT ?= html # Define Node paths: (WARNING: we cannot use an absolute path here because of Webpack which only allows relative paths) NODE_PATH ?= ./node_modules/@stdlib/stdlib/lib/node_modules # DEPENDENCIES # include $(TOOLS_MAKE_DIR)/Makefile
{ "content_hash": "3e8e86ffe1fedecdc616249543d1f89f", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 119, "avg_line_length": 29.78082191780822, "alnum_prop": 0.7410303587856486, "repo_name": "stdlib-js/www", "id": "d6340f555a5fb1567c2e508ff5fea3e36b4c0665", "size": "2832", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Makefile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "190538" }, { "name": "HTML", "bytes": "158086013" }, { "name": "Io", "bytes": "14873" }, { "name": "JavaScript", "bytes": "5395746994" }, { "name": "Makefile", "bytes": "40479" }, { "name": "Shell", "bytes": "9744" } ] }
@interface MSTFirstMenuMapViewController () @end @implementation MSTFirstMenuMapViewController - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. [self loadDefaultView:@""]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
{ "content_hash": "53a4783273c0b5cf860c94f995edabb2", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 80, "avg_line_length": 19.866666666666667, "alnum_prop": 0.7164429530201343, "repo_name": "rajkumarpaneerselvam/MenuPOC", "id": "794a4a416d091361f973fcd2648907f8c1cc8f4d", "size": "806", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ParallaxController/ParallaxController/MenuPOC/MenuItemsViewControllers/MSTFirstMenuMapViewController.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "159420" } ] }
using System; using System.ComponentModel; namespace Azure.AI.Personalizer { /// <summary> The status of the job processing the evaluation. </summary> public readonly partial struct PersonalizerEvaluationJobStatus : IEquatable<PersonalizerEvaluationJobStatus> { private readonly string _value; /// <summary> Initializes a new instance of <see cref="PersonalizerEvaluationJobStatus"/>. </summary> /// <exception cref="ArgumentNullException"> <paramref name="value"/> is null. </exception> public PersonalizerEvaluationJobStatus(string value) { _value = value ?? throw new ArgumentNullException(nameof(value)); } private const string CompletedValue = "completed"; private const string PendingValue = "pending"; private const string FailedValue = "failed"; private const string NotSubmittedValue = "notSubmitted"; private const string TimeoutValue = "timeout"; private const string OptimalPolicyAppliedValue = "optimalPolicyApplied"; private const string OnlinePolicyRetainedValue = "onlinePolicyRetained"; /// <summary> completed. </summary> public static PersonalizerEvaluationJobStatus Completed { get; } = new PersonalizerEvaluationJobStatus(CompletedValue); /// <summary> pending. </summary> public static PersonalizerEvaluationJobStatus Pending { get; } = new PersonalizerEvaluationJobStatus(PendingValue); /// <summary> failed. </summary> public static PersonalizerEvaluationJobStatus Failed { get; } = new PersonalizerEvaluationJobStatus(FailedValue); /// <summary> notSubmitted. </summary> public static PersonalizerEvaluationJobStatus NotSubmitted { get; } = new PersonalizerEvaluationJobStatus(NotSubmittedValue); /// <summary> timeout. </summary> public static PersonalizerEvaluationJobStatus Timeout { get; } = new PersonalizerEvaluationJobStatus(TimeoutValue); /// <summary> optimalPolicyApplied. </summary> public static PersonalizerEvaluationJobStatus OptimalPolicyApplied { get; } = new PersonalizerEvaluationJobStatus(OptimalPolicyAppliedValue); /// <summary> onlinePolicyRetained. </summary> public static PersonalizerEvaluationJobStatus OnlinePolicyRetained { get; } = new PersonalizerEvaluationJobStatus(OnlinePolicyRetainedValue); /// <summary> Determines if two <see cref="PersonalizerEvaluationJobStatus"/> values are the same. </summary> public static bool operator ==(PersonalizerEvaluationJobStatus left, PersonalizerEvaluationJobStatus right) => left.Equals(right); /// <summary> Determines if two <see cref="PersonalizerEvaluationJobStatus"/> values are not the same. </summary> public static bool operator !=(PersonalizerEvaluationJobStatus left, PersonalizerEvaluationJobStatus right) => !left.Equals(right); /// <summary> Converts a string to a <see cref="PersonalizerEvaluationJobStatus"/>. </summary> public static implicit operator PersonalizerEvaluationJobStatus(string value) => new PersonalizerEvaluationJobStatus(value); /// <inheritdoc /> [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is PersonalizerEvaluationJobStatus other && Equals(other); /// <inheritdoc /> public bool Equals(PersonalizerEvaluationJobStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); /// <inheritdoc /> [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode() ?? 0; /// <inheritdoc /> public override string ToString() => _value; } }
{ "content_hash": "0ccd44e0b31042378a6a5c32192719cb", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 150, "avg_line_length": 63.83050847457627, "alnum_prop": 0.7209240573552841, "repo_name": "Azure/azure-sdk-for-net", "id": "389201f0f3dd560ebe292871b33c0db148f3308b", "size": "3904", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "sdk/personalizer/Azure.AI.Personalizer/src/Generated/Models/PersonalizerEvaluationJobStatus.cs", "mode": "33188", "license": "mit", "language": [] }
import bisect import math import os import operator import random import six import sys import yaml from collections import defaultdict from marisa_trie import BytesTrie from geodata.text.phrases import PhraseFilter from geodata.encoding import safe_encode, safe_decode from geodata.i18n.unicode_paths import DATA_DIR from geodata.numbers.numex import NUMEX_DATA_DIR class OrdinalSuffixTrie(PhraseFilter): def __init__(self, ordinal_rules): self.trie = BytesTrie([(safe_decode(k)[::-1], safe_decode('|').join(v).encode('utf-8')) for k, v in six.iteritems(ordinal_rules)]) self.configured = True def search_substring(self, s): if len(s) == 0: return None, 0 for i in xrange(len(s) + 1): if not self.trie.has_keys_with_prefix(s[:i]): i -= 1 break if i > 0: return (self.trie.get(s[:i]), i) else: return None, 0 def search_suffix(self, token): suffix_search, suffix_len = self.search_substring(safe_decode(token[::-1])) if suffix_search: return suffix_search[0].split('|') else: return None class OrdinalExpressions(object): def __init__(self, base_dir=NUMEX_DATA_DIR): self.cardinal_rules = {} self.cardinal_rules_ones = {} self.ordinal_rules = {} self.ordinal_suffix_rules = {} for filename in os.listdir(base_dir): if filename.endswith('.yaml'): lang = filename.split('.yaml')[0] f = open(os.path.join(base_dir, filename)) data = yaml.load(f) rules = data.get('rules') if rules is not None and hasattr(rules, '__getslice__'): cardinals = [] ordinals = defaultdict(list) for rule in rules: name = rule.get('name') value = rule.get('value') rule_type = rule.get('type') if not name or type(value) not in (int, float) or rule_type not in ('cardinal', 'ordinal'): continue gender = rule.get('gender', None) category = rule.get('category', None) if rule_type == 'ordinal': ordinals[(value, gender, category)].append(name) else: cardinals.append(rule) if value == 1: self.cardinal_rules_ones[(lang, gender, category)] = name self.cardinal_rules[lang] = cardinals self.ordinal_rules[lang] = ordinals ordinal_indicators = data.get('ordinal_indicators') if ordinal_indicators is not None and hasattr(ordinal_indicators, '__getslice__'): for rule_set in ordinal_indicators: gender = rule_set.get('gender', None) category = rule_set.get('category', None) self.ordinal_suffix_rules[(lang, gender, category)] = OrdinalSuffixTrie(rule_set['suffixes']) def get_suffixes(self, num, lang, gender=None, category=None): trie = self.ordinal_suffix_rules.get((lang, gender, category)) if not trie: return None return trie.search_suffix(str(num)) def get_suffix(self, num, lang, gender=None, category=None): suffixes = self.get_suffixes(num, lang, gender=gender, category=category) if not suffixes: return None return random.choice(suffixes) def suffixed_number(self, num, lang, gender=None, category=None): suffix = self.get_suffix(num, lang, gender=gender, category=category) if not suffix: return None return six.u('{}{}').format(safe_decode(num), safe_decode(suffix)) ordinal_expressions = OrdinalExpressions()
{ "content_hash": "9d38774ddb342ea6ab42bf5c42eaf2bb", "timestamp": "", "source": "github", "line_count": 108, "max_line_length": 138, "avg_line_length": 37.19444444444444, "alnum_prop": 0.5501618122977346, "repo_name": "openvenues/libpostal", "id": "5be6ebf23c2225f5906e8e303e437a79ec510a61", "size": "4017", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "scripts/geodata/numbers/ordinals.py", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "39379640" }, { "name": "C++", "bytes": "78873" }, { "name": "M4", "bytes": "14888" }, { "name": "Makefile", "bytes": "7817" }, { "name": "Python", "bytes": "799608" }, { "name": "Shell", "bytes": "32951" } ] }
import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core'; import { LanguageDto, Query, QueryModel, StatusInfo } from '@app/shared/internal'; @Component({ selector: 'sqx-query[language][languages][model][statuses]', styleUrls: ['./query.component.scss'], templateUrl: './query.component.html', changeDetection: ChangeDetectionStrategy.OnPush, }) export class QueryComponent { @Output() public queryChange = new EventEmitter<Query>(); @Input() public language!: LanguageDto; @Input() public languages!: ReadonlyArray<LanguageDto>; @Input() public statuses?: ReadonlyArray<StatusInfo> | null; @Input() public model!: QueryModel; @Input() public set query(query: Query | undefined | null) { if (!query) { query = {}; } if (!query.filter) { query.filter = { and: [] }; } if (!query.sort) { query.sort = []; } this.queryValue = query; } public queryValue: Query = {}; public addSorting() { const path = Object.keys(this.model.schema.fields)[0]; if (this.queryValue.sort) { this.queryValue.sort.push({ path, order: 'ascending' }); } this.emitQueryChange(); } public removeSorting(index: number) { if (this.queryValue.sort) { this.queryValue.sort.splice(index, 1); } this.emitQueryChange(); } public emitQueryChange() { this.queryChange.emit(this.queryValue); } }
{ "content_hash": "b6299341c6ea9417fc013a8e159a0324", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 96, "avg_line_length": 23.36764705882353, "alnum_prop": 0.5903083700440529, "repo_name": "Squidex/squidex", "id": "72fe0ffb88b909df041126fd34ffa29f3c81bfec", "size": "1706", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "frontend/src/app/shared/components/search/queries/query.component.ts", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "598" }, { "name": "C#", "bytes": "6497411" }, { "name": "CSS", "bytes": "11107" }, { "name": "Dockerfile", "bytes": "2599" }, { "name": "HTML", "bytes": "829638" }, { "name": "JavaScript", "bytes": "32540" }, { "name": "Mustache", "bytes": "4810" }, { "name": "PowerShell", "bytes": "5434" }, { "name": "SCSS", "bytes": "158966" }, { "name": "Shell", "bytes": "1663" }, { "name": "TypeScript", "bytes": "2124543" } ] }
<md-content layout-padding> <div layout="row"> <div layout="column"> <gravatar name="{{ player.firstName }}" email-hash="{{ player.emailHash }}" size="128"></gravatar> </div> <div layout="column" flex> <md-input-container> <label>Email</label> <input type="email" ng-model="player.email"> </md-input-container> <div layout="row"> <md-input-container> <label>First Name</label> <input ng-model="player.firstName"> </md-input-container> <md-input-container> <label>Last Name</label> <input ng-model="player.lastName"> </md-input-container> </div> </div> </div> <md-subheader>Notifications</md-subheader> <md-switch>Activate text messaging</md-switch> <div layout="row"> <md-input-container> <label>Mobile Phone</label> <input type="tel" ng-model="player.phone"> </md-input-container> <md-select placeholder="Carrier" ng-model="player.carrier"> <md-option value="vzw">Verizon</md-option> <md-option value="att">AT&amp;T</md-option> <md-option value="spr">Sprint</md-option> <md-option value="tmo">T-Mobile</md-option> </md-select> <md-input-container> <label>Confirmation Code</label> <input ng-model="confirmCode"> </md-input-container> </div> <md-list> <md-list-item> <md-switch ng-model="notifications.challenges">Challenges</md-switch> </md-list-item> <md-list-item> <md-switch ng-model="notifications.tournaments">Tournaments</md-switch> </md-list-item> </md-list> <md-subheader>Change Password</md-subheader> <md-content layout-padding> <md-input-container> <label>Old Password</label> <input type="password" ng-model="oldPassword"> </md-input-container> <md-input-container> <label>New Password</label> <input type="password" ng-model="newPassword"> </md-input-container> </md-content> </md-content>
{ "content_hash": "1c9d4c5d680a644a9be2aacf5a547bf4", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 104, "avg_line_length": 33.333333333333336, "alnum_prop": 0.618, "repo_name": "rallyphp/rally", "id": "8fdd71477bbcc79fd7be427e7759f064a180ed8b", "size": "2000", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/partials/settings.html", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "52" }, { "name": "CSS", "bytes": "4534" }, { "name": "HTML", "bytes": "10751" }, { "name": "JavaScript", "bytes": "14489" }, { "name": "PHP", "bytes": "45326" } ] }
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('ingest', '0011_auto_20170302_2130'), ] operations = [ migrations.AddField( model_name='scan', name='file_count', field=models.BigIntegerField(null=True, blank=True), preserve_default=True, ), ]
{ "content_hash": "1652a5f0f85ff57b0339d6a080a8c03b", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 64, "avg_line_length": 22.42105263157895, "alnum_prop": 0.5915492957746479, "repo_name": "ngageoint/scale", "id": "48c8726f0c64db50d0bc090e6352c97ceb6e0cf4", "size": "450", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "scale/ingest/migrations/0012_scan_file_count.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "7219" }, { "name": "CSS", "bytes": "12193" }, { "name": "Dockerfile", "bytes": "14853" }, { "name": "HCL", "bytes": "301" }, { "name": "HTML", "bytes": "48818" }, { "name": "JavaScript", "bytes": "503" }, { "name": "Makefile", "bytes": "5852" }, { "name": "Python", "bytes": "5295677" }, { "name": "Shell", "bytes": "26650" } ] }
var cx = document.querySelector("canvas").getContext("2d"); var total = results.reduce(function(sum, choice) { return sum + choice.count; }, 0); var currentAngle = -0.5 * Math.PI; var centerX = 300, centerY = 150; // Add code to draw the slice labels in this loop. // Your code here results.forEach(function(result) { var sliceAngle = (result.count / total) * 2 * Math.PI; cx.beginPath(); cx.arc(centerX, centerY, 100, currentAngle, currentAngle + sliceAngle); currentAngle += sliceAngle; cx.lineTo(centerX, centerY); cx.fillStyle = result.color; cx.fill(); });
{ "content_hash": "d576dd4d1c362c1e01e1abc20eb6a2f5", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 75, "avg_line_length": 29.8, "alnum_prop": 0.6728187919463087, "repo_name": "nesterone/sf-eng-init-fellow", "id": "4de50185e5b881250761f1ab80d7246915f87b52", "size": "596", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "02-browser/03-drawing-on-canvas/02-the-pie-chart/pieChart.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1130" }, { "name": "HTML", "bytes": "14589" }, { "name": "JavaScript", "bytes": "48453" } ] }
================= Example: WASP 14 ================= Preamble ============================= This example replicates the WASP14 results from Czekala et al. 2015. It's probably a good test to perform before you blindly run the code on any of your data. All of the data to replicate this result are already a part of the repository, so you don't have to worry about any data munging. This example assumes you have already: 1. Downloaded the synthetic spectral libraries. 2. Added the Starfish scripts directory to your `$PATH`. 3. Read the docs 4. Read the paper 5. Read the license 6. Installed the dependencies If you've done everything in the Preamble correctly, you should be able to run this command (*n.b.* input is demarcated by the $ symbol) and see the output below it. .. code-block:: bash $ star.py --help usage: parallel.py [-h] [-r RUN_INDEX] [--generate] [--initPhi] [--optimize {Theta,Phi,Cheb}] [--sample {ThetaCheb,ThetaPhi,ThetaPhiLines}] [--samples SAMPLES] Run Starfish fitting model in parallel. If not, go back and make sure your **$PATH** is set up correctly. Just getting set up. ============================= Before you run any code, you have to get your environment set up. 1. Copy the `config.yaml` that came with the Starfish repo to some directory. Then make empty directories for the data, libraries, output, and plots. .. code-block:: bash $ ls config.yaml data libraries output plots With your text editor of choice, you will have to change or mimic the directory structure in the config.yaml file: 1. **name** from "default" to "example_wasp14" for this demo. 2. Mimic the structure of **files** by placing your `.hdf5` data there. 3. Hardcode the raw library location in **raw_path**. .. code-block:: rst :emphasize-lines: 3, 7, 20 # YAML configuration script name: example_wasp14 data: grid_name: "PHOENIX" files: ["data/WASP14/WASP14-2009-06-14.hdf5"] # data/WASP14/WASP14-2010-03-29.hdf5 # data/WASP14/WASP14-2010-04-24.hdf5 instruments : ["TRES"] orders: [22] #orders: [20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36] outdir : output/ plotdir : plots/ # The parameters defining your raw spectral library live here. grid: raw_path: "/Users/gully/GitHub/Starfish/libraries/raw/PHOENIX/" hdf5_path: "libraries/PHOENIX_TRES_test.hdf5" After doing all that, we can automatically generate the assumed directory and file structure with the following command. This strategy is necessary when you have many tens or hundreds of orders. .. code-block:: bash $ star.py --run_index 1 Creating output/example_wasp14/run01/ Creating output/example_wasp14/run01/s0_o22 Generating the eigenspectra and their weights ============================================== The process of spectral emulation is the main topic of the Appendix of Czekala et al. 2015. It gets pretty complicated, but the main idea is using a type of regression to fit the :math:`m` eigenspectra weights as a function of say 3 stellar parameters :math:`\theta_{*}`. This regression process takes a lot of computational power, and **scales very poorly** with the size of the parameter range. So in practice, we have to pick a small range of the grid, **parrange**, surrounding our guess of :math:`\theta_{*}`. Then, we will want to make the PCA grid, and do many other things regarding optimization and final plotting. These are all done through the `pca.py` script. .. code-block:: python # create the grid using settings in config.yaml pca.py --create # Note, need to create a "plots" directory locally. # Plot all of the eigenspectra and the histogram of weights pca.py --plot=eigenspectra # reconstruct the grid at the synthetic grid points, plotting the difference pca.py --plot=reconstruct # Specify and examine priors stored in config.yaml pca.py --plot=priors # Optimize the emulator using fmin pca.py --optimize=fmin # Optimize the emulator starting from previous parameter estimates pca.py --optimize=fmin --resume # OR optimize using emcee # default samples = 100 pca.py --optimize=emcee --samples=100 pca.py --optimize=emcee --resume # Make a triangle plot of the emcee output pca.py --plot=emcee # Make some plots showing weight interpolations using the emulator pca.py --plot=emulator --params=fmin # OR pca.py --plot=emulator --params=emcee # Once you've OK'd the parameters, then store them to the HDF5 file pca.py --store --params=fmin # OR pca.py --store --params=emcee After doing some more analysis, we'll want to make a bunch of plots showing the scatter of interpolated spectra against what the gridpoint spectrum looks like. Now that you've optimized the emulator for the specific spectrum you'd like to fit, we can use a series of tools to fit the spectrum. Further customization will require writing your own python scripts. These codes are much simpler and just output everything to the local directory. Optimize the grid and observational parameters (:math:`\Theta`) .. code-block:: python star.py --optimize=Theta star.py --optimize=Cheb This script will leave you with a single JSON file which specifies the Theta parameters. The fit might be OK, but is probably not the best you can do, especially since we haven't allowed any flexibility in the Chebyshev paramteters that take care of calibration uncertainties. Hopefully, however, your estimates of radial velocity, Omega, and vsini are in the ballpark of what you might expect. To check that this is the case, it would be a great idea to generate model spectra and plot them to examine the residuals of the fit. .. code-block:: python # Write out model, data, residuals for each order in the CWD star.py --generate Now we can plot these files using our plotting programs. .. code-block:: python splot.py s0_o23_spec.json --matplotlib splot.py --D3 star.py --sample=Theta Optimize the noise parameters (:math:`\Phi`) .. code-block:: python star.py --optimize=Phi Starting values for the nuisance parameters (:math:`\Phi`) are read from `*phi.json` files located in the current working directory. If you don't feel like optimizing the Chebyshev polynomials first, then to generate a set of these files for default values read from your config file, run .. code-block:: python star.py --initPhi Note that this will overwrite any of your current `*phi.json` files in the current working directory. If you previously optimized the Cheb parameters, you may want to borrow these values and use them here. On all subsquent runs, the starting values are taken from these. So, if you are doing many iterative runs where you by now have a good estimate of the final parameter values, it might be worthwhile to use a text editor to go and edit `s0_o22phi.json` and associated files by hand to these values, in order to speed convergence. Sample in the Theta and Chebyhev parameters at the same time. .. code-block:: python star.py --sample=ThetaCheb --samples=100 Sample in the Theta, Chebyshev, and global covariance parameters at the same time. .. code-block:: python star.py --sample=ThetaPhi --samples=5 In actuality you will probably want something like `--samples=5000` or more to get a statistical exploration of the space, but before waiting for a long run to finish it would be good to check that the machinery worked for a small run first. Then, you can use the `chain.py` tool to examine and plot the parameter estimates. First, navigate to the directory that has the samples. Generally this will be something like `output/WASP14/run01` or whatever you have specified in your `config.yaml`. Then, use the tool to examine the Markov Chain .. code-block:: python chain.py --files mc.hdf5 --chain Once you have a reasonable guess at the parameters, update your `config.yaml` file and `*phi.json` files to these best-fit parameters. Then, you'll want to create a new residual spectrum .. code-block:: python star.py --generate Then, we can use this residual spectrum to search for and instantiate the regions for a given order. The JSON file includes the model, data, and residual. .. code-block:: python regions.py s0_o23spec.json --sigma=3 --sigma0=2 This will create a file called something like `s0_o23regions.json`, which contains a list of the centroids of each of these lines. Then, go through and optimize the regions in this list. This will attempt to optimize the line kernels in the list. .. code-block:: python regions_optimize.py --sigma0=2. s0_o23spec.json After a run, if you want to plot everything .. code-block:: python chain_run.py --chain or .. code-block:: python chain_run.py -t If you want to use the last values for the new run (just for nuisances), from within the CWD. .. code-block:: python set_params.py output/WASP14/run02/ Using the linear interpolator ============================= As a backup option to the spectral emulator, we also included an :math:`N`-dimensional linear interpolator, where :math:`N` is the number of dimensions in your synthetic library. Note that unlike the emulator, this interpolator requires that you have a grid with rectilinear spacings in paramaters. Begin by creating a local working directory and copying `config.yaml` to this directory and modify the settings as you wish. Then begin the same way .. code-block:: python # Downsample the grid grid.py create Now, instead of decomposing the library into eigenspectra and then tuning the emulator, we can hook the linear interpolator directly up to the modified grid. Beware, however, that a significant amount of error in the spectra fit is introduced by a poor linear interpolation. If you are fitting moderate to high S/N spectra, we recomend that you stick with the emulator approach for final work. We have replicated the same functionality in `star.py` in a separate script, `star_linear.py`.
{ "content_hash": "bff0a9c2b90d2d6bb42679543cb39e8d", "timestamp": "", "source": "github", "line_count": 262, "max_line_length": 528, "avg_line_length": 39.038167938931295, "alnum_prop": 0.7178333985138835, "repo_name": "gully/Starfish", "id": "91d79efeb12fc266cc201e0c8668427c7a623860", "size": "10228", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/example_wasp14.rst", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "3946035" }, { "name": "Jupyter Notebook", "bytes": "3930783" }, { "name": "Python", "bytes": "378460" }, { "name": "Shell", "bytes": "6095" } ] }
class TableModel; namespace Ilwis { namespace Desktop { class SortColumn : public TableOperation { Q_OBJECT public: SortColumn(); bool canUse(TableModel *tblModel, const QVariantMap &parameter) const; Q_INVOKABLE void execute(const QVariantMap &parameters); static Ilwis::Desktop::TableOperation *create(); }; } } #endif // SORTCOLUMN_H
{ "content_hash": "503a04633472efad9333ee9140038e5e", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 74, "avg_line_length": 18.1, "alnum_prop": 0.7237569060773481, "repo_name": "ridoo/IlwisCore", "id": "a408909caf5e38ad77af0b9ef44bcacbc4757e1e", "size": "477", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ilwiscoreui/tableoperations/sortcolumn.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "141" }, { "name": "C", "bytes": "431263" }, { "name": "C++", "bytes": "3891484" }, { "name": "CSS", "bytes": "26076" }, { "name": "GAP", "bytes": "13857" }, { "name": "GLSL", "bytes": "1100" }, { "name": "HTML", "bytes": "10047427" }, { "name": "JavaScript", "bytes": "137978" }, { "name": "NSIS", "bytes": "13173" }, { "name": "Prolog", "bytes": "529" }, { "name": "Python", "bytes": "843" }, { "name": "QML", "bytes": "448081" }, { "name": "QMake", "bytes": "64945" }, { "name": "Scilab", "bytes": "173" } ] }
PERSON_GROUPS = ( ('diploma', 'Diploma/PG Diploma'), ('students', 'Workshop Students'), ('staff', 'Staff'), ('others', 'Others'), )
{ "content_hash": "c0db90b2d310708f2c83fb14519a8957", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 36, "avg_line_length": 23.333333333333332, "alnum_prop": 0.5785714285714286, "repo_name": "jagannath93/File-Management-System", "id": "e66c848c76101af0861a3385bb2c3b075ba8f8f0", "size": "140", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "fms/constants.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "115553" }, { "name": "JavaScript", "bytes": "28688" }, { "name": "Python", "bytes": "55125" } ] }
package de.hpi.visio.util; import java.util.Comparator; import org.oryxeditor.server.diagram.Shape; /** * Comparator for imported visio shapes that will be compared by the lower right * point's y value. The shape with the lowest value will be first in a sorted * list. * * @author Thamsen */ public class ShapesLowerRightYComparator implements Comparator<Shape> { @Override public int compare(Shape o1, Shape o2) { if (o1 == null) { if (o2 == null) { return 0; } else { return 1; } } else if (o2 == null) { return -1; } if (o1.getLowerRight() == null) { if (o2.getLowerRight() == null) { return 0; } else { return 1; } } else if (o2.getLowerRight() == null) { return -1; } if (o1.getLowerRight().getY() == null) { if (o2.getLowerRight().getY() == null) { return 0; } else { return 1; } } else if (o2.getLowerRight().getY() == null) { return -1; } return o1.getLowerRight().getY().compareTo(o2.getLowerRight().getY()); } }
{ "content_hash": "a2318efe307f3540ea5db83a068c72f6", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 80, "avg_line_length": 21.1875, "alnum_prop": 0.6145526057030481, "repo_name": "grasscrm/gdesigner", "id": "2985f0061d773d15928e4297bf597699c7a07890", "size": "1017", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "editor/server/src/de/hpi/visio/util/ShapesLowerRightYComparator.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "92" }, { "name": "CSS", "bytes": "443648" }, { "name": "Java", "bytes": "5464138" }, { "name": "JavaScript", "bytes": "7473190" }, { "name": "PHP", "bytes": "5127" }, { "name": "Python", "bytes": "1965" }, { "name": "Ruby", "bytes": "47049" }, { "name": "Shell", "bytes": "4096" }, { "name": "Visual Basic", "bytes": "1671" }, { "name": "XSLT", "bytes": "488471" } ] }
using System.Xml; using System.Xml.Serialization; namespace ParatureSDK.ParaObjects { /// <summary> /// An attachment object holds the information about any attachment, whether in the ticket history, in the ticket itself, a download, or any other module that supports the attachments feature. /// </summary> public class Attachment { /// <summary> /// This is the unique identifier of the Attachment/Download file in your Parature license. /// </summary> [XmlElement("Guid")] public string Guid; /// <summary> /// The name of the attachment. /// </summary> [XmlElement("Name")] public string Name; /// <summary> /// This is the public permanent URL /// </summary> [XmlAttribute("href")] public string Href; [XmlAttribute("secure-service-desk-url")] public string SecureServiceDeskUrl; [XmlAttribute("secure-portal-url")] public string SecurePortalUrl; /// <summary> /// The details of the error message, if the call generated an exception. /// </summary> public string Error; /// <summary> /// Whether or not there was an exception. /// </summary> public bool HasException; public Attachment() { } public Attachment(Attachment attachment) { Guid = attachment.Guid; Name = attachment.Name; Error = attachment.Error; HasException = attachment.HasException; Href = attachment.Href; SecurePortalUrl = attachment.SecurePortalUrl; SecureServiceDeskUrl = attachment.SecureServiceDeskUrl; } } }
{ "content_hash": "c06a09453b4113f0cd2bb30757c4ae34", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 196, "avg_line_length": 30.43103448275862, "alnum_prop": 0.5892351274787535, "repo_name": "Parature/ParatureSDK", "id": "ed108970ae775f2158d2770b8118d9848944ca30", "size": "1765", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ParatureSDK/ParaObjects/Attachment.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "432796" }, { "name": "Smalltalk", "bytes": "69786" } ] }
/** * Create a checkerboard tQuery.Mesh */ tQuery.register('createCheckerboard', function(opts){ // handle parameters opts = tQuery.extend(opts, { width : 1, height : 1, segmentsW : 8, segmentsH : 8, materialEven : new THREE.MeshBasicMaterial({ color: 0xcccccc }), materialOdd : new THREE.MeshBasicMaterial({ color: 0x444444 }) }); // create the geometry var geometry = new THREE.PlaneGeometry( opts.width, opts.height, opts.segmentsW, opts.segmentsH ); // set materials per faces geometry.materials = [opts.materialEven, opts.materialOdd]; geometry.faces.forEach(function(face, idx){ var y = Math.floor(idx / opts.segmentsW); var x = idx - (y*opts.segmentsW); face.materialIndex = (y % 2 + x%2 ) %2; }); // create the mesh var material = new THREE.MeshFaceMaterial(); var mesh = new THREE.Mesh(geometry, material); // put it horizontal by default mesh.rotation.x = -Math.PI/2 // return the tQuery return tQuery(mesh); });
{ "content_hash": "58d2da350a672028d0f352ea1b912152", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 100, "avg_line_length": 32.1, "alnum_prop": 0.6936656282450675, "repo_name": "jeromeetienne/augmentedgesture.js", "id": "fb98a6b8db9f44b5d5e763b25cd2fcbd0a617abb", "size": "963", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "examples/punchquake2character/examples/vendor/tquery.checkerboard.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "322530" } ] }
#ifndef WEBRTC_P2P_BASE_PORTINTERFACE_H_ #define WEBRTC_P2P_BASE_PORTINTERFACE_H_ #include <string> #include "webrtc/p2p/base/transport.h" #include "webrtc/base/asyncpacketsocket.h" #include "webrtc/base/socketaddress.h" namespace rtc { class Network; struct PacketOptions; } namespace cricket { class Connection; class IceMessage; class StunMessage; enum ProtocolType { PROTO_UDP, PROTO_TCP, PROTO_SSLTCP, PROTO_LAST = PROTO_SSLTCP }; // Defines the interface for a port, which represents a local communication // mechanism that can be used to create connections to similar mechanisms of // the other client. Various types of ports will implement this interface. class PortInterface { public: virtual ~PortInterface() {} virtual const std::string& Type() const = 0; virtual rtc::Network* Network() const = 0; // Methods to set/get ICE role and tiebreaker values. virtual void SetIceRole(IceRole role) = 0; virtual IceRole GetIceRole() const = 0; virtual void SetIceTiebreaker(uint64_t tiebreaker) = 0; virtual uint64_t IceTiebreaker() const = 0; virtual bool SharedSocket() const = 0; virtual bool SupportsProtocol(const std::string& protocol) const = 0; // PrepareAddress will attempt to get an address for this port that other // clients can send to. It may take some time before the address is ready. // Once it is ready, we will send SignalAddressReady. If errors are // preventing the port from getting an address, it may send // SignalAddressError. virtual void PrepareAddress() = 0; // Returns the connection to the given address or NULL if none exists. virtual Connection* GetConnection( const rtc::SocketAddress& remote_addr) = 0; // Creates a new connection to the given address. enum CandidateOrigin { ORIGIN_THIS_PORT, ORIGIN_OTHER_PORT, ORIGIN_MESSAGE }; virtual Connection* CreateConnection( const Candidate& remote_candidate, CandidateOrigin origin) = 0; // Functions on the underlying socket(s). virtual int SetOption(rtc::Socket::Option opt, int value) = 0; virtual int GetOption(rtc::Socket::Option opt, int* value) = 0; virtual int GetError() = 0; virtual ProtocolType GetProtocol() const = 0; virtual const std::vector<Candidate>& Candidates() const = 0; // Sends the given packet to the given address, provided that the address is // that of a connection or an address that has sent to us already. virtual int SendTo(const void* data, size_t size, const rtc::SocketAddress& addr, const rtc::PacketOptions& options, bool payload) = 0; // Indicates that we received a successful STUN binding request from an // address that doesn't correspond to any current connection. To turn this // into a real connection, call CreateConnection. sigslot::signal6<PortInterface*, const rtc::SocketAddress&, ProtocolType, IceMessage*, const std::string&, bool> SignalUnknownAddress; // Sends a response message (normal or error) to the given request. One of // these methods should be called as a response to SignalUnknownAddress. // NOTE: You MUST call CreateConnection BEFORE SendBindingResponse. virtual void SendBindingResponse(StunMessage* request, const rtc::SocketAddress& addr) = 0; virtual void SendBindingErrorResponse( StunMessage* request, const rtc::SocketAddress& addr, int error_code, const std::string& reason) = 0; // Signaled when this port decides to delete itself because it no longer has // any usefulness. sigslot::signal1<PortInterface*> SignalDestroyed; // Signaled when Port discovers ice role conflict with the peer. sigslot::signal1<PortInterface*> SignalRoleConflict; // Normally, packets arrive through a connection (or they result signaling of // unknown address). Calling this method turns off delivery of packets // through their respective connection and instead delivers every packet // through this port. virtual void EnablePortPackets() = 0; sigslot::signal4<PortInterface*, const char*, size_t, const rtc::SocketAddress&> SignalReadPacket; // Emitted each time a packet is sent on this port. sigslot::signal1<const rtc::SentPacket&> SignalSentPacket; virtual std::string ToString() const = 0; protected: PortInterface() {} }; } // namespace cricket #endif // WEBRTC_P2P_BASE_PORTINTERFACE_H_
{ "content_hash": "319b56e9d286600b6b5de83c4f398a1a", "timestamp": "", "source": "github", "line_count": 123, "max_line_length": 79, "avg_line_length": 36.15447154471545, "alnum_prop": 0.7216100742073308, "repo_name": "ssaroha/node-webrtc", "id": "38945f9e1305fb68a05287baacb4cda507aba477", "size": "4855", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "third_party/webrtc/include/webrtc/p2p/base/portinterface.h", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Batchfile", "bytes": "6179" }, { "name": "C", "bytes": "2679" }, { "name": "C++", "bytes": "54327" }, { "name": "HTML", "bytes": "434" }, { "name": "JavaScript", "bytes": "42707" }, { "name": "Python", "bytes": "3835" } ] }
class ShapeTextureSample; typedef std::shared_ptr<ShapeTextureSample> ShapeTextureSampleRef; class ShapeTextureSample : public po::scene::NodeContainer { public: static ShapeTextureSampleRef create(); void setup(); protected: ShapeTextureSample(); private: po::scene::ShapeRef mRectShape; // rectangle for reference po::scene::ShapeRef mEllipseShape; // ellipse that will have texture po::scene::ShapeRef mTriangleShape; // custom cinder shape ci::gl::TextureRef mTexture; // cinder texture // Container to hold the indicators NodeContainerRef mFitIndicatorContainer; NodeContainerRef mAlignIndicatorContainer; // TextureFit types mapped to indicators std::vector<std::string> mFitIndicatorNames; std::vector<std::string> mAlignIndicatorNames; std::map<std::string, IndicatorRef> mFitIndicators; std::map<std::string, IndicatorRef> mAlignIndicators; TextureFit::Type mCurrentFitType; Alignment mCurrentAlignment; void keyDown(ci::app::KeyEvent &event); void createFitIndicators(); void createAlignmentIndicators(); void activateFitIndicator(int num); void activateAlignmentIndicator(int num); };
{ "content_hash": "ff760d38536bea5e45db4a9bcbde3228", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 77, "avg_line_length": 32.357142857142854, "alnum_prop": 0.6563649742457689, "repo_name": "eriser/Cinder-poScene", "id": "f7c485d56e3d286a4687f98e49edf329f0a0b57e", "size": "1471", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "samples/ShapeTextureSample/src/ShapeTextureSample.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C++", "bytes": "147095" } ] }
import React, { Component } from 'react' import PropTypes from 'prop-types' import { StyleSheet, View, ListView } from 'react-native' import TodoItem from '../components/todo-item' class TodoList extends Component { constructor(props) { super(props) const ds = new ListView.DataSource({ rowHasChanged: this._rowHasChanged, }) this.state = { dataSource: ds.cloneWithRows(props.todos), } this._renderRow = this._renderRow.bind(this) } _rowHasChanged = (r1, r2) => r1 != r2 componentWillReceiveProps({ todos }) { const { todos: oldTodos } = this.props if (oldTodos !== todos) { const dataSource = this.state.dataSource.cloneWithRows([...todos]) this.setState({ dataSource }) } } _renderRow(rowId, todoData) { return ( <TodoItem todo={todoData} onToggleTodoCallback={this.props.onTodoToggleCallback} /> ) } render() { return ( <View style={styles.container}> <ListView dataSource={this.state.dataSource} renderRow={(rowData, sectionID, rowID, highlightRow) => this._renderRow(rowID, rowData)} /> </View> ) } } TodoList.propTypes = { todos: PropTypes.arrayOf( PropTypes.shape({ text: PropTypes.string.isRequired, id: PropTypes.number.isRequired, completed: PropTypes.bool.isRequired, }) ), onTodoToggleCallback: PropTypes.func.isRequired, } const styles = StyleSheet.create({ container: { // flex: 1, }, }) export default TodoList
{ "content_hash": "a7343ea6a807319dc938b55f59a04587", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 72, "avg_line_length": 21.680555555555557, "alnum_prop": 0.6278026905829597, "repo_name": "rameezk/ReactNativeTodo", "id": "6310bfa62276cc8064870eec3571b361ce324746", "size": "1561", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/components/todo-list.js", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "1338" }, { "name": "JavaScript", "bytes": "10441" }, { "name": "Objective-C", "bytes": "4432" }, { "name": "Python", "bytes": "1740" } ] }
using System; using System.Text.RegularExpressions; using dnlib.DotNet; namespace Confuser.Core.Project.Patterns { /// <summary> /// A function that match the full name of the definition with specified RegEx. /// </summary> public class MatchFunction : PatternFunction { internal const string FnName = "match"; /// <inheritdoc /> public override string Name { get { return FnName; } } /// <inheritdoc /> public override int ArgumentCount { get { return 1; } } /// <inheritdoc /> public override object Evaluate(IDnlibDef definition) { string regex = Arguments[0].Evaluate(definition).ToString(); return Regex.IsMatch(definition.FullName, regex); } } /// <summary> /// A function that match the name of the definition with specified RegEx. /// </summary> public class MatchNameFunction : PatternFunction { internal const string FnName = "match-name"; /// <inheritdoc /> public override string Name { get { return FnName; } } /// <inheritdoc /> public override int ArgumentCount { get { return 1; } } /// <inheritdoc /> public override object Evaluate(IDnlibDef definition) { string regex = Arguments[0].Evaluate(definition).ToString(); return Regex.IsMatch(definition.Name, regex); } } /// <summary> /// A function that match the name of declaring type with specified RegEx. /// </summary> public class MatchTypeNameFunction : PatternFunction { internal const string FnName = "match-type-name"; /// <inheritdoc /> public override string Name { get { return FnName; } } /// <inheritdoc /> public override int ArgumentCount { get { return 1; } } /// <inheritdoc /> public override object Evaluate(IDnlibDef definition) { if (definition is TypeDef) { string regex = Arguments[0].Evaluate(definition).ToString(); return Regex.IsMatch(definition.Name, regex); } if (definition is IMemberDef && ((IMemberDef)definition).DeclaringType != null) { string regex = Arguments[0].Evaluate(definition).ToString(); return Regex.IsMatch(((IMemberDef)definition).DeclaringType.Name, regex); } return false; } } }
{ "content_hash": "42607b2572305f88e5cd829046bfcd9d", "timestamp": "", "source": "github", "line_count": 87, "max_line_length": 84, "avg_line_length": 24.839080459770116, "alnum_prop": 0.6807033780657104, "repo_name": "dsuess/ConfuserEx", "id": "b9ba2bac01d3afddcfedb9854be95a739c8bfecc", "size": "2163", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Confuser.Core/Project/Patterns/MatchFunction.cs", "mode": "33188", "license": "mit", "language": [] }
import sensor, image, time, os, tf sensor.reset() # Reset and initialize the sensor. sensor.set_pixformat(sensor.RGB565) # Set pixel format to RGB565 (or GRAYSCALE) sensor.set_framesize(sensor.QVGA) # Set frame size to QVGA (320x240) sensor.set_windowing((240, 240)) # Set 240x240 window. sensor.skip_frames(time=2000) # Let the camera adjust. net = tf.load('<object_detection_network>', load_to_fb=True) labels = [] try: # Load labels if they exist labels = [line.rstrip('\n') for line in open("labels.txt")] except: pass colors = [ # Add more colors if you are detecting more than 7 types of classes at once. (255, 0, 0), ( 0, 255, 0), (255, 255, 0), ( 0, 0, 255), (255, 0, 255), ( 0, 255, 255), (255, 255, 255), ] clock = time.clock() while(True): clock.tick() img = sensor.snapshot() # detect() segments an object using the provided segmentation model. This produces mutliple # grayscale images per object class that we are trying to detect. detect() then runs # find_blobs() internally on the segmented images to find all blob locations and then returns # the bound boxes of all blobs found per object class. So, detect() returns a list of lists of # classification objects and the respective confidence level. for i, detection_list in enumerate(net.detect(img, thresholds=[(128, 255)])): if (i < len(labels)): print("********** %s **********" % labels[i]) for d in detection_list: print(d) img.draw_rectangle(d.rect(), color=colors[i]) print(clock.fps(), "fps", end="\n\n")
{ "content_hash": "b09db26fd16645c68f941de9d405b798", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 98, "avg_line_length": 36.41304347826087, "alnum_prop": 0.6214925373134328, "repo_name": "iabdalkader/openmv", "id": "48a2254ba9929224924c175cbaedcd2c0740dc30", "size": "1875", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "scripts/examples/Arduino/Portenta-H7/25-Machine-Learning/tf_object_detection.py", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "569030" }, { "name": "C", "bytes": "100413378" }, { "name": "C++", "bytes": "97780" }, { "name": "CMake", "bytes": "10173" }, { "name": "Dockerfile", "bytes": "874" }, { "name": "Makefile", "bytes": "72669" }, { "name": "Python", "bytes": "1197447" }, { "name": "Shell", "bytes": "3220" } ] }
// Copyright 2015 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Externs for external dirPagination module. * * @externs */ const paginationService = {}; /** * @param {string} instanceId * @param {number} val */ paginationService.setCurrentPage = function(instanceId, val) {};
{ "content_hash": "7834b7c94108c970ea9f9a4d356c8d46", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 75, "avg_line_length": 31.51851851851852, "alnum_prop": 0.7285546415981199, "repo_name": "danielromlein/dashboard", "id": "2b3b5fad26fe95f40fed20f28c5d0916ddedce84", "size": "851", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/externs/dirPagination.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "56783" }, { "name": "Go", "bytes": "795388" }, { "name": "HTML", "bytes": "424688" }, { "name": "JavaScript", "bytes": "1421777" }, { "name": "Shell", "bytes": "7062" }, { "name": "XSLT", "bytes": "1119" } ] }
[package-url]: https://www.npmjs.com/package/dialogue-builder [version-image]: https://badge.fury.io/js/dialogue-builder.svg [downloads-image]: https://img.shields.io/npm/dt/dialogue-builder.svg [ci-image]: https://circleci.com/gh/nbransby/dialogue-builder.svg?style=shield&circle-token=39554b5870ebd54924230c17c9e79751ee788e40 [ci-url]: https://circleci.com/gh/nbransby/dialogue-builder [coverage-image]:https://codecov.io/gh/nbransby/dialogue-builder/branch/master/graph/badge.svg [coverage-url]:https://codecov.io/gh/nbransby/dialogue-builder The goal of this library is to enable you to write bot dialogue in JavaScript or TypeScript. It utilizes template literals to enable you to write dialogue in a highly readable way, making it easier to review the dialogue at a glance, it currently has been designed to work with Facebook Messenger bots only. See [dialogue-builder-example](https://github.com/nbransby/dialogue-builder-example) for a working example. ```javascript exports.default = dialogue('Onboarding ', (name) => [ say `Hi ${name}, welcome to nosy bot!`, say `This inquisitive little bot will ask a bunch of questions for no reason`, say `It will log your answers pointlessly to the console`, say `You can always type back if you make mistake`, ask `How old are you?`, expect `My age is`, { [onText]: (text) => console.log(`${name}'s age is ${text}`) }, ask `What length is your hair?`, expect `My hair length is`, { 'Long': (text) => console.log(`${name}'s hair is ${text}`), 'Short': (text) => console.log(`${name}'s hair is ${text}`), 'Shaved': (text) => { console.log(`${name}'s hair is ${text}`); return goto `after_hair_colour`; }, }, ask `What colour is your hair?`, expect `My hair colour is`, { 'Black': (text) => console.log(`${name}'s hair colour is ${text}`), 'Brown': (text) => console.log(`${name}'s hair colour is ${text}`), 'Blonde': (text) => console.log(`${name}'s hair colour is ${text}`), }, 'after_hair_colour', ask `Where do you live?`, expect `I live at`, { [location]: (lat, long, title, url) => console.log(`User located at ${lat}, ${long}`) }, say `Thanks ${name}, have a nice day`, ]); ``` ## Installing ```shell npm install dialogue-builder ``` ## How it works If the example dialogue above was defined in a file called `onboarding.js` you would write the following to get your bot to follow it: ````javascript const botBuilder = require('claudia-bot-builder'); const { Dialogue } = require("dialogue-builder"); const onboarding = require('onboarding'); module.exports = botBuilder(function (message, apiRequest) { const dialogue = new Dialogue(onboarding, { store(state: Object) => console.log('Need to persist this somewhere') retrieve() => return Promise.resolve(new Object()) }, 'Dave'); dialogue.setKeywordHandler('back', 'undo'); return dialogue.consume(message, apiRequest); }); ```` Dialogue builder is built on top of the excellent [bot-builder](https://github.com/claudiajs/claudia-bot-builder) by [claudia.js](https://claudiajs.com/) and the code above is the entry point for a bot builder project. Each invocation of the function above is caused by an incoming message from the user. The `consume` method called above would continue the dialogue where it left off, calling any [responses handlers](#location-ontext-onlocation-onimage-onaudio-onvideo-onfile-defaultaction-symbols) for the incoming message and returning the next set of outgoing messages. Except, in the example above, the bot would simply repeat the beginning of the dialogue each time the user sent a message because the storage handler (the `store` and `retrieve` methods) is not persisting the internal dialogue state (which is a JSON object). You would normally store this state under your user record in the persistence storage mechanism on your choosing. See [dialogue-builder-example](https://github.com/nbransby/dialogue-builder-example) for an example on how to implement this using DynamoDB. ## API The `dialogue-builder` module exports the following interface: * [`dialogue` function](#dialogue-function) * [`say`, `ask`, `audio`, `video`, `image`, `file`, `expect`, `goto` template literal tag functions](#say-ask-audio-video-image-file-expect-goto-template-literal-tag-functions) * [`buttons`, `list` functions](#buttons-list-functions) * [`onText`, `location`, `onLocation`, `onImage`, `onAudio`, `onVideo`, `onFile`, `defaultAction` symbols](#location-ontext-onlocation-onimage-onaudio-onvideo-onfile-defaultaction-symbols) * [`UnexpectedInputError` class](#unexpectedinputerror-class) * [`Dialogue` class](#dialogue-class) * [`mock` namespace](#mock-namespace) ### `dialogue` function ````typescript dialogue(name: string, script: (...context: any) => Array<BaseTemplate | Label | Expect | Goto | ResponseHandler>): DialogueBuilder` ```` This function is used to define your script, the first arg is the name of your dialogue (not shown to the user) and the second is your script function which should return an array (the lines of your script). This function is passed any custom args you passed to the [Dialogue constructor](#dialogue-class). ### `say`, `ask`, `audio`, `video`, `image`, `file`, `expect`, `goto` template literal tag functions The array passed to the dialogue function form the lines of your script, an element in this array has to be one of: * `say` _string_: Your bot will simply repeat the string passed in * `ask` _string_: Identical to `say` except only `ask` statements are repeated on [undo](#undo) or an unhandled response * `audio` _string_: Send an audio file, the string passed in should be a url * `video` _string_: Send a video file, the string passed in should be a url * `image` _string_: Send an image file, the string passed in should be a url * `file` _string_: Send a file, the string passed in should be a url * `expect` _string_: This statement marks a break in the dialogue to wait for a user response. The _string_ you pass is the response you expect from the user, it's used as a key when persisting the state of the conversation and so *must* be a string unique amongst all expect statements. An expect statement must always be immediately followed by a [`ResponseHandler`](#location-ontext-onlocation-onimage-onaudio-onvideo-onfile-defaultaction-symbols) * `goto` _string_: A goto statement will cause the dialogue to jump to another location in the script. The string you pass in specifies the label to jump to. `goto` statements can also be returned from a [`ResponseHandler's`](#location-ontext-onlocation-onimage-onaudio-onvideo-onfile-defaultaction-symbols) methods * _string_: Any untagged strings in the array are treated as labels which serve as the destination of goto statements. When gathering the next set of outgoing messages, the dialogue will fall through labels by default. You can override this behavior by prefixing your label with an exclamation mark (!) - this causes the dialogue to break at the label. Once dialogue has stopped at a label only a goto statement will restart it (use this feature when you want to wait for a postback) * `fbTemplate.BaseTemplate`: You can embed any facebook message type supported by bot builder directly in your script, see [Facebook Template Builder](https://github.com/claudiajs/claudia-bot-builder/blob/master/docs/FB_TEMPLATE_MESSAGE_BUILDER.md) for more info ### `buttons`, `list` functions ````typescript type ButtonHandler = { [title: string]: () => Goto | void } type Bubble = [string, string, string, ButtonHandler] function buttons(id: string, text: string, handler: ButtonHandler): Button function list(id: string, type: 'compact' | 'large', bubbles: Bubble[], handler: ButtonHandler): List ```` The `buttons` function allows you to send a [Button Template](https://developers.facebook.com/docs/messenger-platform/send-api-reference/button-template) in your script. The first arg *must* be a string unique amongst all templates defined in your script, the second is the title to display to the user,and the third is your button handler object which defines the buttons names and handler functions in the same way as quick replies in a [`ResponseHandler`](#location-ontext-onlocation-onimage-onaudio-onvideo-onfile-defaultaction-symbols), it returns a [Button](https://github.com/claudiajs/claudia-bot-builder/blob/master/docs/FB_TEMPLATE_MESSAGE_BUILDER.md) The `list` function allows you to send a [List Template](https://developers.facebook.com/docs/messenger-platform/send-api-reference/list-template) in your script. The first arg *must* be a string unique amongst all templates defined in your script, the second is the list type, the third is an array of bubbles in your list, and the forth is a button handler object which defines the button names and handler function in the same way as quick replies in a [`ResponseHandler`](#location-ontext-onlocation-onimage-onaudio-onvideo-onfile-defaultaction-symbols), it returns a [List](https://github.com/claudiajs/claudia-bot-builder/blob/master/docs/FB_TEMPLATE_MESSAGE_BUILDER.md) ### `location`, `onText`, `onLocation`, `onImage`, `onAudio`, `onVideo`, `onFile`, `defaultAction` symbols A `ResponseHandler` is an object who's methods are called on receiving a message from the user to handle the response to the immediately preceding `expect` statement. The supported methods are: * _string_`(text?: string)`: A string property causes a quick reply to be attached to the last outgoing message, the function is called on the user selecting the reply, the text passed in will always be the same as the function name * `[location](lat: number, long: number, title?: string, url?: string)`: The `location` symbol property causes a location quick reply to be attached to the last outgoing message, the function is called on the user selecting the reply * `[onText](text: string)`: The `onText` symbol property is called when the user types a text response that doesn't match any of the quick replies * `[onLocation](lat: number, long: number, title?: string, url?: string)`: The `onLocation` symbol property is called when the user sends a location, you cannot define both `location` and `onLocation` properties on the same response handler * `[onImage](url: string)`: The `onImage` symbol property is called when the user sends an image * `[onAudio](url: string)`: The `onAudio` symbol property is called when the user sends an audio recording * `[onVideo](url: string)`: The `onVideo` symbol property is called when the user sends a video * `[onFile](url: string)`: The `onFile` symbol property is called when the user sends a file * `[defaultAction]()`: The `defaultAction` symbol property is called if no other mathod matches the user's response so can be used as a catch all. It is also used to specify the default action on [buttons and lists](#buttons-list-functions) All response handler methods support returning one of `Goto | Expect | void`, you can also return a promise resolving to one of the same set of types: `Promise<Goto | Expect | void>` Returning a [goto statement](#say-ask-audio-video-image-file-expect-goto-template-literal-tag-functions) from a `ResponseHandler` method will cause the dialogue to jump to the specified label Returning a [expect statement](#say-ask-audio-video-image-file-expect-goto-template-literal-tag-functions) from a `ResponseHandler` method will delegate the handling of the response to the relevant handler function of the response handler defined for the expect statement specified ### `UnexpectedInputError` class ````typescript class UnexpectedInputError { constructor(message: string, repeatQuestion?: boolean) } ```` When a [`ResponseHandler`](#location-ontext-onlocation-onimage-onaudio-onvideo-onfile-defaultaction-symbols) recieves a message from the user for which is does not contain a handler method for an instance of `UnexpectedInputError` is thrown, this will cause the question to be repeated. You can invoke this behaviour in a handled response by throwing this error from the handler method. The string you pass to the constructor will be sent to the user followed by repeating the question (the ask statements). If you don't want to repeat the question, pass `true` as the second constructor arg ### `Dialogue` class ````typescript class Dialogue { constructor(builder: DialogueBuilder, storage: Storage, ...context: any) baseUrl: string execute(directive: Goto | Expect) consume(message: Message, apiRequest: Request): Promise<any[]> setKeywordHandler(keywords: string | string[], handler: 'restart' | 'undo' | (() => void | Goto)): void } ```` The `Dialogue` class constructor has two required args, the first is the dialogue (the return value from the [`dialogue` function](#dialogue-function) and the second is the storage handler, you need to pass an object conforming to the following interface to store the dialogue state, typically under your user record in a persistence storage mechanism on your choosing: ````typescript interface Storage { store(state: Object): Promise<void> retrieve(): Promise<Object> } ```` Any additional args passed to the constructor are passed to the [`dialogue` function](#dialogue-function) this would typically be used to pass through the user's details to customize the dialogue plus any object needed in the [`ResponseHandlers`](#location-ontext-onlocation-onimage-onaudio-onvideo-onfile-defaultaction-symbols) to act on user responses. Setting the `baseUrl` property allows you to pass uris into functions that would normally expect a full url, such as [`audio`, `video`, `image`, `file` template literal tag functions](#say-ask-audio-video-image-file-expect-goto-template-literal-tag-functions) and the [`buttons`, `list` functions](#buttons-list-functions) Call the `execute` method to jump to another location in the script specified by a [`goto` or `expect` statement](#say-ask-audio-video-image-file-expect-goto-template-literal-tag-functions). This is useful for writing unit tests in combination with the [`mock` namespace](#mock-namespace) Call the `consume` method to process the input from the user, you need pass in the message and apiRequest from your bot builder handler method, you can return the result of this method directly from your bot builder handler method. Call the `setKeywordHandler` method to create a keyword which will trigger the callback passed in whenever the user sends any of the keywords passed as the first arg, at any point in the conversation. The callback can return a [goto statement](#say-ask-audio-video-image-file-expect-goto-template-literal-tag-functions) to cause the dialogue to jump to the specified label. Two built-in keyword handlers exist, which you can assign keywords to by replacing the callback with either `undo` or `restart` #### `undo` The undo keyword handler will repeat the last question asked in the dialogue, allowing the user to correct a mistake #### `restart` The restart keyword handler will reset the dialogue to the beginning and is useful to enable during development: *TIP:* Set your restart keyword to match your [Get Started button call to action payload](https://developers.facebook.com/docs/messenger-platform/thread-settings/get-started-button) so when users delete the conversation and initiate a new one your dialogue will begin from the start ### `mock` namespace ````typescript export namespace mock { const apiRequest: Request function message(text: string): Message function postback(payload?: string): Message function location(lat: number, long: number, title?: string, url?: string): Message function multimedia(type: 'image' | 'audio' | 'video' | 'file' | 'location', url: string): Message } ```` The constants and functions defined in the `mock` namespace allow you to easily mock input when calling the [`consume` method of the `Dialogue` class](#dialogue-class), for example: ````typescript dialogue.consume(mock.message('Hi'), mock.apiRequest) ```` ## Behavioral specifications * [it passes the supplied context to the script method](/tests.ts#L24) * [it throws an exception on empty script given](/tests.ts#L32) * [it throws an exception on script only containing labels](/tests.ts#L40) * [it sends the first and only message in a single message dialogue](/tests.ts#L49) * [it sends all messages with NO_PUSH notification type](/tests.ts#L59) * [it throws empty array on consume when complete](/tests.ts#L68) * [it sends multiple messages at once with pauses and typing indicators in between](/tests.ts#L79) * [it ensure total pauses are less then 10 seconds when sending multiple messages at once](/tests.ts#L94) * [it trims extraneous whitespace in messages](/tests.ts#L108) * [it supports bot builder template class instances inline](/tests.ts#L118) * [it supports null lines](/tests.ts#L130) * [it throws an exception on script with duplicate expect statements](/tests.ts#L144) * [it throws an exception on script with duplicate template ids](/tests.ts#L156) * [it throws an exception on expect statement not followed by a response handler](/tests.ts#L166) * [it throws an exception on a response handler not preceded by an expect statement](/tests.ts#L184) * [it pauses on expect to wait for a response](/tests.ts#L195) * [it resumes where it paused on receiving a response](/tests.ts#L211) * [it reevaluates a script after executing a response handler](/tests.ts#L222) * [it reevaluates a script after executing a keyword handler](/tests.ts#L236) * [it reevaluates a script after executing a postback handler](/tests.ts#L252) * [it attaches any quick replies defined in response handler to last message](/tests.ts#L270) * [it attaches location quick reply if defined in response handler](/tests.ts#L288) * [it supports promises being returned from response handlers](/tests.ts#L302) * [it invokes a quick reply's handler on receiving the reply](/tests.ts#L317) * [it invokes a button handler on receiving the postback](/tests.ts#L328) * [it invokes a list bubble's button handler on receiving the postback](/tests.ts#L338) * [it supports empty handlers](/tests.ts#L353) * [it supports null handlers](/tests.ts#L365) * [it throws an error when both location and onLocation specified on a handler](/tests.ts#L390) * [it prefers a quick reply handler to the onText handler](/tests.ts#L403) * [it invokes the location handler on receiving a location quick reply](/tests.ts#L414) * [it invokes the onText handler on receiving a text response](/tests.ts#L426) * [it invokes the onLocation handler on receiving a location response](/tests.ts#L438) * [it invokes the onImage handler on receiving an image response](/tests.ts#L450) * [it invokes the onVideo handler on receiving an video response](/tests.ts#L462) * [it invokes the onAudio handler on receiving an audio response](/tests.ts#L474) * [it invokes the onFile handler on receiving an file response](/tests.ts#L486) * [it invokes the defaultAction handler if no other more suitable handler defined](/tests.ts#L498) * [it invokes the defaultAction handler if no other more suitable handler defined](/tests.ts#L511) * [it prefers any suitable handler over the defaultAction handler](/tests.ts#L524) * [it handles unexpected response types by repeating only the ask statements](/tests.ts#L535) * [it supports the throwing of UnexpectedInputError from response handlers](/tests.ts#L562) * [it does not repeat the question when repeatQuestion arg to UnexpectedInputError constructor is false](/tests.ts#L581) * [it falls through a label not prefixed with an exclamation mark](/tests.ts#L597) * [it breaks on hitting a label prefixed with an exclamation mark](/tests.ts#L613) * [it respects inline gotos](/tests.ts#L634) * [it respects gotos executed on the dialogue instance](/tests.ts#L652) * [it jumps to an expect executed on the dialogue instance](/tests.ts#L668) * [it respects gotos returned from response handlers](/tests.ts#L687) * [it throws an exception on calling goto with a missing label](/tests.ts#L706) * [it throws an exception on script with duplicate labels](/tests.ts#L721) * [it aborts a goto that causes an endless loop](/tests.ts#L733) * [it resumes from the correct line when a goto skips a response handler](/tests.ts#L747) * [it supports expects returned from response handlers to delegate handling](/tests.ts#L772) * [it aborts an expect returned from response handler that causes an endless loop](/tests.ts#L788) * [it ignores return values from handlers if not gotos or expects](/tests.ts#L803) * [it calls a keyword handler when message is received that matches insensitive of case](/tests.ts#L817) * [it calls a keyword handler matching a postback payload if no postback handler found](/tests.ts#L827) * [it prefers a matching keyword handler over the current response handler](/tests.ts#L840) * [it resets the dialogue when user sends a restart keyword](/tests.ts#L854) * [it returns to previously asked question when user sends a undo keyword](/tests.ts#L873) * [it returns to last asked question when user sends a undo keyword when complete](/tests.ts#L896) * [it accounts for skipped questions due to goto statements when user sends a undo keyword](/tests.ts#L915) * [it supports a user sending an undo or restart keyword at the start of a dialogue](/tests.ts#L939) * [it prefixes uris with the baseUrl but leaves full urls as is](/tests.ts#L958)
{ "content_hash": "b4ab6a4f5dd9366639d3c731dbe4dc00", "timestamp": "", "source": "github", "line_count": 271, "max_line_length": 676, "avg_line_length": 79.54612546125462, "alnum_prop": 0.7534443568214501, "repo_name": "nbransby/dialogue-builder", "id": "0dbafea343fa3cfaa1116f2faec3662bfef49a51", "size": "21779", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "TypeScript", "bytes": "82495" } ] }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>geocoq: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / extra-dev</a></li> <li class="active"><a href="">dev / geocoq - 2.2.1</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> geocoq <small> 2.2.1 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-06-09 02:07:39 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-06-09 02:07:39 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 4 Virtual package relying on a GMP lib system installation coq dev Formal proof management system dune 3.2.0 Fast, portable, and opinionated build system ocaml 4.14.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.14.0 Official release 4.14.0 ocaml-config 2 OCaml Switch Configuration ocaml-options-vanilla 1 Ensure that OCaml is compiled with no special options enabled ocamlfind 1.9.3 A library manager for OCaml zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Julien Narboux &lt;julien@narboux.fr&gt;&quot; homepage: &quot;http://geocoq.github.io/GeoCoq/&quot; bug-reports: &quot;https://github.com/GeoCoq/GeoCoq/issues&quot; authors: [&quot;Gabriel Braun &lt;gabriel.braun@unistra.fr&gt;&quot; &quot;Pierre Boutry &lt;pierre.boutry@unistra.fr&gt;&quot; &quot;Charly Gries &lt;Charly.Gries@etu.unistra.fr&gt;&quot; &quot;Julien Narboux &lt;narboux@unistra.fr&gt;&quot;] license: &quot;LGPL 3&quot; build: [ [&quot;./configure.sh&quot;] [make &quot;-j%{jobs}%&quot;] ] install: [ [make &quot;install&quot;] ] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/GeoCoq&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {((&gt;= &quot;8.4pl4&quot; &amp; &lt; &quot;8.5~&quot;) | (&gt;= &quot;8.5&quot; &amp; &lt; &quot;8.6~&quot;) | (&gt;= &quot;8.6&quot; &amp; &lt; &quot;8.7~&quot;))} ] tags: [ &quot;keyword:geometry&quot; &quot;keyword:neutral geometry&quot; &quot;keyword:euclidean geometry&quot; &quot;keyword:foundations&quot; &quot;keyword:Tarski&quot; &quot;keyword:Hilbert&quot; &quot;keyword:Pappus&quot; &quot;keyword:Desargues&quot; &quot;keyword:parallel postulates&quot; &quot;category:Mathematics/Geometry/General&quot; &quot;date:2016-12-22&quot; ] synopsis: &quot;A formalization of foundations of geometry in Coq&quot; flags: light-uninstall url { src: &quot;https://github.com/GeoCoq/GeoCoq/archive/v2.2.1.tar.gz&quot; checksum: &quot;md5=be429fbeba560c84c994d551bb17c894&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-geocoq.2.2.1 coq.dev</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is dev). The following dependencies couldn&#39;t be met: - coq-geocoq -&gt; coq &lt; 8.5~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-geocoq.2.2.1</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "5792a53070bf56cafe0d2fd0a8d9ef7a", "timestamp": "", "source": "github", "line_count": 185, "max_line_length": 159, "avg_line_length": 40.4054054054054, "alnum_prop": 0.5439464882943144, "repo_name": "coq-bench/coq-bench.github.io", "id": "ccf36834a982cfd9ae553d088792279c46cde6c8", "size": "7500", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.14.0-2.0.10/extra-dev/dev/geocoq/2.2.1.html", "mode": "33188", "license": "mit", "language": [] }
package com.amazonaws.services.config.model; import java.io.Serializable; /** * <p> * The details that identify a resource that is discovered by AWS Config, * including the resource type, ID, and (if available) the custom resource name. * </p> */ public class ResourceIdentifier implements Serializable, Cloneable { /** * <p> * The type of resource. * </p> */ private String resourceType; /** * <p> * The ID of the resource (for example., <code>sg-xxxxxx</code>). * </p> */ private String resourceId; /** * <p> * The custom name of the resource (if available). * </p> */ private String resourceName; /** * <p> * The time that the resource was deleted. * </p> */ private java.util.Date resourceDeletionTime; /** * <p> * The type of resource. * </p> * * @param resourceType * The type of resource. * @see ResourceType */ public void setResourceType(String resourceType) { this.resourceType = resourceType; } /** * <p> * The type of resource. * </p> * * @return The type of resource. * @see ResourceType */ public String getResourceType() { return this.resourceType; } /** * <p> * The type of resource. * </p> * * @param resourceType * The type of resource. * @return Returns a reference to this object so that method calls can be * chained together. * @see ResourceType */ public ResourceIdentifier withResourceType(String resourceType) { setResourceType(resourceType); return this; } /** * <p> * The type of resource. * </p> * * @param resourceType * The type of resource. * @return Returns a reference to this object so that method calls can be * chained together. * @see ResourceType */ public void setResourceType(ResourceType resourceType) { this.resourceType = resourceType.toString(); } /** * <p> * The type of resource. * </p> * * @param resourceType * The type of resource. * @return Returns a reference to this object so that method calls can be * chained together. * @see ResourceType */ public ResourceIdentifier withResourceType(ResourceType resourceType) { setResourceType(resourceType); return this; } /** * <p> * The ID of the resource (for example., <code>sg-xxxxxx</code>). * </p> * * @param resourceId * The ID of the resource (for example., <code>sg-xxxxxx</code>). */ public void setResourceId(String resourceId) { this.resourceId = resourceId; } /** * <p> * The ID of the resource (for example., <code>sg-xxxxxx</code>). * </p> * * @return The ID of the resource (for example., <code>sg-xxxxxx</code>). */ public String getResourceId() { return this.resourceId; } /** * <p> * The ID of the resource (for example., <code>sg-xxxxxx</code>). * </p> * * @param resourceId * The ID of the resource (for example., <code>sg-xxxxxx</code>). * @return Returns a reference to this object so that method calls can be * chained together. */ public ResourceIdentifier withResourceId(String resourceId) { setResourceId(resourceId); return this; } /** * <p> * The custom name of the resource (if available). * </p> * * @param resourceName * The custom name of the resource (if available). */ public void setResourceName(String resourceName) { this.resourceName = resourceName; } /** * <p> * The custom name of the resource (if available). * </p> * * @return The custom name of the resource (if available). */ public String getResourceName() { return this.resourceName; } /** * <p> * The custom name of the resource (if available). * </p> * * @param resourceName * The custom name of the resource (if available). * @return Returns a reference to this object so that method calls can be * chained together. */ public ResourceIdentifier withResourceName(String resourceName) { setResourceName(resourceName); return this; } /** * <p> * The time that the resource was deleted. * </p> * * @param resourceDeletionTime * The time that the resource was deleted. */ public void setResourceDeletionTime(java.util.Date resourceDeletionTime) { this.resourceDeletionTime = resourceDeletionTime; } /** * <p> * The time that the resource was deleted. * </p> * * @return The time that the resource was deleted. */ public java.util.Date getResourceDeletionTime() { return this.resourceDeletionTime; } /** * <p> * The time that the resource was deleted. * </p> * * @param resourceDeletionTime * The time that the resource was deleted. * @return Returns a reference to this object so that method calls can be * chained together. */ public ResourceIdentifier withResourceDeletionTime( java.util.Date resourceDeletionTime) { setResourceDeletionTime(resourceDeletionTime); return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getResourceType() != null) sb.append("ResourceType: " + getResourceType() + ","); if (getResourceId() != null) sb.append("ResourceId: " + getResourceId() + ","); if (getResourceName() != null) sb.append("ResourceName: " + getResourceName() + ","); if (getResourceDeletionTime() != null) sb.append("ResourceDeletionTime: " + getResourceDeletionTime()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ResourceIdentifier == false) return false; ResourceIdentifier other = (ResourceIdentifier) obj; if (other.getResourceType() == null ^ this.getResourceType() == null) return false; if (other.getResourceType() != null && other.getResourceType().equals(this.getResourceType()) == false) return false; if (other.getResourceId() == null ^ this.getResourceId() == null) return false; if (other.getResourceId() != null && other.getResourceId().equals(this.getResourceId()) == false) return false; if (other.getResourceName() == null ^ this.getResourceName() == null) return false; if (other.getResourceName() != null && other.getResourceName().equals(this.getResourceName()) == false) return false; if (other.getResourceDeletionTime() == null ^ this.getResourceDeletionTime() == null) return false; if (other.getResourceDeletionTime() != null && other.getResourceDeletionTime().equals( this.getResourceDeletionTime()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getResourceType() == null) ? 0 : getResourceType() .hashCode()); hashCode = prime * hashCode + ((getResourceId() == null) ? 0 : getResourceId().hashCode()); hashCode = prime * hashCode + ((getResourceName() == null) ? 0 : getResourceName() .hashCode()); hashCode = prime * hashCode + ((getResourceDeletionTime() == null) ? 0 : getResourceDeletionTime().hashCode()); return hashCode; } @Override public ResourceIdentifier clone() { try { return (ResourceIdentifier) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException( "Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
{ "content_hash": "c1f9204356d906c83290c64ac6bc149a", "timestamp": "", "source": "github", "line_count": 318, "max_line_length": 83, "avg_line_length": 28.339622641509433, "alnum_prop": 0.5553706169551709, "repo_name": "trasa/aws-sdk-java", "id": "35c015cdb29db4e4d9323d9654462afdfa620a32", "size": "9596", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-config/src/main/java/com/amazonaws/services/config/model/ResourceIdentifier.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "100011199" }, { "name": "Scilab", "bytes": "2354" } ] }
package com.facebook.buck.core.artifact; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import com.facebook.buck.core.exceptions.HumanReadableException; import com.facebook.buck.core.model.BuildTarget; import com.facebook.buck.core.model.BuildTargetFactory; import com.facebook.buck.core.model.label.Label; import com.facebook.buck.core.model.label.LabelSyntaxException; import com.facebook.buck.core.rules.analysis.action.ActionAnalysisData; import com.facebook.buck.core.rules.analysis.action.ActionAnalysisDataKey; import com.facebook.buck.core.sourcepath.ExplicitBuildTargetSourcePath; import java.nio.file.Path; import java.nio.file.Paths; import net.starlark.java.eval.EvalException; import net.starlark.java.eval.Printer; import net.starlark.java.eval.StarlarkValue; import net.starlark.java.syntax.Location; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class ArtifactImplTest { @Rule public ExpectedException expectedException = ExpectedException.none(); private final Path genDir = Paths.get("buck-out/gen"); @Test public void artifactTransitionsToBuildArtifact() { BuildTarget target = BuildTargetFactory.newInstance("//my:foo"); Path packagePath = Paths.get("my/foo__"); Path path = Paths.get("bar"); DeclaredArtifact artifact = ArtifactImpl.of(target, genDir, packagePath, path, Location.BUILTIN); assertFalse(artifact.isBound()); ActionAnalysisDataKey key = ActionAnalysisDataKey.of(target, new ActionAnalysisData.ID("a")); BuildArtifact materialized = artifact.materialize(key); assertTrue(materialized.isBound()); assertEquals(key, materialized.getActionDataKey()); assertEquals( ExplicitBuildTargetSourcePath.of(target, genDir.resolve(packagePath).resolve(path)), materialized.getSourcePath()); } @Test public void rejectsEmptyPath() { BuildTarget target = BuildTargetFactory.newInstance("//my:foo"); Path packagePath = Paths.get("my/foo__"); expectedException.expect(ArtifactDeclarationException.class); ArtifactImpl.of(target, genDir, packagePath, Paths.get(""), Location.BUILTIN); } @Test public void rejectsEmptyPathAfterPathTraversal() { BuildTarget target = BuildTargetFactory.newInstance("//my:foo"); Path packagePath = Paths.get("my/foo__"); expectedException.expect(ArtifactDeclarationException.class); ArtifactImpl.of(target, genDir, packagePath, Paths.get("foo/.."), Location.BUILTIN); } @Test public void rejectsDotPath() { BuildTarget target = BuildTargetFactory.newInstance("//my:foo"); Path packagePath = Paths.get("my/foo__"); expectedException.expect(ArtifactDeclarationException.class); ArtifactImpl.of(target, genDir, packagePath, Paths.get("."), Location.BUILTIN); } @Test public void rejectsPrefixedDotPath() { BuildTarget target = BuildTargetFactory.newInstance("//my:foo"); Path packagePath = Paths.get("my/foo__"); expectedException.expect(ArtifactDeclarationException.class); ArtifactImpl.of(target, genDir, packagePath, Paths.get("./foo/.."), Location.BUILTIN); } @Test public void rejectsSuffixedDotPath() { BuildTarget target = BuildTargetFactory.newInstance("//my:foo"); Path packagePath = Paths.get("my/foo__"); expectedException.expect(ArtifactDeclarationException.class); ArtifactImpl.of(target, genDir, packagePath, Paths.get("foo/../."), Location.BUILTIN); } @Test public void rejectsPrefixedUpwardPathTraversal() { BuildTarget target = BuildTargetFactory.newInstance("//my:foo"); Path genDir = Paths.get("buck-out/gen"); Path packagePath = Paths.get("my/foo__"); expectedException.expect(ArtifactDeclarationException.class); ArtifactImpl.of(target, genDir, packagePath, Paths.get("../bar"), Location.BUILTIN); } @Test public void rejectsSuffixedUpwardPathTraversal() { BuildTarget target = BuildTargetFactory.newInstance("//my:foo"); Path genDir = Paths.get("buck-out/gen"); Path packagePath = Paths.get("my/foo__"); expectedException.expect(ArtifactDeclarationException.class); ArtifactImpl.of(target, genDir, packagePath, Paths.get("foo/../.."), Location.BUILTIN); } @Test public void rejectsUpwardPathTraversal() { BuildTarget target = BuildTargetFactory.newInstance("//my:foo"); Path packagePath = Paths.get("my/foo__"); expectedException.expect(ArtifactDeclarationException.class); ArtifactImpl.of(target, genDir, packagePath, Paths.get("foo/../../bar"), Location.BUILTIN); } @Test public void rejectsAbsolutePath() { BuildTarget target = BuildTargetFactory.newInstance("//my:foo"); Path packagePath = Paths.get("my/foo__"); expectedException.expect(ArtifactDeclarationException.class); ArtifactImpl.of(target, genDir, packagePath, Paths.get("").toAbsolutePath(), Location.BUILTIN); } @Test public void rejectsInvalidPath() { BuildTarget target = BuildTargetFactory.newInstance("//my:foo"); Path packagePath = Paths.get("my/foo__"); expectedException.expect(ArtifactDeclarationException.class); expectedException.expectMessage("Path 'foo\\u0000bar.txt' in target '//my:foo' is not valid"); ArtifactImpl.of(target, genDir, packagePath, "foo\0bar.txt", Location.BUILTIN); } @Test public void normalizesPaths() { BuildTarget target = BuildTargetFactory.newInstance("//my:foo"); Path genDir = Paths.get("buck-out/gen"); Path packagePath = Paths.get("my/foo__"); DeclaredArtifact artifact = ArtifactImpl.of( target, genDir, packagePath, Paths.get("bar/baz/.././blargl.sh"), Location.BUILTIN); assertEquals(Paths.get("my", "foo__", "bar", "blargl.sh").toString(), artifact.getShortPath()); } @Test public void skylarkFunctionsWork() throws LabelSyntaxException { BuildTarget target = BuildTargetFactory.newInstance("//my:foo"); Path packagePath = Paths.get("my/foo__"); ArtifactImpl artifact = ArtifactImpl.of(target, genDir, packagePath, Paths.get("bar/baz.cpp"), Location.BUILTIN); String expectedShortPath = Paths.get("my", "foo__", "bar", "baz.cpp").toString(); assertEquals("baz.cpp", artifact.getBasename()); assertEquals("cpp", artifact.getExtension()); assertEquals(Label.parseAbsolute("//my:foo"), artifact.getOwner()); assertEquals(expectedShortPath, artifact.getShortPath()); assertFalse(artifact.isSource()); assertEquals( String.format("<generated file '%s'>", expectedShortPath), new Printer().repr(artifact).toString()); ArtifactImpl artifact2 = ArtifactImpl.of(target, genDir, packagePath, Paths.get("bar/no_ext"), Location.BUILTIN); assertEquals("no_ext", artifact2.getBasename()); assertEquals("", artifact2.getExtension()); } @Test public void equalsArtifactHasEqualsTrueAndSameHashCode() { BuildTarget target = BuildTargetFactory.newInstance("//my:foo"); Path packagePath = Paths.get("my/foo__"); ArtifactImpl artifact1 = ArtifactImpl.of(target, genDir, packagePath, Paths.get("some/path"), Location.BUILTIN); ArtifactImpl artifact2 = ArtifactImpl.of(target, genDir, packagePath, Paths.get("some/path"), Location.BUILTIN); assertEquals(artifact1, artifact2); assertEquals(artifact1.hashCode(), artifact2.hashCode()); ActionAnalysisDataKey key = ActionAnalysisDataKey.of(target, new ActionAnalysisData.ID("a")); artifact1 = (ArtifactImpl) artifact1.materialize(key); artifact2 = (ArtifactImpl) artifact2.materialize(key); assertEquals(artifact1, artifact2); assertEquals(artifact1.hashCode(), artifact2.hashCode()); } @Test public void differentPathsAreNotEqual() { BuildTarget target = BuildTargetFactory.newInstance("//my:foo"); Path packagePath = Paths.get("my/foo__"); ArtifactImpl artifact1 = ArtifactImpl.of(target, genDir, packagePath, Paths.get("some/path1"), Location.BUILTIN); ArtifactImpl artifact2 = ArtifactImpl.of(target, genDir, packagePath, Paths.get("some/path2"), Location.BUILTIN); assertNotEquals(artifact1, artifact2); } @Test public void differentActionKeysAreNotEqual() { BuildTarget target = BuildTargetFactory.newInstance("//my:foo"); Path packagePath = Paths.get("my/foo__"); ArtifactImpl artifact1 = ArtifactImpl.of(target, genDir, packagePath, Paths.get("some/path"), Location.BUILTIN); ArtifactImpl artifact2 = ArtifactImpl.of(target, genDir, packagePath, Paths.get("some/path"), Location.BUILTIN); ActionAnalysisDataKey key1 = ActionAnalysisDataKey.of(target, new ActionAnalysisData.ID("a")); ActionAnalysisDataKey key2 = ActionAnalysisDataKey.of(target, new ActionAnalysisData.ID("a")); artifact1 = (ArtifactImpl) artifact1.materialize(key1); artifact2 = (ArtifactImpl) artifact2.materialize(key2); assertNotEquals(artifact1, artifact2); } @Test public void toStringMakesSense() throws EvalException { BuildTarget target = BuildTargetFactory.newInstance("//my:foo"); Path packagePath = Paths.get("my", "foo__"); Location location = Location.fromFileLineColumn("foo/bar.bzl", 3, 4); ActionAnalysisDataKey key1 = ActionAnalysisDataKey.of(target, new ActionAnalysisData.ID("a")); ActionAnalysisDataKey key2 = ActionAnalysisDataKey.of(target, new ActionAnalysisData.ID("a")); ArtifactImpl declaredWithLocation = ArtifactImpl.of(target, genDir, packagePath, Paths.get("some/path"), location); ArtifactImpl boundWithLocation = ArtifactImpl.of(target, genDir, packagePath, Paths.get("some/path"), location); boundWithLocation.materialize(key1); ArtifactImpl declaredWithoutLocation = ArtifactImpl.of(target, genDir, packagePath, Paths.get("some/path"), Location.BUILTIN); ArtifactImpl boundWithoutLocation = ArtifactImpl.of(target, genDir, packagePath, Paths.get("some/path"), Location.BUILTIN); boundWithoutLocation.materialize(key2); String artifactPathString = Paths.get("my", "foo__", "some", "path").toString(); // Location always prints with forward slashes, Path uses platform native String extensionPathString = "foo/bar.bzl"; String expectedWithLocation = String.format("Artifact<%s, declared at %s:3:4>", artifactPathString, extensionPathString); String expectedBoundWithLocation = String.format( "Artifact<%s, bound to %s, declared at %s:3:4>", artifactPathString, key1, extensionPathString); String expectedWithoutLocation = String.format("Artifact<%s, declared>", artifactPathString); String expectedBoundWithoutLocation = String.format("Artifact<%s, bound to %s>", artifactPathString, key2); String expectedWithLocationAsOutput = String.format( "Artifact<%s, as output, declared at %s:3:4>", artifactPathString, extensionPathString); String expectedWithoutLocationAsOutput = String.format("Artifact<%s, as output, declared>", artifactPathString); assertEquals(expectedWithLocation, declaredWithLocation.toString()); assertEquals( expectedWithLocationAsOutput, declaredWithLocation.asSkylarkOutputArtifact().toString()); assertEquals(expectedWithLocationAsOutput, declaredWithLocation.asOutputArtifact().toString()); assertEquals(expectedBoundWithLocation, boundWithLocation.toString()); assertEquals(expectedWithoutLocation, declaredWithoutLocation.toString()); assertEquals( expectedWithoutLocationAsOutput, declaredWithoutLocation.asSkylarkOutputArtifact().toString()); assertEquals( expectedWithoutLocationAsOutput, declaredWithoutLocation.asOutputArtifact().toString()); assertEquals(expectedBoundWithoutLocation, boundWithoutLocation.toString()); } @Test public void refusesToCreateSkylarkOutputArtifactIfBound() throws EvalException { BuildTarget target = BuildTargetFactory.newInstance("//my:foo"); Path packagePath = Paths.get("my/foo__"); Path path = Paths.get("bar"); ArtifactImpl artifact = ArtifactImpl.of(target, genDir, packagePath, path, Location.BUILTIN); ActionAnalysisDataKey key = ActionAnalysisDataKey.of(target, new ActionAnalysisData.ID("a")); BuildArtifact materialized = artifact.materialize(key); assertTrue(materialized.isBound()); expectedException.expect(EvalException.class); expectedException.expectMessage("cannot be used as an output artifact"); artifact.asSkylarkOutputArtifact(); } @Test public void refusesToCreateOutputArtifactIfBound() { BuildTarget target = BuildTargetFactory.newInstance("//my:foo"); Path packagePath = Paths.get("my/foo__"); Path path = Paths.get("bar"); ArtifactImpl artifact = ArtifactImpl.of(target, genDir, packagePath, path, Location.BUILTIN); ActionAnalysisDataKey key = ActionAnalysisDataKey.of(target, new ActionAnalysisData.ID("a")); BuildArtifact materialized = artifact.materialize(key); assertTrue(materialized.isBound()); expectedException.expect(HumanReadableException.class); expectedException.expectMessage("cannot be used as an output artifact"); artifact.asOutputArtifact(); } @Test public void isImmutable() throws EvalException { BuildTarget target = BuildTargetFactory.newInstance("//my:foo"); Path packagePath = Paths.get("my/foo__"); Path path = Paths.get("bar"); ArtifactImpl artifact = ArtifactImpl.of(target, genDir, packagePath, path, Location.BUILTIN); assertFalse(artifact.isBound()); assertTrue(artifact.isImmutable()); assertTrue(((StarlarkValue) artifact.asSkylarkOutputArtifact()).isImmutable()); ActionAnalysisDataKey key = ActionAnalysisDataKey.of(target, new ActionAnalysisData.ID("a")); BuildArtifact materialized = artifact.materialize(key); assertTrue(materialized.isBound()); assertTrue(artifact.isImmutable()); } }
{ "content_hash": "16d90f2f42fb5ba3f4bdfad8bfda8b6b", "timestamp": "", "source": "github", "line_count": 341, "max_line_length": 100, "avg_line_length": 41.29032258064516, "alnum_prop": 0.7330255681818182, "repo_name": "JoelMarcey/buck", "id": "14b0184819110e9a4260c92c6555bc59abd2f1d6", "size": "14696", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "test/com/facebook/buck/core/artifact/ArtifactImplTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "579" }, { "name": "Batchfile", "bytes": "2093" }, { "name": "C", "bytes": "255521" }, { "name": "C#", "bytes": "237" }, { "name": "C++", "bytes": "10992" }, { "name": "CSS", "bytes": "54863" }, { "name": "D", "bytes": "1017" }, { "name": "Go", "bytes": "16819" }, { "name": "Groovy", "bytes": "3362" }, { "name": "HTML", "bytes": "6115" }, { "name": "Haskell", "bytes": "895" }, { "name": "IDL", "bytes": "385" }, { "name": "Java", "bytes": "19430296" }, { "name": "JavaScript", "bytes": "932672" }, { "name": "Kotlin", "bytes": "2079" }, { "name": "Lex", "bytes": "2731" }, { "name": "Makefile", "bytes": "1816" }, { "name": "Matlab", "bytes": "47" }, { "name": "OCaml", "bytes": "4384" }, { "name": "Objective-C", "bytes": "138150" }, { "name": "Objective-C++", "bytes": "34" }, { "name": "PowerShell", "bytes": "244" }, { "name": "Prolog", "bytes": "858" }, { "name": "Python", "bytes": "1786899" }, { "name": "Roff", "bytes": "1109" }, { "name": "Rust", "bytes": "3618" }, { "name": "Scala", "bytes": "4906" }, { "name": "Shell", "bytes": "49876" }, { "name": "Smalltalk", "bytes": "3355" }, { "name": "Standard ML", "bytes": "15" }, { "name": "Swift", "bytes": "6897" }, { "name": "Thrift", "bytes": "26256" }, { "name": "Yacc", "bytes": "323" } ] }
package org.apache.jmeter.functions; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.apache.jmeter.engine.util.CompoundVariable; import org.apache.jmeter.samplers.SampleResult; import org.apache.jmeter.samplers.Sampler; import org.apache.jmeter.util.JMeterUtils; /** * Function to get a JMeter Variable * * Parameters: * - variable name * * Returns: * - the variable value, but if not found * - the variable name itself * @since 2.3RC3 */ public class Variable extends AbstractFunction { private static final List<String> desc = new LinkedList<String>(); private static final String KEY = "__V"; //$NON-NLS-1$ // Number of parameters expected - used to reject invalid calls private static final int MIN_PARAMETER_COUNT = 1; private static final int MAX_PARAMETER_COUNT = 1; static { desc.add(JMeterUtils.getResString("variable_name_param")); //$NON-NLS-1$ } private Object[] values; public Variable() { } /** {@inheritDoc} */ @Override public String execute(SampleResult previousResult, Sampler currentSampler) throws InvalidVariableException { String variableName = ((CompoundVariable) values[0]).execute(); String variableValue = getVariables().get(variableName); return variableValue == null? variableName : variableValue; } /** {@inheritDoc} */ @Override public void setParameters(Collection<CompoundVariable> parameters) throws InvalidVariableException { checkParameterCount(parameters, MIN_PARAMETER_COUNT, MAX_PARAMETER_COUNT); values = parameters.toArray(); } /** {@inheritDoc} */ @Override public String getReferenceKey() { return KEY; } /** {@inheritDoc} */ @Override public List<String> getArgumentDesc() { return desc; } }
{ "content_hash": "d391d67400bc46cf652808bfb9cde358", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 104, "avg_line_length": 26.5, "alnum_prop": 0.6552779194288628, "repo_name": "saketh7/Jmeter", "id": "7f533ef0dd6181e382dd36ca1c36c6e71c376ef5", "size": "2779", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/functions/org/apache/jmeter/functions/Variable.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2796" }, { "name": "CSS", "bytes": "1321" }, { "name": "HTML", "bytes": "13278" }, { "name": "Java", "bytes": "7233227" }, { "name": "Shell", "bytes": "1873" }, { "name": "XSLT", "bytes": "62457" } ] }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.07.30 at 11:36:03 AM CEST // package gov.nist.scap.schema.cve._0; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import gov.nist.scap.schema.scap_core._0.ReferenceType; /** * <p>Java class for cveType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="cveType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="status" type="{http://scap.nist.gov/schema/cve/0.1}cveStatus" minOccurs="0"/> * &lt;element name="description" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="references" type="{http://scap.nist.gov/schema/scap-core/0.1}referenceType" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;attribute name="id" use="required" type="{http://scap.nist.gov/schema/cve/0.1}cveNamePatternType" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "cveType", propOrder = { "status", "description", "references" }) public class CveType { @XmlSchemaType(name = "token") protected CveStatus status; protected String description; protected List<ReferenceType> references; @XmlAttribute(name = "id", required = true) @XmlJavaTypeAdapter(CollapsedStringAdapter.class) protected String id; /** * Gets the value of the status property. * * @return * possible object is * {@link CveStatus } * */ public CveStatus getStatus() { return status; } /** * Sets the value of the status property. * * @param value * allowed object is * {@link CveStatus } * */ public void setStatus(CveStatus value) { this.status = value; } /** * Gets the value of the description property. * * @return * possible object is * {@link String } * */ public String getDescription() { return description; } /** * Sets the value of the description property. * * @param value * allowed object is * {@link String } * */ public void setDescription(String value) { this.description = value; } /** * Gets the value of the references property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the references property. * * <p> * For example, to add a new item, do as follows: * <pre> * getReferences().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ReferenceType } * * */ public List<ReferenceType> getReferences() { if (references == null) { references = new ArrayList<ReferenceType>(); } return this.references; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } }
{ "content_hash": "41d036672771608418f3d6bdfcecdbee", "timestamp": "", "source": "github", "line_count": 162, "max_line_length": 142, "avg_line_length": 27.166666666666668, "alnum_prop": 0.6069075210179504, "repo_name": "frosenberg/elasticsearch-nvd-river", "id": "0e0ae2dde0991212713957575b8a1333a220f963", "size": "4401", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/gov/nist/scap/schema/cve/_0/CveType.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "252565" } ] }
package ru.job4j; /** * Created by aleks on 28.08.2017. */ public class Characters { public int characters(String allSymbols, char symbol) { int number = 0; for (int index = 0; index < allSymbols.length(); index++){ if (allSymbols.charAt(index) == symbol) { number++; } } return number; } }
{ "content_hash": "b2c6ff6249c3911b90fbd756a30c3048", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 66, "avg_line_length": 23.125, "alnum_prop": 0.5378378378378378, "repo_name": "new-x/study", "id": "5645930fadc9691e9ff2e5b2e8cce90a35677065", "size": "370", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "workstring/src/main/java/ru/job4j/Characters.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "502" }, { "name": "HTML", "bytes": "14398" }, { "name": "Java", "bytes": "332241" }, { "name": "JavaScript", "bytes": "545679" }, { "name": "XSLT", "bytes": "508" } ] }
package io.quarkus.resteasy.reactive.server.test.customproviders; import static org.assertj.core.api.Assertions.assertThat; import java.util.function.Supplier; import org.hamcrest.Matchers; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import io.quarkus.test.QuarkusUnitTest; import io.restassured.RestAssured; import io.restassured.http.Headers; public class CustomFiltersTest { @RegisterExtension static QuarkusUnitTest test = new QuarkusUnitTest() .setArchiveProducer(new Supplier<>() { @Override public JavaArchive get() { return ShrinkWrap.create(JavaArchive.class) .addClasses(CustomContainerRequestFilter.class, CustomFiltersResource.class, CustomContainerResponseFilter.class, AssertContainerFilter.class, SomeBean.class, Metal.class, MetalFilter.class); } }); @Test public void testFilters() { Headers responseHeaders = RestAssured.given().header("some-input", "bar").get("/custom/req") .then().statusCode(200).body(Matchers.containsString("/custom/req-bar-null")).extract().headers(); assertThat(responseHeaders.getValues("java-method")).containsOnly("filters"); Assertions.assertEquals(3, AssertContainerFilter.COUNT.get()); assertThat(responseHeaders.getValues("very")).isEmpty(); responseHeaders = RestAssured.given().header("some-input", "bar").get("/custom/metal") .then().statusCode(200).body(Matchers.containsString("/custom/metal-bar-metal")).extract().headers(); assertThat(responseHeaders.getValues("very")).containsOnly("heavy"); } }
{ "content_hash": "215eb9f6c3e278d9e7875d0696aefad5", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 117, "avg_line_length": 44.02272727272727, "alnum_prop": 0.6799173980382034, "repo_name": "quarkusio/quarkus", "id": "e92475042209ac15d5d9d460ced936ce393ef93f", "size": "1937", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "extensions/resteasy-reactive/quarkus-resteasy-reactive/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/customproviders/CustomFiltersTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "23342" }, { "name": "Batchfile", "bytes": "13096" }, { "name": "CSS", "bytes": "6685" }, { "name": "Dockerfile", "bytes": "459" }, { "name": "FreeMarker", "bytes": "8106" }, { "name": "Groovy", "bytes": "16133" }, { "name": "HTML", "bytes": "1418749" }, { "name": "Java", "bytes": "38584810" }, { "name": "JavaScript", "bytes": "90960" }, { "name": "Kotlin", "bytes": "704351" }, { "name": "Mustache", "bytes": "13191" }, { "name": "Scala", "bytes": "9756" }, { "name": "Shell", "bytes": "71729" } ] }
package org.apache.airavata.helix.impl.task.parsing.models; public class ParsingTaskInput { private String id; private String name; private String contextVariableName; private String value; private String type; public String getContextVariableName() { return contextVariableName; } public void setContextVariableName(String contextVariableName) { this.contextVariableName = contextVariableName; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
{ "content_hash": "f71e557ecf6afd2ecc102b545153fccb", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 68, "avg_line_length": 19.755102040816325, "alnum_prop": 0.6198347107438017, "repo_name": "apache/airavata", "id": "aeff9a5b8faff5d01a737a14d6b964f3fd867ade", "size": "968", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "modules/airavata-helix/helix-spectator/src/main/java/org/apache/airavata/helix/impl/task/parsing/models/ParsingTaskInput.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2959" }, { "name": "Blade", "bytes": "640580" }, { "name": "C", "bytes": "29278" }, { "name": "C++", "bytes": "8274651" }, { "name": "CSS", "bytes": "34425" }, { "name": "Dockerfile", "bytes": "7386" }, { "name": "HTML", "bytes": "91922" }, { "name": "Java", "bytes": "36030164" }, { "name": "JavaScript", "bytes": "404261" }, { "name": "Jinja", "bytes": "234378" }, { "name": "PHP", "bytes": "1176284" }, { "name": "Python", "bytes": "633278" }, { "name": "Shell", "bytes": "153797" }, { "name": "Thrift", "bytes": "472909" }, { "name": "XSLT", "bytes": "3266" } ] }
End of preview.

No dataset card yet

Downloads last month
3