<commit_before>var vows = require('vows'),
    assert = require('assert'),
    AssetGraph = require('../lib/AssetGraph'),
    cssText = '';

vows.describe('transforms.splitCssIfIeLimitIsReached').addBatch({
    'After loading a simple Css test case': {
        topic: function () {
            new AssetGraph({root: __dirname + '/splitCssIfIeLimitReached/'})
                .loadAssets('index.html')
                .populate()
                .minifyAssets({ type: 'Css', isLoaded: true})
                .run(this.callback);
        },
        'the graph should contain 1 Css asset': function (assetGraph) {
            var cssAssets = assetGraph.findAssets({type: 'Css'});

            assert.equal(cssAssets.length, 1);

            cssText = cssAssets.map(function (cssAsset) {
                return cssAsset.text;
            }).join('');
        },
        'the Css asset should contain 4096 rules': function (assetGraph) {
            assert.equal(assetGraph.findAssets({ type: 'Css' })[0].parseTree.cssRules.length, 4096);
        },
        'then running the splitCssIfIeLimitIsReached transform': {
            topic: function (assetGraph) {
                assetGraph.__infos = [];

                assetGraph
                    .on('info', function (err) {
                        assetGraph.__infos.push(err);
                    })
                    .splitCssIfIeLimitIsReached()
                    .run(this.callback);
            },
            'the graph should have 1 emitted info': function (assetGraph) {
                assert.equal(assetGraph.__infos.length, 1);
            },
            'the graph should contain 2 Css asset': function (assetGraph) {
                assert.equal(assetGraph.findAssets({type: 'Css'}).length, 2);
            },
            'each Css asset should be smaller than the original': function (assetGraph) {
                assetGraph.findAssets({type: 'Css'}).forEach(function (cssAsset) {
                    assert(cssAsset.text.length < cssText.length);
                });
            },
            'the concatenated css text content should be unchanged from before': function (assetGraph) {
                assert.equal(assetGraph.findAssets({type: 'Css'}).map(function (cssAsset) {
                        return cssAsset.text;
                    }).join(''), cssText);
            }
        }
    },

    'After loading a real life huge Css test case': {
        topic: function () {
            new AssetGraph({root: __dirname + '/splitCssIfIeLimitReached/'})
                .loadAssets('falcon.html')
                .populate()
                .minifyAssets({ type: 'Css', isLoaded: true})
                .run(this.callback);
        },
        'the graph should contain 1 Css asset': function (assetGraph) {
            var cssAssets = assetGraph.findAssets({type: 'Css'});

            assert.equal(cssAssets.length, 1);

            cssText = cssAssets.map(function (cssAsset) {
                return cssAsset.text;
            }).join('');
        },
        'the Css asset should contain 6290 rules': function (assetGraph) {
            var rules = assetGraph.findAssets({ type: 'Css' })[0].parseTree.cssRules.length;
            assetGraph.__rules = rules;
            assert.equal(rules, 6290);
        },
        'then running the splitCssIfIeLimitIsReached transform': {
            topic: function (assetGraph) {
                assetGraph.__infos = [];

                assetGraph
                    .on('info', function (err) {
                        assetGraph.__infos.push(err);
                    })
                    .splitCssIfIeLimitIsReached()
                    .run(this.callback);
            },
            'the graph should have 1 emitted info': function (assetGraph) {
                assert.equal(assetGraph.__infos.length, 1);
            },
            'the graph should contain 3 Css asset': function (assetGraph) {
                assert.equal(assetGraph.findAssets({type: 'Css'}).length, 3);
            },
            'each Css asset should be smaller than the original': function (assetGraph) {
                var cssAssets = assetGraph.findAssets({type: 'Css'}),
                    rules = [2806, 2398, 1086],
                    sum = 0;

                cssAssets.forEach(function (cssAsset, idx) {
                    var assetRules = cssAsset.parseTree.cssRules.length;
                    assert(cssAsset.text.length < cssText.length);
                    assert.equal(assetRules, rules[idx]);
                    sum += assetRules;
                });

                assert.equal(sum, assetGraph.__rules);
            },
            'the concatenated css text content should be unchanged from before': function (assetGraph) {
                assert.equal(assetGraph.findAssets({type: 'Css'}).map(function (cssAsset) {
                        return cssAsset.text;
                    }).join(''), cssText);
            }
        }
    }
})['export'](module);
<commit_msg>Added test case to make sure the splitCssIfIeLimitReached transform keeps relations to assets after splitting CSS<commit_after>var vows = require('vows'),
    assert = require('assert'),
    AssetGraph = require('../lib/AssetGraph'),
    cssText = '';

vows.describe('transforms.splitCssIfIeLimitIsReached').addBatch({
    'After loading a simple Css test case': {
        topic: function () {
            new AssetGraph({root: __dirname + '/splitCssIfIeLimitReached/'})
                .loadAssets('index.html')
                .populate()
                .minifyAssets({ type: 'Css', isLoaded: true})
                .run(this.callback);
        },
        'the graph should contain 1 Css asset': function (assetGraph) {
            var cssAssets = assetGraph.findAssets({type: 'Css'});

            assert.equal(cssAssets.length, 1);

            cssText = cssAssets.map(function (cssAsset) {
                return cssAsset.text;
            }).join('');
        },
        'the Css asset should contain 4096 rules': function (assetGraph) {
            assert.equal(assetGraph.findAssets({ type: 'Css' })[0].parseTree.cssRules.length, 4096);
        },
        'then running the splitCssIfIeLimitIsReached transform': {
            topic: function (assetGraph) {
                assetGraph.__infos = [];

                assetGraph
                    .on('info', function (err) {
                        assetGraph.__infos.push(err);
                    })
                    .splitCssIfIeLimitIsReached()
                    .run(this.callback);
            },
            'the graph should have 1 emitted info': function (assetGraph) {
                assert.equal(assetGraph.__infos.length, 1);
            },
            'the graph should contain 2 Css asset': function (assetGraph) {
                assert.equal(assetGraph.findAssets({type: 'Css'}).length, 2);
            },
            'each Css asset should be smaller than the original': function (assetGraph) {
                assetGraph.findAssets({type: 'Css'}).forEach(function (cssAsset) {
                    assert(cssAsset.text.length < cssText.length);
                });
            },
            'the concatenated css text content should be unchanged from before': function (assetGraph) {
                assert.equal(assetGraph.findAssets({type: 'Css'}).map(function (cssAsset) {
                        return cssAsset.text;
                    }).join(''), cssText);
            }
        }
    },

    'After loading a real life huge Css test case': {
        topic: function () {
            new AssetGraph({root: __dirname + '/splitCssIfIeLimitReached/'})
                .loadAssets('falcon.html')
                .populate()
                .minifyAssets({ type: 'Css', isLoaded: true})
                .mergeIdenticalAssets({
                    isLoaded: true
                })
                .run(this.callback);
        },
        'the graph should contain 1 Css asset': function (assetGraph) {
            var cssAssets = assetGraph.findAssets({type: 'Css'});

            assert.equal(cssAssets.length, 1);

            cssText = cssAssets.map(function (cssAsset) {
                return cssAsset.text;
            }).join('');
        },
        'the Css asset should contain 6290 rules': function (assetGraph) {
            var rules = assetGraph.findAssets({ type: 'Css' })[0].parseTree.cssRules.length;
            assetGraph.__rules = rules;
            assert.equal(rules, 6290);
        },
        'the graph should have 1 of each of asset types "png", "gif", "svg", "ttf", "eot", "woff"': function (assetGraph) {
            ['png', 'gif', 'svg', 'ttf', 'eot', 'woff'].forEach(function (extension) {
                assert.equal(assetGraph.findAssets({
                    url: new RegExp('\\.' + extension + '(?:$|#)')
                }).length, 1);
            });
        },
        'the graph should contain 6 files named fake.*': function (assetGraph) {
            assert.equal(assetGraph.findAssets({
                url: /fake\./
            }).length, 6);
        },
        'then running the splitCssIfIeLimitIsReached transform': {
            topic: function (assetGraph) {
                assetGraph.__infos = [];

                assetGraph
                    .on('info', function (err) {
                        assetGraph.__infos.push(err);
                    })
                    .splitCssIfIeLimitIsReached()
                    .run(this.callback);
            },
            'the graph should have 1 emitted info': function (assetGraph) {
                assert.equal(assetGraph.__infos.length, 1);
            },
            'the graph should contain 3 Css asset': function (assetGraph) {
                assert.equal(assetGraph.findAssets({type: 'Css'}).length, 3);
            },
            'each Css asset should be smaller than the original': function (assetGraph) {
                var cssAssets = assetGraph.findAssets({type: 'Css'}),
                    rules = [2806, 2398, 1086],
                    sum = 0;

                cssAssets.forEach(function (cssAsset, idx) {
                    var assetRules = cssAsset.parseTree.cssRules.length;
                    assert(cssAsset.text.length < cssText.length);
                    assert.equal(assetRules, rules[idx]);
                    sum += assetRules;
                });

                assert.equal(sum, assetGraph.__rules);
            },
            'the concatenated css text content should be unchanged from before': function (assetGraph) {
                assert.equal(assetGraph.findAssets({type: 'Css'}).map(function (cssAsset) {
                        return cssAsset.text;
                    }).join(''), cssText);
            },
            'the graph should have 1 of each of asset types "png", "gif", "svg", "ttf", "eot", "woff"': function (assetGraph) {
                ['png', 'gif', 'svg', 'ttf', 'eot', 'woff'].forEach(function (extension) {
                    assert.equal(assetGraph.findAssets({
                        url: new RegExp('\\.' + extension + '(?:$|#)')
                    }).length, 1);
                });
            },
            'the graph should no longer contain any files named fake.*': function (assetGraph) {
                assert.equal(assetGraph.findAssets({
                    url: /fake\./
                }).length, 0);
            }
        }
    }
})['export'](module);
<|endoftext|>


<commit_before>import './_project.scss';
import React, { Component } from 'react';

class Project extends React.Component {
  constructor(props) {
    super(props);
    this.state = {

    };
  }

  render() {
    return (

{this.props.projectName}

    );
  }

}

export default Project;
<commit_msg>changed placehold.it link to https to stop a warning in console.<commit_after>import './_project.scss';
import React, { Component } from 'react';

class Project extends React.Component {
  constructor(props) {
    super(props);
    this.state = {

    };
  }

  render() {
    return (

{this.props.projectName}

             Brief Description:

    );
  }

}

export default Project;
<|endoftext|>


<commit_before>/* eslint no-shadow: 0 */
'use strict';

var test = require('tape');
var ss = require('../');

function rnd(x) {
    return Math.round(x * 1000) / 1000;
}

test('sumNthPowerDeviations', function(t) {
    t.equal(
        ss.sumNthPowerDeviations([0, 0, 0], 2),
        0);
    t.equal(
        ss.sumNthPowerDeviations([0, 1], 2),
        0.5);
    t.equal(
        ss.sumNthPowerDeviations([0, 1], 3),
        0);
    t.equal(
        ss.sumNthPowerDeviations([0, 1, 2], 2),
        2);
    t.end();
});
<commit_msg>Remove unused include<commit_after>/* eslint no-shadow: 0 */
'use strict';

var test = require('tape');
var ss = require('../');

test('sumNthPowerDeviations', function(t) {
    t.equal(
        ss.sumNthPowerDeviations([0, 0, 0], 2),
        0);
    t.equal(
        ss.sumNthPowerDeviations([0, 1], 2),
        0.5);
    t.equal(
        ss.sumNthPowerDeviations([0, 1], 3),
        0);
    t.equal(
        ss.sumNthPowerDeviations([0, 1, 2], 2),
        2);
    t.end();
});
<|endoftext|>


<commit_before>OC.L10N.register(
    "audioplayer",
    {

	"Add new Songs to playlist" : "Neue Titel hinzufügen",
	"Scan for new audio files" : "Nach neuen Titeln suchen",
	"Sort Playlist" : "Wiedergabeliste sortieren",
	"Delete Playlist" : "Wiedergabeliste löschen",
	"Delete Song from Playlist" :"Titel von der Playlist löschen",
	"No Songs found in current Playlist! Add new Songs per Drag & Drop from album view" : "Keine Titel für ausgewählte Wiedergabeliste gefunden! Fügen Sie per Drag & Drop von der Albenansicht neue Titel hinzu",
	"No Playlist selected!" : "Keine Wiedergabeliste ausgewählt!",
	"Sort modus active" : "Bearbeitung aktiviert",
	"Delete playlist success!" : "Wiedergabeliste wurde erfolgreich gelöscht!",
	"Rename Playlist" : "Wiedergabeliste umbennen",
	"Start scanning ..." : "Starte Suche nach neuen Titeln",
	"Scanning finished! New Audios found!" :"Suche beendet! Es wurden neue Titel gefunden!",
	"Yes" : "Ja",
	"No" : "Nein",
	"Are you sure?" : "Sind Sie sicher?",
	"Track" : "Nr",
	"File" : "Datei",
	"Title" : "Titel",
	"Interpret" : "Künstler",
	"Year" : "Jahr",
	"Album" : "Album",
	"Edit Song from Playlist" : "Titel bearbeiten",
	"Edit track information (ID3)" : "Titelinformationen (ID3) bearbeiten",
	"Missing Permissions for editing ID3 Tags of song!" : "Fehlende Berechtigungen zum Bearbeiten für ID3 Tags des Titels!",
	"Existing Albums" : "Vorhandene Alben",
	"New Album" : "Neues Album",
	"Genre" : "Genre",
	"Add as Albumcover" : "Als Albumcover verwenden",
	"of" : "von",
	"Total" : "Gesamt",
	"Select from cloud" : "Bild aus Cloud wählen",
	"Edit" : "Bearbeiten",
	"Delete" : "Löschen",
	"Upload" : "Neues Bild hochladen",
	"Drop Photo" : "Drag & Drop Bild",
	"Drag Image Here!" : "Bild per Drag & Drop hinzufügen",
	"Reset Media Library" : "Musikbibliothek zurücksetzen",
	"Start deleting and resetting media library ..." : "Musikbibliothek wird gelöscht und zurückgesetzt ...",
	"Resetting finished!" : "Zurücksetzen Musikbibliothek beendet!",
	"Are you sure? All music database entries will be deleted!" : "Sind Sie sicher? Alle Musikeinträge in der Datenbank werden gelöscht!",
	"Close" : "Abbrechen",
	"Play" : "Abspielen",
	"Save" : "Speichern",
	"Existing Artists" : "Vorhandene Künstler",
	"New Artist" : " Neuer Künstler",
	"Existing Genres" : "Vorhandene Genres",
	"New Genre" : " Neues Genre"
},
"");
<commit_msg>Delete de_DE.js<commit_after><|endoftext|>


<commit_before>var fs = require('fs')
var path = require('path')

var mkdirp = require('mkdirp')
var mr = require('npm-registry-mock')
var osenv = require('osenv')
var rimraf = require('rimraf')
var test = require('tap').test

var common = require('../common-tap.js')
var npm = npm = require('../../')

var pkg = path.resolve(__dirname, 'shrinkwrap-dev-dependency')

test("shrinkwrap doesn't strip out the dependency", function (t) {
  t.plan(1)

  mr({port: common.port}, function (er, s) {
    setup(function (err) {
      if (err) return t.fail(err)

      npm.install('.', function (err) {
        if (err) return t.fail(err)

        npm.commands.shrinkwrap([], true, function (err, results) {
          if (err) return t.fail(err)

          t.deepEqual(results, desired)
          s.close()
          t.end()
        })
      })
    })
  })
})

test('cleanup', function (t) {
  cleanup()
  t.end()
})

var desired = {
  name: 'npm-test-shrinkwrap-dev-dependency',
  version: '0.0.0',
  dependencies: {
    request: {
      version: '0.9.0',
      from: 'request@0.9.0',
      resolved: common.registry + '/request/-/request-0.9.0.tgz'
    },
    underscore: {
      version: '1.3.1',
      from: 'underscore@1.3.1',
      resolved: common.registry + '/underscore/-/underscore-1.3.1.tgz'
    }
  }
}

var json = {
  author: 'Domenic Denicola',
  name: 'npm-test-shrinkwrap-dev-dependency',
  version: '0.0.0',
  dependencies: {
    request: '0.9.0',
    underscore: '1.3.1'
  },
  devDependencies: {
    underscore: '1.5.1'
  }
}

function setup (cb) {
  cleanup()
  mkdirp.sync(pkg)
  fs.writeFileSync(path.join(pkg, 'package.json'), JSON.stringify(json, null, 2))
  process.chdir(pkg)

  var opts = {
    cache: path.resolve(pkg, 'cache'),
    registry: common.registry
  }
  npm.load(opts, cb)
}

function cleanup () {
  process.chdir(osenv.tmpdir())
  rimraf.sync(pkg)
}
<commit_msg>test: rewrite shrinkwrap-dev-dependency as common.npm<commit_after>var fs = require('fs')
var path = require('path')

var mkdirp = require('mkdirp')
var mr = require('npm-registry-mock')
var osenv = require('osenv')
var rimraf = require('rimraf')
var test = require('tap').test

var common = require('../common-tap.js')

var pkg = path.resolve(__dirname, 'shrinkwrap-dev-dependency')

var opts = [
  '--cache', path.resolve(pkg, 'cache'),
  '--registry', common.registry
]

var desired = {
  name: 'npm-test-shrinkwrap-dev-dependency',
  version: '0.0.0',
  dependencies: {
    request: {
      version: '0.9.0',
      from: 'request@0.9.0',
      resolved: common.registry + '/request/-/request-0.9.0.tgz'
    },
    underscore: {
      version: '1.3.1',
      from: 'underscore@1.3.1',
      resolved: common.registry + '/underscore/-/underscore-1.3.1.tgz'
    }
  }
}

var json = {
  author: 'Domenic Denicola',
  name: 'npm-test-shrinkwrap-dev-dependency',
  version: '0.0.0',
  dependencies: {
    request: '0.9.0',
    underscore: '1.3.1'
  },
  devDependencies: {
    underscore: '1.5.1'
  }
}

function setup () {
  cleanup()
  mkdirp.sync(pkg)
  fs.writeFileSync(path.join(pkg, 'package.json'), JSON.stringify(json, null, 2))
  process.chdir(pkg)
}

function cleanup () {
  process.chdir(osenv.tmpdir())
  rimraf.sync(pkg)
}

test('setup', function (t) {
  setup()
  t.end()
})

test("shrinkwrap doesn't strip out the dependency", function (t) {
  t.plan(3)
  setup()

  mr({port: common.port}, function (er, s) {
    common.npm(opts.concat(['install', '.']), {stdio: [0, 'pipe', 2]}, function (err, code) {
      if (err) throw err
      if (!t.is(code, 0)) return (s.close(), t.end())
      common.npm(opts.concat(['shrinkwrap']), {stdio: [0, 2, 2]}, function (err, code) {
        if (err) throw err
        t.is(code, 0)
        try {
          var results = JSON.parse(fs.readFileSync(path.join(pkg, 'npm-shrinkwrap.json')))
        } catch (ex) {
          t.comment(ex)
        }
        t.deepEqual(results, desired)
        s.close()
        t.end()
      })
    })
  })
})

test('cleanup', function (t) {
  cleanup()
  t.end()
})
<|endoftext|>


<commit_before>/*
Copyright 2015 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

'use strict';

var React = require('react');
var DropTarget = require('react-dnd').DropTarget;
var sdk = require('matrix-react-sdk')
var dis = require('matrix-react-sdk/lib/dispatcher');

// turn this on for drop & drag console debugging galore
var debug = false;

var roomListTarget = {
    canDrop: function() {
        return true;
    },

    drop: function(props, monitor, component) {
        if (debug) console.log("dropped on sublist")
    },

    hover: function(props, monitor, component) {
        var item = monitor.getItem();

        if (component.state.sortedList.length == 0 && props.editable) {
            if (debug) console.log("hovering on sublist " + props.label + ", isOver=" + monitor.isOver());

            if (item.targetList !== component) {
                 item.targetList.removeRoomTile(item.room);
                 item.targetList = component;
            }

            component.moveRoomTile(item.room, 0);
        }
    },
};

var RoomSubList = React.createClass({
    displayName: 'RoomSubList',

    debug: debug,

    propTypes: {
        list: React.PropTypes.arrayOf(React.PropTypes.object).isRequired,
        label: React.PropTypes.string.isRequired,
        tagName: React.PropTypes.string,
        editable: React.PropTypes.bool,
        order: React.PropTypes.string.isRequired,
        bottommost: React.PropTypes.bool,
        selectedRoom: React.PropTypes.string.isRequired,
        activityMap: React.PropTypes.object.isRequired,
        collapsed: React.PropTypes.bool.isRequired
    },

    getInitialState: function() {
        return {
            hidden: false,
            sortedList: [],
        };
    },

    componentWillMount: function() {
        this.sortList(this.props.list, this.props.order);
    },

    componentWillReceiveProps: function(newProps) {
        // order the room list appropriately before we re-render
        //if (debug) console.log("received new props, list = " + newProps.list);
        this.sortList(newProps.list, newProps.order);
    },

    onClick: function(ev) {
        this.setState({ hidden : !this.state.hidden });
    },

    tsOfNewestEvent: function(room) {
        if (room.timeline.length) {
            return room.timeline[room.timeline.length - 1].getTs();
        }
        else {
            return Number.MAX_SAFE_INTEGER;
        }
    },

    // TODO: factor the comparators back out into a generic comparator
    // so that view_prev_room and view_next_room can do the right thing

    recentsComparator: function(roomA, roomB) {
        return this.tsOfNewestEvent(roomB) - this.tsOfNewestEvent(roomA);
    },

    manualComparator: function(roomA, roomB) {
        if (!roomA.tags[this.props.tagName] || !roomB.tags[this.props.tagName]) return 0;
        var a = roomA.tags[this.props.tagName].order;
        var b = roomB.tags[this.props.tagName].order;
        return a == b ? this.recentsComparator(roomA, roomB) : ( a > b  ? 1 : -1);
    },

    sortList: function(list, order) {
        if (list === undefined) list = this.state.sortedList;
        if (order === undefined) order = this.props.order;
        var comparator;
        list = list || [];
        if (order === "manual") comparator = this.manualComparator;
        if (order === "recent") comparator = this.recentsComparator;

        //if (debug) console.log("sorting list for sublist " + this.props.label + " with length " + list.length + ", this.props.list = " + this.props.list);
        this.setState({ sortedList: list.sort(comparator) });
    },

    moveRoomTile: function(room, atIndex) {
        if (debug) console.log("moveRoomTile: id " + room.roomId + ", atIndex " + atIndex);
        //console.log("moveRoomTile before: " + JSON.stringify(this.state.rooms));
        var found = this.findRoomTile(room);
        var rooms = this.state.sortedList;
        if (found.room) {
            if (debug) console.log("removing at index " + found.index + " and adding at index " + atIndex);
            rooms.splice(found.index, 1);
            rooms.splice(atIndex, 0, found.room);
        }
        else {
            if (debug) console.log("Adding at index " + atIndex);
            rooms.splice(atIndex, 0, room);
        }
        this.setState({ sortedList: rooms });
        // console.log("moveRoomTile after: " + JSON.stringify(this.state.rooms));
    },

    // XXX: this isn't invoked via a property method but indirectly via
    // the roomList property method.  Unsure how evil this is.
    removeRoomTile: function(room) {
        if (debug) console.log("remove room " + room.roomId);
        var found = this.findRoomTile(room);
        var rooms = this.state.sortedList;
        if (found.room) {
            rooms.splice(found.index, 1);
        }
        else {
            console.warn("Can't remove room " + room.roomId + " - can't find it");
        }
        this.setState({ sortedList: rooms });
    },

    findRoomTile: function(room) {
        var index = this.state.sortedList.indexOf(room);
        if (index >= 0) {
            // console.log("found: room: " + room.roomId + " with index " + index);
        }
        else {
            if (debug) console.log("didn't find room");
            room = null;
        }
        return ({
            room: room,
            index: index,
        });
    },

    calcManualOrderTagData: function(room) {
        var index = this.state.sortedList.indexOf(room);

        // we sort rooms by the lexicographic ordering of the 'order' metadata on their tags.
        // for convenience, we calculate this for now a floating point number between 0.0 and 1.0.

        var orderA = 0.0; // by default we're next to the beginning of the list
        if (index > 0) {
            var prevTag = this.state.sortedList[index - 1].tags[this.props.tagName];
            if (!prevTag) {
                console.error("Previous room in sublist is not tagged to be in this list. This should never happen.")
            }
            else if (prevTag.order === undefined) {
                console.error("Previous room in sublist has no ordering metadata. This should never happen.");
            }
            else {
                orderA = prevTag.order;
            }
        }

        var orderB = 1.0; // by default we're next to the end of the list too
        if (index < this.state.sortedList.length - 1) {
            var nextTag = this.state.sortedList[index + 1].tags[this.props.tagName];
            if (!nextTag) {
                console.error("Next room in sublist is not tagged to be in this list. This should never happen.")
            }
            else if (nextTag.order === undefined) {
                console.error("Next room in sublist has no ordering metadata. This should never happen.");
            }
            else {
                orderB = nextTag.order;
            }
        }

        var order = (orderA + orderB) / 2.0;
        if (order === orderA || order === orderB) {
            console.error("Cannot describe new list position.  This should be incredibly unlikely.");
            // TODO: renumber the list
        }

        return order;
    },

    makeRoomTiles: function() {
        var self = this;
        var RoomTile = sdk.getComponent("rooms.RoomTile");
        return this.state.sortedList.map(function(room) {
            var selected = room.roomId == self.props.selectedRoom;
            // XXX: is it evil to pass in self as a prop to RoomTile?
            return (
                <RoomTile
                    room={ room }
                    roomSubList={ self }
                    key={ room.roomId }
                    collapsed={ self.props.collapsed || false}
                    selected={ selected }
                    unread={ self.props.activityMap[room.roomId] === 1 }
                    highlight={ self.props.activityMap[room.roomId] === 2 }
                    isInvite={ self.props.label === 'Invites' } />
            );
        });
    },

    render: function() {
        var connectDropTarget = this.props.connectDropTarget;
        var RoomDropTarget = sdk.getComponent('rooms.RoomDropTarget');

        var label = this.props.collapsed ? null : this.props.label;

        //console.log("render: " + JSON.stringify(this.state.sortedList));

        var target;
        if (this.state.sortedList.length == 0 && this.props.editable) {
            target = <RoomDropTarget label={ 'Drop here to ' + this.props.verb }/>;
        }

        if (this.state.sortedList.length > 0 || this.props.editable) {
            var subList;
            var classes = "mx_RoomSubList" +
                          (this.props.bottommost ? " mx_RoomSubList_bottommost" : "");

            if (!this.state.hidden) {
                subList =

                                { target }
                                { this.makeRoomTiles() }

;
            }
            else {
                subList =

;
            }

            return connectDropTarget(

{ this.props.collapsed ? '' : this.props.label }

                    { subList }

            );
        }
        else {
            return (

            );
        }
    }
});

// Export the wrapped version, inlining the 'collect' functions
// to more closely resemble the ES7
module.exports =
DropTarget('RoomTile', roomListTarget, function(connect) {
    return {
        connectDropTarget: connect.dropTarget(),
    }
})(RoomSubList);
<commit_msg>Use UnreadStatus to determine whether an event affects a room;s unread status. Unify rooms going bold with their sort order and don't go bold for m.notify.<commit_after>/*
Copyright 2015 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

'use strict';

var React = require('react');
var DropTarget = require('react-dnd').DropTarget;
var sdk = require('matrix-react-sdk')
var dis = require('matrix-react-sdk/lib/dispatcher');
var UnreadStatus = require('matrix-react-sdk/lib/UnreadStatus');

// turn this on for drop & drag console debugging galore
var debug = false;

var roomListTarget = {
    canDrop: function() {
        return true;
    },

    drop: function(props, monitor, component) {
        if (debug) console.log("dropped on sublist")
    },

    hover: function(props, monitor, component) {
        var item = monitor.getItem();

        if (component.state.sortedList.length == 0 && props.editable) {
            if (debug) console.log("hovering on sublist " + props.label + ", isOver=" + monitor.isOver());

            if (item.targetList !== component) {
                 item.targetList.removeRoomTile(item.room);
                 item.targetList = component;
            }

            component.moveRoomTile(item.room, 0);
        }
    },
};

var RoomSubList = React.createClass({
    displayName: 'RoomSubList',

    debug: debug,

    propTypes: {
        list: React.PropTypes.arrayOf(React.PropTypes.object).isRequired,
        label: React.PropTypes.string.isRequired,
        tagName: React.PropTypes.string,
        editable: React.PropTypes.bool,
        order: React.PropTypes.string.isRequired,
        bottommost: React.PropTypes.bool,
        selectedRoom: React.PropTypes.string.isRequired,
        activityMap: React.PropTypes.object.isRequired,
        collapsed: React.PropTypes.bool.isRequired
    },

    getInitialState: function() {
        return {
            hidden: false,
            sortedList: [],
        };
    },

    componentWillMount: function() {
        this.sortList(this.props.list, this.props.order);
    },

    componentWillReceiveProps: function(newProps) {
        // order the room list appropriately before we re-render
        //if (debug) console.log("received new props, list = " + newProps.list);
        this.sortList(newProps.list, newProps.order);
    },

    onClick: function(ev) {
        this.setState({ hidden : !this.state.hidden });
    },

    tsOfNewestEvent: function(room) {
        for (var i = room.timeline.length - 1; i >= 0; --i) {
            var ev = room.timeline[i];
            // logic copied from RoomList.js for when we do/don't highlight
            if (UnreadStatus.eventTriggersUnreadCount(ev)) {
                return ev.getTs();
            }
        }

        // we might only have events that don't trigger the unread indicator,
        // in which case use the oldest event even if normally it wouldn't count.
        // This is better than just assuming the last event was forever ago.
        if (room.timeline.length) {
            return room.timeline[0].getTs();
        } else {
            return Number.MAX_SAFE_INTEGER;
        }
    },

    // TODO: factor the comparators back out into a generic comparator
    // so that view_prev_room and view_next_room can do the right thing

    recentsComparator: function(roomA, roomB) {
        return this.tsOfNewestEvent(roomB) - this.tsOfNewestEvent(roomA);
    },

    manualComparator: function(roomA, roomB) {
        if (!roomA.tags[this.props.tagName] || !roomB.tags[this.props.tagName]) return 0;
        var a = roomA.tags[this.props.tagName].order;
        var b = roomB.tags[this.props.tagName].order;
        return a == b ? this.recentsComparator(roomA, roomB) : ( a > b  ? 1 : -1);
    },

    sortList: function(list, order) {
        if (list === undefined) list = this.state.sortedList;
        if (order === undefined) order = this.props.order;
        var comparator;
        list = list || [];
        if (order === "manual") comparator = this.manualComparator;
        if (order === "recent") comparator = this.recentsComparator;

        //if (debug) console.log("sorting list for sublist " + this.props.label + " with length " + list.length + ", this.props.list = " + this.props.list);
        this.setState({ sortedList: list.sort(comparator) });
    },

    moveRoomTile: function(room, atIndex) {
        if (debug) console.log("moveRoomTile: id " + room.roomId + ", atIndex " + atIndex);
        //console.log("moveRoomTile before: " + JSON.stringify(this.state.rooms));
        var found = this.findRoomTile(room);
        var rooms = this.state.sortedList;
        if (found.room) {
            if (debug) console.log("removing at index " + found.index + " and adding at index " + atIndex);
            rooms.splice(found.index, 1);
            rooms.splice(atIndex, 0, found.room);
        }
        else {
            if (debug) console.log("Adding at index " + atIndex);
            rooms.splice(atIndex, 0, room);
        }
        this.setState({ sortedList: rooms });
        // console.log("moveRoomTile after: " + JSON.stringify(this.state.rooms));
    },

    // XXX: this isn't invoked via a property method but indirectly via
    // the roomList property method.  Unsure how evil this is.
    removeRoomTile: function(room) {
        if (debug) console.log("remove room " + room.roomId);
        var found = this.findRoomTile(room);
        var rooms = this.state.sortedList;
        if (found.room) {
            rooms.splice(found.index, 1);
        }
        else {
            console.warn("Can't remove room " + room.roomId + " - can't find it");
        }
        this.setState({ sortedList: rooms });
    },

    findRoomTile: function(room) {
        var index = this.state.sortedList.indexOf(room);
        if (index >= 0) {
            // console.log("found: room: " + room.roomId + " with index " + index);
        }
        else {
            if (debug) console.log("didn't find room");
            room = null;
        }
        return ({
            room: room,
            index: index,
        });
    },

    calcManualOrderTagData: function(room) {
        var index = this.state.sortedList.indexOf(room);

        // we sort rooms by the lexicographic ordering of the 'order' metadata on their tags.
        // for convenience, we calculate this for now a floating point number between 0.0 and 1.0.

        var orderA = 0.0; // by default we're next to the beginning of the list
        if (index > 0) {
            var prevTag = this.state.sortedList[index - 1].tags[this.props.tagName];
            if (!prevTag) {
                console.error("Previous room in sublist is not tagged to be in this list. This should never happen.")
            }
            else if (prevTag.order === undefined) {
                console.error("Previous room in sublist has no ordering metadata. This should never happen.");
            }
            else {
                orderA = prevTag.order;
            }
        }

        var orderB = 1.0; // by default we're next to the end of the list too
        if (index < this.state.sortedList.length - 1) {
            var nextTag = this.state.sortedList[index + 1].tags[this.props.tagName];
            if (!nextTag) {
                console.error("Next room in sublist is not tagged to be in this list. This should never happen.")
            }
            else if (nextTag.order === undefined) {
                console.error("Next room in sublist has no ordering metadata. This should never happen.");
            }
            else {
                orderB = nextTag.order;
            }
        }

        var order = (orderA + orderB) / 2.0;
        if (order === orderA || order === orderB) {
            console.error("Cannot describe new list position.  This should be incredibly unlikely.");
            // TODO: renumber the list
        }

        return order;
    },

    makeRoomTiles: function() {
        var self = this;
        var RoomTile = sdk.getComponent("rooms.RoomTile");
        return this.state.sortedList.map(function(room) {
            var selected = room.roomId == self.props.selectedRoom;
            // XXX: is it evil to pass in self as a prop to RoomTile?
            return (
                <RoomTile
                    room={ room }
                    roomSubList={ self }
                    key={ room.roomId }
                    collapsed={ self.props.collapsed || false}
                    selected={ selected }
                    unread={ self.props.activityMap[room.roomId] === 1 }
                    highlight={ self.props.activityMap[room.roomId] === 2 }
                    isInvite={ self.props.label === 'Invites' } />
            );
        });
    },

    render: function() {
        var connectDropTarget = this.props.connectDropTarget;
        var RoomDropTarget = sdk.getComponent('rooms.RoomDropTarget');

        var label = this.props.collapsed ? null : this.props.label;

        //console.log("render: " + JSON.stringify(this.state.sortedList));

        var target;
        if (this.state.sortedList.length == 0 && this.props.editable) {
            target = <RoomDropTarget label={ 'Drop here to ' + this.props.verb }/>;
        }

        if (this.state.sortedList.length > 0 || this.props.editable) {
            var subList;
            var classes = "mx_RoomSubList" +
                          (this.props.bottommost ? " mx_RoomSubList_bottommost" : "");

            if (!this.state.hidden) {
                subList =

                                { target }
                                { this.makeRoomTiles() }

;
            }
            else {
                subList =

;
            }

            return connectDropTarget(

{ this.props.collapsed ? '' : this.props.label }

                    { subList }

            );
        }
        else {
            return (

            );
        }
    }
});

// Export the wrapped version, inlining the 'collect' functions
// to more closely resemble the ES7
module.exports =
DropTarget('RoomTile', roomListTarget, function(connect) {
    return {
        connectDropTarget: connect.dropTarget(),
    }
})(RoomSubList);
<|endoftext|>


<commit_before><commit_msg>Updating user tests to fix name property bug<commit_after><|endoftext|>


<commit_before>// @flow

import { red } from 'chalk';
import R from 'ramda';

type Clog = typeof console.log;
type GraphQLError = { message: string };

export function exitNoConfig(clog: Clog): number {
  clog('Could not find .amazeeio.yml config file');
  return 1;
}

export function exitError(clog: Clog, ...errors: Array<string>): number {
  R.compose(
    R.apply(clog),
    R.tail,
    R.flatten,
    R.map(err => ['\n', err]),
    R.map(err => (err.stack ? red(err.stack) : red(err))),
  )(errors);
  return 1;
}

export function exitGraphQLError(
  clog: Clog,
  errors: Array<GraphQLError>,
  code?: number = 1,
): number {
  clog(red('Oops! The server returned errors:'));
  R.forEach(err => clog('\n', err), errors);
  return code;
}
<commit_msg>Improve compose functions in error functions<commit_after>// @flow

import { red } from 'chalk';
import R from 'ramda';

type Clog = typeof console.log;
type GraphQLError = { message: string };

// FIXME: Improve naming
export function exitError(clog: Clog, ...errors: Array<string>): number {
  R.compose(
    R.apply(clog),
    R.tail,
    R.chain(err => ['\n', err]),
    R.map(err => (err.stack ? red(err.stack) : red(err))),
  )(errors);
  return 1;
}

export function exitNoConfig(clog: Clog): number {
  return exitError(clog, '.amazeeio.yml config file not found.');
}

export function exitGraphQLError(clog: Clog, errors: Array<GraphQLError>): number {
  R.compose(
    R.apply(clog),
    R.tail,
    R.chain(err => ['\n', red(err)]),
    R.prepend(red('Oops! The server returned errors:')),
  )(errors);
  return 1;
}
<|endoftext|>


<commit_before>'use strict';
app.factory('ercView', ['$rootScope', 'httpRequests', function($rootScope, httpRequests){
	var executionStatus = {};
	var jobDone = true;

	/*
	* @Desc checks type of file to be displayed
	* @Param string, MIME type of file
	* @Return result, true if highlightjs should be used, false otherwise
	*/
	var checkDisplayType = function(string){
        if(typeof string == 'undefined'){ return; }
        var result = true;
        var _mime = string.split('/')[0];
        if( (string == 'application/pdf') || (_mime == 'image') || (_mime == 'audio') || (_mime == 'video')){
            result = false;
        }
        return result;
    };

    /*
    * @Desc httpRequest for getting information about a job status
    * @Param id, id of compendium
    */
    var callJobs = function(id){
	    httpRequests.listJobs({'compendium_id': id}, function(response){
	        if(response.error){
	            setExecStatus({'Information': {'status': 'No jobs executed yet'}});
                setJobDone(false);
	        } else {
	            httpRequests.listSingleJob(response.results[response.results.length-1], function(res){
	                getJobStatus(res.steps);
	            });
	        }
	    });
    };

    /*
    * @Desc getting job status and checking if execution succeeded or failed
    * @Param status, object containing status information
    */
    var getJobStatus = function(status){
        var _checkStatus = function(object){
            var allSuccess = true;
            var oneFail = false;
            for(var step in object){
                if(object[step].status != 'success') allSuccess = false;
                if(object[step].status == 'failure') oneFail = true;
            }
            if(allSuccess) return true;
            if(oneFail) return true;
            return false;
        };
        setExecStatus(status);
        if(_checkStatus(status)){
            setJobDone(true);
        } else {
            setJobDone(false);
        }
    };

    /*
    * @Desc executes a new job
    * @Param id, id of compendium
    */
    var executeJob = function(id){
        httpRequests.newJob({'compendium_id': id}, function(response){
            httpRequests.listSingleJob(response.data.job_id, function(res){
                getJobStatus(res.steps);
            });
        });
    };

    var getExecStatus = function(){
    	return executionStatus;
    };

    var getJobDone = function(){
    	return jobDone;
    };

    var setExecStatus = function(status){
    	executionStatus = status;
    	$rootScope.$broadcast('changedExecStatus');
    };

    var setJobDone = function(bool){
    	jobDone = bool;
    	$rootScope.$broadcast('changedJobDone');
    };

    return{
    	checkDisplayType: checkDisplayType,
    	callJobs: callJobs,
    	getJobStatus: getJobStatus,
    	executeJob: executeJob,
    	getExecStatus: getExecStatus,
    	getJobDone: getJobDone
    };
}]);<commit_msg>executeJob bugfix<commit_after>'use strict';
app.factory('ercView', ['$rootScope', 'httpRequests', function($rootScope, httpRequests){
	var executionStatus = {};
	var jobDone = true;

	/*
	* @Desc checks type of file to be displayed
	* @Param string, MIME type of file
	* @Return result, true if highlightjs should be used, false otherwise
	*/
	var checkDisplayType = function(string){
        if(typeof string == 'undefined'){ return; }
        var result = true;
        var _mime = string.split('/')[0];
        if( (string == 'application/pdf') || (_mime == 'image') || (_mime == 'audio') || (_mime == 'video')){
            result = false;
        }
        return result;
    };

    /*
    * @Desc httpRequest for getting information about a job status
    * @Param id, id of compendium
    */
    var callJobs = function(id){
	    httpRequests.listJobs({'compendium_id': id}, function(response){
	        if(response.error){
	            setExecStatus({'Information': {'status': 'No jobs executed yet'}});
                setJobDone(true);
	        } else {
	            httpRequests.listSingleJob(response.results[response.results.length-1], function(res){
	                getJobStatus(res.steps);
	            });
	        }
	    });
    };

    /*
    * @Desc getting job status and checking if execution succeeded or failed
    * @Param status, object containing status information
    */
    var getJobStatus = function(status){
        var _checkStatus = function(object){
            var allSuccess = true;
            var oneFail = false;
            for(var step in object){
                if(object[step].status != 'success') allSuccess = false;
                if(object[step].status == 'failure') oneFail = true;
            }
            if(allSuccess) return true;
            if(oneFail) return true;
            return false;
        };
        setExecStatus(status);
        if(_checkStatus(status)){
            setJobDone(true);
        } else {
            setJobDone(false);
        }
    };

    /*
    * @Desc executes a new job
    * @Param id, id of compendium
    */
    var executeJob = function(id){
        httpRequests.newJob({'compendium_id': id}, function(response){
            httpRequests.listSingleJob(response.data.job_id, function(res){
                getJobStatus(res.steps);
            });
        });
    };

    var getExecStatus = function(){
    	return executionStatus;
    };

    var getJobDone = function(){
    	return jobDone;
    };

    var setExecStatus = function(status){
    	executionStatus = status;
    	$rootScope.$broadcast('changedExecStatus');
    };

    var setJobDone = function(bool){
    	jobDone = bool;
    	$rootScope.$broadcast('changedJobDone');
    };

    return{
    	checkDisplayType: checkDisplayType,
    	callJobs: callJobs,
    	getJobStatus: getJobStatus,
    	executeJob: executeJob,
    	getExecStatus: getExecStatus,
    	getJobDone: getJobDone
    };
}]);<|endoftext|>


<commit_before>/* global module, angular, console, describe, expect, it, before, beforeEach, inject, spyOn, AnalyticsProvider */

'use strict';

describe('angular-google-analytics', function(){

    beforeEach(module('angular-google-analytics'));
    beforeEach(module(function(AnalyticsProvider) {
      AnalyticsProvider.setAccount('UA-XXXXXX-xx');
    }));

   describe('automatic trackPages', function() {

      it('should inject the GA script', function() {
        inject(function(Analytics) {
          expect(document.querySelectorAll("script[src='http://www.google-analytics.com/ga.js']").length).toBe(1);
        });
      });

      it('should generate pageTracks', function() {
        inject(function(Analytics) {
          expect(Analytics._logs.length).toBe(0);
          Analytics.trackPage('test');
          expect(Analytics._logs.length).toBe(1);
          Analytics.trackEvent('test');
          expect(Analytics._logs.length).toBe(2);
        });
      });

      it('should generate an trackpage to routeChangeSuccess', function() {
        inject(function(Analytics, $rootScope) {
          $rootScope.$broadcast('$routeChangeSuccess');
          expect(Analytics._logs.length).toBe(1);
        });
      });
  });

  describe('e-commerce transactions', function() {

      it('should add transcation', function() {
        inject(function(Analytics) {
          expect(Analytics._logs.length).toBe(0);
          Analytics.addTrans('1', '', '2.42', '0.42', '0', 'Amsterdam', '', 'Netherlands');
          expect(Analytics._logs.length).toBe(1);
        });
      });

      it('should add an item to transaction', function() {
        inject(function(Analytics) {
          expect(Analytics._logs.length).toBe(0);
          Analytics.addItem('1', 'sku-1', 'Test product 1', 'Testing', '1', '1');
          expect(Analytics._logs.length).toBe(1);
          Analytics.addItem('1', 'sku-2', 'Test product 2', 'Testing', '1', '1');
          expect(Analytics._logs.length).toBe(2);
        });
      });

      it('should track the transaction', function() {
        inject(function(Analytics) {
          expect(Analytics._logs.length).toBe(0);
          Analytics.trackTrans();
          expect(Analytics._logs.length).toBe(1);
        });
      });
  });

  describe('NOT automatic trackPages', function() {
    beforeEach(module(function(AnalyticsProvider) {
      AnalyticsProvider.trackPages(false);
    }));

    it('should NOT generate an trackpage to routeChangeSuccess', function() {
      inject(function(Analytics, $rootScope) {
        $rootScope.$broadcast('$routeChangeSuccess');
        expect(Analytics._logs.length).toBe(0);
      });
    });
  });

  describe('Supports ignoreFirstPageLoad', function() {
    beforeEach(module(function(AnalyticsProvider) {
      AnalyticsProvider.ignoreFirstPageLoad(true);
    }));

    it('Supports ignoreFirstPageLoad config', function() {
      inject(function(Analytics, $rootScope) {

        expect(Analytics.ignoreFirstPageLoad).toBe(true);
      });
    });
  });

  describe('supports analytics.js', function() {
    var cookieConfig = {
      cookieDomain: 'foo.example.com',
      cookieName: 'myNewName',
      cookieExpires: 20000
    };

    beforeEach(module(function(AnalyticsProvider) {
      AnalyticsProvider.useAnalytics(true);
      AnalyticsProvider.setCookieConfig(cookieConfig);
      AnalyticsProvider.useECommerce(true);
      AnalyticsProvider.useEnhancedLinkAttribution(true);
      AnalyticsProvider.setExperimentId('12345');
    }));

    it('should inject the Analytics script', function() {
      inject(function(Analytics) {
        expect(document.querySelectorAll("script[src='//www.google-analytics.com/analytics.js']").length).toBe(1);
      });
    });

    it('should support ecommerce config', function () {
      inject(function(Analytics) {
        expect(Analytics.ecommerce).toBe(true);
      });
    });

    it('should support enhancedLinkAttribution config', function () {
      inject(function(Analytics) {
        expect(Analytics.enhancedLinkAttribution).toBe(true);
      });
    });

    it('should support experimentId config', function () {
      inject(function(Analytics) {
        expect(Analytics.experimentId).toBe('12345');
      });
    });

    it('should allow transaction clearing', function () {
      inject(function (Analytics) {
        expect(Analytics._logs.length).toBe(0);
        Analytics.clearTrans();
        expect(Analytics._logs.length).toBe(1);
      });
    });

    it('should allow sending custom events', function () {
      inject(function (Analytics) {
        var social = {
          hitType: 'social',
          socialNetwork: 'facebook',
          socialAction: 'like',
          socialTarget: 'http://mycoolpage.com',
          page: '/my-new-page'
        };

        expect(Analytics._logs.length).toBe(0);
        Analytics.send(social);
        expect(Analytics._logs.length).toBe(1);
        expect(Analytics._logs[0]).toEqual({
          '0': 'send',
          '1': social
        });
      });
    });

    it('should allow setting custom dimensions, metrics or experiment', function(){
      inject(function (Analytics) {
        var data = {
          name: "dimension1",
          value: "value1",
        }
        expect(Analytics._logs.length).toBe(0);
        Analytics.set(data.name, data.value);
        expect(Analytics._logs.length).toBe(1);
        expect(Analytics._logs[0]).toEqual({
          '0': 'set',
          '1': data.name,
          '2': data.value
        });
      });
    });
  });

  describe('e-commerce transactions with analytics.js', function() {
    beforeEach(module(function(AnalyticsProvider) {
      AnalyticsProvider.useAnalytics(true);
      AnalyticsProvider.useECommerce(true);
    }));

    it('should add transcation', function() {
      inject(function(Analytics) {
        expect(Analytics._logs.length).toBe(0);
        Analytics.addTrans('1', '', '2.42', '0.42', '0', 'Amsterdam', '', 'Netherlands');
        expect(Analytics._logs.length).toBe(1);
        expect(Analytics._logs[0]['0']).toBe('ecommerce:addTransaction');
      });
    });

    it('should add an item to transaction', function() {
      inject(function(Analytics) {
        expect(Analytics._logs.length).toBe(0);
        Analytics.addItem('1', 'sku-1', 'Test product 1', 'Testing', '1', '1');
        expect(Analytics._logs.length).toBe(1);
        expect(Analytics._logs[0]['0']).toBe('ecommerce:addItem');
      });
    });

    it('should track the transaction', function() {
      inject(function(Analytics) {
        expect(Analytics._logs.length).toBe(0);
        Analytics.trackTrans();
        expect(Analytics._logs.length).toBe(1);
        expect(Analytics._logs[0]['0']).toBe('ecommerce:send');
      });
    });
  });

  describe('supports arbitrary page events', function() {
    beforeEach(module(function(AnalyticsProvider) {
      AnalyticsProvider.setPageEvent('$stateChangeSuccess');
    }));

    it('should inject the Analytics script', function() {
      inject(function(Analytics, $rootScope) {
        $rootScope.$broadcast('$stateChangeSuccess');
        expect(Analytics._logs.length).toBe(1);
      });
    });

    it('should inject the Analytics script', function() {
      inject(function(Analytics, $rootScope) {
        $rootScope.$broadcast('$stateChangeSuccess');
        expect(Analytics._logs.length).toBe(1);
      });
    });

  });

  describe('supports RegExp path scrubbing', function() {
    beforeEach(module(function(AnalyticsProvider) {
      AnalyticsProvider.setRemoveRegExp(new RegExp(/\/\d+?$/));
    }));

    it('should scrub urls', function() {
      inject(function(Analytics, $rootScope, $location) {
        $location.path('/some-crazy/page/with/numbers/123456');
        expect(Analytics.getUrl()).toBe('/some-crazy/page/with/numbers');
      });

    });

  });

});

<commit_msg>Fix lint error: missing semicolon<commit_after>/* global module, angular, console, describe, expect, it, before, beforeEach, inject, spyOn, AnalyticsProvider */

'use strict';

describe('angular-google-analytics', function(){

    beforeEach(module('angular-google-analytics'));
    beforeEach(module(function(AnalyticsProvider) {
      AnalyticsProvider.setAccount('UA-XXXXXX-xx');
    }));

   describe('automatic trackPages', function() {

      it('should inject the GA script', function() {
        inject(function(Analytics) {
          expect(document.querySelectorAll("script[src='http://www.google-analytics.com/ga.js']").length).toBe(1);
        });
      });

      it('should generate pageTracks', function() {
        inject(function(Analytics) {
          expect(Analytics._logs.length).toBe(0);
          Analytics.trackPage('test');
          expect(Analytics._logs.length).toBe(1);
          Analytics.trackEvent('test');
          expect(Analytics._logs.length).toBe(2);
        });
      });

      it('should generate an trackpage to routeChangeSuccess', function() {
        inject(function(Analytics, $rootScope) {
          $rootScope.$broadcast('$routeChangeSuccess');
          expect(Analytics._logs.length).toBe(1);
        });
      });
  });

  describe('e-commerce transactions', function() {

      it('should add transcation', function() {
        inject(function(Analytics) {
          expect(Analytics._logs.length).toBe(0);
          Analytics.addTrans('1', '', '2.42', '0.42', '0', 'Amsterdam', '', 'Netherlands');
          expect(Analytics._logs.length).toBe(1);
        });
      });

      it('should add an item to transaction', function() {
        inject(function(Analytics) {
          expect(Analytics._logs.length).toBe(0);
          Analytics.addItem('1', 'sku-1', 'Test product 1', 'Testing', '1', '1');
          expect(Analytics._logs.length).toBe(1);
          Analytics.addItem('1', 'sku-2', 'Test product 2', 'Testing', '1', '1');
          expect(Analytics._logs.length).toBe(2);
        });
      });

      it('should track the transaction', function() {
        inject(function(Analytics) {
          expect(Analytics._logs.length).toBe(0);
          Analytics.trackTrans();
          expect(Analytics._logs.length).toBe(1);
        });
      });
  });

  describe('NOT automatic trackPages', function() {
    beforeEach(module(function(AnalyticsProvider) {
      AnalyticsProvider.trackPages(false);
    }));

    it('should NOT generate an trackpage to routeChangeSuccess', function() {
      inject(function(Analytics, $rootScope) {
        $rootScope.$broadcast('$routeChangeSuccess');
        expect(Analytics._logs.length).toBe(0);
      });
    });
  });

  describe('Supports ignoreFirstPageLoad', function() {
    beforeEach(module(function(AnalyticsProvider) {
      AnalyticsProvider.ignoreFirstPageLoad(true);
    }));

    it('Supports ignoreFirstPageLoad config', function() {
      inject(function(Analytics, $rootScope) {

        expect(Analytics.ignoreFirstPageLoad).toBe(true);
      });
    });
  });

  describe('supports analytics.js', function() {
    var cookieConfig = {
      cookieDomain: 'foo.example.com',
      cookieName: 'myNewName',
      cookieExpires: 20000
    };

    beforeEach(module(function(AnalyticsProvider) {
      AnalyticsProvider.useAnalytics(true);
      AnalyticsProvider.setCookieConfig(cookieConfig);
      AnalyticsProvider.useECommerce(true);
      AnalyticsProvider.useEnhancedLinkAttribution(true);
      AnalyticsProvider.setExperimentId('12345');
    }));

    it('should inject the Analytics script', function() {
      inject(function(Analytics) {
        expect(document.querySelectorAll("script[src='//www.google-analytics.com/analytics.js']").length).toBe(1);
      });
    });

    it('should support ecommerce config', function () {
      inject(function(Analytics) {
        expect(Analytics.ecommerce).toBe(true);
      });
    });

    it('should support enhancedLinkAttribution config', function () {
      inject(function(Analytics) {
        expect(Analytics.enhancedLinkAttribution).toBe(true);
      });
    });

    it('should support experimentId config', function () {
      inject(function(Analytics) {
        expect(Analytics.experimentId).toBe('12345');
      });
    });

    it('should allow transaction clearing', function () {
      inject(function (Analytics) {
        expect(Analytics._logs.length).toBe(0);
        Analytics.clearTrans();
        expect(Analytics._logs.length).toBe(1);
      });
    });

    it('should allow sending custom events', function () {
      inject(function (Analytics) {
        var social = {
          hitType: 'social',
          socialNetwork: 'facebook',
          socialAction: 'like',
          socialTarget: 'http://mycoolpage.com',
          page: '/my-new-page'
        };

        expect(Analytics._logs.length).toBe(0);
        Analytics.send(social);
        expect(Analytics._logs.length).toBe(1);
        expect(Analytics._logs[0]).toEqual({
          '0': 'send',
          '1': social
        });
      });
    });

    it('should allow setting custom dimensions, metrics or experiment', function(){
      inject(function (Analytics) {
        var data = {
          name: "dimension1",
          value: "value1",
        };
        expect(Analytics._logs.length).toBe(0);
        Analytics.set(data.name, data.value);
        expect(Analytics._logs.length).toBe(1);
        expect(Analytics._logs[0]).toEqual({
          '0': 'set',
          '1': data.name,
          '2': data.value
        });
      });
    });
  });

  describe('e-commerce transactions with analytics.js', function() {
    beforeEach(module(function(AnalyticsProvider) {
      AnalyticsProvider.useAnalytics(true);
      AnalyticsProvider.useECommerce(true);
    }));

    it('should add transcation', function() {
      inject(function(Analytics) {
        expect(Analytics._logs.length).toBe(0);
        Analytics.addTrans('1', '', '2.42', '0.42', '0', 'Amsterdam', '', 'Netherlands');
        expect(Analytics._logs.length).toBe(1);
        expect(Analytics._logs[0]['0']).toBe('ecommerce:addTransaction');
      });
    });

    it('should add an item to transaction', function() {
      inject(function(Analytics) {
        expect(Analytics._logs.length).toBe(0);
        Analytics.addItem('1', 'sku-1', 'Test product 1', 'Testing', '1', '1');
        expect(Analytics._logs.length).toBe(1);
        expect(Analytics._logs[0]['0']).toBe('ecommerce:addItem');
      });
    });

    it('should track the transaction', function() {
      inject(function(Analytics) {
        expect(Analytics._logs.length).toBe(0);
        Analytics.trackTrans();
        expect(Analytics._logs.length).toBe(1);
        expect(Analytics._logs[0]['0']).toBe('ecommerce:send');
      });
    });
  });

  describe('supports arbitrary page events', function() {
    beforeEach(module(function(AnalyticsProvider) {
      AnalyticsProvider.setPageEvent('$stateChangeSuccess');
    }));

    it('should inject the Analytics script', function() {
      inject(function(Analytics, $rootScope) {
        $rootScope.$broadcast('$stateChangeSuccess');
        expect(Analytics._logs.length).toBe(1);
      });
    });

    it('should inject the Analytics script', function() {
      inject(function(Analytics, $rootScope) {
        $rootScope.$broadcast('$stateChangeSuccess');
        expect(Analytics._logs.length).toBe(1);
      });
    });

  });

  describe('supports RegExp path scrubbing', function() {
    beforeEach(module(function(AnalyticsProvider) {
      AnalyticsProvider.setRemoveRegExp(new RegExp(/\/\d+?$/));
    }));

    it('should scrub urls', function() {
      inject(function(Analytics, $rootScope, $location) {
        $location.path('/some-crazy/page/with/numbers/123456');
        expect(Analytics.getUrl()).toBe('/some-crazy/page/with/numbers');
      });

    });

  });

});

<|endoftext|>


<commit_before>'use strict';

//  ==========================================================================
//  Array UpperCase
//  ==========================================================================

	// Syntax
	str.toUpperCase();

	// Simple
	console.log("Hello Word!".toUpperCase());
	//	return "HELLO WORD!"

	var hi = "hello worde!";
	console.log(hi.toUpperCase());
	//	return "HELLO WORD!"<commit_msg>correction<commit_after>'use strict';

//  ==========================================================================
//  Array UpperCase
//  ==========================================================================

	// Syntax
	str.toUpperCase();

	// Simple
	console.log("Hello Word!".toUpperCase());
	//	return "HELLO WORD!"

	var hi = "hello worde!";
	console.log(hi.toUpperCase());
	//	return "HELLO WORD!"

	var hello = "Hello Worde!";
	console.log(hello.toUpperCase());
	//	return "HELLO WORD!"<|endoftext|>


<commit_before>$(document).ready(function () {
    var path = window.location.pathname;
    var splitPath = path.split('/');
    splitPath = splitPath.filter(function (v) { return v !== '' });
    if (splitPath.length > 2)
    {
        //Only bind if the page is searchable. (ie. we're in a repository)
        window.History.Adapter.bind(window, 'statechange', handleStateChange);
    }

    // Drag-to-resize search results pane
    // Adapted from http://www.catchmyfame.com/2010/08/12/adjustable-columns-with-jquery/

    var stopTwoLeft = parseInt($('#main-content').offset().left) + 300;
    var stopTwoRight = parseInt($('#browser').offset().left) + $('#browser').width() - 200;

    $("#drag-handle").draggable({
        axis: 'x',
        start: function (event, ui) {
            leftOneStart = $('#main-content').width();
            leftThreeStart = $('#browser').width();
        },
        drag: function (event, ui) {
            $('#main-content').width(leftOneStart + (ui.position.left - ui.originalPosition.left));
            $('#browser').width(leftThreeStart - (ui.position.left - ui.originalPosition.left));
        },
        containment: [stopTwoLeft, 0, stopTwoRight, 0]
    });
});

search = {
    //Keeps track of whether a search is ongoing.
    //We only want to send one query at a time.
    isSearching: false,
    //Retains the state of the most recent query.
    //When we're done searching, we check the text box to see
    //if the query has changed.
    lastQuery: "",
    beginSearch: function () {
        if (search.isSearching)
            return;
        var query = $("#search-box").val();
        //If there's no query, just clear everything
        if (query === "") {
            search.clearSearch();
            return;
        }
        search.lastQuery = query;
        //Split path, removing empty entries
        var path = window.location.pathname;
        var splitPath = path.split('/');
        splitPath = splitPath.filter(function (v) { return v !== '' });

        //Only search if we're in a repository
        if (splitPath.length > 2) {
            var username = splitPath[1];
            var repository = splitPath[2];

            search.searchRepository(username, repository, query);
        }

        return false;
    },

    searchRepository: function (username, repository, query) {
        data = JSON.stringify({
            "username": username,
            "repository": repository,
            "query": query
        });

        $.ajax({
            type: "POST",
            url: "/Search/Repository/",
            //TODO: If anyone knows a better way to do this, please share it.
            //My Javascript is not strong...
            data: "username=" + username + "&repository=" + repository + "&query=" + query,
            success: search.handleSuccess,
            error: search.handleError
        });
    },

    handleError: function (e) {
        search.isSearching = false;
        search.checkIfSearchTextChanged();
    },

    handleSuccess: function (results) {
        $("#tree-view").hide();
        //If we can't find any results, tell the user.
        if (results.length === 0) {
            $("#search-results").hide();
            $("#no-results").show();
        }
        else {
            $("#no-results").hide();
            $("#search-results").show();
            var htmlResults = search.buildResults(results);
            $("#search-results").empty().append(htmlResults);
            $("#search-results a").click(search.handleSearchClick);
        }
        search.isSearching = false;
        search.checkIfSearchTextChanged();
    },

    buildResults: function (results) {
        var htmlResults = "";
        for (var i = 0; i < results.length; i++) {
            var searchResult = results[i];
            var lineNumber = searchResult["LineNumber"];
            var link = "/Browse/" + searchResult["Path"] + "#" + lineNumber;
            html = "";
            html += "";
            html += ""
            html += searchResult["DisplayName"];
            html += "";
            html += ""
            html += searchResult["FullyQualifiedName"];
            html += "";
            html += "";

            htmlResults += html;
        }
        return htmlResults;
    },

    //After searching, we need to check to see if the user has typed
    //any additional characters into search while we were waiting
    //for the server
    checkIfSearchTextChanged: function () {
        var currentQuery = $("#search-box").val();
        if (currentQuery != search.lastQuery)
            search.beginSearch();
    },

    clearSearch: function () {
        $("#search-results").hide();
        $("#no-results").hide();
        $("#tree-view").show();
    },

    handleSearchClick: function (ex) {
        //If we're already on the page, allow the browser to scroll.
        var currentPath= window.location.pathname;
        var newPath = ex.currentTarget.pathname

        if (currentPath === newPath)
            return;

        //Stop navigation. We'll take it from here.
        ex.preventDefault();

        var url = ex.currentTarget.href;
        var host = ex.currentTarget.host;

        var splitByHash = url.split('#');
        if(splitByHash.length > 2)
            throw "Too many #'s in path";

        var newUrl = splitByHash[0];
        var lineNumber = Number(splitByHash[1]);

        window.History.pushState({ lineNumber: lineNumber }, null, newUrl);
    }
}

function handleStateChange(e) {
    var state = History.getState();
    var cleanUrl = state.url;
    var data = state.data;
    lineNumber = data["lineNumber"];

    $.ajax({
        type: "GET",
        url: cleanUrl,
        success: function (args) {
            $("#main-content").html(args["SourceCode"]);
             var newUrl = cleanUrl + "#" + lineNumber;
             window.history.replaceState(null, null, newUrl);
             window.location = newUrl;
        },
        error: handlePageLoadError
    });
}

function handlePageLoadError(args) {
    var errorHtml = "
There was an error processing your request.
";
    $("#line-numbers").empty();
    $(".source-code").html(errorHtml);
}

$("#search-box").keyup(function () {
    search.beginSearch();
});

$("#search-button").click(function () {
    search.beginSearch();
});

<commit_msg>Fixes page title when browsing search results<commit_after>$(document).ready(function () {
    var path = window.location.pathname;
    var splitPath = path.split('/');
    splitPath = splitPath.filter(function (v) { return v !== '' });
    if (splitPath.length > 2)
    {
        //Only bind if the page is searchable. (ie. we're in a repository)
        window.History.Adapter.bind(window, 'statechange', handleStateChange);
    }

    // Drag-to-resize search results pane
    // Adapted from http://www.catchmyfame.com/2010/08/12/adjustable-columns-with-jquery/

    var stopTwoLeft = parseInt($('#main-content').offset().left) + 300;
    var stopTwoRight = parseInt($('#browser').offset().left) + $('#browser').width() - 200;

    $("#drag-handle").draggable({
        axis: 'x',
        start: function (event, ui) {
            leftOneStart = $('#main-content').width();
            leftThreeStart = $('#browser').width();
        },
        drag: function (event, ui) {
            $('#main-content').width(leftOneStart + (ui.position.left - ui.originalPosition.left));
            $('#browser').width(leftThreeStart - (ui.position.left - ui.originalPosition.left));
        },
        containment: [stopTwoLeft, 0, stopTwoRight, 0]
    });
});

search = {
    //Keeps track of whether a search is ongoing.
    //We only want to send one query at a time.
    isSearching: false,
    //Retains the state of the most recent query.
    //When we're done searching, we check the text box to see
    //if the query has changed.
    lastQuery: "",
    beginSearch: function () {
        if (search.isSearching)
            return;
        var query = $("#search-box").val();
        //If there's no query, just clear everything
        if (query === "") {
            search.clearSearch();
            return;
        }
        search.lastQuery = query;
        //Split path, removing empty entries
        var path = window.location.pathname;
        var splitPath = path.split('/');
        splitPath = splitPath.filter(function (v) { return v !== '' });

        //Only search if we're in a repository
        if (splitPath.length > 2) {
            var username = splitPath[1];
            var repository = splitPath[2];

            search.searchRepository(username, repository, query);
        }

        return false;
    },

    searchRepository: function (username, repository, query) {
        data = JSON.stringify({
            "username": username,
            "repository": repository,
            "query": query
        });

        $.ajax({
            type: "POST",
            url: "/Search/Repository/",
            //TODO: If anyone knows a better way to do this, please share it.
            //My Javascript is not strong...
            data: "username=" + username + "&repository=" + repository + "&query=" + query,
            success: search.handleSuccess,
            error: search.handleError
        });
    },

    handleError: function (e) {
        search.isSearching = false;
        search.checkIfSearchTextChanged();
    },

    handleSuccess: function (results) {
        $("#tree-view").hide();
        //If we can't find any results, tell the user.
        if (results.length === 0) {
            $("#search-results").hide();
            $("#no-results").show();
        }
        else {
            $("#no-results").hide();
            $("#search-results").show();
            var htmlResults = search.buildResults(results);
            $("#search-results").empty().append(htmlResults);
            $("#search-results a").click(search.handleSearchClick);
        }
        search.isSearching = false;
        search.checkIfSearchTextChanged();
    },

    buildResults: function (results) {
        var htmlResults = "";
        for (var i = 0; i < results.length; i++) {
            var searchResult = results[i];
            var lineNumber = searchResult["LineNumber"];
            var link = "/Browse/" + searchResult["Path"] + "#" + lineNumber;
            html = "";
            html += "";
            html += ""
            html += searchResult["DisplayName"];
            html += "";
            html += ""
            html += searchResult["FullyQualifiedName"];
            html += "";
            html += "";

            htmlResults += html;
        }
        return htmlResults;
    },

    //After searching, we need to check to see if the user has typed
    //any additional characters into search while we were waiting
    //for the server
    checkIfSearchTextChanged: function () {
        var currentQuery = $("#search-box").val();
        if (currentQuery != search.lastQuery)
            search.beginSearch();
    },

    clearSearch: function () {
        $("#search-results").hide();
        $("#no-results").hide();
        $("#tree-view").show();
    },

    handleSearchClick: function (ex) {
        //If we're already on the page, allow the browser to scroll.
        var currentPath= window.location.pathname;
        var newPath = ex.currentTarget.pathname

        if (currentPath === newPath)
            return;

        //Stop navigation. We'll take it from here.
        ex.preventDefault();

        var url = ex.currentTarget.href;
        var host = ex.currentTarget.host;

        var splitByHash = url.split('#');
        if(splitByHash.length > 2)
            throw "Too many #'s in path";

        var newUrl = splitByHash[0];
        var lineNumber = Number(splitByHash[1]);

        var splitBySlash = newUrl.split('/');
        var fileName = splitBySlash[splitBySlash.length - 1];

        window.History.pushState({ lineNumber: lineNumber }, null, newUrl);
        document.title = fileName + " | Source Browser";
    }
}

function handleStateChange(e) {
    var state = History.getState();
    var cleanUrl = state.url;
    var data = state.data;
    lineNumber = data["lineNumber"];

    $.ajax({
        type: "GET",
        url: cleanUrl,
        success: function (args) {
            $("#main-content").html(args["SourceCode"]);
             var newUrl = cleanUrl + "#" + lineNumber;
             window.history.replaceState(null, null, newUrl);
             window.location = newUrl;
        },
        error: handlePageLoadError
    });
}

function handlePageLoadError(args) {
    var errorHtml = "
There was an error processing your request.
";
    $("#line-numbers").empty();
    $(".source-code").html(errorHtml);
}

$("#search-box").keyup(function () {
    search.beginSearch();
});

$("#search-button").click(function () {
    search.beginSearch();
});

<|endoftext|>


<commit_before>// @flow

import React from 'react';
import { Card, Image } from 'semantic-ui-react';

const Book = (props: {
	title: string,
	subtitle?: string,
	description: string,
	authors: Array<string>,
	coverImageUrl: string
}) => {
	return (
		<Card>
			<Card.Content>
				<Image floated="right" size="mini" src={props.coverImageUrl} />
				<Card.Header>
					{props.title}
				</Card.Header>
				{props.subtitle &&
					<Card.Meta>
						{props.subtitle}
					</Card.Meta>}
				{/* FIXME: show No description message when description is empty */}
				{props.description &&
					<Card.Description>
						{props.description.substring(0, 140) + '...'}
					</Card.Description>}
			</Card.Content>
			{/* FIXME: show no author message */}
			{props.authors &&
				<Card.Content extra>
					{props.authors.join(', ')}
				</Card.Content>}
		</Card>
	);
};

export default Book;
<commit_msg>sketch out basic (working!) update functionality in a Dropdown<commit_after>// @flow

import React, { Component } from 'react';
import { Card, Dropdown, Image } from 'semantic-ui-react';
import { update } from '../utils/BooksAPI';
import { BookType } from '../common/flowTypes';

class Book extends Component {
	props: {
		title: string,
		subtitle?: string,
		description: string,
		authors: Array<string>,
		coverImageUrl: string,
		book: BookType
	};

	onChange = (event, data) => {
		console.log(data.value);
		update(this.props.book, data.value).then(console.log('updated shelf!'));
	};

	render() {
		const shelfOptions = [
			{ key: 'Read', text: 'Read', value: 'read' },
			{
				key: 'Currently Reading',
				text: 'Currently Reading',
				value: 'currentlyReading'
			},
			{
				key: 'Want To Read',
				text: 'Want To Read',
				value: 'wantToRead'
			}
		];
		const { title, subtitle, description, authors, coverImageUrl } = this.props;
		return (
			<Card>
				<Card.Content>
					<Image floated="right" size="mini" src={coverImageUrl} />
					<Card.Header>
						{title}
					</Card.Header>
					{subtitle &&
						<Card.Meta>
							{subtitle}
						</Card.Meta>}
					{/* FIXME: show No description message when description is empty */}
					{description &&
						<Card.Description>
							{description.substring(0, 140) + '...'}
						</Card.Description>}
				</Card.Content>
				{/* FIXME: show no author message */}
				{authors &&
					<Card.Content extra>
						{authors.join(', ')}
					</Card.Content>}
				<Card.Content extra>
					<Dropdown
						text="Add to a shelf?"
						fluid
						floating
						labeled
						button
						className="icon"
						icon="zip"
						onChange={this.onChange}
						options={shelfOptions}
					/>
				</Card.Content>
			</Card>
		);
	}
}

export default Book;
<|endoftext|>


<commit_before>import React from 'react';
import { Text, View, Button,StyleSheet } from 'react-native';
import { Card, ListItem, Button } from 'react-native-elements';

class FirstScreen extends React.Component {
    constructor(props){
        super(props);
        console.log('first screen',this.props)
    }
    static navigationOptions = ({ navigation }) => ({
        title: 'First',
    });
    render() {

        const { navigate } = this.props.navigation;
        return (
            <View style={styles.wrapper}>
               <Card title="ingredient">
               <View>
                   <Text>Card 1</Text>

                   </View>
               </Card>

            </View>
        )
    }
}

const styles = StyleSheet.create({
    wrapper: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center'
      }
})

export default FirstScreen;<commit_msg>landing view updated<commit_after>import React from 'react';
import { Text, View, StyleSheet, StatusBar, ScrollView } from 'react-native';
import { Card, ListItem, Button, SearchBar } from 'react-native-elements';
import * as Progress from 'react-native-progress';
import KnowledgeComponent from './KnowledgeComponent';
class FirstScreen extends React.Component {
    constructor(props) {
        super(props);
        console.log('first screen', this.props)
    }
    static navigationOptions = ({ navigation }) => ({
        title: 'First',
    });
    render() {

        const { navigate } = this.props.navigation;
        return (
            <ScrollView style={{
                flex: 1, alignSelf: 'stretch'
            }}>
                <View>
                    <View style={styles.SearhbarStyle}>
                        <SearchBar
                            lightTheme
                            round
                            placeholder='Search Recipes' />
                    </View>
                    <View>
                        <Card title="Recipe 1">
                            <KnowledgeComponent fieldLevel={0.3} fieldText="Carbs" fieldValue="32g | 23%" />
                            <KnowledgeComponent fieldLevel={0.5} fieldText="Protein" fieldValue="22g | 50%" />
                            <KnowledgeComponent fieldLevel={0.8} fieldText="Fat" fieldValue="188g | 80%" />
                        </Card>
                        <Card title="Recipe 2">
                            <KnowledgeComponent fieldLevel={0.3} fieldText="Carbs" fieldValue="32g | 23%" />
                            <KnowledgeComponent fieldLevel={0.5} fieldText="Protein" fieldValue="22g | 50%" />
                            <KnowledgeComponent fieldLevel={0.8} fieldText="Fat" fieldValue="188g | 80%" />
                        </Card>
                        <Card title="Recipe 3">
                            <KnowledgeComponent fieldLevel={0.3} fieldText="Carbs" fieldValue="32g | 23%" />
                            <KnowledgeComponent fieldLevel={0.5} fieldText="Protein" fieldValue="22g | 50%" />
                            <KnowledgeComponent fieldLevel={0.8} fieldText="Fat" fieldValue="188g | 80%" />
                        </Card>
                    </View>
                </View>
            </ScrollView>

        )
    }
}

const styles = StyleSheet.create({
    SearhbarStyle: {
        marginTop: 30
    },
    wrapper: {
        flex: 1
    },
    progress: {
        margin: 10,
    }
})

export default FirstScreen;<|endoftext|>


<commit_before>(function($) {

	Symphony.Language.add({
		'today': false,
		'yesterday': false,
		'tomorrow': false
	});

	/**
	 * The Date and Time extension provides an interface to add
	 * one or more single dates or date ranges to an entry.
	 *
	 * @author: Nils Hörrmann, post@nilshoerrmann.de
	 * @source: http://github.com/nilshoerrmann/datetime
	 */
	$(document).ready(function() {

		// Date and time
		$('div.field-datetime').each(function() {
			var manager = $(this),
				help = manager.find('label i'),
				stage = manager.find('div.stage'),
				selection = stage.find('ul.selection');

		/*---- Events -----------------------------------------------------------*/

			// Visualising
			selection.delegate('input', 'focus.datetime', function() {
				var input = $(this),
					item = input.parents('li'),
					calendar = item.find('div.calendar');
					dates = input.parent().addClass('focus'),
					date = input.attr('data-timestamp');

				// Show help
				help.fadeIn('fast');

				// Set focus
				dates.addClass('focus').siblings('.focus').removeClass('focus');

				// Visualise
				calendar.slideDown('fast');
				item.trigger('visualise');
			});

			// Setting
			selection.delegate('li', 'set.datetime', function(event, range, focus) {
				var item = $(this),
					start = item.find('.start'),
					end = item.find('.end');

				// Start date
				if(range.start != null && range.start != start.attr('data-timestamp')) {
					validate(start, range.start, false);
				}

				// End date
				if(range.end != null && range.end != end.attr('data-timestamp')) {
					validate(end, range.end, false);
				}
			});

			// Validating
			selection.delegate('input', 'blur.datetime', function(event) {
				var input = $(this),
					date = input.val(),
					validated = input.data('validated');

				// Validate
				if(date != '' && date != validated) {
					validate(input, date, true);
				}

				// Empty date
				else if(date == '') {
					empty(input);
				}
			});

			// Closing
			$('body').bind('click.datetime', function() {

				// Hide help
				help.fadeOut('fast');

				// Hide calendar
				selection.find('div.calendar').slideUp('fast');
				selection.find('.focus').removeClass('focus');
			});

		/*---- Functions --------------------------------------------------------*/

			// Validate and set date
			var validate = function(input, date, visualise) {
				var item = input.parents('li'),
					dates = input.parent();

				// Call validator
				$.ajax({
					type: 'GET',
					dataType: 'json',
					url: Symphony.Context.get('root') + '/symphony/extension/datetime/get/',
					data: {
						date: date
					},
					success: function(parsed) {
						console.log(parsed);

						// Valid date
						if(parsed.status == 'valid') {
							input.attr('data-timestamp', parsed.timestamp).val(parsed.date).removeClass('invalid');
						}

						// Invalid date
						else {
							input.attr('data-timestamp', '').addClass('invalid');
						}

						// Store date
						input.data('validated', parsed.date);

						// Display status
						displayStatus(dates);

						// Get date context
						contextualise(input);

						// Visualise
						if(visualise === true) {
							item.trigger('visualise', [{
								start: dates.find('.start').attr('data-timestamp'),
								end: dates.find('.end').attr('data-timestamp')
							}, input.attr('data-timestamp')]);
						}
					}
				});
			};

			// Empty date
			var empty = function(input) {
				var item = input.parents('li'),
					dates = input.parent(),
					end = dates.find('.end');

				// Empty dates are valid
				input.removeClass('invalid');

				// Merge with end date
				if(input.is('.start') && end.val() != '') {
					input.val(end.val());
					end.val('');

					// Keep errors
					if(end.is('.invalid')) {
						end.removeClass('invalid');
						input.addClass('invalid');
					}
				}

				// Display status
				displayStatus(dates);

				// Hide end date
				end.slideUp('fast', function() {
					item.removeClass('range');
				});
			};

			// Display validity status
			var displayStatus = function(dates) {

				console.log(dates, dates.find('input.invalid').size());

				// At least one date is invalid
				if(dates.find('input.invalid').size() > 0) {
					dates.addClass('invalid');
				}

				// All dates are valid
				else {
					dates.removeClass('invalid');
				}
			};

			// Get context
			var contextualise = function(input) {
				var dates = input.parent(),
					time = parseInt(input.attr('data-timestamp')),
					now = new Date(),
					day, today, yesterday, tomorrow, label;

				// Reduze timestamps to days:
				day = reduce(time);
				today = reduce(now.getTime());

				// Create label
				if(day == today) {
					label = Symphony.Language.get('today');
				}
				else if(today - day == 1) {
					label = Symphony.Language.get('yesterday');
				}
				else if(day - today == 1) {
					label = Symphony.Language.get('tomorrow');
				}

				// Attach label
				if(label) {
					input.next('em.label').text(label).fadeIn('fast');
				}

				// Detach label
				else {
					input.next('em.label').fadeOut('fast');
				}
			};

			// Reduce timestamp to days
			var reduce = function(timestamp) {

				// Add an hour = 60 * 60 * 1000 = 3600000 to identify midnight (0:00) correctly,
				// divide by one day = 24 * 60 * 60 * 1000 = 86400000
				return Math.floor((parseInt(timestamp) + 3600000) / 86400000);
			};

		/*---- Initialisation ---------------------------------------------------*/

			// Create calendar and timer
			selection.symphonyCalendar();
			selection.symphonyTimer();

			// Store and contextualise dates
			selection.find('input').each(function() {
				var input = $(this);
				input.data('validated', input.val());
				contextualise(input);
			}).load();

			// Set errors
			selection.find('input.invalid').parents('span.dates').addClass('invalid');

			// Hide help
			help.hide();

		});

	});

})(jQuery.noConflict());
<commit_msg>Contextualise newly created items<commit_after>(function($) {

	Symphony.Language.add({
		'today': false,
		'yesterday': false,
		'tomorrow': false
	});

	/**
	 * The Date and Time extension provides an interface to add
	 * one or more single dates or date ranges to an entry.
	 *
	 * @author: Nils Hörrmann, post@nilshoerrmann.de
	 * @source: http://github.com/nilshoerrmann/datetime
	 */
	$(document).ready(function() {

		// Date and time
		$('div.field-datetime').each(function() {
			var manager = $(this),
				help = manager.find('label i'),
				stage = manager.find('div.stage'),
				selection = stage.find('ul.selection');

		/*---- Events -----------------------------------------------------------*/

			// Constructing
			stage.bind('constructstop', function(event, item) {
				var input = item.find('input.start');

				// Store and contextualise date
				input.data('validated', input.val());
				contextualise(input);
			});

			// Visualising
			selection.delegate('input', 'focus.datetime', function() {
				var input = $(this),
					item = input.parents('li'),
					calendar = item.find('div.calendar');
					dates = input.parent().addClass('focus'),
					date = input.attr('data-timestamp');

				// Show help
				help.fadeIn('fast');

				// Set focus
				dates.addClass('focus').siblings('.focus').removeClass('focus');

				// Visualise
				calendar.slideDown('fast');
				item.trigger('visualise');
			});

			// Setting
			selection.delegate('li', 'set.datetime', function(event, range, focus) {
				var item = $(this),
					start = item.find('.start'),
					end = item.find('.end');

				// Start date
				if(range.start != null && range.start != start.attr('data-timestamp')) {
					validate(start, range.start, false);
				}

				// End date
				if(range.end != null && range.end != end.attr('data-timestamp')) {
					validate(end, range.end, false);
				}
			});

			// Validating
			selection.delegate('input', 'blur.datetime', function(event) {
				var input = $(this),
					date = input.val(),
					validated = input.data('validated');

				// Validate
				if(date != '' && date != validated) {
					validate(input, date, true);
				}

				// Empty date
				else if(date == '') {
					empty(input);
				}
			});

			// Closing
			$('body').bind('click.datetime', function() {

				// Hide help
				help.fadeOut('fast');

				// Hide calendar
				selection.find('div.calendar').slideUp('fast');
				selection.find('.focus').removeClass('focus');
			});

		/*---- Functions --------------------------------------------------------*/

			// Validate and set date
			var validate = function(input, date, visualise) {
				var item = input.parents('li'),
					dates = input.parent();

				// Call validator
				$.ajax({
					type: 'GET',
					dataType: 'json',
					url: Symphony.Context.get('root') + '/symphony/extension/datetime/get/',
					data: {
						date: date
					},
					success: function(parsed) {
						console.log(parsed);

						// Valid date
						if(parsed.status == 'valid') {
							input.attr('data-timestamp', parsed.timestamp).val(parsed.date).removeClass('invalid');
						}

						// Invalid date
						else {
							input.attr('data-timestamp', '').addClass('invalid');
						}

						// Store date
						input.data('validated', parsed.date);

						// Display status
						displayStatus(dates);

						// Get date context
						contextualise(input);

						// Visualise
						if(visualise === true) {
							item.trigger('visualise', [{
								start: dates.find('.start').attr('data-timestamp'),
								end: dates.find('.end').attr('data-timestamp')
							}, input.attr('data-timestamp')]);
						}
					}
				});
			};

			// Empty date
			var empty = function(input) {
				var item = input.parents('li'),
					dates = input.parent(),
					end = dates.find('.end');

				// Empty dates are valid
				input.removeClass('invalid');

				// Merge with end date
				if(input.is('.start') && end.val() != '') {
					input.val(end.val());
					end.val('');

					// Keep errors
					if(end.is('.invalid')) {
						end.removeClass('invalid');
						input.addClass('invalid');
					}
				}

				// Display status
				displayStatus(dates);

				// Hide end date
				end.slideUp('fast', function() {
					item.removeClass('range');
				});
			};

			// Display validity status
			var displayStatus = function(dates) {

				console.log(dates, dates.find('input.invalid').size());

				// At least one date is invalid
				if(dates.find('input.invalid').size() > 0) {
					dates.addClass('invalid');
				}

				// All dates are valid
				else {
					dates.removeClass('invalid');
				}
			};

			// Get context
			var contextualise = function(input) {
				var dates = input.parent(),
					time = parseInt(input.attr('data-timestamp')),
					now = new Date(),
					day, today, yesterday, tomorrow, label;

				// Reduze timestamps to days:
				day = reduce(time);
				today = reduce(now.getTime());

				// Create label
				if(day == today) {
					label = Symphony.Language.get('today');
				}
				else if(today - day == 1) {
					label = Symphony.Language.get('yesterday');
				}
				else if(day - today == 1) {
					label = Symphony.Language.get('tomorrow');
				}

				// Attach label
				if(label) {
					input.next('em.label').text(label).fadeIn('fast');
				}

				// Detach label
				else {
					input.next('em.label').fadeOut('fast');
				}
			};

			// Reduce timestamp to days
			var reduce = function(timestamp) {

				// Add an hour = 60 * 60 * 1000 = 3600000 to identify midnight (0:00) correctly,
				// divide by one day = 24 * 60 * 60 * 1000 = 86400000
				return Math.floor((parseInt(timestamp) + 3600000) / 86400000);
			};

		/*---- Initialisation ---------------------------------------------------*/

			// Create calendar and timer
			selection.symphonyCalendar();
			selection.symphonyTimer();

			// Store and contextualise dates
			selection.find('input').each(function() {
				var input = $(this);
				input.data('validated', input.val());
				contextualise(input);
			}).load();

			// Set errors
			selection.find('input.invalid').parents('span.dates').addClass('invalid');

			// Hide help
			help.hide();

		});

	});

})(jQuery.noConflict());
<|endoftext|>