<commit_before>module.exports = {
  systemBusy:                         { code: -1,    message: 'system busy, retry later'},
  success:                            { code: 0,     message: 'success'},
  internalError:                      { code: 1,     message: 'internal error, contact us'},
  requireAppKey:                      { code: 10001, message: 'require appKey'},
  requireAppSecret:                   { code: 10002, message: 'require appSecret'},
  requireDeviceUdid:                  { code: 10003, message: 'require deviceUdid'},
  invalidAppKey:                      { code: 10004, message: 'invalid appKey'},
  invalidAppSecret:                   { code: 10005, message: 'invalid appSecret'},
  failedToSaveDevice:                 { code: 10006, message: 'failed to create/update device, contact us'},
  invalidToken:                       { code: 10007, message: 'invalid token'},
  tokenExpired:                       { code: 10008, message: 'token is expired'},
  failedToGenerateToken:              { code: 10009, message: 'failed to generate token, contact us'},
  requireToken:                       { code: 10010, message: 'require token'},
  requireDataFile:                    { code: 10011, message: 'require uploaded data file'},
  requireAppBundle:                   { code: 10012, message: 'require appBundle'},
  failedToGetApp:                     { code: 10013, message: 'rpc error, failed to Get App'},
  requireUsername:                    { code: 11001, message: 'require username'},
  requirePassword:                    { code: 11002, message: 'require password'},
  userNotExist:                       { code: 11003, message: 'user not exist'},
  passwordNotMatch:                   { code: 11004, message: 'password not match'},
  failedToCreateUser:                 { code: 11006, message: 'failed to create user'},
  failedToHashPassword:               { code: 11007, message: 'failed to hash password'},
  failedToSaveUser:                   { code: 11008, message: 'failed to save user, please check if required field is correct'},
  failedToSaveFile:                   { code: 11009, message: 'failed to save file'},
  failedToDeleteFile:                 { code: 11010, message: 'failed to delete file'},
  fileNotExist:                       { code: 11011, message: 'file not exist'},
  failedToReadFile:                   { code: 11012, message: 'error when read file'},
  requireClientKey:                   { code: 11014, message: 'require clientKey'},
  requireClientSecret:                { code: 11015, message: 'require clientSecret'},
  clientNotExist:                     { code: 11016, message: 'client not exist'},
  invalidClientKey:                   { code: 11017, message: 'invalid clientKey'},
  invalidClientSecret:                { code: 11018, message: 'invalid clientSecret'},
  requirePoi:                         { code: 11020, message: 'require poi'},
  requireOwner:                       { code: 11021, message: 'require owner'},
  pendingPoiPullRequestExists:        { code: 11020, message: 'pending poi pull request exists'},
  failedToUpdatePoi:                  { code: 11021, message: 'failed to update poi'},
  failedToGetPoi:                     { code: 11022, message: 'rpc error, failed to get poi'},
  failedToFindResource:               { code: 12001, message: 'failed to find specified resource'},
  wrongParameter:                     { code: 12003, message: 'wrong parameter'},
  failedToFindUserBehaviors:          { code: 12004, message: 'failed to find user behaviors'},
  failedToFindCubePoint:              { code: 12005, message: 'failed to find cube point'},
  failedToValidateEmail:              { code: 14001, message: 'failed to validate email'},
  failedToSendMail:                   { code: 14026, message: 'failed to send mail'},
  alreadyActivated:                   { code: 14028, message: 'already activated'},
  invalidPasswordResetCode:           { code: 14029, message: 'invalid password reset code'},
  requireUserOrCodeToResetPassword:   { code: 14031, message: 'require user or code to reset password'},
  failedToCreateDevice:               { code: 40001, message: 'failed to create device, contact us'},
  failedToGetDevice:                  { code: 40002, message: 'failed to get device, contact us'},
  failedToUpdateDevice:               { code: 40003, message: 'failed to update device, contact us'},
  failedToQueueDeviceDataCollectJob:  { code: 40004, message: 'failed to queue device data collect job'},
  failedToQueuePoiImportJob:          { code: 40005, message: 'failed to queue poi import job'},
  failedToFindRegions:                { code: 40006, message: 'failed to find regions'},
  failedToFindPois:                   { code: 40007, message: 'failed to find pois'},
  failedToEnsureDevice:               { code: 40008, message: 'rpc error, failed to ensure device'},
  requirePoiId:                       { code: 40009, message: 'require poi id'},
  poiNotExist:                        { code: 40010, message: 'poi not exist'},
  requirePoiPullRequest:              { code: 40011, message: 'require poi pull request info'},
  requirePoiPullRequestId:            { code: 40012, message: 'require poi pull request id'},
  poiNotReady:                        { code: 40013, message: 'poi not ready'},
  failedToFindPoiPullRequest:         { code: 40014, message: 'failed to find poi pull request, contact us'},
  poiPullRequestNotExist:             { code: 40015, message: 'poi pull request not exist'},
  poiPullRequestNotActive:            { code: 40016, message: 'poi pull request not active'},
  failedToUpdatePoiPullRequest:       { code: 40017, message: 'failed to update poi pull request'},
  requireAttachment:                  { code: 40019, message: 'require attachment'},
  requireAttachmentId:                { code: 40020, message: 'require attachment id'},
  failedToFindAttachment:             { code: 40021, message: 'failed to find attachment'},
  attachmentNotExist:                 { code: 40022, message: 'attachment not exist'},
  failedToCreateAttachment:           { code: 40023, message: 'failed to create attachment'},
  failedToUpdateAttachment:           { code: 40024, message: 'failed to update attachment'},
  failedToDestroyAttachment:          { code: 40025, message: 'failed to destroy attachment'},
  requireScenario:                    { code: 40026, message: 'require scenario'},
  requireScenarioId:                  { code: 40027, message: 'require scenario id'},
  failedToFindScenario:               { code: 40028, message: 'failed to find scenario'},
  scenarioNotExist:                   { code: 40029, message: 'scenario not exist'},
  failedToCreateScenario:             { code: 40030, message: 'failed to create scenario'},
  failedToUpdateScenario:             { code: 40031, message: 'failed to update scenario'},
  failedToDestroyScenario:            { code: 40032, message: 'failed to destroy scenario'},
  requireApp:                         { code: 40033, message: 'require app'},
  notYourApp:                         { code: 40034, message: 'app is not yours'},
  failedToUpdateScenarioLastOperation:{ code: 40035, message: 'failed to update scenario last operation'},
  requireAppPlatformSettingsId:       { code: 40036, message: 'require app platform settings id'},
  failedToFindAppPlatformSettings:    { code: 40037, message: 'failed to find app platform settings'},
  appPlatformSettingsNotExist:        { code: 40038, message: 'app platform settings not exist'},
  failedToCreateAppPlatformSettings:  { code: 40039, message: 'failed to create app platform settings'},
  failedToUpdateAppPlatformSettings:  { code: 40040, message: 'failed to update app platform settings'},
  failedToDestroyAppPlatformSettings: { code: 40041, message: 'failed to destroy app platform settings'},
  failedToQueuePoiExportJob:          { code: 40042, message: 'failed to queue poi export job'},
  failedToFindApp:                    { code: 41002, message: 'failed to get app, check if appKey is valid'},
  appNotExist:                        { code: 41003, message: 'app not exist'},
  failedToUpdateApp:                  { code: 41004, message: 'failed to update app'},
  requireAdId:                        { code: 42001, message: 'require ad id'},
  failedToFindAd:                     { code: 42002, message: 'failed to find ad'},
  adNotExist:                         { code: 42003, message: 'ad not exist'},
  requireAd:                          { code: 42004, message: 'require ad'},
  failedToCreateAd:                   { code: 42005, message: 'failed to create ad'},
  failedToUpdateAd:                   { code: 42006, message: 'failed to update ad'},
  failedToDestroyAd:                  { code: 42007, message: 'failed to destroy ad'},
  failedToUpdateAdLastOperation:      { code: 42008, message: 'failed to update ad last operation'},
  failedToUpdateAppLastOperation:     { code: 42009, message: 'failed to update app last operation'},
  requireUmm:                         { code: 42010, message: 'require umm'},
  requireJobId:                       { code: 50001, message: 'require job id'},
  failedToGetJob:                     { code: 50002, message: 'failed to get job status'}
};
<commit_msg>add code for poi get request<commit_after>module.exports = {
  systemBusy:                         { code: -1,    message: 'system busy, retry later'},
  success:                            { code: 0,     message: 'success'},
  internalError:                      { code: 1,     message: 'internal error, contact us'},
  requireAppKey:                      { code: 10001, message: 'require appKey'},
  requireAppSecret:                   { code: 10002, message: 'require appSecret'},
  requireDeviceUdid:                  { code: 10003, message: 'require deviceUdid'},
  invalidAppKey:                      { code: 10004, message: 'invalid appKey'},
  invalidAppSecret:                   { code: 10005, message: 'invalid appSecret'},
  failedToSaveDevice:                 { code: 10006, message: 'failed to create/update device, contact us'},
  invalidToken:                       { code: 10007, message: 'invalid token'},
  tokenExpired:                       { code: 10008, message: 'token is expired'},
  failedToGenerateToken:              { code: 10009, message: 'failed to generate token, contact us'},
  requireToken:                       { code: 10010, message: 'require token'},
  requireDataFile:                    { code: 10011, message: 'require uploaded data file'},
  requireAppBundle:                   { code: 10012, message: 'require appBundle'},
  failedToGetApp:                     { code: 10013, message: 'rpc error, failed to Get App'},
  requireUsername:                    { code: 11001, message: 'require username'},
  requirePassword:                    { code: 11002, message: 'require password'},
  userNotExist:                       { code: 11003, message: 'user not exist'},
  passwordNotMatch:                   { code: 11004, message: 'password not match'},
  failedToCreateUser:                 { code: 11006, message: 'failed to create user'},
  failedToHashPassword:               { code: 11007, message: 'failed to hash password'},
  failedToSaveUser:                   { code: 11008, message: 'failed to save user, please check if required field is correct'},
  failedToSaveFile:                   { code: 11009, message: 'failed to save file'},
  failedToDeleteFile:                 { code: 11010, message: 'failed to delete file'},
  fileNotExist:                       { code: 11011, message: 'file not exist'},
  failedToReadFile:                   { code: 11012, message: 'error when read file'},
  requireClientKey:                   { code: 11014, message: 'require clientKey'},
  requireClientSecret:                { code: 11015, message: 'require clientSecret'},
  clientNotExist:                     { code: 11016, message: 'client not exist'},
  invalidClientKey:                   { code: 11017, message: 'invalid clientKey'},
  invalidClientSecret:                { code: 11018, message: 'invalid clientSecret'},
  requirePoi:                         { code: 11020, message: 'require poi'},
  requireOwner:                       { code: 11021, message: 'require owner'},
  pendingPoiPullRequestExists:        { code: 11020, message: 'pending poi pull request exists'},
  failedToUpdatePoi:                  { code: 11021, message: 'failed to update poi'},
  failedToGetPoi:                     { code: 11022, message: 'rpc error, failed to get poi'},
  failedToFindResource:               { code: 12001, message: 'failed to find specified resource'},
  wrongParameter:                     { code: 12003, message: 'wrong parameter'},
  failedToFindUserBehaviors:          { code: 12004, message: 'failed to find user behaviors'},
  failedToFindCubePoint:              { code: 12005, message: 'failed to find cube point'},
  failedToValidateEmail:              { code: 14001, message: 'failed to validate email'},
  failedToSendMail:                   { code: 14026, message: 'failed to send mail'},
  alreadyActivated:                   { code: 14028, message: 'already activated'},
  invalidPasswordResetCode:           { code: 14029, message: 'invalid password reset code'},
  requireUserOrCodeToResetPassword:   { code: 14031, message: 'require user or code to reset password'},
  failedToCreateDevice:               { code: 40001, message: 'failed to create device, contact us'},
  failedToGetDevice:                  { code: 40002, message: 'failed to get device, contact us'},
  failedToUpdateDevice:               { code: 40003, message: 'failed to update device, contact us'},
  failedToQueueDeviceDataCollectJob:  { code: 40004, message: 'failed to queue device data collect job'},
  failedToQueuePoiImportJob:          { code: 40005, message: 'failed to queue poi import job'},
  failedToFindRegions:                { code: 40006, message: 'failed to find regions'},
  failedToFindPois:                   { code: 40007, message: 'failed to find pois'},
  failedToEnsureDevice:               { code: 40008, message: 'rpc error, failed to ensure device'},
  requirePoiId:                       { code: 40009, message: 'require poi id'},
  poiNotExist:                        { code: 40010, message: 'poi not exist'},
  requirePoiPullRequest:              { code: 40011, message: 'require poi pull request info'},
  requirePoiPullRequestId:            { code: 40012, message: 'require poi pull request id'},
  poiNotReady:                        { code: 40013, message: 'poi not ready'},
  failedToFindPoiPullRequest:         { code: 40014, message: 'failed to find poi pull request, contact us'},
  poiPullRequestNotExist:             { code: 40015, message: 'poi pull request not exist'},
  poiPullRequestNotActive:            { code: 40016, message: 'poi pull request not active'},
  failedToUpdatePoiPullRequest:       { code: 40017, message: 'failed to update poi pull request'},
  requireAttachment:                  { code: 40019, message: 'require attachment'},
  requireAttachmentId:                { code: 40020, message: 'require attachment id'},
  failedToFindAttachment:             { code: 40021, message: 'failed to find attachment'},
  attachmentNotExist:                 { code: 40022, message: 'attachment not exist'},
  failedToCreateAttachment:           { code: 40023, message: 'failed to create attachment'},
  failedToUpdateAttachment:           { code: 40024, message: 'failed to update attachment'},
  failedToDestroyAttachment:          { code: 40025, message: 'failed to destroy attachment'},
  requireScenario:                    { code: 40026, message: 'require scenario'},
  requireScenarioId:                  { code: 40027, message: 'require scenario id'},
  failedToFindScenario:               { code: 40028, message: 'failed to find scenario'},
  scenarioNotExist:                   { code: 40029, message: 'scenario not exist'},
  failedToCreateScenario:             { code: 40030, message: 'failed to create scenario'},
  failedToUpdateScenario:             { code: 40031, message: 'failed to update scenario'},
  failedToDestroyScenario:            { code: 40032, message: 'failed to destroy scenario'},
  requireApp:                         { code: 40033, message: 'require app'},
  notYourApp:                         { code: 40034, message: 'app is not yours'},
  failedToUpdateScenarioLastOperation:{ code: 40035, message: 'failed to update scenario last operation'},
  requireAppPlatformSettingsId:       { code: 40036, message: 'require app platform settings id'},
  failedToFindAppPlatformSettings:    { code: 40037, message: 'failed to find app platform settings'},
  appPlatformSettingsNotExist:        { code: 40038, message: 'app platform settings not exist'},
  failedToCreateAppPlatformSettings:  { code: 40039, message: 'failed to create app platform settings'},
  failedToUpdateAppPlatformSettings:  { code: 40040, message: 'failed to update app platform settings'},
  failedToDestroyAppPlatformSettings: { code: 40041, message: 'failed to destroy app platform settings'},
  failedToQueuePoiExportJob:          { code: 40042, message: 'failed to queue poi export job'},
  failedToFindApp:                    { code: 41002, message: 'failed to get app, check if appKey is valid'},
  appNotExist:                        { code: 41003, message: 'app not exist'},
  failedToUpdateApp:                  { code: 41004, message: 'failed to update app'},
  requireAdId:                        { code: 42001, message: 'require ad id'},
  failedToFindAd:                     { code: 42002, message: 'failed to find ad'},
  adNotExist:                         { code: 42003, message: 'ad not exist'},
  requireAd:                          { code: 42004, message: 'require ad'},
  failedToCreateAd:                   { code: 42005, message: 'failed to create ad'},
  failedToUpdateAd:                   { code: 42006, message: 'failed to update ad'},
  failedToDestroyAd:                  { code: 42007, message: 'failed to destroy ad'},
  failedToUpdateAdLastOperation:      { code: 42008, message: 'failed to update ad last operation'},
  failedToUpdateAppLastOperation:     { code: 42009, message: 'failed to update app last operation'},
  requireUmm:                         { code: 42010, message: 'require umm'},
  requirePoiIdOrUmm:                  { code: 42011, message: 'require poi id or umm'},
  requireJobId:                       { code: 50001, message: 'require job id'},
  failedToGetJob:                     { code: 50002, message: 'failed to get job status'}
};
<|endoftext|>


<commit_before>(function () {
	'use strict';

	angular
		.module("plugins.config")
		.component('configView', {
			templateUrl: 'plugins/config/config.tmpl.html',
			controllerAs: 'vm',
			controller: configController
		});

	function configController($http, base64, $mdDialog, CacheFactory, configService) {
		var vm = this;

		vm.$onInit = activate;
		vm.updateTheme = updateTheme;
		vm.saveConfig = saveConfig;

		var aceThemeCache;

		function activate() {
			loadConfig();
			initCache();

			setupAceOptions();
		}

		function initCache() {
			if (!CacheFactory.get('aceThemeCache')) {
				CacheFactory('aceThemeCache', {
					storageMode: 'localStorage'
				});
			}

			aceThemeCache = CacheFactory.get('aceThemeCache');
		}

		function loadConfig() {
			configService.getRawConfig().then(function (data) {
				var encoded = data.raw_config;
				vm.config = base64.decode(encoded);
				saveOriginalConfig();
			});
		}

		function saveOriginalConfig() {
			vm.origConfig = angular.copy(vm.config);
		}

		function setupAceOptions() {
			vm.aceOptions = {
				mode: 'yaml',
				theme: getTheme(),
				onLoad: aceLoaded
			}

			var themelist = ace.require('ace/ext/themelist');
			vm.themes = themelist.themes;
		}

		function aceLoaded(_editor) {
			_editor.setShowPrintMargin(false);
		}

		function getTheme() {
			var theme = aceThemeCache.get('theme');
			return theme ? theme : 'chrome';
		}

		function updateTheme() {
			aceThemeCache.put('theme', vm.aceOptions.theme);
		}

		function saveConfig() {
			var encoded = base64.encode(vm.config);
			$http.post('/api/server/raw_config', { raw_config: encoded })
				.then(function () {
					var dialog = $mdDialog.alert()
						.title("Update success")
						.ok("Ok")
						.textContent("Your config file has been successfully updated")

					$mdDialog.show(dialog);
					saveOriginalConfig();
				}, function (error) {
					vm.errors = error.data.errors;
				});
		}
	}
})();
<commit_msg>[WebUI] Removed some anoying keybindings in the config editor, bound Ctrl+S to Save and apply<commit_after>(function () {
	'use strict';

	angular
		.module("plugins.config")
		.component('configView', {
			templateUrl: 'plugins/config/config.tmpl.html',
			controllerAs: 'vm',
			controller: configController
		});

	function configController($http, base64, $mdDialog, CacheFactory, configService) {
		var vm = this;

		vm.$onInit = activate;
		vm.updateTheme = updateTheme;
		vm.saveConfig = saveConfig;

		var aceThemeCache;

		function activate() {
			loadConfig();
			initCache();

			setupAceOptions();
		}

		function initCache() {
			if (!CacheFactory.get('aceThemeCache')) {
				CacheFactory('aceThemeCache', {
					storageMode: 'localStorage'
				});
			}

			aceThemeCache = CacheFactory.get('aceThemeCache');
		}

		function loadConfig() {
			configService.getRawConfig().then(function (data) {
				var encoded = data.raw_config;
				vm.config = base64.decode(encoded);
				saveOriginalConfig();
			});
		}

		function saveOriginalConfig() {
			vm.origConfig = angular.copy(vm.config);
		}

		function setupAceOptions() {
			vm.aceOptions = {
				mode: 'yaml',
				theme: getTheme(),
				onLoad: aceLoaded
			}

			var themelist = ace.require('ace/ext/themelist');
			vm.themes = themelist.themes;
		}

		function aceLoaded(_editor) {
			//Get all commands, but keep the find command
			var commandsToRemove = [
				"transposeletters",
				"gotoline"
			]

			_editor.commands.removeCommands(commandsToRemove);

			_editor.commands.addCommand({
				name: 'saveConfig',
				bindKey: { win: 'Ctrl-S', mac: 'Command-S' },
				exec: function (editor) {
					if (vm.config != vm.origConfig) {
						saveConfig();
					}
				}
			});

			_editor.setShowPrintMargin(false);
		}

		function getTheme() {
			var theme = aceThemeCache.get('theme');
			return theme ? theme : 'chrome';
		}

		function updateTheme() {
			aceThemeCache.put('theme', vm.aceOptions.theme);
		}

		function saveConfig() {
			var encoded = base64.encode(vm.config);
			$http.post('/api/server/raw_config', { raw_config: encoded })
				.then(function () {
					var dialog = $mdDialog.alert()
						.title("Update success")
						.ok("Ok")
						.textContent("Your config file has been successfully updated")

					$mdDialog.show(dialog);
					saveOriginalConfig();
				}, function (error) {
					vm.errors = error.data.errors;
				});
		}
	}
})();
<|endoftext|>


<commit_before>import React, {useContext, useMemo, useState, useEffect} from 'react';
import { StateNavigator } from 'navigation';
import { NavigationContext } from 'navigation-react';
import { NavigationStack } from 'navigation-react-native';

const Stack = ({children, ...props}) => {
  const {stateNavigator, state} = useContext(NavigationContext);
  const scenes = useMemo(() => (
    React.Children.toArray(children)
      .reduce((scenes, scene) => ({...scenes, [scene.props.stateKey]: scene}), {})
  ), [children]);
  const [allScenes, setAllScenes] = useState(scenes);
  useEffect(() => {
    setAllScenes(prevScenes => ({...prevScenes, ...scenes}));
    const {crumbs, nextCrumb} = stateNavigator.stateContext;
    const invalid = [...crumbs, nextCrumb].find(({state}) => !scenes[state.key]);
    if (invalid) {
      const {stateKey} = React.Children.toArray(children)[0].props;
      stateNavigator.navigateLink(stateNavigator.fluent().navigate(stateKey).url);
    }
  }, [children, stateNavigator, scenes]);
  useEffect(() => {
    const validate = ({key}) => !!scenes[key];
    stateNavigator.onBeforeNavigate(validate);
    return () => stateNavigator.offBeforeNavigate(validate);
  }, [stateNavigator, scenes]);
  return (
      <NavigationStack {...props} renderScene={({key}) => allScenes[key]} />
  )
}

Stack.Scene = ({children}) => children;

export default Stack;
<commit_msg>Removed Stack now incorporated in NavigationStack<commit_after><|endoftext|>


<commit_before>#!/usr/bin/env node

'use strict';

const fs = require('fs');
const path = require('path');
const package_json = path.resolve('./package.json');
const tsconfig_json = path.resolve('./tsconfig.json');
const webpack_config_js = path.resolve('./webpack.config.js');
const git_ignore_file = path.resolve('./.gitignore');
const index_html = path.resolve('./index.html');
const main_tsx = path.resolve('./main.tsx');
const execSync = require('child_process').execSync;
const program = require('commander');

// webpack 2.x
const webpack_config = `const path = require('path');
module.exports = {
  entry: {
    'app': './main.tsx',
  },
  output: {
    filename: '[name].js'
  },
  resolve: {
    extensions: ['.webpack.js', '.web.js', '.ts', '.tsx', '.js']
  },
  module: {
    rules: [
      { test: /\.tsx?$/, loader: 'ts-loader' }
    ]
  },
  devServer: {
  }
}`;

const tsconfig = `{
  "compilerOptions": {
    "target": "es5",
    "jsx": "react",
    "reactNamespace": "app",
    "lib": ["dom", "es2015.promise", "es5"]
  }
}`

const git_ignore =
`.DS_Store
node_modules
*.log
`;

const index = `<!doctype html>

  <meta charset="utf-8">
  <title>apprun</title>

`;

const main = `import app from './node_modules/apprun/index';
const model = 'Hello world - AppRun';
const view = (state) =>
{state}
;
const update = {
}
const element = document.getElementById('my-app');
app.start(element, model, view, update);
`;

function write(file_name, text, title = 'Creating') {
  const file = path.resolve(file_name);
  if (!fs.existsSync(file)) {
    process.stdout.write(`${title}: ${file} ... `);
    fs.writeFileSync(
      file,
      text
    );
    process.stdout.write('Done\n');
  } else {
    process.stdout.write(`No change made. File exists: ${file}\n`);
  }
}

function init() {
  RegExp.prototype.toJSON = RegExp.prototype.toString;

  if (!fs.existsSync(package_json)) {
    console.log('Initializing package.json');
    execSync('npm init -y');
  }

  console.log('Installing packages. This might take a couple minutes.');
  execSync('npm install webpack webpack-dev-server ts-loader typescript --save-dev');
  execSync('npm install apprun --save');

  write(tsconfig_json, tsconfig);
  write(webpack_config_js, webpack_config)
  write(index_html, index);
  write(main_tsx, main);
  write(git_ignore_file, git_ignore);

  console.log('Adding npm scripts');
  const package_info = require(package_json);
  if (!package_info.scripts || ! package_info.scripts['start']) {
    package_info["scripts"]["start"] = 'webpack-dev-server';
  }
  if (!package_info.scripts || ! package_info.scripts['build']) {
    package_info["scripts"]["build"] = 'webpack -p';
  }
  fs.writeFileSync(
    package_json,
    JSON.stringify(package_info, null, 2)
  );

  console.log('Initializing git');
  execSync('git init');
}

const component_template = `import {Component} from './node_modules/apprun/index';
let app;
var model = '#name';

const view = (state) => {
  return

{state}

}

const update = {
  mount: state => state,
}

export default (element) => {
  app = new Component(element, model, view, update).app;
  window['app'].on('##name', () => app.run('mount'));
}

// to use this component in main.tsx
// import #name from './#name';
// const element = document.getElementById('my-app');
// #name(element);
`;

function component(name) {
  const fn = path.resolve(name + '.tsx');
  write(name + '.tsx', component_template.replace(/\#name/g, name),
    `Creating component ${name}`)
}

program
 .version('1.0.0')
 .option('-i, --init', 'Initialize AppRun Project')
 .option('-c, --component <file>', 'Generate AppRun component')
 .parse(process.argv);

 if (!program.init && !program.component) {
   program.outputHelp();
 }

 if (program.init) init();
 if (program.component) component(program.component);<commit_msg>Set cli name to be apprun<commit_after>#!/usr/bin/env node

'use strict';

const fs = require('fs');
const path = require('path');
const package_json = path.resolve('./package.json');
const tsconfig_json = path.resolve('./tsconfig.json');
const webpack_config_js = path.resolve('./webpack.config.js');
const git_ignore_file = path.resolve('./.gitignore');
const index_html = path.resolve('./index.html');
const main_tsx = path.resolve('./main.tsx');
const execSync = require('child_process').execSync;
const program = require('commander');

// webpack 2.x
const webpack_config = `const path = require('path');
module.exports = {
  entry: {
    'app': './main.tsx',
  },
  output: {
    filename: '[name].js'
  },
  resolve: {
    extensions: ['.webpack.js', '.web.js', '.ts', '.tsx', '.js']
  },
  module: {
    rules: [
      { test: /\.tsx?$/, loader: 'ts-loader' }
    ]
  },
  devServer: {
  }
}`;

const tsconfig = `{
  "compilerOptions": {
    "target": "es5",
    "jsx": "react",
    "reactNamespace": "app",
    "lib": ["dom", "es2015.promise", "es5"]
  }
}`

const git_ignore =
`.DS_Store
node_modules
*.log
`;

const index = `<!doctype html>

  <meta charset="utf-8">
  <title>apprun</title>

`;

const main = `import app from './node_modules/apprun/index';
const model = 'Hello world - AppRun';
const view = (state) =>
{state}
;
const update = {
}
const element = document.getElementById('my-app');
app.start(element, model, view, update);
`;

function write(file_name, text, title = 'Creating') {
  const file = path.resolve(file_name);
  if (!fs.existsSync(file)) {
    process.stdout.write(`${title}: ${file} ... `);
    fs.writeFileSync(
      file,
      text
    );
    process.stdout.write('Done\n');
  } else {
    process.stdout.write(`No change made. File exists: ${file}\n`);
  }
}

function init() {
  RegExp.prototype.toJSON = RegExp.prototype.toString;

  if (!fs.existsSync(package_json)) {
    console.log('Initializing package.json');
    execSync('npm init -y');
  }

  console.log('Installing packages. This might take a couple minutes.');
  execSync('npm install webpack webpack-dev-server ts-loader typescript --save-dev');
  execSync('npm install apprun --save');

  write(tsconfig_json, tsconfig);
  write(webpack_config_js, webpack_config)
  write(index_html, index);
  write(main_tsx, main);
  write(git_ignore_file, git_ignore);

  console.log('Adding npm scripts');
  const package_info = require(package_json);
  if (!package_info.scripts || ! package_info.scripts['start']) {
    package_info["scripts"]["start"] = 'webpack-dev-server';
  }
  if (!package_info.scripts || ! package_info.scripts['build']) {
    package_info["scripts"]["build"] = 'webpack -p';
  }
  fs.writeFileSync(
    package_json,
    JSON.stringify(package_info, null, 2)
  );

  console.log('Initializing git');
  execSync('git init');
}

const component_template = `import {Component} from './node_modules/apprun/index';
let app;
var model = '#name';

const view = (state) => {
  return

{state}

}

const update = {
  mount: state => state,
}

export default (element) => {
  app = new Component(element, model, view, update).app;
  window['app'].on('##name', () => app.run('mount'));
}

// to use this component in main.tsx
// import #name from './#name';
// const element = document.getElementById('my-app');
// #name(element);
`;

function component(name) {
  const fn = path.resolve(name + '.tsx');
  write(name + '.tsx', component_template.replace(/\#name/g, name),
    `Creating component ${name}`)
}

program
 .version('1.0.1')
 .option('-i, --init', 'Initialize AppRun Project')
 .option('-c, --component <file>', 'Generate AppRun component')
 .parse(process.argv);

program._name = 'apprun';

if (!program.init && !program.component) {
  program.outputHelp();
}

if (program.init) init();
if (program.component) component(program.component);<|endoftext|>


<commit_before>/* eslint-env mocha */

import React from 'react';
import expect from 'expect';
import expectJSX from './index';

expect.extend(expectJSX);

class TestComponent extends React.Component {
  render() {
    return
Hi! {this.props.name}
;
  }
}

describe('expect(ReactElement).toEqualJSX(ReactElement)', () => {
  context('api', () => {
    it('has toEqualJSX', () => {
      expect(expect().toEqualJSX).toBeA('function');
    });

    it('has toNotEqualJSX', () => {
      expect(expect().toNotEqualJSX).toBeA('function');
    });

    it('has toIncludeJSX', () => {
      expect(expect().toIncludeJSX).toBeA('function');
    });
  });

  context('toEqualJSX', () => {
    it('can diff React elements', () => {
      expect(
        <TestComponent />
      ).toEqualJSX(
        <TestComponent />
      );
    });

    it('throws when elements are different', () => {
      try {
        expect(<TestComponent extra="neous" />).toEqualJSX(<TestComponent />);
      } catch (err) {
        expect(err instanceof Error).toBe(true);
        expect(err.message).toEqual(`Expected '<TestComponent extra="neous" />' to equal '<TestComponent />'`);
      }
    });

    it('does not care about function', () => {
      var fns = {
        one() {return 'one';},
        two() {return 'two';}
      };

      expect(
        <TestComponent fn={fns.one} />
      ).toEqualJSX(
        <TestComponent fn={fns.two} />
      );
    });

    it('handle render method with interpolation', () => {
      expect(
        <TestComponent name="Jon" />
      ).toNotEqual(
      <TestComponent name="Marry" />
      );
    });
  });

  context('toNotEqualJSX', () => {
    it('works', () => {
      expect(
).toNotEqualJSX(
);
    });

    it('throws when elements are the same', () => {
      try {
        expect(
).toNotEqualJSX(
);
      } catch (err) {
        expect(err instanceof Error).toBe(true);
        expect(err.message).toEqual(`Expected '<div />' to not equal '<div />'`);
      }
    });
  });

  context('toIncludeJSX', () => {
    it('works', () => {
      expect(

<TestComponent Hello=", world!"/>

)
        .toIncludeJSX(
<TestComponent Hello=", world!"/>
);
    });

    it('throws when element is not included', () => {
      try {
        expect(
).toIncludeJSX(
);
      } catch (err) {
        expect(err instanceof Error).toBe(true);
        expect(err.message).toEqual(`Expected '<div />' to include '<div Hello=", world!" />'`);
      }
    });
  });
});
<commit_msg>chore: fix lint<commit_after>/* eslint-env mocha */

import React from 'react';
import expect from 'expect';
import expectJSX from './index';

expect.extend(expectJSX);

class TestComponent extends React.Component {
  render() {
    return
Hi! {this.props.name}
;
  }
}

describe('expect(ReactElement).toEqualJSX(ReactElement)', () => {
  context('api', () => {
    it('has toEqualJSX', () => {
      expect(expect().toEqualJSX).toBeA('function');
    });

    it('has toNotEqualJSX', () => {
      expect(expect().toNotEqualJSX).toBeA('function');
    });

    it('has toIncludeJSX', () => {
      expect(expect().toIncludeJSX).toBeA('function');
    });
  });

  context('toEqualJSX', () => {
    it('can diff React elements', () => {
      expect(
        <TestComponent />
      ).toEqualJSX(
        <TestComponent />
      );
    });

    it('throws when elements are different', () => {
      try {
        expect(<TestComponent extra="neous" />).toEqualJSX(<TestComponent />);
      } catch (err) {
        expect(err instanceof Error).toBe(true);
        expect(err.message)
          .toEqual(`Expected '<TestComponent extra="neous" />' to equal '<TestComponent />'`);
      }
    });

    it('does not care about function', () => {
      var fns = {
        one() {return 'one';},
        two() {return 'two';}
      };

      expect(
        <TestComponent fn={fns.one} />
      ).toEqualJSX(
        <TestComponent fn={fns.two} />
      );
    });

    it('handle render method with interpolation', () => {
      expect(
        <TestComponent name="Jon" />
      ).toNotEqual(
      <TestComponent name="Marry" />
      );
    });
  });

  context('toNotEqualJSX', () => {
    it('works', () => {
      expect(
).toNotEqualJSX(
);
    });

    it('throws when elements are the same', () => {
      try {
        expect(
).toNotEqualJSX(
);
      } catch (err) {
        expect(err instanceof Error).toBe(true);
        expect(err.message).toEqual(`Expected '<div />' to not equal '<div />'`);
      }
    });
  });

  context('toIncludeJSX', () => {
    it('works', () => {
      expect(

<TestComponent Hello=", world!"/>

)
        .toIncludeJSX(
<TestComponent Hello=", world!"/>
);
    });

    it('throws when element is not included', () => {
      try {
        expect(
).toIncludeJSX(
);
      } catch (err) {
        expect(err instanceof Error).toBe(true);
        expect(err.message).toEqual(`Expected '<div />' to include '<div Hello=", world!" />'`);
      }
    });
  });
});
<|endoftext|>


<commit_before>'use strict';

/**
 * POSTs newswire stories to Slack via an incoming webhook.
 *
 * @author Ændrew Rininsland      <aendrew@aendrew.com>
 * @since  30 Aug. 2015
 */

require('dotenv').load();

// module dependencies
var xml2js = require('xml2js');
var xpath = require('xml2js-xpath');
var scale = require('d3-scale');
var format = require('util').format;
var request = require('request');
var environment = process.env.NODE_ENV ? process.env.NODE_ENV : 'testing';

/**
 * The handler function.
 *
 * @param {object}  event       The data regarding the event.
 * @param {object}  context     The AWS Lambda execution context.
 */
exports.handler = function(event, context) {
  /**
   * Parses an old NewsML XML file (Press Association)
   */
  function parseArticle(article, type, priority) {
    var color = scale.linear().domain([8, 3, 1]).range(['green', 'yellow', 'red']);
    var headline = xpath.evalFirst(article, '//headline');
    var body = xpath.evalFirst(article, '//body');
    var bodyCopy, excerpt, byline, link, newsitem;

    if (body.hasOwnProperty('body.content')) { // PA
      excerpt = bodyCopy = body['body.content'][0].p[0];
      bodyCopy = body['body.content'][0].p.join('\n');
      byline = xpath.evalFirst(article, '//byline').replace('By ', '');
      link = 'https://www.pressassociation.com/';
      newsitem = xpath.evalFirst(article, '//newsitemid');
    } else { // Reuters
      excerpt = body.p[0];
      bodyCopy = body.p.join('\n');
      // var authors = body.p[body.p.length - 1];
      byline = 'Thomson Reuters'; // TODO write some regex to extract reporter's name.
      link = 'http://about.reuters.com/';
      newsitem = article.$.guid.split(':')[2].replace('newsml_', '');
    }

    return {
      fallback: format('%s [%d] -- %s', headline, priority, excerpt),
      color: color(priority),
      title: format('%s [%d]', headline, priority),
      pretext: priority <= (process.env.ALERT_PRIORITY || 3) ? '@channel' : '', // Alert everyone for priorities above 3 (default)
      text: bodyCopy,
      author_name: byline,
      author_link: link,
      fields: [
        {
          title: 'slugline',
          value: xpath.evalFirst(article, '//slugline', true)
        },
        {
          title: 'Methode Name',
          value: undefined
        },
        {
          title: 'News Item ID',
          value: newsitem
        }
      ]
    };
  }

  xml2js.parseString(event.body, {normalizeTags: true}, function(err, xml){
    var type;
    var payload = {
      text: String(),
      attachments: []
    };

    var articles = xpath.find(xml, '//newsitem');
    var priority = xpath.evalFirst(xml, '//priority');
    var metadataProperties = xpath.find(xml, '//nimetadata/property');
    var methode = metadataProperties.filter(function(v){
      return v.$.FormalName === 'NIMethodeName';
    })[0].$.Value;

    if (xml.hasOwnProperty('newsmessage')) { // Reuters, expectedly, uses the modern version.
      type = 'Reuters';
    } else if (xml.hasOwnProperty('newsml')) { // PA, regrettably, does not.
      type = 'PA';
      priority = priority.$.FormalName;
    } else {
      throw 'Not valid NewsML';
    }
    payload.type = type;

    if (articles.length > 0) {
      articles.forEach(function(article){
        var parsed = parseArticle(article, type, priority);
        parsed.fields[1].value = methode;
        payload.attachments.push(parsed);
      });
    }

    // Send to Slack
    if (environment === 'production' && process.env.hasOwnProperty('SLACK_WEBHOOK')) {
      request.post({uri: process.env.SLACK_WEBHOOK, method: 'POST', json: payload}, function (error, response, body) {
        context.succeed(body);
      });
    } else {
      context.succeed(payload);
    }
  });
};
<commit_msg>Adding condition for PA bylines.<commit_after>'use strict';

/**
 * POSTs newswire stories to Slack via an incoming webhook.
 *
 * @author Ændrew Rininsland      <aendrew@aendrew.com>
 * @since  30 Aug. 2015
 */

require('dotenv').load();

// module dependencies
var xml2js = require('xml2js');
var xpath = require('xml2js-xpath');
var scale = require('d3-scale');
var format = require('util').format;
var request = require('request');
var environment = process.env.NODE_ENV ? process.env.NODE_ENV : 'testing';

/**
 * The handler function.
 *
 * @param {object}  event       The data regarding the event.
 * @param {object}  context     The AWS Lambda execution context.
 */
exports.handler = function(event, context) {
  /**
   * Parses an old NewsML XML file (Press Association)
   */
  function parseArticle(article, type, priority) {
    var color = scale.linear().domain([8, 3, 1]).range(['green', 'yellow', 'red']);
    var headline = xpath.evalFirst(article, '//headline');
    var body = xpath.evalFirst(article, '//body');
    var bodyCopy, excerpt, byline, link, newsitem;

    if (body.hasOwnProperty('body.content')) { // PA
      excerpt = bodyCopy = body['body.content'][0].p[0];
      bodyCopy = body['body.content'][0].p.join('\n');
      byline = xpath.evalFirst(article, '//byline');

      if (byline) {
        byline.replace('By ', '');
      }

      link = 'https://www.pressassociation.com/';
      newsitem = xpath.evalFirst(article, '//newsitemid');
    } else { // Reuters
      excerpt = body.p[0];
      bodyCopy = body.p.join('\n');
      // var authors = body.p[body.p.length - 1];
      byline = 'Thomson Reuters'; // TODO write some regex to extract reporter's name.
      link = 'http://about.reuters.com/';
      newsitem = article.$.guid.split(':')[2].replace('newsml_', '');
    }

    return {
      fallback: format('%s [%d] -- %s', headline, priority, excerpt),
      color: color(priority),
      title: format('%s [%d]', headline, priority),
      pretext: priority <= (process.env.ALERT_PRIORITY || 3) ? '@channel' : '', // Alert everyone for priorities above 3 (default)
      text: bodyCopy,
      author_name: byline,
      author_link: link,
      fields: [
        {
          title: 'slugline',
          value: xpath.evalFirst(article, '//slugline', true)
        },
        {
          title: 'Methode Name',
          value: undefined
        },
        {
          title: 'News Item ID',
          value: newsitem
        }
      ]
    };
  }

  xml2js.parseString(event.body, {normalizeTags: true}, function(err, xml){
    var type;
    var payload = {
      text: String(),
      attachments: []
    };

    var articles = xpath.find(xml, '//newsitem');
    var priority = xpath.evalFirst(xml, '//priority');
    var metadataProperties = xpath.find(xml, '//nimetadata/property');
    var methode = metadataProperties.filter(function(v){
      return v.$.FormalName === 'NIMethodeName';
    })[0].$.Value;

    if (xml.hasOwnProperty('newsmessage')) { // Reuters, expectedly, uses the modern version.
      type = 'Reuters';
    } else if (xml.hasOwnProperty('newsml')) { // PA, regrettably, does not.
      type = 'PA';
      priority = priority.$.FormalName;
    } else {
      throw 'Not valid NewsML';
    }

    payload.type = type;

    if (articles.length > 0) {
      articles.forEach(function(article){
        var parsed = parseArticle(article, type, priority);
        parsed.fields[1].value = methode;
        payload.attachments.push(parsed);
      });
    }

    // Send to Slack
    if (environment === 'production' && process.env.hasOwnProperty('SLACK_WEBHOOK')) {
      request.post({uri: process.env.SLACK_WEBHOOK, method: 'POST', json: payload}, function (error, response, body) {
        context.succeed(body);
      });
    } else {
      context.succeed(payload);
    }
  });
};
<|endoftext|>


<commit_before>(function(angular){
	'use strict';

	/**
	 * Assumptions: 1-spring api is configured at server-root/api/**
	 *
	 */
	var apiModule = angular.module('api',[]);

	apiModule.service('api',
			['$http','$timeout',function($http,$timeout){

				var pathname = window.location.pathname;
				var pathnameWithoutSlash = pathname.substring(1,pathname.length);
				var slashIndex = pathnameWithoutSlash.indexOf('/')
				if (slashIndex){
					pathname = pathname.substring(0,slashIndex + 1);
				}
				var baseUrl = pathname + '/api/';

				this.getReferenceData = function(entityName,onSuccess,onError){
					var url = baseUrl + entityName + '?page=0&size=200';
					$http
						.get(url,this.configContentUndefined())
						.then(onSuccess,onError);

				}

				this.getProfile = function(entity,onSuccess,onError){
					var that = this;
					var url = baseUrl + '/profile/' + entity;
					$http
						.get(url,this.configContentUndefined())
						.then(onSuccess,onError);
				}

				this.fetchSortedPage = function(
                    entity,
                    searchEntity,
                    args,
                    $scope,
                    onSuccess,
                    onError){

                    var url = baseUrl + entity;
                    if (searchEntity){
                        url+='/search/';
                        url+=searchEntity;
                    }
                    for (var i=0;i<args.length;i++){
                        if (i==0) url+='?';
                        for(var prop in args[i]){
                            url+=(prop+'='+args[i][prop]);
                        }
                        if (i+1!=args.length)url+='&';
                    }

                    $http
                        .get(url,this.configContentUndefined())
                        .then(onSuccess,onError);
                }

				this.create = function(entityName,entity,$scope,onSuccess,onError){
					var url= baseUrl + entityName;
					var that = this;
					var headerz = [];
					headerz['Content-Type'] = 'application/json';
					if ($scope.csrfHeaderName && $scope.csrfHeaderName != ''){
                        headers[$scope.csrfHeaderName] = $scope.csrfToken;
                    }

					$http.post(url,JSON.stringify(entity),{
                        transformRequest : angular.identity,
                        headers : headerz
                    })
                    .then(onSuccess,onError);

				}

				this.update = function(entityName,entity,$scope,onSuccess,onError){

					var headers = [];
					headers['Content-Type'] = 'application/merge-patch+json';
					if ($scope.csrfHeaderName && $scope.csrfHeaderName != ''){
					    headers[$scope.csrfHeaderName] = $scope.csrfToken;
					}

					$http.patch(
					    this.getSelfLink(entity),
					    JSON.stringify(entity),
					    {
						    transformRequest : angular.identity,
						    headers : headers
					    }
                    )
					.then(onSuccess,onError);
				}

				this.delete = function(object,$scope,onSuccess,onError){

					var url = this.getSelfLink(object)
					var headers = [];
					if ($scope.csrfHeaderName && $scope.csrfHeaderName != ''){
                        headers[$scope.csrfHeaderName] = $scope.csrfToken;
                    }

					$http.delete(
					    this.getSelfLink(object),
					    {
						    transformRequest : angular.identity,
						    headers : headers
					    }
                    )
					.then(onSuccess,onError);
				}

				this.getSelfLink = function(object){
					var url = object._links.self.href;
					var projectionIndex = url.indexOf('{');
                    if (projectionIndex > 0){
                        url = url.substring(0,projectionIndex);
                    }
                    var index = url.indexOf(pathname);
                    url = url.substring(index,url.length);
                    return url;
				}
				this.configContentUndefined = function(){
					return	{	transformRequest : angular.identity,
								headers : {'Content-Type' : undefined}
					 	   	};
				}
			}]);
}(window.angular));<commit_msg>Update api.js<commit_after>(function(angular){
	'use strict';

	/**
	 * Assumptions: 1-spring api is configured at server-root/api/**
	 *
	 */
	var apiModule = angular.module('api',[]);

	apiModule.service('api',
			['$http','$timeout',function($http,$timeout){

				var pathname = window.location.pathname;
				var pathnameWithoutSlash = pathname.substring(1,pathname.length);
				var slashIndex = pathnameWithoutSlash.indexOf('/')
				if (slashIndex){
					pathname = pathname.substring(0,slashIndex + 1);
				}
				var baseUrl = pathname + '/api/';

				this.getReferenceData = function(entityName,onSuccess,onError){
					var url = baseUrl + entityName + '?page=0&size=200';
					$http
						.get(url,this.configContentUndefined())
						.then(onSuccess,onError);

				}

				this.getProfile = function(entity,onSuccess,onError){
					var that = this;
					var url = baseUrl + '/profile/' + entity;
					$http
						.get(url,this.configContentUndefined())
						.then(onSuccess,onError);
				}

				this.fetchSortedPage = function(
                    entity,
                    searchEntity,
                    args,
                    $scope,
                    onSuccess,
                    onError){

                    var url = baseUrl + entity;
                    if (searchEntity){
                        url+='/search/';
                        url+=searchEntity;
                    }
                    for (var i=0;i<args.length;i++){
                        if (i==0) url+='?';
                        for(var prop in args[i]){
                            url+=(prop+'='+args[i][prop]);
                        }
                        if (i+1!=args.length)url+='&';
                    }

                    $http
                        .get(url,this.configContentUndefined())
                        .then(onSuccess,onError);
                }

				this.create = function(entityName,entity,$scope,onSuccess,onError){
					var url= baseUrl + entityName;
					var that = this;
					var headers = [];
					headers['Content-Type'] = 'application/json';
					if ($scope.csrfHeaderName && $scope.csrfHeaderName != ''){
                        headers[$scope.csrfHeaderName] = $scope.csrfToken;
                    }

					$http.post(url,JSON.stringify(entity),{
                        transformRequest : angular.identity,
                        headers : headers
                    })
                    .then(onSuccess,onError);

				}

				this.update = function(entityName,entity,$scope,onSuccess,onError){

					var headers = [];
					headers['Content-Type'] = 'application/merge-patch+json';
					if ($scope.csrfHeaderName && $scope.csrfHeaderName != ''){
					    headers[$scope.csrfHeaderName] = $scope.csrfToken;
					}

					$http.patch(
					    this.getSelfLink(entity),
					    JSON.stringify(entity),
					    {
						    transformRequest : angular.identity,
						    headers : headers
					    }
                    )
					.then(onSuccess,onError);
				}

				this.delete = function(object,$scope,onSuccess,onError){

					var url = this.getSelfLink(object)
					var headers = [];
					if ($scope.csrfHeaderName && $scope.csrfHeaderName != ''){
                        headers[$scope.csrfHeaderName] = $scope.csrfToken;
                    }

					$http.delete(
					    this.getSelfLink(object),
					    {
						    transformRequest : angular.identity,
						    headers : headers
					    }
                    )
					.then(onSuccess,onError);
				}

				this.getSelfLink = function(object){
					var url = object._links.self.href;
					var projectionIndex = url.indexOf('{');
                    if (projectionIndex > 0){
                        url = url.substring(0,projectionIndex);
                    }
                    var index = url.indexOf(pathname);
                    url = url.substring(index,url.length);
                    return url;
				}
				this.configContentUndefined = function(){
					return	{	transformRequest : angular.identity,
								headers : {'Content-Type' : undefined}
					 	   	};
				}
			}]);
}(window.angular));
<|endoftext|>


<commit_before>/*
@page developwithgit Developing With Git

Thank you so much for developing with git.  You're making
the world better for yourself and others.  With GIT we can see any change
you make to JavaScriptMVC and share them with other people.

Before we get started, we're assuming you:

 - know git
 - have a github account setup
 - have a project that is already using git

If you don't, you might find the following resources helpful:

 - [http://git.or.cz/course/svn.html Git - SVN Crash Course]
 - [http://github.com/ Github] - creat an account here
 - [http://help.github.com/msysgit-key-setup/ SSH Key Setup]

## Git -ing JavaScriptMVC

JavaScriptMVC is comprised of four sub projects:

 - [http://github.com/jupiterjs/steal]
 - [http://github.com/jupiterjs/jquerymx]
 - [http://github.com/jupiterjs/documentjs]
 - [http://github.com/jupiterjs/funcunit]

We're going to fork each of these projects and add them as submodules to your
master git project.

#### Forking

Assuming you have a github account set up, and are signed in,
click each of the github links and click
the  button (in the upper right of the page).

PRO TIP:
  If you're working for a company, you should create company forks and give
  employees access to the company forks.  This will keep everyone using the
  same version.

#### Adding a submodule

Now add your forked repositories as submodules
to your project like:

@codestart text
git submodule add git@github.com:_YOU_/steal.git public/steal
git submodule add git@github.com:_YOU_/jquerymx.git public/jquery
git submodule add git@github.com:_YOU_/documentjs.git public/documentjs
git submodule add git@github.com:_YOU_/funcunit.git public/funcunit
@codeend

_Note_: Learn a little more about submodules [here](http://johnleach.co.uk/words/archives/2008/10/12/323/git-submodules-in-n-easy-steps Submodules).

There are 3 important things to notice:

 1. Change _YOU_ with your github username.

 2. Add the submodules in a public folder, where the server hosts static content.

 3. Copy the javascriptmvc repository into a jquery folder.

Next, you have to install and update the submodules.  Run:

@codestart
git submodule init
git submodule update
@codeend

Finally, you just have to move the 'js' commands out of steal for convienence:

@codestart text
[WINDOWS] > steal\js steal\make.js

[Lin/Mac] > ./steal/js steal/make.js
@codeend

Yes, that was more annoying then just downloading it, but you're making the
world a better place for yourself and for others.

 */
//break<commit_msg>adding git page<commit_after>/*
@page developwithgit Developing With Git

Thank you so much for developing with git.  You're making
the world better for yourself and others.  With GIT we can see any change
you make to JavaScriptMVC and share them with other people.

Before we get started, we're assuming you:

 - know git
 - have a github account setup
 - have a project that is already using git

If you don't, you might find the following resources helpful:

 - [http://git.or.cz/course/svn.html Git - SVN Crash Course]
 - [http://github.com/ Github] - create an account here
 - [http://help.github.com/msysgit-key-setup/ SSH Key Setup]

## Git -ing JavaScriptMVC

JavaScriptMVC is comprised of five sub projects:

 - [http://github.com/jupiterjs/steal]
 - [http://github.com/jupiterjs/jquerymx]
 - [http://github.com/jupiterjs/documentjs]
 - [http://github.com/jupiterjs/funcunit]
 - [http://github.com/jupiterjs/syn]

We're going to fork each of these projects and add them as submodules to your
master git project.

#### Forking

Assuming you have a github account set up, and are signed in,
click each of the github links and click
the  button (in the upper right of the page).

PRO TIP:
  If you're working for a company, you should create company forks and give
  employees access to the company forks.  This will keep everyone using the
  same version.

#### Adding a submodule

Now add the first four forked repositories as submodules
to your project like:

@codestart text
git submodule add git@github.com:_YOU_/steal.git public/steal
git submodule add git@github.com:_YOU_/jquerymx.git public/jquery
git submodule add git@github.com:_YOU_/documentjs.git public/documentjs
git submodule add git@github.com:_YOU_/funcunit.git public/funcunit
@codeend

_Note_: Learn a little more about submodules [here](http://johnleach.co.uk/words/archives/2008/10/12/323/git-submodules-in-n-easy-steps Submodules).

There are 3 important things to notice:

 1. Change _YOU_ with your github username.

 2. Add the submodules in a public folder, where the server hosts static content.

 3. Copy the javascriptmvc repository into a jquery folder.

Next, you have to install and update the submodules.  Run:

@codestart
git submodule init
git submodule update
@codeend

You may also have to change to each directory and checkout the master branch:

@codestart
cd steal
git checkout master
@codeend

#### Installing Syn

Syn is a submodule of the funcunit project.  To add your fork to funcunit,
first you have to change the submodule to point to your fork
(because it points to the jupiterjs fork).  To do this, open funcunit/.gitmodules.  You'll see:

@codestart text
[submodule "syn"]
	path = syn
	url = git@github.com:jupiterjs/syn.git
	update = merge
@codeend

Change the URL to your own fork, like:

@codestart text
url = git@github.com:_YOU_/syn.git
@codeend

Now install syn, like the other submodules:

@codestart
cd funcunit
git submodule init
git submodule update
cd syn
git checkout master
@codeend

Finally, you just have to move the 'js' commands out of steal for convienence:

@codestart text
[WINDOWS] > steal\js steal\make.js

[Lin/Mac] > ./steal/js steal/make.js
@codeend

Yes, that was more annoying then just downloading it, but you're making the
world a better place for yourself and for others.

 */
//break<|endoftext|>


<commit_before>frappe.provide('frappe.views');

frappe.views.GanttView = frappe.views.ListRenderer.extend({
	name: 'Gantt',
	prepare: function(values) {
		this.items = values;
		this.prepare_tasks();
		this.prepare_dom();
	},

	render_view: function(values) {
		var me = this;
		this.prepare(values);
		this.render_gantt();
	},

	set_defaults: function() {
		this._super();
		this.no_realtime = true;
		this.page_title = this.page_title + ' ' + __('Gantt');
	},

	init_settings: function() {
		this._super();
		this.field_map = frappe.views.calendar[this.doctype].field_map;
		this.order_by = this.order_by || this.field_map.start + ' asc';
	},

	prepare_dom: function() {
		this.wrapper.css('overflow', 'auto')
			.append('<svg class="gantt-container" width="20" height="20"></svg>')
	},

	render_gantt: function(tasks) {
		var me = this;
		this.gantt_view_mode = this.user_settings.gantt_view_mode || 'Day';
		var field_map = frappe.views.calendar[this.doctype].field_map;

		this.gantt = new Gantt(".gantt-container", this.tasks, {
			view_mode: this.gantt_view_mode,
			date_format: "YYYY-MM-DD",
			on_click: function (task) {
				frappe.set_route('Form', task.doctype, task.id);
			},
			on_date_change: function(task, start, end) {
				if(!me.can_write()) return;
				me.update_gantt_task(task, start, end);
			},
			on_progress_change: function(task, progress) {
				if(!me.can_write()) return;
				var progress_fieldname = 'progress';

				if($.isFunction(field_map.progress)) {
					progress_fieldname = null;
				} else if(field_map.progress) {
					progress_fieldname = field_map.progress;
				}

				if(progress_fieldname) {
					frappe.db.set_value(task.doctype, task.id,
						progress_fieldname, parseInt(progress));
				}
			},
			on_view_change: function(mode) {
				// save view mode
				frappe.model.user_settings.save(me.doctype, 'Gantt', {
					gantt_view_mode: mode
				});
			},
			custom_popup_html: function(task) {
				var item = me.get_item(task.id);

				var html =
					`
${task.name}

${task._start.format('MMM D')} - ${task._end.format('MMM D')}
`;

				// custom html in doctype settings
				var custom = me.settings.gantt_custom_popup_html;
				if(custom && $.isFunction(custom)) {
					var ganttobj = task;
					html = custom(ganttobj, item);
				}
				return '
' + html + '
';
			}
		});
		this.render_dropdown();
		this.set_colors();
	},

	render_dropdown: function() {
		var me = this;
		var view_modes = this.gantt.config.view_modes || [];
		var dropdown = "
" +
			"" +
			""+__(this.gantt_view_mode)+"" +
			"

" +
			"
";

		// view modes (for translation) __("Day"), __("Week"), __("Month"),
		//__("Half Day"), __("Quarter Day")

		var dropdown_list = "";
		view_modes.forEach(function(view_mode) {
			dropdown_list += "
" +
				"" +
				__(view_mode) + "
";
		});
		var $dropdown = $(dropdown)
		$dropdown.find(".dropdown-menu").append(dropdown_list);
		me.list_view.$page
			.find(`[data-list-renderer='Gantt'] > .list-row-right`)
			.css("margin-right", "15px").html($dropdown)
		$dropdown.on("click", ".option", function() {
			var mode = $(this).data('value');
			me.gantt.change_view_mode(mode);
			$dropdown.find(".dropdown-text").text(mode);
		});
	},

	set_colors: function() {
		const classes = this.tasks
			.map(t => t.custom_class)
			.filter(c => c && c.startsWith('color-'));

		let style = classes.map(c => {
			const class_name = c.replace('#', '');
			const bar_color = '#' + c.substr(6);
			const progress_color = frappe.ui.color.get_contrast_color(bar_color);
			return `
				.gantt .bar-wrapper.${class_name} .bar {
					fill: ${bar_color};
				}
				.gantt .bar-wrapper.${class_name} .bar-progress {
					fill: ${progress_color};
				}
			`;
		}).join("");

		style = `<style>${style}</style>`;

		this.wrapper.prepend(style);
	},

	prepare_tasks: function() {
		var me = this;
		var meta = frappe.get_meta(this.doctype);
		var field_map = frappe.views.calendar[this.doctype].field_map;
		this.tasks = this.items.map(function(item) {
			// set progress
			var progress = 0;
			if(field_map.progress && $.isFunction(field_map.progress)) {
				progress = field_map.progress(item);
			} else if(field_map.progress) {
				progress = item[field_map.progress]
			}

			// title
			if(meta.title_field) {
				var label = $.format("{0} ({1})", [item[meta.title_field], item.name]);
			} else {
				var label = item[field_map.title];
			}

			var r = {
				start: item[field_map.start],
				end: item[field_map.end],
				name: label,
				id: item[field_map.id || 'name'],
				doctype: me.doctype,
				progress: progress,
				dependencies: item.depends_on_tasks || ""
			};

			if(item.color && frappe.ui.color.validate_hex(item.color)) {
				r['custom_class'] = 'color-' + item.color.substr(1);
			}

			if(item.is_milestone) {
				r['custom_class'] = 'bar-milestone';
			}

			return r;
		});
	},
	get_item: function(name) {
		return this.items.find(function(item) {
			return item.name === name;
		});
	},
	update_gantt_task: function(task, start, end) {
		var me = this;
		if(me.gantt.updating_task) {
			setTimeout(me.update_gantt_task.bind(me, task, start, end), 200)
			return;
		}
		me.gantt.updating_task = true;

		var field_map = frappe.views.calendar[this.doctype].field_map;
		frappe.call({
			method: 'frappe.desk.gantt.update_task',
			args: {
				args: {
					doctype: task.doctype,
					name: task.id,
					start: start.format('YYYY-MM-DD'),
					end: end.format('YYYY-MM-DD')
				},
				field_map: field_map
			},
			callback: function() {
				me.gantt.updating_task = false;
				frappe.show_alert({message:__("Saved"), indicator: 'green'}, 1);
			}
		});
	},
	get_header_html: function() {
		return frappe.render_template('list_item_row_head', { main: '', list: this });
	},
	refresh: function(values) {
		this.prepare(values);
		this.render();
	},
	can_write: function() {
		if(frappe.model.can_write(this.doctype)) {
			return true;
		} else {
			// reset gantt state
			this.gantt.change_view_mode(this.gantt_view_mode);
			frappe.show_alert({message: __("Not permitted"), indicator: 'red'}, 1);
			return false;
		}
	},
	set_columns: function() {},
	required_libs: [
		"assets/frappe/js/lib/snap.svg-min.js",
		"assets/frappe/js/lib/frappe-gantt/frappe-gantt.js"
	]
});<commit_msg>Dropdown to select view mode fix (#5100)<commit_after>frappe.provide('frappe.views');

frappe.views.GanttView = frappe.views.ListRenderer.extend({
	name: 'Gantt',
	prepare: function(values) {
		this.items = values;
		this.prepare_tasks();
		this.prepare_dom();
	},

	render_view: function(values) {
		var me = this;
		this.prepare(values);
		this.render_gantt();
	},

	set_defaults: function() {
		this._super();
		this.no_realtime = true;
		this.page_title = this.page_title + ' ' + __('Gantt');
	},

	init_settings: function() {
		this._super();
		this.field_map = frappe.views.calendar[this.doctype].field_map;
		this.order_by = this.order_by || this.field_map.start + ' asc';
	},

	prepare_dom: function() {
		this.wrapper.css('overflow', 'auto')
			.append('<svg class="gantt-container" width="20" height="20"></svg>')
	},

	render_gantt: function(tasks) {
		var me = this;
		this.gantt_view_mode = this.user_settings.gantt_view_mode || 'Day';
		var field_map = frappe.views.calendar[this.doctype].field_map;

		this.gantt = new Gantt(".gantt-container", this.tasks, {
			view_mode: this.gantt_view_mode,
			date_format: "YYYY-MM-DD",
			on_click: function (task) {
				frappe.set_route('Form', task.doctype, task.id);
			},
			on_date_change: function(task, start, end) {
				if(!me.can_write()) return;
				me.update_gantt_task(task, start, end);
			},
			on_progress_change: function(task, progress) {
				if(!me.can_write()) return;
				var progress_fieldname = 'progress';

				if($.isFunction(field_map.progress)) {
					progress_fieldname = null;
				} else if(field_map.progress) {
					progress_fieldname = field_map.progress;
				}

				if(progress_fieldname) {
					frappe.db.set_value(task.doctype, task.id,
						progress_fieldname, parseInt(progress));
				}
			},
			on_view_change: function(mode) {
				// save view mode
				frappe.model.user_settings.save(me.doctype, 'Gantt', {
					gantt_view_mode: mode
				});
			},
			custom_popup_html: function(task) {
				var item = me.get_item(task.id);

				var html =
					`
${task.name}

${task._start.format('MMM D')} - ${task._end.format('MMM D')}
`;

				// custom html in doctype settings
				var custom = me.settings.gantt_custom_popup_html;
				if(custom && $.isFunction(custom)) {
					var ganttobj = task;
					html = custom(ganttobj, item);
				}
				return '
' + html + '
';
			}
		});
		this.render_dropdown();
		this.set_colors();
	},

	render_dropdown: function() {
		var me = this;
		var view_modes = this.gantt.config.view_modes || [];
		var dropdown = "
" +
			"" +
			""+__(this.gantt_view_mode)+"" +
			"

" +
			"
";

		// view modes (for translation) __("Day"), __("Week"), __("Month"),
		//__("Half Day"), __("Quarter Day")

		var dropdown_list = "";
		view_modes.forEach(function(view_mode) {
			dropdown_list += "
" +
				"" +
				__(view_mode) + "
";
		});
		var $dropdown = $(dropdown)
		$dropdown.find(".dropdown-menu").append(dropdown_list);
		me.list_view.$page
			.find(`[data-list-renderer='Gantt'] > .list-row-right`)
			.css("margin-right", "15px").html($dropdown)
		$dropdown.on("click", ".option", function() {
			var mode = $(this).data('value');
			me.gantt.change_view_mode(mode);
			$dropdown.find(".dropdown-text").text(mode);
			$dropdown.removeClass('open');
		});
		$dropdown.on('click', '.dropdown-toggle', function() {
			$dropdown.addClass('open');
		});
	},

	set_colors: function() {
		const classes = this.tasks
			.map(t => t.custom_class)
			.filter(c => c && c.startsWith('color-'));

		let style = classes.map(c => {
			const class_name = c.replace('#', '');
			const bar_color = '#' + c.substr(6);
			const progress_color = frappe.ui.color.get_contrast_color(bar_color);
			return `
				.gantt .bar-wrapper.${class_name} .bar {
					fill: ${bar_color};
				}
				.gantt .bar-wrapper.${class_name} .bar-progress {
					fill: ${progress_color};
				}
			`;
		}).join("");

		style = `<style>${style}</style>`;

		this.wrapper.prepend(style);
	},

	prepare_tasks: function() {
		var me = this;
		var meta = frappe.get_meta(this.doctype);
		var field_map = frappe.views.calendar[this.doctype].field_map;
		this.tasks = this.items.map(function(item) {
			// set progress
			var progress = 0;
			if(field_map.progress && $.isFunction(field_map.progress)) {
				progress = field_map.progress(item);
			} else if(field_map.progress) {
				progress = item[field_map.progress]
			}

			// title
			if(meta.title_field) {
				var label = $.format("{0} ({1})", [item[meta.title_field], item.name]);
			} else {
				var label = item[field_map.title];
			}

			var r = {
				start: item[field_map.start],
				end: item[field_map.end],
				name: label,
				id: item[field_map.id || 'name'],
				doctype: me.doctype,
				progress: progress,
				dependencies: item.depends_on_tasks || ""
			};

			if(item.color && frappe.ui.color.validate_hex(item.color)) {
				r['custom_class'] = 'color-' + item.color.substr(1);
			}

			if(item.is_milestone) {
				r['custom_class'] = 'bar-milestone';
			}

			return r;
		});
	},
	get_item: function(name) {
		return this.items.find(function(item) {
			return item.name === name;
		});
	},
	update_gantt_task: function(task, start, end) {
		var me = this;
		if(me.gantt.updating_task) {
			setTimeout(me.update_gantt_task.bind(me, task, start, end), 200)
			return;
		}
		me.gantt.updating_task = true;

		var field_map = frappe.views.calendar[this.doctype].field_map;
		frappe.call({
			method: 'frappe.desk.gantt.update_task',
			args: {
				args: {
					doctype: task.doctype,
					name: task.id,
					start: start.format('YYYY-MM-DD'),
					end: end.format('YYYY-MM-DD')
				},
				field_map: field_map
			},
			callback: function() {
				me.gantt.updating_task = false;
				frappe.show_alert({message:__("Saved"), indicator: 'green'}, 1);
			}
		});
	},
	get_header_html: function() {
		return frappe.render_template('list_item_row_head', { main: '', list: this });
	},
	refresh: function(values) {
		this.prepare(values);
		this.render();
	},
	can_write: function() {
		if(frappe.model.can_write(this.doctype)) {
			return true;
		} else {
			// reset gantt state
			this.gantt.change_view_mode(this.gantt_view_mode);
			frappe.show_alert({message: __("Not permitted"), indicator: 'red'}, 1);
			return false;
		}
	},
	set_columns: function() {},
	required_libs: [
		"assets/frappe/js/lib/snap.svg-min.js",
		"assets/frappe/js/lib/frappe-gantt/frappe-gantt.js"
	]
});<|endoftext|>


<commit_before>var Hellrazor = (function () {
  this.createError = function(name, message) {

    if(!name) {
      throw new Error("name: is not defined");
    }
    else if(typeof name != "string") {
      throw new Error("name: is not of type String");
    }

    if(!message) {
      throw new Error("message: is not defined");
    }
    else if(typeof message != "string") {
      throw new Error("message: is not of type String");
    }

    function customError(msg) {
      var tmp = Error.call(this); // temporary Object from the Error Object

      if(msg) {
        if(typeof msg != "string") {
          throw new Error("message: is not of type String");
        }
      }

      if(Object.defineProperties) {
        Object.defineProperties(this, {
          "stack": {
            value: tmp.stack
          },
          "name": {
            value: name
          },
          "message": {
            value: (msg || message)
          }
        });
      }
      else {
        this.name = name;
        this.message = msg || message;
      }
    }

    if(Object.create) {
      customError.prototype = Object.create(Error.prototype);
    }
    else {
      customError.prototype = new Error();
    }
    customError.prototype.constructor = customError;

    return customError;
  };

  return this;
}());
<commit_msg>stopped caring 15 commits ago<commit_after>var Hellrazor = (function () {
  this.createError = function(name, message) {
    if(!name) {
      throw new Error("name: is not defined");
    }
    else if(typeof name != "string") {
      throw new Error("name: is not of type String");
    }

    if(!message) {
      throw new Error("message: is not defined");
    }
    else if(typeof message != "string") {
      throw new Error("message: is not of type String");
    }

    function customError(msg) {
      var tmp = Error.call(this); // temporary Object from the Error Object

      if(msg) {
        if(typeof msg != "string") {
          throw new Error("message: is not of type String");
        }
      }

      if(Object.defineProperties) {
        Object.defineProperties(this, {
          "stack": {
            value: tmp.stack
          },
          "name": {
            value: name
          },
          "message": {
            value: (msg || message)
          }
        });
      }
      else {
        this.name = name;
        this.message = msg || message;
      }
    }

    if(Object.create) {
      customError.prototype = Object.create(Error.prototype);
    }
    else {
      customError.prototype = new Error();
    }
    customError.prototype.constructor = customError;

    return customError;
  };

  return this;
}());
<|endoftext|>


<commit_before>'use strict';
var React = require('react');
var _ = require('underscore');
var globals = require('../globals');
var form = require('../../libs/bootstrap/form');

var Input = form.Input;
var Form = form.Form;
var FormMixin = form.FormMixin;
var queryKeyValue = globals.queryKeyValue;
var editQueryValue = globals.editQueryValue;
var addQueryKey = globals.addQueryKey;

// General purpose title rendering
var Title = module.exports.Title = React.createClass({
    mixins: [FormMixin],

    propTypes: {
        data: React.PropTypes.object, // ClinVar data payload
        interpretationUuid: React.PropTypes.string,
        interpretation: React.PropTypes.object,
        setSummaryVisibility: React.PropTypes.func,
        summaryVisible: React.PropTypes.bool,
        getSelectedTab: React.PropTypes.func,
        persistProvisionalCheckBox: React.PropTypes.func,
        disabledProvisionalCheckbox: React.PropTypes.bool
    },

    getInitialState: function() {
        return {
            interpretation: null, // parent interpretation object
            summaryVisible: this.props.summaryVisible,
            disabledProvisionalCheckbox: this.props.disabledProvisionalCheckbox
        };
    },

    componentWillReceiveProps: function(nextProps) {
        // this block is for handling props and states when props (external data) is updated after the initial load/rendering
        // when props are updated, update the parent interpreatation object, if applicable
        if (typeof nextProps.interpretation !== undefined && !_.isEqual(nextProps.interpretation, this.props.interpretation)) {
            this.setState({interpretation: nextProps.interpretation});
        }
        this.setState({
            summaryVisible: nextProps.summaryVisible,
            disabledProvisionalCheckbox: nextProps.disabledProvisionalCheckbox
        });
    },

    renderSubtitle: function(interpretation, variant) {
        var associatedDisease = 'Evidence View Only';
        if (interpretation) {
            if (interpretation.disease && interpretation.disease.term) {
                associatedDisease = This interpretation is associated with the disease {interpretation.disease.term};
            } else {
                associatedDisease = 'This interpretation is not yet associated with a disease';
            }
        }
        return associatedDisease;
    },

    renderSummaryButtonTitle: function() {
        let title = '';
        let summaryKey = queryKeyValue('summary', this.props.href);
        let summaryState = this.state.isSummaryVisible;
        if (summaryKey) {
            title = 'Return to Interpretation';
        } else {
            title = 'View Summary';
        }
        return title;
    },

    // handler for 'View Summary' & 'Return to Interpretation' button click events
    handleSummaryButtonEvent: function(e) {
        e.preventDefault(); e.stopPropagation();
        let summaryVisible = this.state.summaryVisible;
        let summaryKey = queryKeyValue('summary', window.location.href);
        if (!summaryVisible) {
            this.props.setSummaryVisibility(true);
            this.props.persistProvisionalCheckBox(this.state.disabledProvisionalCheckbox);
            if (!summaryKey) {
                window.history.replaceState(window.state, '', addQueryKey(window.location.href, 'summary', 'true'));
            }
        }
        if (summaryVisible) {
            this.props.setSummaryVisibility(false);
            this.props.persistProvisionalCheckBox(this.state.disabledProvisionalCheckbox);
            if (summaryKey) {
                window.history.replaceState(window.state, '', editQueryValue(window.location.href, 'summary', null));
                let tabKey = queryKeyValue('tab', window.location.href);
                if (tabKey) {
                    this.props.getSelectedTab(tabKey);
                }
            }
        }
    },

    render: function() {
        var variant = this.props.data;
        var interpretation = this.state.interpretation;

        var variantTitle = (variant && variant.clinvarVariantTitle) ? variant.clinvarVariantTitle : null;
        if (variant && !variantTitle && variant.hgvsNames && variant.hgvsNames != {}) {
            variantTitle = variant.hgvsNames.GRCh38 ? variant.hgvsNames.GRCh38+' (GRCh38)': (variant.carId ? variant.carId : null);
        } else if (!variantTitle) {
            variantTitle = 'A preferred title is not available';
        }

        var calculatePatho_button = false;
        if (this.props.interpretationUuid) {
            calculatePatho_button = true;
        }

        const summaryButtonTitle = this.state.summaryVisible ? 'Return to Interpretation' : 'View Summary';

        return (

{variantTitle}{this.props.children}

{this.renderSubtitle(interpretation, variant)}

                {variant && calculatePatho_button ?

                                <Input type="button-button" inputClassName="btn btn-primary pull-right view-summary"
                                    title={summaryButtonTitle} clickHandler={this.handleSummaryButtonEvent} />

                : null}

        );
    }
});
<commit_msg>Removed provisional interpretation checkbox state/props handling<commit_after>'use strict';
var React = require('react');
var _ = require('underscore');
var globals = require('../globals');
var form = require('../../libs/bootstrap/form');

var Input = form.Input;
var Form = form.Form;
var FormMixin = form.FormMixin;
var queryKeyValue = globals.queryKeyValue;
var editQueryValue = globals.editQueryValue;
var addQueryKey = globals.addQueryKey;

// General purpose title rendering
var Title = module.exports.Title = React.createClass({
    mixins: [FormMixin],

    propTypes: {
        data: React.PropTypes.object, // ClinVar data payload
        interpretationUuid: React.PropTypes.string,
        interpretation: React.PropTypes.object,
        setSummaryVisibility: React.PropTypes.func,
        summaryVisible: React.PropTypes.bool,
        getSelectedTab: React.PropTypes.func
    },

    getInitialState: function() {
        return {
            interpretation: null, // parent interpretation object
            summaryVisible: this.props.summaryVisible
        };
    },

    componentWillReceiveProps: function(nextProps) {
        // this block is for handling props and states when props (external data) is updated after the initial load/rendering
        // when props are updated, update the parent interpreatation object, if applicable
        if (typeof nextProps.interpretation !== undefined && !_.isEqual(nextProps.interpretation, this.props.interpretation)) {
            this.setState({interpretation: nextProps.interpretation});
        }
        this.setState({
            summaryVisible: nextProps.summaryVisible
        });
    },

    renderSubtitle: function(interpretation, variant) {
        var associatedDisease = 'Evidence View Only';
        if (interpretation) {
            if (interpretation.disease && interpretation.disease.term) {
                associatedDisease = This interpretation is associated with the disease {interpretation.disease.term};
            } else {
                associatedDisease = 'This interpretation is not yet associated with a disease';
            }
        }
        return associatedDisease;
    },

    renderSummaryButtonTitle: function() {
        let title = '';
        let summaryKey = queryKeyValue('summary', this.props.href);
        let summaryState = this.state.isSummaryVisible;
        if (summaryKey) {
            title = 'Return to Interpretation';
        } else {
            title = 'View Summary';
        }
        return title;
    },

    // handler for 'View Summary' & 'Return to Interpretation' button click events
    handleSummaryButtonEvent: function(e) {
        e.preventDefault(); e.stopPropagation();
        let summaryVisible = this.state.summaryVisible;
        let summaryKey = queryKeyValue('summary', window.location.href);
        if (!summaryVisible) {
            this.props.setSummaryVisibility(true);
            if (!summaryKey) {
                window.history.replaceState(window.state, '', addQueryKey(window.location.href, 'summary', 'true'));
            }
        }
        if (summaryVisible) {
            this.props.setSummaryVisibility(false);
            if (summaryKey) {
                window.history.replaceState(window.state, '', editQueryValue(window.location.href, 'summary', null));
                let tabKey = queryKeyValue('tab', window.location.href);
                if (tabKey) {
                    this.props.getSelectedTab(tabKey);
                }
            }
        }
    },

    render: function() {
        var variant = this.props.data;
        var interpretation = this.state.interpretation;

        var variantTitle = (variant && variant.clinvarVariantTitle) ? variant.clinvarVariantTitle : null;
        if (variant && !variantTitle && variant.hgvsNames && variant.hgvsNames != {}) {
            variantTitle = variant.hgvsNames.GRCh38 ? variant.hgvsNames.GRCh38+' (GRCh38)': (variant.carId ? variant.carId : null);
        } else if (!variantTitle) {
            variantTitle = 'A preferred title is not available';
        }

        var calculatePatho_button = false;
        if (this.props.interpretationUuid) {
            calculatePatho_button = true;
        }

        const summaryButtonTitle = this.state.summaryVisible ? 'Return to Interpretation' : 'View Summary';

        return (

{variantTitle}{this.props.children}

{this.renderSubtitle(interpretation, variant)}

                {variant && calculatePatho_button ?

                                <Input type="button-button" inputClassName="btn btn-primary pull-right view-summary"
                                    title={summaryButtonTitle} clickHandler={this.handleSummaryButtonEvent} />

                : null}

        );
    }
});
<|endoftext|>


<commit_before>'use strict'

const _ = require('lodash'),
      request = require('request'),
      urljoin = require('url-join');

class Client {
  constructor(options) {
    const _defaultOptions = {
      endpoint: null,
      token: null,
      intervalInSeconds: 5 * 60,
      requestTimeoutInSeconds: 1 * 60,
      production: process.env.NODE_ENV === 'production',
      debug: false
    };

    const mergedOptions = _.extend(
      _.clone(_defaultOptions),
      _.clone(options)
    );

    this.endpoint = mergedOptions.endpoint;
    this.intervalInSeconds = mergedOptions.intervalInSeconds;
    this.requestTimeoutInSeconds = mergedOptions.requestTimeoutInSeconds;
    this.token = mergedOptions.token;
    this.production = mergedOptions.production;
    this.debug = mergedOptions.debug;

    if(!this.endpoint) {
      throw new Error('An endpoint must be provided!');
    }

    if(!this.token) {
      throw new Error('A token must be provided!');
    }

    if(this.intervalInSeconds <= this.requestTimeoutInSeconds) {
      throw new Error(`The interval (${this.intervalInSeconds}s) must be greater than the request timeout (${this.requestTimeoutInSeconds}s)`);
    }

    if(!this.production) {
      console.log('meerkat-client:', 'The production option is set to false. No API calls will be made');
    }

    if(this.debug) {
      console.log('meerkat-client:', 'Debug mode is active');
    }

    this._sendPing();

    setInterval(() => {
        this._sendPing();
      }.bind(this),
      this.intervalInSeconds * 1000
    );
  }

  _sendPing() {
    const options = {
      url: urljoin(this.endpoint, '/api/v1/heartbeat'),
      method: 'POST',
      json: true,
      timeout: this.requestTimeoutInSeconds * 1000,
      headers: {
        'X-MEERKAT-TOKEN': this.token
      }
    };

    if(!this.production) {
      return;
    }

    request(options, (error, response, body) => {
      if(this.debug) {
        if(error) {
          return console.error('meerkat-client:', 'Failed to send meerkat heartbeat:', error);
        }

        console.log('meerkat-client:', 'heartbeat sent!');
      }
    });
  }

}

module.exports = Client
<commit_msg>renamed ping to heatbeat<commit_after>'use strict'

const _ = require('lodash'),
      request = require('request'),
      urljoin = require('url-join');

class Client {
  constructor(options) {
    const _defaultOptions = {
      endpoint: null,
      token: null,
      intervalInSeconds: 5 * 60,
      requestTimeoutInSeconds: 1 * 60,
      production: process.env.NODE_ENV === 'production',
      debug: false
    };

    const mergedOptions = _.extend(
      _.clone(_defaultOptions),
      _.clone(options)
    );

    this.endpoint = mergedOptions.endpoint;
    this.intervalInSeconds = mergedOptions.intervalInSeconds;
    this.requestTimeoutInSeconds = mergedOptions.requestTimeoutInSeconds;
    this.token = mergedOptions.token;
    this.production = mergedOptions.production;
    this.debug = mergedOptions.debug;

    if(!this.endpoint) {
      throw new Error('An endpoint must be provided!');
    }

    if(!this.token) {
      throw new Error('A token must be provided!');
    }

    if(this.intervalInSeconds <= this.requestTimeoutInSeconds) {
      throw new Error(`The interval (${this.intervalInSeconds}s) must be greater than the request timeout (${this.requestTimeoutInSeconds}s)`);
    }

    if(!this.production) {
      console.log('meerkat-client:', 'The production option is set to false. No API calls will be made');
    }

    if(this.debug) {
      console.log('meerkat-client:', 'Debug mode is active');
    }

    this._sendHeartbeat();

    setInterval(() => {
        this._sendHeartbeat();
      }.bind(this),
      this.intervalInSeconds * 1000
    );
  }

  _sendHeartbeat() {
    const options = {
      url: urljoin(this.endpoint, '/api/v1/heartbeat'),
      method: 'POST',
      json: true,
      timeout: this.requestTimeoutInSeconds * 1000,
      headers: {
        'X-MEERKAT-TOKEN': this.token
      }
    };

    if(!this.production) {
      return;
    }

    request(options, (error, response, body) => {
      if(this.debug) {
        if(error || response.statusCode !== 200) {
          return console.error('meerkat-client:', 'Failed to send meerkat heartbeat:', error);
        }

        console.log('meerkat-client:', 'heartbeat sent!');
      }
    });
  }

  _sendReport(type, payload, cb) {
    const options = {
      url: urljoin(this.endpoint, '/api/v1/report'),
      method: 'POST',
      json: true,
      body: { type: type, payload: JSON.stringify(payload) },
      timeout: this.requestTimeoutInSeconds * 1000,
      headers: {
        'X-MEERKAT-TOKEN': this.token
      }
    };

    request(options, (error, response, body) => {
      if(error || response.statusCode !== 201) {
        return cb(error || new Error(`Failed to send heartbeat. Server sent a HTTP ${response.statusCode}`));
      }

      return cb(null);
    });
  }

  reportError(error, cb) {
    return this._sendReport(
      'error',
      {
        message: error.message,
        stack: error.stack ? error.stack : null
      }, cb
    );
  }

}

module.exports = Client
<|endoftext|>


<commit_before>	function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

	var yetki_duzeyi = readCookie('yetki');
	var giris_yapan_ad=readCookie('ad');
	var giris_yapan_soyad=readCookie('soyad');

	var arac_cubugu;

	if(yetki_duzeyi==1){
	  arac_cubugu= new Ext.Toolbar({
         style:'margin-top: 0px',//100
		 height:30,
	     region: "north",
	    items:[
		{
                text:'Sorgulama İşlemleri',
                xtype:'splitbutton',
                icon:'Images/16/moduller.png',
                menu:[
				{
                        text:'Şehir İşlemleri',
						 handler:function () {
						sehirWindow.show();
                        }
						},

                  {
                        text:'Bölge İşlemleri',
						 handler:function () {
						bolgeWindow.show();
                        }

				} ,

            	{
                    text:'Seçmen İşlemleri',

                        handler:function () {
							secmenWindow.show();

                        }
                },

						{
                        text:'Anket İşlemleri',
                        icon:'Images/16/maden.png',
                        handler:function () {
						anketWindow.show();
                        }
                    }
            ]
            },

      <commit_msg>araç çubuğu devam<commit_after>	function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

	var yetki_duzeyi = readCookie('yetki');
	var giris_yapan_ad=readCookie('ad');
	var giris_yapan_soyad=readCookie('soyad');

	var arac_cubugu;

	if(yetki_duzeyi==1){
	  arac_cubugu= new Ext.Toolbar({
         style:'margin-top: 0px',//100
		 height:30,
	     region: "north",
	    items:[
		{
                text:'Sorgulama İşlemleri',
                xtype:'splitbutton',
                icon:'Images/16/moduller.png',
                menu:[
				{
                        text:'Şehir İşlemleri',
						 handler:function () {
						sehirWindow.show();
                        }
						},

                  {
                        text:'Bölge İşlemleri',
						 handler:function () {
						bolgeWindow.show();
                        }

				} ,

            	{
                    text:'Seçmen İşlemleri',

                        handler:function () {
							secmenWindow.show();

                        }
                },

						{
                        text:'Anket İşlemleri',
                        icon:'Images/16/maden.png',
                        handler:function () {
						anketWindow.show();
                        }
                    }
            ]
            },

		{
                text:'Kullanıcı İşlemleri',
			    xtype:'splitbutton',
                icon:'Images/16/yonetici.png',
                menu:[
                    {
                        text:'Yönetici İşlemleri',
                        icon:'Images/16/users.png',
                        handler:function () {
						  window.location = 'KULLANICILAR.php';

                        }
                    },
					 {
                        text:'Anketör İşlemleri',
                        icon:'Images/16/stil.png',
                        handler:function () {
						labelWindow.show();
                        }
                    }
                ]
            },

			{
                text:'Raporlama İşlemleri',
                xtype:'splitbutton',
                icon:'Images/16/yonetici.png',
                menu:[
                     {
                        text:'Anket raporlama',
                        icon:'Images/resmikurum.png',
                        handler:function () {

                             anketWindow.show();
                        }
                    },

                ]
            },

            {
                id:'HaritaTemizle',
                text:'Temizle',
                icon:'Images/clear.png',
                handler:function () {

      <|endoftext|>