How to use source class

Best Atoum code snippet using source

search_source.go

Source:search_source.go Github

copy

Full Screen

1// Copyright 2012-2015 Oliver Eilhard. All rights reserved.2// Use of this source code is governed by a MIT-license.3// See http://olivere.mit-license.org/license.txt for details.45package elastic67import (8 "fmt"9)1011// SearchSource enables users to build the search source.12// It resembles the SearchSourceBuilder in Elasticsearch.13type SearchSource struct {14 query Query15 postQuery Query16 from int17 size int18 explain *bool19 version *bool20 sorters []Sorter21 trackScores bool22 minScore *float6423 timeout string24 terminateAfter *int25 fieldNames []string26 fieldDataFields []string27 scriptFields []*ScriptField28 fetchSourceContext *FetchSourceContext29 aggregations map[string]Aggregation30 highlight *Highlight31 globalSuggestText string32 suggesters []Suggester33 rescores []*Rescore34 defaultRescoreWindowSize *int35 indexBoosts map[string]float6436 stats []string37 innerHits map[string]*InnerHit38}3940// NewSearchSource initializes a new SearchSource.41func NewSearchSource() *SearchSource {42 return &SearchSource{43 from: -1,44 size: -1,45 trackScores: false,46 sorters: make([]Sorter, 0),47 fieldDataFields: make([]string, 0),48 scriptFields: make([]*ScriptField, 0),49 aggregations: make(map[string]Aggregation),50 rescores: make([]*Rescore, 0),51 indexBoosts: make(map[string]float64),52 stats: make([]string, 0),53 innerHits: make(map[string]*InnerHit),54 }55}5657// Query sets the query to use with this search source.58func (s *SearchSource) Query(query Query) *SearchSource {59 s.query = query60 return s61}6263// PostFilter will be executed after the query has been executed and64// only affects the search hits, not the aggregations.65// This filter is always executed as the last filtering mechanism.66func (s *SearchSource) PostFilter(postFilter Query) *SearchSource {67 s.postQuery = postFilter68 return s69}7071// From index to start the search from. Defaults to 0.72func (s *SearchSource) From(from int) *SearchSource {73 s.from = from74 return s75}7677// Size is the number of search hits to return. Defaults to 10.78func (s *SearchSource) Size(size int) *SearchSource {79 s.size = size80 return s81}8283// MinScore sets the minimum score below which docs will be filtered out.84func (s *SearchSource) MinScore(minScore float64) *SearchSource {85 s.minScore = &minScore86 return s87}8889// Explain indicates whether each search hit should be returned with90// an explanation of the hit (ranking).91func (s *SearchSource) Explain(explain bool) *SearchSource {92 s.explain = &explain93 return s94}9596// Version indicates whether each search hit should be returned with97// a version associated to it.98func (s *SearchSource) Version(version bool) *SearchSource {99 s.version = &version100 return s101}102103// Timeout controls how long a search is allowed to take, e.g. "1s" or "500ms".104func (s *SearchSource) Timeout(timeout string) *SearchSource {105 s.timeout = timeout106 return s107}108109// TimeoutInMillis controls how many milliseconds a search is allowed110// to take before it is canceled.111func (s *SearchSource) TimeoutInMillis(timeoutInMillis int) *SearchSource {112 s.timeout = fmt.Sprintf("%dms", timeoutInMillis)113 return s114}115116// TerminateAfter allows the request to stop after the given number117// of search hits are collected.118func (s *SearchSource) TerminateAfter(terminateAfter int) *SearchSource {119 s.terminateAfter = &terminateAfter120 return s121}122123// Sort adds a sort order.124func (s *SearchSource) Sort(field string, ascending bool) *SearchSource {125 s.sorters = append(s.sorters, SortInfo{Field: field, Ascending: ascending})126 return s127}128129// SortWithInfo adds a sort order.130func (s *SearchSource) SortWithInfo(info SortInfo) *SearchSource {131 s.sorters = append(s.sorters, info)132 return s133}134135// SortBy adds a sort order.136func (s *SearchSource) SortBy(sorter ...Sorter) *SearchSource {137 s.sorters = append(s.sorters, sorter...)138 return s139}140141func (s *SearchSource) hasSort() bool {142 return len(s.sorters) > 0143}144145// TrackScores is applied when sorting and controls if scores will be146// tracked as well. Defaults to false.147func (s *SearchSource) TrackScores(trackScores bool) *SearchSource {148 s.trackScores = trackScores149 return s150}151152// Aggregation adds an aggreation to perform as part of the search.153func (s *SearchSource) Aggregation(name string, aggregation Aggregation) *SearchSource {154 s.aggregations[name] = aggregation155 return s156}157158// DefaultRescoreWindowSize sets the rescore window size for rescores159// that don't specify their window.160func (s *SearchSource) DefaultRescoreWindowSize(defaultRescoreWindowSize int) *SearchSource {161 s.defaultRescoreWindowSize = &defaultRescoreWindowSize162 return s163}164165// Highlight adds highlighting to the search.166func (s *SearchSource) Highlight(highlight *Highlight) *SearchSource {167 s.highlight = highlight168 return s169}170171// Highlighter returns the highlighter.172func (s *SearchSource) Highlighter() *Highlight {173 if s.highlight == nil {174 s.highlight = NewHighlight()175 }176 return s.highlight177}178179// GlobalSuggestText defines the global text to use with all suggesters.180// This avoids repetition.181func (s *SearchSource) GlobalSuggestText(text string) *SearchSource {182 s.globalSuggestText = text183 return s184}185186// Suggester adds a suggester to the search.187func (s *SearchSource) Suggester(suggester Suggester) *SearchSource {188 s.suggesters = append(s.suggesters, suggester)189 return s190}191192// Rescorer adds a rescorer to the search.193func (s *SearchSource) Rescorer(rescore *Rescore) *SearchSource {194 s.rescores = append(s.rescores, rescore)195 return s196}197198// ClearRescorers removes all rescorers from the search.199func (s *SearchSource) ClearRescorers() *SearchSource {200 s.rescores = make([]*Rescore, 0)201 return s202}203204// FetchSource indicates whether the response should contain the stored205// _source for every hit.206func (s *SearchSource) FetchSource(fetchSource bool) *SearchSource {207 if s.fetchSourceContext == nil {208 s.fetchSourceContext = NewFetchSourceContext(fetchSource)209 } else {210 s.fetchSourceContext.SetFetchSource(fetchSource)211 }212 return s213}214215// FetchSourceContext indicates how the _source should be fetched.216func (s *SearchSource) FetchSourceContext(fetchSourceContext *FetchSourceContext) *SearchSource {217 s.fetchSourceContext = fetchSourceContext218 return s219}220221// NoFields indicates that no fields should be loaded, resulting in only222// id and type to be returned per field.223func (s *SearchSource) NoFields() *SearchSource {224 s.fieldNames = make([]string, 0)225 return s226}227228// Field adds a single field to load and return (note, must be stored) as229// part of the search request. If none are specified, the source of the230// document will be returned.231func (s *SearchSource) Field(fieldName string) *SearchSource {232 if s.fieldNames == nil {233 s.fieldNames = make([]string, 0)234 }235 s.fieldNames = append(s.fieldNames, fieldName)236 return s237}238239// Fields sets the fields to load and return as part of the search request.240// If none are specified, the source of the document will be returned.241func (s *SearchSource) Fields(fieldNames ...string) *SearchSource {242 if s.fieldNames == nil {243 s.fieldNames = make([]string, 0)244 }245 s.fieldNames = append(s.fieldNames, fieldNames...)246 return s247}248249// FieldDataField adds a single field to load from the field data cache250// and return as part of the search request.251func (s *SearchSource) FieldDataField(fieldDataField string) *SearchSource {252 s.fieldDataFields = append(s.fieldDataFields, fieldDataField)253 return s254}255256// FieldDataFields adds one or more fields to load from the field data cache257// and return as part of the search request.258func (s *SearchSource) FieldDataFields(fieldDataFields ...string) *SearchSource {259 s.fieldDataFields = append(s.fieldDataFields, fieldDataFields...)260 return s261}262263// ScriptField adds a single script field with the provided script.264func (s *SearchSource) ScriptField(scriptField *ScriptField) *SearchSource {265 s.scriptFields = append(s.scriptFields, scriptField)266 return s267}268269// ScriptFields adds one or more script fields with the provided scripts.270func (s *SearchSource) ScriptFields(scriptFields ...*ScriptField) *SearchSource {271 s.scriptFields = append(s.scriptFields, scriptFields...)272 return s273}274275// IndexBoost sets the boost that a specific index will receive when the276// query is executed against it.277func (s *SearchSource) IndexBoost(index string, boost float64) *SearchSource {278 s.indexBoosts[index] = boost279 return s280}281282// Stats group this request will be aggregated under.283func (s *SearchSource) Stats(statsGroup ...string) *SearchSource {284 s.stats = append(s.stats, statsGroup...)285 return s286}287288// InnerHit adds an inner hit to return with the result.289func (s *SearchSource) InnerHit(name string, innerHit *InnerHit) *SearchSource {290 s.innerHits[name] = innerHit291 return s292}293294// Source returns the serializable JSON for the source builder.295func (s *SearchSource) Source() (interface{}, error) {296 source := make(map[string]interface{})297298 if s.from != -1 {299 source["from"] = s.from300 }301 if s.size != -1 {302 source["size"] = s.size303 }304 if s.timeout != "" {305 source["timeout"] = s.timeout306 }307 if s.terminateAfter != nil {308 source["terminate_after"] = *s.terminateAfter309 }310 if s.query != nil {311 src, err := s.query.Source()312 if err != nil {313 return nil, err314 }315 source["query"] = src316 }317 if s.postQuery != nil {318 src, err := s.postQuery.Source()319 if err != nil {320 return nil, err321 }322 source["post_filter"] = src323 }324 if s.minScore != nil {325 source["min_score"] = *s.minScore326 }327 if s.version != nil {328 source["version"] = *s.version329 }330 if s.explain != nil {331 source["explain"] = *s.explain332 }333 if s.fetchSourceContext != nil {334 src, err := s.fetchSourceContext.Source()335 if err != nil {336 return nil, err337 }338 source["_source"] = src339 }340341 if s.fieldNames != nil {342 switch len(s.fieldNames) {343 case 1:344 source["fields"] = s.fieldNames[0]345 default:346 source["fields"] = s.fieldNames347 }348 }349350 if len(s.fieldDataFields) > 0 {351 source["fielddata_fields"] = s.fieldDataFields352 }353354 if len(s.scriptFields) > 0 {355 sfmap := make(map[string]interface{})356 for _, scriptField := range s.scriptFields {357 src, err := scriptField.Source()358 if err != nil {359 return nil, err360 }361 sfmap[scriptField.FieldName] = src362 }363 source["script_fields"] = sfmap364 }365366 if len(s.sorters) > 0 {367 var sortarr []interface{}368 for _, sorter := range s.sorters {369 src, err := sorter.Source()370 if err != nil {371 return nil, err372 }373 sortarr = append(sortarr, src)374 }375 source["sort"] = sortarr376 }377378 if s.trackScores {379 source["track_scores"] = s.trackScores380 }381382 if len(s.indexBoosts) > 0 {383 source["indices_boost"] = s.indexBoosts384 }385386 if len(s.aggregations) > 0 {387 aggsMap := make(map[string]interface{})388 for name, aggregate := range s.aggregations {389 src, err := aggregate.Source()390 if err != nil {391 return nil, err392 }393 aggsMap[name] = src394 }395 source["aggregations"] = aggsMap396 }397398 if s.highlight != nil {399 src, err := s.highlight.Source()400 if err != nil {401 return nil, err402 }403 source["highlight"] = src404 }405406 if len(s.suggesters) > 0 {407 suggesters := make(map[string]interface{})408 for _, s := range s.suggesters {409 src, err := s.Source(false)410 if err != nil {411 return nil, err412 }413 suggesters[s.Name()] = src414 }415 if s.globalSuggestText != "" {416 suggesters["text"] = s.globalSuggestText417 }418 source["suggest"] = suggesters419 }420421 if len(s.rescores) > 0 {422 // Strip empty rescores from request423 var rescores []*Rescore424 for _, r := range s.rescores {425 if !r.IsEmpty() {426 rescores = append(rescores, r)427 }428 }429430 if len(rescores) == 1 {431 rescores[0].defaultRescoreWindowSize = s.defaultRescoreWindowSize432 src, err := rescores[0].Source()433 if err != nil {434 return nil, err435 }436 source["rescore"] = src437 } else {438 var slice []interface{}439 for _, r := range rescores {440 r.defaultRescoreWindowSize = s.defaultRescoreWindowSize441 src, err := r.Source()442 if err != nil {443 return nil, err444 }445 slice = append(slice, src)446 }447 source["rescore"] = slice448 }449 }450451 if len(s.stats) > 0 {452 source["stats"] = s.stats453 }454455 if len(s.innerHits) > 0 {456 // Top-level inner hits457 // See http://www.elastic.co/guide/en/elasticsearch/reference/1.5/search-request-inner-hits.html#top-level-inner-hits458 // "inner_hits": {459 // "<inner_hits_name>": {460 // "<path|type>": {461 // "<path-to-nested-object-field|child-or-parent-type>": {462 // <inner_hits_body>,463 // [,"inner_hits" : { [<sub_inner_hits>]+ } ]?464 // }465 // }466 // },467 // [,"<inner_hits_name_2>" : { ... } ]*468 // }469 m := make(map[string]interface{})470 for name, hit := range s.innerHits {471 if hit.path != "" {472 src, err := hit.Source()473 if err != nil {474 return nil, err475 }476 path := make(map[string]interface{})477 path[hit.path] = src478 m[name] = map[string]interface{}{479 "path": path,480 }481 } else if hit.typ != "" {482 src, err := hit.Source()483 if err != nil {484 return nil, err485 }486 typ := make(map[string]interface{})487 typ[hit.typ] = src488 m[name] = map[string]interface{}{489 "type": typ,490 }491 } else {492 // TODO the Java client throws here, because either path or typ must be specified493 }494 }495 source["inner_hits"] = m496 }497498 return source, nil499} ...

Full Screen

Full Screen

AssetSourcesService.php

Source:AssetSourcesService.php Github

copy

Full Screen

...29 private $_viewableSources;30 /**31 * @var32 */33 private $_sourcesById;34 /**35 * @var bool36 */37 private $_fetchedAllSources = false;38 // Public Methods39 // =========================================================================40 // Source Types41 // -------------------------------------------------------------------------42 /**43 * Returns all available source types.44 *45 * @return array46 */47 public function getAllSourceTypes()48 {49 if (craft()->getEdition() == Craft::Pro)50 {51 return craft()->components->getComponentsByType(ComponentType::AssetSource);52 }53 else54 {55 return array(craft()->components->getComponentByTypeAndClass(ComponentType::AssetSource, 'Local'));56 }57 }58 /**59 * Returns an asset source type by its class handle.60 *61 * @param string $class62 *63 * @return BaseAssetSourceType|null64 */65 public function getSourceType($class)66 {67 return craft()->components->getComponentByTypeAndClass(ComponentType::AssetSource, $class);68 }69 /**70 * Populates an asset source type with a given source.71 *72 * @param AssetSourceModel $source73 *74 * @return BaseAssetSourceType|null75 */76 public function populateSourceType(AssetSourceModel $source)77 {78 return craft()->components->populateComponentByTypeAndModel(ComponentType::AssetSource, $source);79 }80 /**81 * Returns a source type by a given source ID.82 *83 * @param $sourceId84 *85 * @return BaseAssetSourceType86 */87 public function getSourceTypeById($sourceId)88 {89 $source = $this->getSourceById($sourceId);90 return $this->populateSourceType($source);91 }92 // Sources93 // -------------------------------------------------------------------------94 /**95 * Returns all of the source IDs.96 *97 * @return array98 */99 public function getAllSourceIds()100 {101 if (!isset($this->_allSourceIds))102 {103 if ($this->_fetchedAllSources)104 {105 $this->_allSourceIds = array_keys($this->_sourcesById);106 }107 else108 {109 $this->_allSourceIds = craft()->db->createCommand()110 ->select('id')111 ->from('assetsources')112 ->queryColumn();113 }114 }115 return $this->_allSourceIds;116 }117 /**118 * Returns all source IDs that are viewable by the current user.119 *120 * @return array121 */122 public function getViewableSourceIds()123 {124 if (!isset($this->_viewableSourceIds))125 {126 $this->_viewableSourceIds = array();127 foreach ($this->getAllSourceIds() as $sourceId)128 {129 if (craft()->userSession->checkPermission('viewAssetSource:'.$sourceId))130 {131 $this->_viewableSourceIds[] = $sourceId;132 }133 }134 }135 return $this->_viewableSourceIds;136 }137 /**138 * Returns all sources that are viewable by the current user.139 *140 * @param string|null $indexBy141 *142 * @return array143 */144 public function getViewableSources($indexBy = null)145 {146 if (!isset($this->_viewableSources))147 {148 $this->_viewableSources = array();149 foreach ($this->getAllSources() as $source)150 {151 if (craft()->userSession->checkPermission('viewAssetSource:'.$source->id))152 {153 $this->_viewableSources[] = $source;154 }155 }156 }157 if (!$indexBy)158 {159 return $this->_viewableSources;160 }161 else162 {163 $sources = array();164 foreach ($this->_viewableSources as $source)165 {166 $sources[$source->$indexBy] = $source;167 }168 return $sources;169 }170 }171 /**172 * Returns the total number of sources173 *174 * @return int175 */176 public function getTotalSources()177 {178 return count($this->getAllSourceIds());179 }180 /**181 * Returns the total number of sources that are viewable by the current user.182 *183 * @return int184 */185 public function getTotalViewableSources()186 {187 return count($this->getViewableSourceIds());188 }189 /**190 * Returns all sources.191 *192 * @param string|null $indexBy193 *194 * @return array195 */196 public function getAllSources($indexBy = null)197 {198 if (!$this->_fetchedAllSources)199 {200 $this->_sourcesById = array();201 $results = $this->_createSourceQuery()->queryAll();202 foreach ($results as $result)203 {204 $source = $this->_populateSource($result);205 $this->_sourcesById[$source->id] = $source;206 }207 $this->_fetchedAllSources = true;208 }209 if ($indexBy == 'id')210 {211 return $this->_sourcesById;212 }213 else if (!$indexBy)214 {215 return array_values($this->_sourcesById);216 }217 else218 {219 $sources = array();220 foreach ($this->_sourcesById as $source)221 {222 $sources[$source->$indexBy] = $source;223 }224 return $sources;225 }226 }227 /**228 * Returns a source by its ID.229 *230 * @param int $sourceId231 *232 * @return AssetSourceModel|null233 */234 public function getSourceById($sourceId)235 {236 // Temporary source?237 if (is_null($sourceId))238 {239 $source = new AssetSourceModel();240 $source->id = $sourceId;241 $source->name = TempAssetSourceType::sourceName;242 $source->type = TempAssetSourceType::sourceType;243 $source->settings = array('path' => craft()->path->getAssetsTempSourcePath(), 'url' => rtrim(UrlHelper::getResourceUrl(), '/').'/tempassets/');244 return $source;245 }246 else247 {248 // If we've already fetched all sources we can save ourselves a trip to the DB for source IDs that don't249 // exist250 if (!$this->_fetchedAllSources &&251 (!isset($this->_sourcesById) || !array_key_exists($sourceId, $this->_sourcesById))252 )253 {254 $result = $this->_createSourceQuery()255 ->where('id = :id', array(':id' => $sourceId))256 ->queryRow();257 if ($result)258 {259 $source = $this->_populateSource($result);260 }261 else262 {263 $source = null;264 }265 $this->_sourcesById[$sourceId] = $source;266 }267 if (!empty($this->_sourcesById[$sourceId]))268 {269 return $this->_sourcesById[$sourceId];270 }271 }272 }273 /**274 * Saves an asset source.275 *276 * @param AssetSourceModel $source277 *278 * @throws \Exception279 * @return bool280 */281 public function saveSource(AssetSourceModel $source)282 {283 $sourceRecord = $this->_getSourceRecordById($source->id);284 $isNewSource = $sourceRecord->isNewRecord();285 if (!$isNewSource)286 {287 $oldSource = AssetSourceModel::populateModel($sourceRecord);288 }289 $sourceRecord->name = $source->name;290 $sourceRecord->handle = $source->handle;291 $sourceRecord->type = $source->type;292 $sourceRecord->fieldLayoutId = $source->fieldLayoutId;293 $sourceType = $this->populateSourceType($source);294 $processedSettings = $sourceType->prepSettings($source->settings);295 $sourceRecord->settings = $source->settings = $processedSettings;296 $sourceType->setSettings($processedSettings);297 $recordValidates = $sourceRecord->validate();298 $settingsValidate = $sourceType->getSettings()->validate();299 $sourceErrors = $sourceType->getSourceErrors();300 if ($recordValidates && $settingsValidate && empty($sourceErrors))301 {302 $transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null;303 try304 {305 if ($isNewSource)306 {307 // Set the sort order308 $maxSortOrder = craft()->db->createCommand()309 ->select('max(sortOrder)')310 ->from('assetsources')311 ->queryScalar();312 $sourceRecord->sortOrder = $maxSortOrder + 1;313 }314 if (!$isNewSource && $oldSource->fieldLayoutId)315 {316 // Drop the old field layout317 craft()->fields->deleteLayoutById($oldSource->fieldLayoutId);318 }319 // Save the new one320 $fieldLayout = $source->getFieldLayout();321 craft()->fields->saveLayout($fieldLayout);322 // Update the source record/model with the new layout ID323 $source->fieldLayoutId = $fieldLayout->id;324 $sourceRecord->fieldLayoutId = $fieldLayout->id;325 // Save the source326 $sourceRecord->save(false);327 if ($isNewSource)328 {329 // Now that we have a source ID, save it on the model330 $source->id = $sourceRecord->id;331 }332 else333 {334 // Update the top folder's name with the source's new name335 $topFolder = craft()->assets->findFolder(array('sourceId' => $source->id, 'parentId' => ':empty:'));336 if ($topFolder->name != $source->name)337 {338 $topFolder->name = $source->name;339 craft()->assets->storeFolder($topFolder);340 }341 }342 craft()->assetIndexing->ensureTopFolder($source);343 if ($transaction !== null)344 {345 $transaction->commit();346 }347 }348 catch (\Exception $e)349 {350 if ($transaction !== null)351 {352 $transaction->rollback();353 }354 throw $e;355 }356 if ($isNewSource && $this->_fetchedAllSources)357 {358 $this->_sourcesById[$source->id] = $source;359 }360 if (isset($this->_viewableSourceIds))361 {362 if (craft()->userSession->checkPermission('viewAssetSource:'.$source->id))363 {364 $this->_viewableSourceIds[] = $source->id;365 }366 }367 return true;368 }369 else370 {371 $source->addErrors($sourceRecord->getErrors());372 $source->addSettingErrors($sourceType->getSettings()->getErrors());373 $source->addSettingErrors($sourceErrors);374 return false;375 }376 }377 /**378 * Reorders asset sources.379 *380 * @param array $sourceIds381 *382 * @throws \Exception383 * @return bool384 */385 public function reorderSources($sourceIds)386 {387 $transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null;388 try389 {390 foreach ($sourceIds as $sourceOrder => $sourceId)391 {392 $sourceRecord = $this->_getSourceRecordById($sourceId);393 $sourceRecord->sortOrder = $sourceOrder+1;394 $sourceRecord->save();395 }396 if ($transaction !== null)397 {398 $transaction->commit();399 }400 }401 catch (\Exception $e)402 {403 if ($transaction !== null)404 {405 $transaction->rollback();406 }407 throw $e;408 }409 return true;410 }411 /**412 * Deletes an asset source by its ID.413 *414 * @param int $sourceId415 *416 * @throws \Exception417 * @return bool418 */419 public function deleteSourceById($sourceId)420 {421 if (!$sourceId)422 {423 return false;424 }425 $transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null;426 try427 {428 // Grab the asset file ids so we can clean the elements table.429 $assetFileIds = craft()->db->createCommand()430 ->select('id')431 ->from('assetfiles')432 ->where(array('sourceId' => $sourceId))433 ->queryColumn();434 craft()->elements->deleteElementById($assetFileIds);435 // Nuke the asset source.436 $affectedRows = craft()->db->createCommand()->delete('assetsources', array('id' => $sourceId));437 if ($transaction !== null)438 {439 $transaction->commit();440 }441 return (bool) $affectedRows;442 }443 catch (\Exception $e)444 {445 if ($transaction !== null)446 {447 $transaction->rollback();448 }449 throw $e;450 }451 }452 // Private Methods453 // =========================================================================454 /**455 * Returns a DbCommand object prepped for retrieving sources.456 *457 * @return DbCommand458 */459 private function _createSourceQuery()460 {461 return craft()->db->createCommand()462 ->select('id, fieldLayoutId, name, handle, type, settings, sortOrder')463 ->from('assetsources')464 ->order('sortOrder');465 }466 /**467 * Populates a source from its DB result.468 *469 * @param array $result470 *471 * @return AssetSourceModel472 */473 private function _populateSource($result)474 {475 if ($result['settings'])476 {477 $result['settings'] = JsonHelper::decode($result['settings']);478 }479 return new AssetSourceModel($result);480 }481 /**482 * Gets a source's record.483 *484 * @param int $sourceId485 *486 * @throws Exception487 * @return AssetSourceRecord488 */489 private function _getSourceRecordById($sourceId = null)490 {491 if ($sourceId)492 {493 $sourceRecord = AssetSourceRecord::model()->findById($sourceId);494 if (!$sourceRecord)495 {496 throw new Exception(Craft::t('No source exists with the ID “{id}”.', array('id' => $sourceId)));497 }498 }499 else500 {501 $sourceRecord = new AssetSourceRecord();502 }503 return $sourceRecord;504 }505}...

Full Screen

Full Screen

search_aggs_metrics_top_hits.go

Source:search_aggs_metrics_top_hits.go Github

copy

Full Screen

1// Copyright 2012-2015 Oliver Eilhard. All rights reserved.2// Use of this source code is governed by a MIT-license.3// See http://olivere.mit-license.org/license.txt for details.45package elastic67// TopHitsAggregation keeps track of the most relevant document8// being aggregated. This aggregator is intended to be used as a9// sub aggregator, so that the top matching documents10// can be aggregated per bucket.11//12// It can effectively be used to group result sets by certain fields via13// a bucket aggregator. One or more bucket aggregators determines by14// which properties a result set get sliced into.15//16// See: http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations-metrics-top-hits-aggregation.html17type TopHitsAggregation struct {18 searchSource *SearchSource19}2021func NewTopHitsAggregation() *TopHitsAggregation {22 return &TopHitsAggregation{23 searchSource: NewSearchSource(),24 }25}2627func (a *TopHitsAggregation) From(from int) *TopHitsAggregation {28 a.searchSource = a.searchSource.From(from)29 return a30}3132func (a *TopHitsAggregation) Size(size int) *TopHitsAggregation {33 a.searchSource = a.searchSource.Size(size)34 return a35}3637func (a *TopHitsAggregation) TrackScores(trackScores bool) *TopHitsAggregation {38 a.searchSource = a.searchSource.TrackScores(trackScores)39 return a40}4142func (a *TopHitsAggregation) Explain(explain bool) *TopHitsAggregation {43 a.searchSource = a.searchSource.Explain(explain)44 return a45}4647func (a *TopHitsAggregation) Version(version bool) *TopHitsAggregation {48 a.searchSource = a.searchSource.Version(version)49 return a50}5152func (a *TopHitsAggregation) NoFields() *TopHitsAggregation {53 a.searchSource = a.searchSource.NoFields()54 return a55}5657func (a *TopHitsAggregation) FetchSource(fetchSource bool) *TopHitsAggregation {58 a.searchSource = a.searchSource.FetchSource(fetchSource)59 return a60}6162func (a *TopHitsAggregation) FetchSourceContext(fetchSourceContext *FetchSourceContext) *TopHitsAggregation {63 a.searchSource = a.searchSource.FetchSourceContext(fetchSourceContext)64 return a65}6667func (a *TopHitsAggregation) FieldDataFields(fieldDataFields ...string) *TopHitsAggregation {68 a.searchSource = a.searchSource.FieldDataFields(fieldDataFields...)69 return a70}7172func (a *TopHitsAggregation) FieldDataField(fieldDataField string) *TopHitsAggregation {73 a.searchSource = a.searchSource.FieldDataField(fieldDataField)74 return a75}7677func (a *TopHitsAggregation) ScriptFields(scriptFields ...*ScriptField) *TopHitsAggregation {78 a.searchSource = a.searchSource.ScriptFields(scriptFields...)79 return a80}8182func (a *TopHitsAggregation) ScriptField(scriptField *ScriptField) *TopHitsAggregation {83 a.searchSource = a.searchSource.ScriptField(scriptField)84 return a85}8687func (a *TopHitsAggregation) Sort(field string, ascending bool) *TopHitsAggregation {88 a.searchSource = a.searchSource.Sort(field, ascending)89 return a90}9192func (a *TopHitsAggregation) SortWithInfo(info SortInfo) *TopHitsAggregation {93 a.searchSource = a.searchSource.SortWithInfo(info)94 return a95}9697func (a *TopHitsAggregation) SortBy(sorter ...Sorter) *TopHitsAggregation {98 a.searchSource = a.searchSource.SortBy(sorter...)99 return a100}101102func (a *TopHitsAggregation) Highlight(highlight *Highlight) *TopHitsAggregation {103 a.searchSource = a.searchSource.Highlight(highlight)104 return a105}106107func (a *TopHitsAggregation) Highlighter() *Highlight {108 return a.searchSource.Highlighter()109}110111func (a *TopHitsAggregation) Source() (interface{}, error) {112 // Example:113 // {114 // "aggs": {115 // "top_tag_hits": {116 // "top_hits": {117 // "sort": [118 // {119 // "last_activity_date": {120 // "order": "desc"121 // }122 // }123 // ],124 // "_source": {125 // "include": [126 // "title"127 // ]128 // },129 // "size" : 1130 // }131 // }132 // }133 // }134 // This method returns only the { "top_hits" : { ... } } part.135136 source := make(map[string]interface{})137 src, err := a.searchSource.Source()138 if err != nil {139 return nil, err140 }141 source["top_hits"] = src142 return source, nil143} ...

Full Screen

Full Screen

smarty_internal_resource_registered.php

Source:smarty_internal_resource_registered.php Github

copy

Full Screen

1<?php2/**3 * Smarty Internal Plugin Resource Registered4 *5 * @package Smarty6 * @subpackage TemplateResources7 * @author Uwe Tews8 * @author Rodney Rehm9 */10/**11 * Smarty Internal Plugin Resource Registered12 * Implements the registered resource for Smarty template13 *14 * @package Smarty15 * @subpackage TemplateResources16 * @deprecated17 */18class Smarty_Internal_Resource_Registered extends Smarty_Resource19{20 /**21 * populate Source Object with meta data from Resource22 *23 * @param Smarty_Template_Source $source source object24 * @param Smarty_Internal_Template $_template template object25 *26 * @return void27 */28 public function populate(Smarty_Template_Source $source, Smarty_Internal_Template $_template = null)29 {30 $source->filepath = $source->type . ':' . $source->name;31 $source->uid = sha1($source->filepath);32 if ($source->smarty->compile_check) {33 $source->timestamp = $this->getTemplateTimestamp($source);34 $source->exists = !!$source->timestamp;35 }36 }37 /**38 * populate Source Object with timestamp and exists from Resource39 *40 * @param Smarty_Template_Source $source source object41 *42 * @return void43 */44 public function populateTimestamp(Smarty_Template_Source $source)45 {46 $source->timestamp = $this->getTemplateTimestamp($source);47 $source->exists = !!$source->timestamp;48 }49 /**50 * Get timestamp (epoch) the template source was modified51 *52 * @param Smarty_Template_Source $source source object53 *54 * @return integer|boolean timestamp (epoch) the template was modified, false if resources has no timestamp55 */56 public function getTemplateTimestamp(Smarty_Template_Source $source)57 {58 // return timestamp59 $time_stamp = false;60 call_user_func_array($source->smarty->registered_resources[$source->type][0][1], array($source->name, &$time_stamp, $source->smarty));61 return is_numeric($time_stamp) ? (int) $time_stamp : $time_stamp;62 }63 /**64 * Load template's source by invoking the registered callback into current template object65 *66 * @param Smarty_Template_Source $source source object67 *68 * @return string template source69 * @throws SmartyException if source cannot be loaded70 */71 public function getContent(Smarty_Template_Source $source)72 {73 // return template string74 $t = call_user_func_array($source->smarty->registered_resources[$source->type][0][0], array($source->name, &$source->content, $source->smarty));75 if (is_bool($t) && !$t) {76 throw new SmartyException("Unable to read template {$source->type} '{$source->name}'");77 }78 return $source->content;79 }80 /**81 * Determine basename for compiled filename82 *83 * @param Smarty_Template_Source $source source object84 *85 * @return string resource's basename86 */87 protected function getBasename(Smarty_Template_Source $source)88 {89 return basename($source->name);90 }91}...

Full Screen

Full Screen

main.go

Source:main.go Github

copy

Full Screen

1package main2import "fmt"3// StringPair consists of source and target strings4type StringPair struct {5 Source string6 Target string7}8func main() {9 strs := []StringPair{10 StringPair{"oliver", "olivia"},11 StringPair{"oliver", "olive"},12 StringPair{"oliver", "oirlve"},13 StringPair{"oliver", "revilo"},14 }15 for _, s := range strs {16 fmt.Println(s.Source, s.Target, LevenshteinDistanceRecur(s.Source, s.Target), LevenshteinDistanceOptimized(s.Source, s.Target))17 }18}19// LevenshteinDistanceOptimized has time complexity of len(s)*len(t) and needs space of len(t)20func LevenshteinDistanceOptimized(source, target string) int {21 if source == target {22 return 023 }24 if len(source) == 0 {25 return len(target)26 }27 if len(target) == 0 {28 return len(source)29 }30 row := make([]int, len(target)+1)31 for j := 0; j <= len(target); j++ {32 row[j] = j33 }34 for i := 1; i <= len(source); i++ {35 last := i36 for j := 1; j <= len(target); j++ {37 cost := 138 if source[i-1] == target[j-1] {39 cost = 040 }41 temp := MinInt(row[j]+1, last+1, row[j-1]+cost)42 row[j-1] = last43 last = temp44 }45 row[len(target)] = last46 }47 return row[len(target)]48}49// LevenshteinDistance has time complexity of len(s)*len(t) and needs space of len(s)*len(t)50func LevenshteinDistance(source, target string) int {51 f := make([][]int, len(source)+1)52 for i := 0; i <= len(source); i++ {53 f[i] = make([]int, len(target)+1)54 }55 for i := 1; i <= len(source); i++ {56 f[i][0] = i57 }58 for j := 1; j <= len(target); j++ {59 f[0][j] = j60 }61 for i := 1; i <= len(source); i++ {62 for j := 1; j <= len(target); j++ {63 //fmt.Println(i, j)64 cost := 165 if source[i-1] == target[j-1] {66 cost = 067 }68 f[i][j] = MinInt(f[i-1][j]+1, f[i][j-1]+1, f[i-1][j-1]+cost)69 }70 }71 return f[len(source)][len(target)]72}73// LevenshteinDistanceRecur has time complexity of 3^(len(s)+len(t))74func LevenshteinDistanceRecur(source, target string) int {75 if len(source) == 0 {76 return len(target)77 }78 if len(target) == 0 {79 return len(source)80 }81 cost := 182 if source[len(source)-1] == target[len(target)-1] {83 cost = 084 }85 return MinInt(86 LevenshteinDistanceRecur(source[:len(source)-1], target)+1,87 LevenshteinDistanceRecur(source, target[:len(target)-1])+1,88 LevenshteinDistanceRecur(source[:len(source)-1], target[:len(target)-1])+cost)89}90// MinInt returns the minimum one among multiple integer values91func MinInt(v1 int, v ...int) int {92 min := v193 for _, v := range v {94 if v < min {95 min = v96 }97 }98 return min99}...

Full Screen

Full Screen

fetch_source_context.go

Source:fetch_source_context.go Github

copy

Full Screen

1// Copyright 2012-2015 Oliver Eilhard. All rights reserved.2// Use of this source code is governed by a MIT-license.3// See http://olivere.mit-license.org/license.txt for details.45package elastic67import (8 "net/url"9 "strings"10)1112type FetchSourceContext struct {13 fetchSource bool14 transformSource bool15 includes []string16 excludes []string17}1819func NewFetchSourceContext(fetchSource bool) *FetchSourceContext {20 return &FetchSourceContext{21 fetchSource: fetchSource,22 includes: make([]string, 0),23 excludes: make([]string, 0),24 }25}2627func (fsc *FetchSourceContext) FetchSource() bool {28 return fsc.fetchSource29}3031func (fsc *FetchSourceContext) SetFetchSource(fetchSource bool) {32 fsc.fetchSource = fetchSource33}3435func (fsc *FetchSourceContext) Include(includes ...string) *FetchSourceContext {36 fsc.includes = append(fsc.includes, includes...)37 return fsc38}3940func (fsc *FetchSourceContext) Exclude(excludes ...string) *FetchSourceContext {41 fsc.excludes = append(fsc.excludes, excludes...)42 return fsc43}4445func (fsc *FetchSourceContext) TransformSource(transformSource bool) *FetchSourceContext {46 fsc.transformSource = transformSource47 return fsc48}4950func (fsc *FetchSourceContext) Source() (interface{}, error) {51 if !fsc.fetchSource {52 return false, nil53 }54 return map[string]interface{}{55 "includes": fsc.includes,56 "excludes": fsc.excludes,57 }, nil58}5960// Query returns the parameters in a form suitable for a URL query string.61func (fsc *FetchSourceContext) Query() url.Values {62 params := url.Values{}63 if !fsc.fetchSource {64 params.Add("_source", "false")65 return params66 }67 if len(fsc.includes) > 0 {68 params.Add("_source_include", strings.Join(fsc.includes, ","))69 }70 if len(fsc.excludes) > 0 {71 params.Add("_source_exclude", strings.Join(fsc.excludes, ","))72 }73 return params74} ...

Full Screen

Full Screen

source

Using AI Code Generation

copy

Full Screen

1use \mageekguy\atoum;2use \mageekguy\atoum;3use \mageekguy\atoum;4use \mageekguy\atoum;5use \mageekguy\atoum;6use \mageekguy\atoum;7use \mageekguy\atoum;8use \mageekguy\atoum;9use \mageekguy\atoum;10use \mageekguy\atoum;11use \mageekguy\atoum;12use \mageekguy\atoum;13use \mageekguy\atoum;14use \mageekguy\atoum;15use \mageekguy\atoum;16use \mageekguy\atoum;17use \mageekguy\atoum;18use \mageekguy\atoum;19use \mageekguy\atoum;20use \mageekguy\atoum;

Full Screen

Full Screen

source

Using AI Code Generation

copy

Full Screen

1$atoumPath = __DIR__ . '/vendor/atoum/atoum/classes/';2require_once $atoumPath . 'mageekguy/atoum/source.class.php';3require_once $atoumPath . 'mageekguy/atoum/adapter.class.php';4require_once $atoumPath . 'mageekguy/atoum/report.class.php';5require_once $atoumPath . 'mageekguy/atoum/report/field.class.php';6require_once $atoumPath . 'mageekguy/atoum/report/fields.class.php';7require_once $atoumPath . 'mageekguy/atoum/report/fields/runner.class.php';8require_once $atoumPath . 'mageekguy/atoum/report/fields/test.class.php';9require_once $atoumPath . 'mageekguy/atoum/report/fields/case.class.php';10require_once $atoumPath . 'mageekguy/atoum/report/fields/coverage.class.php';11require_once $atoumPath . 'mageekguy/atoum/report/fields/runner/execute.class.php';12require_once $atoumPath . 'mageekguy/atoum/report/fields/runner/stop.class.php';13require_once $atoumPath . 'mageekguy/atoum/report/fields/runner/start.class.php';14require_once $atoumPath . 'mageekguy/atoum/report/fields/runner/exception.class.php';15require_once $atoumPath . 'mageekguy/atoum/report/fields/runner/terminate.class.php';16require_once $atoumPath . 'mageekguy/atoum/report/fields/runner/timeout.class.php';17require_once $atoumPath . 'mageekguy/atoum/report/fields/test/exception.class.php';18require_once $atoumPath . 'mageekguy/atoum/report/fields/test/fail.class.php';19require_once $atoumPath . 'mageekguy/atoum/report/fields/test/uncompleted.class.php';20require_once $atoumPath . 'mageekguy/atoum/report/fields/test/error.class.php';

Full Screen

Full Screen

source

Using AI Code Generation

copy

Full Screen

1require_once 'atoum.php';2use atoum\atoum;3use atoum\atoum\test;4use atoum\atoum\test\assertion;5use atoum\atoum\test\assertion\manager;6use atoum\atoum\test\assertion\manager\php;7use atoum\atoum\test\assertion\manager\php\casters;8use atoum\atoum\test\assertion\manager\php\casters\variable;9use atoum\atoum\test\assertion\manager\php\casters\variable\object;10use atoum\atoum\test\assertion\manager\php\casters\variable\string;11use atoum\atoum\test\assertion\manager\php\casters\variable\scalar;12use atoum\atoum\test\assertion\manager\php\casters\variable\resource;13use atoum\atoum\test\assertion\manager\php\casters\variable\null;14use atoum\atoum\test\assertion\manager\php\casters\variable\boolean;15use atoum\atoum\test\assertion\manager\php\casters\variable\array;16use atoum\atoum\test\assertion\manager\php\casters\variable\array\value;

Full Screen

Full Screen

source

Using AI Code Generation

copy

Full Screen

1use mageekguy\atoum;2{3 public function testAdd()4 {5 $this->assert('test add')6 ->if($obj = new calculator())7 ->integer($obj->add(1, 1))->isIdenticalTo(2);8 }9}10use mageekguy\atoum;11{12 public function testSub()13 {14 $this->assert('test sub')15 ->if($obj = new calculator())16 ->integer($obj->sub(1, 1))->isIdenticalTo(0);17 }18}19use mageekguy\atoum;20{21 public function testMul()22 {23 $this->assert('test mul')24 ->if($obj = new calculator())25 ->integer($obj->mul(1, 1))->isIdenticalTo(1);26 }27}28use mageekguy\atoum;29{30 public function testDiv()31 {32 $this->assert('test div')33 ->if($obj = new calculator())34 ->integer($obj->div(1, 1))->isIdenticalTo(1);35 }36}37use mageekguy\atoum;38{39 public function testMod()40 {41 $this->assert('test mod')42 ->if($obj = new calculator())43 ->integer($obj->mod(1, 1))->isIdenticalTo(0);44 }45}

Full Screen

Full Screen

source

Using AI Code Generation

copy

Full Screen

1use Atoum\Source;2$source = new Source();3$source->setPath('1.php');4$source->read();5var_dump($source->getLines());6use Atoum\Source;7$source = new Source();8$source->setPath('1.php');9$source->read();10var_dump($source->getLines());11$source->setPath('1.php');12$source->read();13var_dump($source->getLines());14$source->setPath('1.php');15$source->read();16var_dump($source->getLines());17$source->setPath('1.php');18$source->read();19var_dump($source->getLines());20$source->setPath('1.php');21$source->read();22var_dump($source->getLines());23$source->setPath('1.php');24$source->read();25var_dump($source->getLines());26$source->setPath('1.php');27$source->read();28var_dump($source->getLines());29$source->setPath('1.php');30$source->read();31var_dump($source->getLines());32$source->setPath('1.php');33$source->read();34var_dump($source->getLines());35$source->setPath('1.php');36$source->read();37var_dump($source->getLines());38$source->setPath('1.php');39$source->read();40var_dump($source->getLines());41$source->setPath('1.php');42$source->read();43var_dump($source->getLines());44$source->setPath('1.php');45$source->read();46var_dump($source->getLines());47$source->setPath('1.php');48$source->read();49var_dump($source->getLines());50$source->setPath('1.php');51$source->read();52var_dump($source->getLines());53$source->setPath('1.php');54$source->read();55var_dump($source->getLines());56$source->setPath('1.php');57$source->read();58var_dump($source->getLines());59$source->setPath('1.php');60$source->read();61var_dump($source->getLines());62$source->setPath('1.php');63$source->read();64var_dump($source->getLines());65$source->setPath('1.php');66$source->read();

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Atoum automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful