Created by manthanhd on 17/10/2016.
513326
function DefaultSkillResolutionStrategyFn() {
    const util = require('util');
    const extend = util._extend;
    const skillsMap = {};
    const undefinedSkills = [];

    this.addSkill = function(skill, options) {
        var minConfidence = 0;
        if(options instanceof Number) {
            minConfidence = options;
        } else if (options && options.minConfidence !== undefined) {
            minConfidence = options.minConfidence;
        }

        var skillClone = extend({}, skill);
        var botSkillObject = {skill: skillClone, minConfidence: minConfidence};

        if (skillClone.topic === undefined || skillClone.topic === 'undefined') {
            skillClone.topic = undefined;
            undefinedSkills.push(botSkillObject);
        }

        if(skillClone.topic instanceof Array) {
            skillClone.topic.forEach(function(topic) {
                if(skillsMap[topic] === undefined) skillsMap[topic] = [];
                skillsMap[topic].push(skillClone);
            });
        } else {
            if (skillsMap[skillClone.topic] === undefined) {
                skillsMap[skillClone.topic] = [];
            }

            skillsMap[skillClone.topic].push(botSkillObject);
        }
    };

    this.getSkills = function() {
        var topics = Object.keys(skillsMap);
        var skills = [];

        topics.forEach(function (topic) {
            skills.push(skillsMap[topic]);
        });

        return skills;
    };

    var _resolveSkillFromTopicWithConfidence = function ResolveSkillFromTopicWithConfidenceFn(topic) {
        if (topic.name === undefined) {
            if (undefinedSkills && undefinedSkills.length > 0) {
                return undefinedSkills[0];
            }

            return;
        }

        var botSkills = skillsMap[topic.name];
        var minConfidenceSkill = undefinedSkills[0];
        var minDistance = 999;
        if (botSkills !== undefined && botSkills.length > 0) {
            for (var i = 0; i < botSkills.length; i++) {
                var botSkill = botSkills[i];
                var distance = topic.confidence - botSkill.minConfidence;
                if (distance < 0) continue;
                if (distance < minDistance) {
                    minDistance = distance;
                    minConfidenceSkill = botSkill;
                }
                if (distance === 0) break;
            }
        }

        return minConfidenceSkill;
    };

    this.resolve = function(err, resolutionContext, callback) {
        var topics = resolutionContext.topics;
        var sentence = resolutionContext.sentence;
        var mostConfidentTopic = topics[0];
        var resolvedBotSkill = _resolveSkillFromTopicWithConfidence(mostConfidentTopic);
        var skill = resolvedBotSkill ? resolvedBotSkill.skill : undefined;

        if (skill === undefined) {
            return callback(new Error("could not resolve any skills"));
        }

        var clonedSkill = extend({}, skill);
        clonedSkill.sentence = sentence;
        clonedSkill.topic = mostConfidentTopic;

        return callback(undefined, clonedSkill);
    };

    return this;
}
1306807
function f_nesne_idleri(_olay, _tahta_id) {
        return f_olaya_uygun_idler(_olay)
            .then(function (_cekilen_idler) {
                if (_cekilen_idler && _cekilen_idler.length > 0) {
                    switch (_olay) {
                        case schema.SABIT.OLAY.IHALE_EKLENDI:
                        case schema.SABIT.OLAY.IHALE_GUNCELLENDI:
                        case schema.SABIT.OLAY.IHALE_SILINDI:
                        case schema.SABIT.OLAY.IHALE_TARIHI_ERTELENDI:
                        {
                            var db_ihale = require('./db_ihale');
                            return db_ihale.f_db_tahta_ihale_idler_aktif(_tahta_id)
                                .then(function (_ihale_idler) {
                                    return _.intersection(_ihale_idler, _cekilen_idler);
                                });
                        }
                            break;
                        case schema.SABIT.OLAY.KALEM_DURUMU_GUNCELLENDI:
                        case schema.SABIT.OLAY.KALEM_EKLENDI:
                        case schema.SABIT.OLAY.KALEM_GUNCELLENDI:
                        case schema.SABIT.OLAY.KALEM_SILINDI:
                        {
                            var db_kalem = require('./db_kalem');
                            return db_kalem.f_db_tahta_kalem_idler_aktif(_tahta_id)
                                .then(function (_kalem_idler) {
                                    return _.intersection(_kalem_idler, _cekilen_idler);
                                });
                        }
                            break;
                        case schema.SABIT.OLAY.TEKLIF_DURUMU_GUNCELLENDI:
                        case schema.SABIT.OLAY.TEKLIF_EKLENDI:
                        case schema.SABIT.OLAY.TEKLIF_GUNCELLENDI:
                        case schema.SABIT.OLAY.TEKLIF_SILINDI:
                        {
                            var db_tahta = require('./db_tahta');
                            return db_tahta.f_db_tahta_teklif_idleri(_tahta_id)
                                .then(function (_teklif_idler) {
                                    return _.intersection(_teklif_idler, _cekilen_idler);
                                });
                        }
                            break;

                        case schema.SABIT.OLAY.URUN_EKLENDI:
                        case schema.SABIT.OLAY.URUN_GUNCELLENDI:
                        case schema.SABIT.OLAY.URUN_SILINDI:
                        case schema.SABIT.OLAY.URUN_ANAHTAR_EKLENDI:
                        case schema.SABIT.OLAY.URUN_ANAHTAR_SILINDI:
                        {
                            var db_urun = require('./db_urun')
                            return db_urun.f_db_urun_aktif_urun_idleri(_tahta_id)
                                .then(function (_urun_idler) {
                                    return _.intersection(_urun_idler, _cekilen_idler);
                                });
                        }
                            break;

                        case schema.SABIT.OLAY.KURUM_EKLENDI:
                        case schema.SABIT.OLAY.KURUM_GUNCELLENDI:
                        case schema.SABIT.OLAY.KURUM_SILINDI:
                        {
                            var db_kurum = require('./db_kurum');
                            return db_kurum.f_db_aktif_kurum_idleri(_tahta_id)
                                .then(function (_kurum_idler) {
                                    return _.intersection(_kurum_idler, _cekilen_idler);
                                });
                        }
                            break;

                        default:
                            break;
                    }
                } else {
                    return null;
                }
            });
    }
175202
function createTemporaryStorageFolder() {
  fs.mkdir(imageDir, '0775', function(err) {
    if (err && err.code !== 'EEXIST') {
      console.log(err);
      throw new Error(err);
    }
  });
}
1359126
function createFreebusy() {
    $cnt = count( $this->freebusy );
    if( 0 >= $cnt )
      return;
    $output = null;
    foreach( $this->freebusy as $freebusyPart ) {
      $attributes = $content = null;
      if( isset( $freebusyPart['value']['fbtype'] )) {
        $attributes .= $this->intAttrDelimiter.'FBTYPE='.$freebusyPart['value']['fbtype'];
        unset( $freebusyPart['value']['fbtype'] );
        $freebusyPart['value'] = array_values( $freebusyPart['value'] );
      }
      else
        $attributes .= $this->intAttrDelimiter.'FBTYPE=BUSY';
      $attributes .= $this->_createParams( $freebusyPart['params'] );
      $fno = 1;
      $cnt = count( $freebusyPart['value']);
      foreach( $freebusyPart['value'] as $periodix => $freebusyPeriod ) {
        $formatted   = $this->_format_date_time( $freebusyPeriod[0] );
        $content .= $formatted;
        $content .= '/';
        $cnt2 = count( $freebusyPeriod[1]);
        if( array_key_exists( 'year', $freebusyPeriod[1] ))      // date-time
          $cnt2 = 7;
        elseif( array_key_exists( 'week', $freebusyPeriod[1] ))  // duration
          $cnt2 = 5;
        if(( 7 == $cnt2 )   &&    // period=  -> date-time
            isset( $freebusyPeriod[1]['year'] )  &&
            isset( $freebusyPeriod[1]['month'] ) &&
            isset( $freebusyPeriod[1]['day'] )) {
          $content .= $this->_format_date_time( $freebusyPeriod[1] );
        }
        else {                                  // period=  -> dur-time
          $content .= $this->_format_duration( $freebusyPeriod[1] );
        }
        if( $fno < $cnt )
          $content .= ',';
        $fno++;
      }
      $output .= $this->_createElement( 'FREEBUSY', $attributes, $content );
    }
    return $output;
  }
1350220
function (cb) {
            var self = this;
            var dirs = ['classes', 'modules', 'files'];
            if (self.options.dumpview) {
                dirs.push('json');
            }
            var writeRedirect = function (dir, file, cb) {
                Y.Files.exists(file, function (x) {
                    if (x) {
                        var out = path.join(dir, 'index.html');
                        fs.createReadStream(file).pipe(fs.createWriteStream(out));
                    }
                    cb();
                });
            };
            var defaultIndex = path.join(themeDir, 'assets', 'index.html');
            var stack = new Y.Parallel();
            Y.log('Making default directories: ' + dirs.join(','), 'info', 'builder');
            dirs.forEach(function (d) {
                var dir = path.join(self.options.outdir, d);
                Y.Files.exists(dir, stack.add(function (x) {
                    if (!x) {
                        fs.mkdir(dir, 0777, stack.add(function () {
                            writeRedirect(dir, defaultIndex, stack.add(noop));
                        }));
                    } else {
                        writeRedirect(dir, defaultIndex, stack.add(noop));
                    }
                }));
            });
            stack.done(function () {
                if (cb) {
                    cb();
                }
            });
        }
889020
function create (todoList, text) {
  // Hand waving here -- not showing how this interacts with XHR or persistent
  // server-side storage.
  // Using the current timestamp in place of a real id.
  var id = Date.now();
  _todos[id] = {
    id: id,
    todo_list_id: todoList.id,
    complete: false,
    text: text
  };
}
617705
async function createSchema() {
  await knex.schema
    .dropTableIfExists('Person_Movie')
    .dropTableIfExists('Animal')
    .dropTableIfExists('Movie')
    .dropTableIfExists('Person');

  await knex.schema
    .createTable('Person', table => {
      table.increments('id').primary();
      table
        .integer('parentId')
        .unsigned()
        .references('id')
        .inTable('Person');
      table.string('firstName');
      table.string('lastName');
      table.integer('age');
      table.json('address');
    })
    .createTable('Movie', table => {
      table.increments('id').primary();
      table.string('name');
    })
    .createTable('Animal', table => {
      table.increments('id').primary();
      table
        .integer('ownerId')
        .unsigned()
        .references('id')
        .inTable('Person');
      table.string('name');
      table.string('species');
    })
    .createTable('Person_Movie', table => {
      table.increments('id').primary();
      table
        .integer('personId')
        .unsigned()
        .references('id')
        .inTable('Person')
        .onDelete('CASCADE');
      table
        .integer('movieId')
        .unsigned()
        .references('id')
        .inTable('Movie')
        .onDelete('CASCADE');
    });
}
162809
static function __duo($masterfile, $palette = null, $tint = null, array $overrides = null)
	{
		//	THEME vs. SCHEME vs. SKIN
		//	Theme = light/dark! AKA `tint` in the current system ... ie. `What theme would you like?` asking the user to choose a color scheme!
		//	Scheme = `Color Scheme` = club/brand colors = several headers/borders colored with this color scheme
		//	Skin = related to Scheme ... The club/brand skin is the backgrounds, like watermarks, background images representing a club/brand!
		static $basepath = '../app/duo/';
		static $cachepath = '../app/duo/cache/';
		static $duos = array();
		if (!isset($duos[$masterfile])) $duos[$masterfile] = require($basepath . $masterfile . '.php');
		$arr =& $duos[$masterfile];
		$files = array();
		$max_mtime = 0;
		if ($palette === null && $tint === null && $overrides === null)
		{
			if (isset($arr['static']))
				foreach ($arr['static'] as $static)
				{
					$mtime = filemtime($basepath . $static);
					$max_mtime = max($max_mtime, $mtime);
					$files[] = $cachepath . pathinfo($static, PATHINFO_FILENAME) . '-' . $mtime . /* '-' . md5($static) */ '.css';
				}
			$global_md5 = md5(serialize($arr['global']));
			foreach ($arr['themeable'] as $themeable)
			{
				$mtime = filemtime($basepath . $themeable);
				$max_mtime = max($max_mtime, $mtime);
				$files[] = $cachepath . pathinfo($themeable, PATHINFO_FILENAME) . '-' . $mtime . '-' . $global_md5 . '.css';
			}
			$result = 'styles/duo-' . $max_mtime . '-' . md5(serialize($files)) . '.css';
			if (file_exists($result)) return $result;
			//
			//	Global/base style file doesn't exists, create a new one!
			//
			$result_contents = null;	//	contents of the final file!
			require_once APP_LIB . 'duocss.php';
			$index = 0;	//	$files[$index] ... because static messes up the counter! ... can't we just add the count($arr['static']) ???
			if (isset($arr['static']))
				foreach ($arr['static'] as $static)
				{
					if (!file_exists($files[$index]))
					{
						$result_contents .= $contents = minify_css(file_get_contents($basepath . $static));
						file_put_contents($files[$index], $contents);
					}
					else
						$result_contents .= file_get_contents($files[$index]);
					$index++;
				}
			$global_keys = array_keys($arr['global']);	//	Get the global keys for str_replace()
			foreach ($arr['themeable'] as $themeable)
			{
				if (!file_exists($files[$index]))
				{
					$pattern = array();	//	Remove ALL lines with palette styles! Even if they include global styles!
					foreach ($arr['palette'] as $key => $unused)		//	We run the preg_replace() first, because it will reduce the contents, making str_replace() slightly faster!
						$pattern[] = '~[^{;]*' . $key . '[^;}]*;?~';
					//	We need to minify FIRST, because there might be some comments with styles! eg. border: BORDER /* BORDER-OLD */; But there might be other cases that screw up the regular expressions!
					$result_contents .= $contents = minify_css(str_replace($global_keys, $arr['global'], preg_replace($pattern, '', minify_css(file_get_contents($basepath . $themeable)))));
					file_put_contents($files[$index], $contents);
				}
				else
					$result_contents .= file_get_contents($files[$index]);
				$index++;
			}
			file_put_contents($result, $result_contents);
			return $result;
		}
		else
		{
		//	There `should` be too many variables and tints for an array_merge() to be feasable/viable! Also, this cannot account for $arr['palette'][$tint] coming before loading the palette file!
		//	$palettes = $palette === null ? $arr['palette'] : array_merge($arr['palette'], require '../app/duo/palettes/' . $palette . '.php');
			//
			//	Generate Palette
			//
			if ($palette !== null) $palette = require '../app/duo/palettes/' . $palette . '.php';
			//	`$files` is currently a blank array, so we use it as an empty array paceholder
			$palette = array_merge($arr['palette'], isset($arr['tints'][$tint]) ? $arr['tints'][$tint] : $files, isset($palette[0]) ? $palette[0] : $files, isset($palette[$tint]) ? $palette[$tint] : $files, $overrides === null ? $files : $overrides);
			//	Create an md5 hash of the palette. Used as part of the filename in each cached themeable file!
			$palette_md5 = md5(serialize($palette));	//	. serialize($arr['global']) .... DISABLED (the serialize) FOR NOW!  TEST  IT !! The reason why we need to include the global, is in-case a global value changed ... HOWEVER, in that case, wouldn't the files also change ??? However again, we might be using dynamic overrides !?!?
			//	Add each `themeable` file to the files array! To be serialized and md5 hashed later to test the existance of the final file!
			foreach ($arr['themeable'] as $themeable)
			{
				$mtime = filemtime($basepath . $themeable);
				$max_mtime = max($max_mtime, $mtime);
				$files[] = $cachepath . pathinfo($themeable, PATHINFO_FILENAME) . '-' . $mtime . '-' . $palette_md5 . '.css';
			}
			$result = 'styles/duo-' . $max_mtime . '-' . md5(serialize($files)) . '.css';
			if (file_exists($result)) return $result;
			//
			//	Public styled palette doesn't exist; test the existence of each cached themeable file
			//
			$result_contents = null;	//	contents of the final file!
			require_once APP_LIB . 'duocss.php';
			$keys = array_merge(array_keys($arr['global']), array_keys($arr['palette']));	//	Create an array of the merged global and palette keys!
			$keys_md5 = md5(serialize($keys));
			$patterns = array();
			//	Build an array of keys to extract! We will split each file into class names and content, then scan the content for our keys and extract them!
			foreach ($keys as $key)
				$patterns[] = '~[^;]*' . $key . '[^;]*~';
			$global_keys = array_keys($arr['global']);
			$palette_keys = array_keys($palette);
			$palette_patterns = array();
			foreach ($palette_keys as $key)
				$palette_patterns[] = '~[^;]*' . $key . '[^;]*~';	//	Build the palette patterns! Once we split the cached contents into classes and attributes, then we can run these patterns!

			foreach ($arr['themeable'] as $key => $themeable)
			{
				if (!file_exists($files[$key]))
				{	//	First test for the intermediate cached file. This file contains ALL the possible styleable global and palette variables/attributes/styles.
					$mtime = filemtime($basepath . $themeable);
					$filename = pathinfo($themeable, PATHINFO_FILENAME);
					$cache = $cachepath . $filename . '-' . $mtime . '-' . $keys_md5 . '.css';
					if (!file_exists($cache))
					{	//	Create the intermediate cached file with ALL possible overwriteable styles!
						$path = $basepath . $themeable;
						$contents = minify_css(file_get_contents($path));	//	Minify the contents, mainly to remove the comments, because they CAN interfere with the class names and the regular expression matches (because they can contain the following characters {;} !!!
						preg_match_all('~([^{;}]+){([^{}]+)}~', $contents, $split);	//	Split the file into classes and content!	eg. html{overflow:auto} => `html` && `overflow:auto`
						$preserve = array();	//	classes and attributes/styles to preserve, basically we `remove` all the styles which are not configurable (we do this by INCLUDING only valid styleable classes and attributes here)! Leaving only styles that include a global or palette constant!
						foreach ($split[2] as $index => $value)	//	loop through each class and attribute list and extract the customizeable styles!
							foreach ($patterns as $pattern)
								if (preg_match_all($pattern, $value, $matches))	//	our `$patterns` don't actually capture anything, so we are able to use $matches[0]!
									if (isset($preserve[$split[1][$index]]))
										$preserve[$split[1][$index]] .= ';' . implode(';', $matches[0]);
									else
										$preserve[$split[1][$index]] = implode(';', $matches[0]);
						$contents = ''; // reset & rebuild contents with our `preserved` classes and constants!
						foreach ($preserve as $class => $style)
							$contents .= $class . '{' . $style . '}';
						file_put_contents($cache, $contents);
					}
					else
						$contents = file_get_contents($cache);

					//	Now we have the intermediate content, which includes both global and palette styles! Now we need to extract only the styles we need! For example, many `global` styles will be dropped here!
					preg_match_all('~([^{;}]+){([^{}]+)}~', $contents, $split);
					$preserve = array();
					foreach ($split[2] as $index => $value)
						foreach ($palette_patterns as $pattern)
							if (preg_match_all($pattern, $value, $matches))
								if (isset($preserve[$split[1][$index]]))
									$preserve[$split[1][$index]] .= ';' . implode(';', $matches[0]);
								else
									$preserve[$split[1][$index]] = implode(';', $matches[0]);
					$contents = '';	//	rebuild the contents, unused styles should have been removed!?!?
					foreach ($preserve as $class => $style)
						$contents .= $class . '{' . $style . '}';

				/*	//	This is only necessary if we use the str_replace() variant !!!
					if (!env::$production && preg_match_all('|[A-Z]{2,}(?:-[A-Z]{2,})+|', $contents, $matches))
						foreach ($matches[0] as $match)
							if (!isset($palette[$match]))
								die('<b>ERROR</b> finding the CSS variable: <b>' . $match . '</b> in file: <b>' . $themeable);
				*/

					// Now we have rebuilt the content, we need to replace the style placeholders!
					//	First, we replace the PALETTE styles, which could include global style overrides! THEN we place the global styles, if there are any left over! This has to be done if we've mixed palette with global styles! eg. border: BORDER-WIDTH BORDER-COLOR ... where BORDER-WIDTH might be a global, and BORDER-COLOR is a palette value!
				//	$result_contents .= $contents = str_replace($global_keys, $arr['global'], str_replace($palette_keys, $palette, $contents));	//	we `could` run the minifier AGAIN, but it's already 99.9% minified! For example, the placeholders could be unminified eg. `BORDER` => `0 0 0 0` instead of just 0 ... or `0px` instead of 0
					$result_contents .= $contents = preg_replace_callback('|[A-Z]{2,}(?:-[A-Z]{2,})+|', function($matches)use($palette){return $palette[$matches[0]];}, $contents);	// The preg_replace_callback() variant was about 30% faster than str_replace() on a very large file (about +200K)! They still executed at 0.01s vs. 0.007 on a very large file with 30 other files!

					file_put_contents($files[$key], $contents);
				}
				else
					$result_contents .= file_get_contents($files[$key]);
			}

			file_put_contents($result, $result_contents);
			return $result;
		}
	}
432666
def __create_rec(*args, **kwargs):
        '''
        
        '''
        uid = args[0]
        kind = args[1]
        post_data = kwargs['post_data']

        try:
            TabWiki.create(
                uid=uid,
                title=post_data['title'].strip(),
                date=datetime.datetime.now(),
                cnt_html=tools.markdown2html(post_data['cnt_md']),
                time_create=tools.timestamp(),
                user_name=post_data['user_name'],
                cnt_md=tornado.escape.xhtml_escape(post_data['cnt_md']),
                time_update=tools.timestamp(),
                view_count=1,
                kind=kind,  # 1 for wiki,  2 for page
            )
            return True
        except:
            return False
559058
public function create()
    {
        if (!userHasPermission('admin:blog:tag:' . $this->blog->id . ':create')) {

            unauthorised();
        }

        // --------------------------------------------------------------------------

        if ($this->input->post()) {

            $oFormValidation = Factory::service('FormValidation');

            $oFormValidation->set_rules('label', '', 'required');
            $oFormValidation->set_rules('description', '', '');
            $oFormValidation->set_rules('seo_title', '', 'max_length[150]');
            $oFormValidation->set_rules('seo_description', '', 'max_length[300]');
            $oFormValidation->set_rules('seo_keywords', '', 'max_length[150]');

            $oFormValidation->set_message('required', lang('fv_required'));
            $oFormValidation->set_message('max_length', lang('fv_max_length'));

            if ($oFormValidation->run()) {

                $aInsertData                    = array();
                $aInsertData['blog_id']         = $this->blog->id;
                $aInsertData['label']           = $this->input->post('label');
                $aInsertData['description']     = $this->input->post('description');
                $aInsertData['seo_title']       = $this->input->post('seo_title');
                $aInsertData['seo_description'] = $this->input->post('seo_description');
                $aInsertData['seo_keywords']    = $this->input->post('seo_keywords');

                if ($this->blog_tag_model->create($aInsertData)) {

                    $status  = 'success';
                    $message = 'Tag created successfully.';
                    $this->session->set_flashdata($status, $message);
                    redirect('admin/blog/tag/index/' . $this->blog->id . $this->isModal);

                } else {

                    $this->data['error']  = 'There was a problem creating the Tag. ';
                    $this->data['error'] .= $this->blog_tag_model->lastError();
                }

            } else {

                $this->data['error'] = lang('fv_there_were_errors');
            }
        }

        // --------------------------------------------------------------------------

        //  Page data
        $this->data['page']->title = 'Blog &rsaquo; Tags &rsaquo; Create';

        // --------------------------------------------------------------------------

        //  Fetch data
        $this->data['tags'] = $this->blog_tag_model->getAll();

        // --------------------------------------------------------------------------

        //  Load views
        Helper::loadView('edit');
    }
397161
public function createAction()
    {
        if ($this->enableScreens) {
            $edit = false;
            $org  = $this->getRespondent()->getOrganization();
            if (! $org) {
                $org = $this->currentOrganization;
            }

            if ($org) {
                $edit = $org->getRespondentEditScreen();
            }

            if (! $edit) {
                $group = $this->currentUser->getGroup();
                if ($group) {
                    $edit = $group->getRespondentEditScreen();
                }
            }

            if ($edit ) {
                if ($edit instanceof ProcessModelInterface) {
                    $edit->processModel($this->getModel());
                }

                // All are arrays, so easy to set
                $this->createParameters = $edit->getCreateParameters() + $this->createParameters;
                $editSnippets = $edit->getSnippets();
                if (false !== $editSnippets) {
                    $this->createEditSnippets = $editSnippets;
                }
            }
        }

        parent::createAction();
    }
540407
function createMemorySource(initialPathname = "/") {
    let index = 0;
    let states = [];
    let stack = [{
        pathname: initialPathname,
        search: ""
    }];

    let target = {
        // location
        addEventListener(name, fn) {},
        removeEventListener(name, fn) {},
        history: {
            // index
            // entries,
            // state
            back(){},
            pushState(state, _, uri) {
                index++;
                stack.push(uri2obj(uri));
                states.push(state);
                sync(target);
            },
            replaceState(state, _, uri) {
                stack[index] = uri2obj(uri);
                states[index] = state;
                sync(target);
            }
        }
    };

    function sync(target) {
        var history = target.history;
        history.index = index;
        history.entries = stack;
        history.state = states[index];
        target.location = stack[index];
    }
    sync(target);
    return target;
}
242781
function distManhattan(rgb0, rgb1) {
		var rd = Math.abs(rgb1[0]-rgb0[0]),
			gd = Math.abs(rgb1[1]-rgb0[1]),
			bd = Math.abs(rgb1[2]-rgb0[2]);

		return (Pr*rd + Pg*gd + Pb*bd) / manhMax;
	}
628531
@Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(cn.leancloud.sample.R.layout.main);

    setupAVOSCloud(false);
    setupGroupAdapter();
  }
1149856
function createAtlas(width, height, name, repeat) {
         return {
           "meta": {
             "app": "melonJS",
             "size": {
               "w": width,
               "h": height
             },
             "repeat": repeat || "no-repeat",
             "image": "default"
           },
           "frames": [{
             "filename": name || "default",
             "frame": {
               "x": 0,
               "y": 0,
               "w": width,
               "h": height
             }
           }]
         };
       }
662359
function samlCreateId() 
   {
      $rndChars = 'abcdefghijklmnop';
      $rndId = '';
      for ($i = 0; $i < 40; $i++ ) {
         $rndId .= $rndChars[rand(0,strlen($rndChars)-1)];
      }
      return $rndId;
   }
887101
public function CreatePage() 
	{
		parent::CreatePage(); // Doesnt necessary get PX, because PX is protected!
		
		$deleteMode = false;
		
		//Strings
		$action = strtolower($this->_action);
		$id = $this->_context->get("id");
		$group = $this->_context->get("group");
		$contents = "";
		$titleIndex = $this->_context->get("titleIndex");		
		$summaryIndex = $this->_context->get("summaryIndex");
		$groupKeyword = $this->_context->get("groupKeyword");

		$myWords = $this->WordCollection();
		$this->setHelp($myWords->Value("DESCRIPTION"));
		$this->setTitlePage($myWords->Value("TITLE"));
		
		//XmlNode 
		$block = $this->_px->addBlockCenter($myWords->Value("WORKINGAREA"));

		$this->addMenuOption($myWords->Value("TXT_BACK"), "module:Xmlnuke.Admin.ListXML");
		/*
		XmlNode paragraph;
		XmlNode form;
		XmlNode boxButton;
		XmlNode editNode; // (For Index)
		processor.XMLFilenameProcessor xmlFile;
		*/

		// Open Index File
		$indexFile = new XMLFilenameProcessor("index");
		//XmlDocument 
		
		$index = $this->_context->getXMLDataBase()->getDocument($indexFile->FullQualifiedName(),null);

		// --------------------------------------
		// CHECK ACTION
		// --------------------------------------
		
		if ( ($action == "edit") || ($action == "new") )
		{
			$contents = $this->_context->get("contents");				
			$contents = stripslashes($contents);
			$this->_context->setSession("texto", $contents); 
			
			/*echo "<PRE>";
			echo htmlentities($contents);
			echo "</PRE>";*/
			
			try
			{
				$title = "";
				$summary = "";
				//XmlNode $node;

				// Get edited XML and update info about INDEX.
				//XmlDocument
				$xml = XmlUtil::CreateXmlDocumentFromStr($contents);

				//$node = XmlUtil::SelectSingleNode($xml->documentElement, "/page/meta/title");
				$node = XmlUtil::SelectSingleNode($xml->documentElement, "meta/title");
				if ($node != null)
				{
					$title = $node->nodeValue;
				}
				//$node = XmlUtil::SelectSingleNode($xml->documentElement,"/page/meta/abstract");
				$node = XmlUtil::SelectSingleNode($xml->documentElement,"meta/abstract");
				if ($node != null)
				{
					$summary = $node->nodeValue;
				}
				//$node = XmlUtil::SelectSingleNode($xml->documentElement,"/page/meta/modified");
				$node = XmlUtil::SelectSingleNode($xml->documentElement,"meta/modified");
				if ($node != null)
				{
					$node->nodeValue = date("D M j Y G:i:s");
				}
				//$node = XmlUtil::SelectSingleNode($xml->documentElement,"/page/meta/groupkeyword");
				$node = XmlUtil::SelectSingleNode($xml->documentElement,"meta/groupkeyword");
				
				if ($node != null)
				{
					$node->nodeValue = $groupKeyword;
				}

				if ($id != "_all")
				{
					if ($action == "edit")
					{
						//$editNode = XmlUtil::SelectSingleNode($index->documentElement, "/xmlindex/group[id='" . $group . "']/page[id='" . $id . "']");
						$editNode = XmlUtil::SelectSingleNode($index->documentElement, "group[id='" . $group . "']/page[id='" . $id . "']");
						if ($titleIndex == "")
						{
							$titleIndex = $title;
						}
						XmlUtil::SelectSingleNode($editNode,"title")->nodeValue = $titleIndex;

						if ($summaryIndex == "")
						{
							$summaryIndex = $summary;
						}
						XmlUtil::SelectSingleNode($editNode,"summary")->nodeValue = $summaryIndex;
					}
					else
					{
						
						//$editNode = XmlUtil::SelectSingleNode($index->documentElement,"/xmlindex/group[id='" . $group . "']");		
						$editNode = XmlUtil::SelectSingleNode($index->documentElement,"group[id='" . $group . "']");
						$newNode = XmlUtil::CreateChild($editNode, "page", "");
						XmlUtil::CreateChild($newNode, "id", $id);
						XmlUtil::CreateChild($newNode, "title", $title);
						XmlUtil::CreateChild($newNode, "summary", $summary);
						$titleIndex = $title;
						$summaryIndex = $summary;
					}
				}

				$xmlFile = new XMLFilenameProcessor($id);
					
				$this->_context->getXMLDataBase()->saveDocumentXML($xmlFile->FullQualifiedName(), $xml);
				$this->_context->getXMLDataBase()->saveDocumentXML($indexFile->FullQualifiedName(), $index);
				$this->_context->getXMLDataBase()->saveIndex();
				$paragraph = $this->_px->addParagraph($block);
				FileUtil::DeleteFilesFromPath($this->_cacheFile);
				FileUtil::DeleteFilesFromPath(new XSLCacheFilenameProcessor(""));
				$this->_px->addBold($paragraph, $myWords->Value("SAVED"));
			}
			//catch (XmlException ex)
			catch (Exception $ex)
			{
				
				$paragraph = $this->_px->addParagraph($block);
				$this->_px->AddErrorMessage($paragraph, $contents, $ex);
			}
		}

		// Get the group from the Index and Update Edit Fields
		//$editNode = XmlUtil::SelectSingleNode( $index->documentElement,"/xmlindex/group[page[id='" . $id . "']]/id");
		$editNode = XmlUtil::SelectSingleNode( $index->documentElement,"group[page[id='" . $id . "']]/id");
		if ($editNode != null)
		{
			$group = $editNode->nodeValue;
			//$editNode = XmlUtil::SelectSingleNode($index->documentElement,"/xmlindex/group[id='" . $group . "']/page[id='" . $id . "']");
			$editNode = XmlUtil::SelectSingleNode($index->documentElement,"group[id='" . $group . "']/page[id='" . $id . "']");
			$titleIndex = XmlUtil::SelectSingleNode($editNode,"title")->nodeValue;
			$summaryIndex = XmlUtil::SelectSingleNode($editNode,"summary")->nodeValue;
		}
		
		if ($action == "delete")
		{
			$paragraph = $this->_px->addParagraph($block);
			$this->_px->addHref($paragraph, "module:Xmlnuke.Admin.ManageXML?id=" . $this->_context->get("id") . "&action=confirmdelete", $myWords->Value("CONFIRMDELETE", $this->_context->get("id")), null);
			$deleteMode = true;
		}

		if ($action == "confirmdelete")
		{
			$paragraph = $this->_px->addParagraph($block);
			//$editNode = XmlUtil::SelectSingleNode($index->documentElement,"/xmlindex/group[id='" . $group . "']");		
			$editNode = XmlUtil::SelectSingleNode($index->documentElement,"group[id='" . $group . "']");
			$delNode = XmlUtil::SelectSingleNode($editNode,"page[id='" . $id . "']");
			if ($delNode != null)
			{
				$editNode->removeChild($delNode);
			}
			
			$this->_context->getXMLDataBase()->saveDocumentXML($indexFile->FullQualifiedName(), $index);
			//util.FileUtil.DeleteFile(new processor.XMLFilenameProcessor(_context.get("id"), this._context));
			$this->_context->getXMLDataBase()->saveIndex();
			$this->_px->addBold($paragraph, $myWords->Value("DELETED"));
			$deleteMode = true;
		}

		// --------------------------------------
		// EDIT XML PAGE
		// --------------------------------------
		// If doesnt have an ID, list all pages or add new!
		if ($id == "")
		{
			$action = "new";
		}
		else
		{
			$this->addMenuOption($myWords->Value("PREVIEWMENU"), "engine:xmlnuke?xml=" . $id . "&xsl=[param:xsl]&lang=[param:lang]", "preview");
			$this->addMenuOption($myWords->Value("NEWXMLMENU"), "module:Xmlnuke.Admin.ManageXML", null);
			$langAvail = $this->_context->LanguagesAvailable();
			$processorFile = new XMLFilenameProcessor($id);
			foreach(array_keys($langAvail) as $key) 				
			{
				if ($key != strtolower($this->_context->Language()->getName()));
				{
					$repositorio = 	new XmlnukeDB($this->_context->XmlHashedDir(), $this->_context->XmlPath(), $key);
					$fileToCheck = $processorFile->FullName($id, "", $key) . $processorFile->Extension();
					if ($repositorio->existsDocument($fileToCheck))
					{
						$this->addMenuOption($myWords->ValueArgs("EDITXMLMENU" ,array($langAvail[$key])), "module:Xmlnuke.Admin.ManageXML?id=" . $id . "&lang=".$key, null);
					}
					else
					{
						$this->addMenuOption($myWords->ValueArgs("CREATEXMLMENU", array($langAvail[$key])), "module:Xmlnuke.Admin.ManageXML?id=" . $id . "&lang=".$key, null);
					}
				}
			}
			$action = "edit";
		}


		// Show form to Edit/Insert
		if (!$deleteMode)
		{
			$paragraph = $this->_px->addParagraph($block);
			//XmlNodeS 
			$table = $this->_px->addTable($paragraph);
			$row = $this->_px->addTableRow($table);
			$col = $this->_px->addTableColumn($row);
			$form = $this->_px->addForm($col, "module:Xmlnuke.Admin.ManageXML", "","form", true );

			$xmlExist = true;
			if ($id != "")
			{
				$xmlTestExist = new XMLFilenameProcessor($id);
				$xmlExist = $this->_context->getXMLDataBase()->existsDocument($xmlTestExist->FullQualifiedName());
			}

			$canUseNew = (($action != "new") && !$xmlExist);
			
			//Trecho acrescentado para manter o conteudo do textarea mesmo no caso de erro.
			$contents = $this->_context->getSession("texto");
			//echo $contents;
			if (($action == "new") || $canUseNew)
			{
				$action = "new"; // This is necessary, because user can Create a predefined ID...
				if (!$canUseNew || ($id == ""))
				{
					$this->_px->addTextBox($form, $myWords->Value("XMLBOX"), "id", "", 20, true, INPUTTYPE::TEXT);
				}
				else
				{
					$this->_px->addLabelField($form, $myWords->Value("XMLBOX"), $id);
					$this->_px->addHidden($form, "id", $id);
				}
				$this->_px->addLabelField($form, $myWords->Value("LANGUAGEBOX"), strtolower($this->_context->Language()->getName()));
				//if($contents!="")
				//{
					$contents = 
						"<page>\n" .
						"  <meta>\n" .
						"    <title>Put your title here</title>\n" .
						"    <abstract>Put page abstract informations here</abstract>\n" .
						"    <created>" . date("D M j Y G:i:s") . "</created>\n" .
						"    <modified/>\n" .
						"    <keyword>xmlnuke</keyword>\n" . 
						"    <groupkeyword>all</groupkeyword>\n" .
						"  </meta>\n" .
						"  <blockcenter>\n" . 
						"    <title>Block Title</title>\n" .
						"    <body>\n" .
						"      <p>This is the first paragraph</p>\n" .
						"    </body>\n" .
						"  </blockcenter>\n" .
						"</page>\n";
				//}
				session_unregister("texto");
			}
			else
			{
				$this->_px->addLabelField($form, $myWords->Value("LANGUAGEBOX"), strtolower($this->_context->Language()->getName()));
				$this->_px->addHidden($form, "id", $id);
				$xmlFile = new XMLFilenameProcessor($id);
				//XmlDocument 
				$xml = $this->_context->getXMLDataBase()->getDocument($xmlFile->FullQualifiedName(), null);
				//if($contents!="")					
					$contents = str_replace("&amp;", "&", XmlUtil::GetFormattedDocument($xml));
				$editNode = XmlUtil::SelectSingleNode($xml->documentElement,"meta/groupkeyword");
				if ($editNode != null)
				{
					$groupKeyword = $editNode->nodeValue;
				}
				session_unregister("texto");
			}

			if ($id != "_all")
			{
				$this->_px->addCaption($form, $myWords->Value("SITEMAPINFO"));
				$this->_px->addTextBox($form, $myWords->Value("INDEXBOX"), "titleIndex", $titleIndex, 60, true, INPUTTYPE::TEXT);
				$selectNode = $this->_px->addSelect($form, $myWords->Value("LISTEDBOX"), "group");
				$this->_px->addTextBox($form, $myWords->Value("INDEXSUMMARYBOX"), "summaryIndex", $summaryIndex, 60, true, INPUTTYPE::TEXT);

				$this->_px->addCaption($form, $myWords->Value("PAGEINFO"));
				//XmlNode 
				$selectPageNode = $this->_px->addSelect($form,$myWords->Value("SHOWMENUBOX"), "groupKeyword");
				$this->_px->addOption($selectPageNode, $myWords->Value("NOTLISTEDOPTION"), "-", null);					
				
				//XmlNodeList 
				//$groupList = XmlUtil::SelectNodes($index->documentElement,"/xmlindex/group");
				$groupList = XmlUtil::SelectNodes($index->documentElement,"/group");
				
				foreach( $groupList as $node )					
				{				
					
					$value = XmlUtil::SelectSingleNode($node,"title")->nodeValue;
										
					$this->_px->addOption($selectNode, XmlUtil::SelectSingleNode($node,"title")->nodeValue . " (" . XmlUtil::SelectSingleNode($node,"/id")->nodeValue . ")", XmlUtil::SelectSingleNode($node,"/id")->nodeValue, XmlUtil::SelectSingleNode($node,"/id")->nodeValue == $group);
					
					$this->_px->addOption($selectPageNode, XmlUtil::SelectSingleNode($node,"title")->nodeValue . " (" . XmlUtil::SelectSingleNode($node,"/keyword")->nodeValue . ")", XmlUtil::SelectSingleNode($node,"/keyword")->nodeValue, XmlUtil::SelectSingleNode($node,"/keyword")->nodeValue == $groupKeyword);
				
				}
			
			}
			
			$this->_px->addHidden($form, "action", $action);
			$this->_px->addCaption($form, $myWords->Value("XMLEDITINFO"));
			$this->_px->addMemo($form, $myWords->Value("XMLCONTENTBOX"), "contents", $contents, 80, 30, "soft");
			$boxButton = $this->_px->addBoxButtons($form);
			$this->_px->addSubmit($boxButton, "", $myWords->Value("TXT_SAVE"));
		}
		
		return $this->_px;
	}