<commit_before>var $ = require('./dm')
var Mux = require('./mux')
var util = require('./util')
var conf = require('./conf')
var Directive = require('./directive')

/**
 *  private vars
 */
var preset = require('./preset') // preset directives getter
var directives = [null, {}] // [preset, global]
var gdirs = directives[1]

/**
 *  Global API
 */
function Zect(options) {
    return ViewModel.call(this, options || {})
}
Zect.extend = function(options) {
    return function() {
        _insertProto(this, Zect.prototype)
        return ViewModel.call(this, options || {})
    }
}
Zect.directive = function(id, definition) {
    gdirs[id] = definition
}
Zect.namespace = function(n) {
    conf.namespace = n
}

function ViewModel(options) {
    var proto = this.__proto__
    var vm = this
    var el = options.el

    /**
     *  Mounted element detect
     */
    if (!el && options.template) {
        el = document.createElement('div')
        el.innerHTML = options.template
    } else if (util.type(el) == 'string') {
        el = document.querySelector(el)
    } else if (!(el instanceof HTMLElement)) {
        throw new Error('Unmatch el option')
    }
    vm.$el = el

    /**
     *  assign methods
     */
    var methods = options.methods
    util.objEach(methods, function(k, v) {
        vm[k] = v
    })

    var $data
    if (options.$data) {
        $data = options.$data
    } else {
        /**
         *  Init state model
         */
        var mopts = {
            deep: true,
            props: options.data,
            computed: options.computed
        }
        var $data = new Mux(mopts)
    }
    Object.defineProperty(vm, '$data', {
        enumerable: true,
        get: function() {
            return $data
        },
        set: function(v) {
            $data.$set(v)
        }
    })

    var exprReg = /^\{.*?\}&/
    util.walk(el, function(n) {
        var type = n.nodeType // 1. ELEMENT_NODE; 2. ATTRIBUTE_NODE; 3. TEXT_NODE; 8. COMMENT_NODE; 9. DOCUMENT_NODE
        var value = n.nodeValue
        var name = n.tagName

        switch (type) {
            case 1:
                if (isComponent(name)) {
                    // child component
                    new Zect({
                        el: n,
                        $parent: vm
                    })
                } else {

                    var attrs = n.attributes
                    var ast = {
                        varAttName: {},
                        directives: {},
                        expression: {}
                    }
                    for (var i = 0; i < attrs.length; i++) {
                        var att = attrs[i]
                        var n = att.name
                        var v = att.value
                        // parse att
                        if (n.match(match(exprReg))) {
                            // variable attribute name
                            ast.varAttName[n] = v
                        } else if(n.indexOf(conf.namespace == 0)) {
                            // directive
                            ast.directives[n] = v
                        } else if(v.trim().match(exprReg)) {
                            // named attribute with expression
                            ast.expression[n] = v
                        }
                    }

                    /**
                     *  parse attributes to directive
                     */
                    function compile (ast) {
                        directives.objEach(function(d) {
                            util.objEach(d, function(id, def) {
                                if(vm.$el.contains(n)) return false
                                if (ast[id]) {
                                    new Directive(vm, n, id, def)
                                }
                            })
                        })
                    }
                }

                break
            case 3:
                break
            default:
                return false
        }
    }.bind(this))

    /**
     *  Directive bindings
     */
    directives[0] = preset(Zect) // set preset directives

    directives.forEach(function(d) {
        util.objEach(d, function(id, def) {
            parseDirective(vm, id, def)
        })
    })

    /**
     *  Life cycle methods
     */
    options.ready && options.ready.call(vm)
}

var definition = {}
function extractExp(node) {
    var attrs = node.attributes
    for (var i = 0; i < attrs.length; i ++) {
        var name = attrs[i].name
        var value = attrs[i].value
        if (name.match(/[\w]-[\w]/)) {

        } else if (value.match(/^\s*\{.*?\}\s*$/)) {
            new Directive(vm, node, name, {
                bind: function () {
                    return []
                },
                update:function () {

                }
            })
        }
    }
}

function parseDirective(vm, id, definition) {
    var atn = conf.namespace + id
        /**
         *  using selector to parse declare syntax
         */
    vm.$el.hasAttribute(atn) && new Directive(vm, vm.$el, atn, definition)

    $(vm.$el).find('[' + atn + ']').each(function(tar) {
        if (!vm.$el.contains(tar)) return
        new Directive(vm, tar, atn, definition)
    })
}

/**
 *  utils
 */
function _insertProto(obj, proto) {
    var end = obj.__proto__
    obj.__proto__ = proto
    obj.__proto__.__proto__ = end
}

module.exports = Zect
<commit_msg>ready to compile template expression syntax<commit_after>var $ = require('./dm')
var Mux = require('./mux')
var util = require('./util')
var conf = require('./conf')
var Directive = require('./directive')

/**
 *  private vars
 */
var preset = require('./preset') // preset directives getter
var directives = [null, {}] // [preset, global]
var gdirs = directives[1]

/**
 *  Global API
 */
function Zect(options) {
    return ViewModel.call(this, options || {})
}
Zect.extend = function(options) {
    return function() {
        _insertProto(this, Zect.prototype)
        return ViewModel.call(this, options || {})
    }
}
Zect.directive = function(id, definition) {
    gdirs[id] = definition
}
Zect.namespace = function(n) {
    conf.namespace = n
}

function ViewModel(options) {
    var proto = this.__proto__
    var vm = this
    var el = options.el

    /**
     *  Mounted element detect
     */
    if (!el && options.template) {
        el = document.createElement('div')
        el.innerHTML = options.template
    } else if (util.type(el) == 'string') {
        el = document.querySelector(el)
    } else if (!(el instanceof HTMLElement)) {
        throw new Error('Unmatch el option')
    }
    vm.$el = el

    /**
     *  assign methods
     */
    var methods = options.methods
    util.objEach(methods, function(k, v) {
        vm[k] = v
    })

    var $data
    if (options.$data) {
        $data = options.$data
    } else {
        /**
         *  Init state model
         */
        var mopts = {
            deep: true,
            props: options.data,
            computed: options.computed
        }
        var $data = new Mux(mopts)
    }
    Object.defineProperty(vm, '$data', {
        enumerable: true,
        get: function() {
            return $data
        },
        set: function(v) {
            $data.$set(v)
        }
    })

    var exprReg = /^\{.*?\}&/
    util.walk(el, function(n) {
        var type = n.nodeType // 1. ELEMENT_NODE; 2. ATTRIBUTE_NODE; 3. TEXT_NODE; 8. COMMENT_NODE; 9. DOCUMENT_NODE
        var value = n.nodeValue
        var name = n.tagName

        switch (type) {
            case 1:
                if (isComponent(name)) {
                    // child component
                    new Zect({
                        el: n,
                        $parent: vm
                    })
                } else {

                    var attrs = n.attributes
                    var ast = {
                        varAttName: {},
                        directives: {},
                        expression: {}
                    }
                    for (var i = 0; i < attrs.length; i++) {
                        var att = attrs[i]
                        var n = att.name
                        var v = att.value
                        // parse att
                        if (n.match(match(exprReg))) {
                            // variable attribute name
                            ast.varAttName[n] = v
                        } else if(n.indexOf(conf.namespace == 0)) {
                            // directive
                            ast.directives[n] = v
                        } else if(v.trim().match(exprReg)) {
                            // named attribute with expression
                            ast.expression[n] = v
                        }
                    }

                    /**
                     *  parse attributes to directive
                     */
                    function compile (ast) {
                        directives.objEach(function(d) {
                            util.objEach(d, function(id, def) {
                                if(vm.$el.contains(n)) return false
                                if (ast.directives[id]) {
                                    new Directive(vm, n, id, def)
                                }
                            })
                        })
                    }

                    /**
                     *  'xx {title} sss' -- > xx zect.js sss
                     */
                    function compileCtn (n) {
                        var childs = n.childNodes
                        for (var i = 0; i < childs.length; i ++) {
                            var c = childs[i]
                            if (c.nodeType == 3) {
                                var v = c.nodeValue
                                // parse text node only
                                v = v.replace(/\\{/g, '\uFFF0').replace(/\\}/g, '\uFFF1')
                                // extract vars
                                var exprs = v.match(/({[\s\S]*?})/)

                            }
                        }
                    }

                }

                break
            case 3:
                break
            default:
                return false
        }
    }.bind(this))

    /**
     *  Directive bindings
     */
    // directives[0] = preset(Zect) // set preset directives

    // directives.forEach(function(d) {
    //     util.objEach(d, function(id, def) {
    //         parseDirective(vm, id, def)
    //     })
    // })

    /**
     *  Life cycle methods
     */
    options.ready && options.ready.call(vm)
}

var definition = {}
function extractExp(node) {
    var attrs = node.attributes
    for (var i = 0; i < attrs.length; i ++) {
        var name = attrs[i].name
        var value = attrs[i].value
        if (name.match(/[\w]-[\w]/)) {

        } else if (value.match(/^\s*\{.*?\}\s*$/)) {
            new Directive(vm, node, name, {
                bind: function () {
                    return []
                },
                update:function () {

                }
            })
        }
    }
}

function parseDirective(vm, id, definition) {
    var atn = conf.namespace + id
        /**
         *  using selector to parse declare syntax
         */
    vm.$el.hasAttribute(atn) && new Directive(vm, vm.$el, atn, definition)

    $(vm.$el).find('[' + atn + ']').each(function(tar) {
        if (!vm.$el.contains(tar)) return
        new Directive(vm, tar, atn, definition)
    })
}

/**
 *  utils
 */
function _insertProto(obj, proto) {
    var end = obj.__proto__
    obj.__proto__ = proto
    obj.__proto__.__proto__ = end
}

module.exports = Zect
<|endoftext|>


<commit_before>// Get the modal
var modal = document.getElementById('myModal');

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on the button, open the modal
btn.onclick = function() {
    modal.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
<commit_msg>Delete modal.js<commit_after><|endoftext|>


<commit_before>app.service('corporations', function($http) {
  this.information = function(){
    return [
          {
            id: 1,
            title: 'CreativeAI',
            description: 'This post-modernist ad agency uses the latest in artifical intelligence to develop highly-targeted messages to reach consumers. They are experts at manipulating culture and human emotion to convince people to do horrible things. The only humans CreativeAI hires are "data scientists"; all of their other employees are algorithms.',
            industries: "Public Relations, Advertising, Entertainment",
            pro_quote: "[The noises from video compression] are more beautiful to me than most things deliberately made by humans.--Loren Schmidt, Human Co-Founder",
            anti_quote: "CreativeAI's work is...decent. Not as good as a human, of course. But the corporations don't care about quality. They care about cost. And a computer is much cheaper than a human.---Argyros Naevius, former journalist",
            favorite_policy: "Transperancy Mandate",
            alignment: "left"
          },
          {
            id: 2,
            title: 'Vanguard',
            description: "A left-wing organization dedicated to leading a People's Revolution to overthrow capitalism. To raise funds for its lofty goal, Vanguard sells its 'espionage' and 'security' services to the other corporations. Vanguard has been linked to many high-profile assassinations of corporate executives...all of them paid for by other corporate executives.",
            pro_quote: "Remember that we do not want our sons and daughters to live in this cursed hell. We will fight for their sake.---Dori Iodocus, CEO",
            anti_quote: "It is cliche to point out that the Vanguard leadership lives in skyscrapers and mansions while their employees are dirt-poor, expendable cannon fooder. But at least the Vanguard leadership recognizes the irony and pretends to cry about it.---Argyros Naevius, former journalist",
            favorite_policy: "E-Democracy",
            industries: "Corporate Espionage, Military",
            alignment: "left"
          },
          {
            id: 3,
            title: 'Centaurs Incorporated',
            description: "Humans who have decided to 'upgrade' themselves by merging with their machines, turning into a weird hybrid of 'artifical intelligence' and 'natural intelligence'. They are the workforce that are responsible for manufacturing most of the goods that the other corporations repackage and sell to other people. They are strong advocates for uplifting other people to the 'next stage of human evolution', and will happily kidnap and brainwash those who refuses upliftment.",
            pro_quote: "I am unable to see why if AI becomes effective and productive it would result in anything other than an age of practical abundance.--friendsie, Vice-President of Marketing",
            anti_quote: "In the past, we humans used technology. Now, technology uses us, and is using us for some greater, unfathomable purpose.---Yamato Izz al-Din, former Centaur employee",
            favorite_policy: "Basic Income",
            industries: "Industrial Automation, Research and Development"
            alignment: "libertarian"
          },
          {
            id: 4,
            title: "Baudrillard Associates",
            description: "An alliance of rogue financial traders and bankers who had given up pretending to comply with arbitrary government regulations and appeasing corrupt financial regulators. The white collar crime may be boring, but the pay is more than worth it. Currently the most popular corporation in the city, due to their reluctance to use violence to settle disputes.",
            industries: "Financial Services, Investment Banking, Accounting",
            anti_quote: "There is no evidence that the Baudrillard Associates even *exists*. Either the leadership has hidden themselves very well, or these bankers invented up the organization just to give themselves an excuse to do what they always wanted to do.---Tadeo Waldobert, Police Officer",
            pro_quote: "When the government treats the law as a pliable instrument to be used creatively, it tends to encourage citizens to treat it the same way. ... [The corporations] treated the law as a game to be played, a puzzle to be solved as aggressively as possible, rather than a moral obligation. THE JUSTICE DEPARTMENT DOES TOO.---Matt Levine, Senior Vice President of Public Relations",
            favorite_policy: "Deregulation",
            alignment: "libertarian"
          },
          {
            id: 5,
            title: "PAGAD",
            description: "The 'People Against Gangsterism and Drugs' movement had its roots in the chaotic violence in 1990s South Africa. It has since spread throughout the world as an anti-globalization political force. Members of PAGAD use car bombings, intimidation, and extortion in its eternal crusade against corporate crime, in the hopes of bringing sanity to an often insane world. Despite its supposedly secular nature, PAGAD has attracted its fair share of religious zealots.",
            industries: "Security & Investigations, Law Enforcement",
            favorite_policy: "Vigilante Legalization",
            anti_quote: "They believe they can go against the law if it means ridding the area of a drug dealer or gangster. How are they any better than the criminals when they resort to criminal tactics?---John Davids, South African Civilian",
            pro_quote: "If you do not mobilise yourselves, no one will do it for you. Drugs and gangsterism is destroying our society and everyone is affected.---Haroun Orrie, PAGAD spokesperson",
            alignment: "rightist"
          },
          {
            id: 6,
            title: "Room 39",
            description: "A criminal organization that was founded in the late 1970s with explicit purpose of securing funding for the North Korean dictatorship, through the use of criminal activities such as drug smuggling and weapons trafficking.  After the fall of the North Korean dictatorship, Room 39 went 'legit' in return for legal immunity for its previous crimes. Room 39 is slowly and gradually adjusting to the capitalist system.",
            pro_quote: "Ideologies are like clothing; when one is worn out, it's time to buy a new one.---Ji-Hun Yeong-Ho, Room 39 agent",
            anti_quote: "It's a mockery of our laws that a criminal gang is able to freely reinvent themselves as a honorable corporation. And they probably haven't given up on the crime yet.---Argyros Naevius, former journalist",
            favorite_policy: "Slush Fund",
            industries: "Pharmaceuticals, Weapon Production",
            alignment: "rightist"
          },
          {
            id: 7,
            title: "Singularity LLC",
            description: "Radical political activists who (after being repeatedly disappointed at the failure of human politicans and regulators to solve problems) are attempting to build an Artifical General Intelligence that will control human society. They sometimes rent their experiments as 'consultants' to the other corporations to help raise revenue.",
            pro_quote: "People are superstitios [sic] about self-modifying code because once you employ this for solving usual engineering problems, you will often find it to be difficult to trace down the reasons for your program's behavior and that the ability of a program to modify itself can be exploited to gain access / information by people / other programs they not allowed to have. However, if these aren't problematic, then any Lisp or Prolog is a safe bet. Something that speaks to broader audience: Python, JavaScript, Lua.---wvxvw, Singularity LLC employee",
            anti_quote: "Humans *don't* agree on how to run our society! Why should we trust a computer to know any better?---Bassam Petru, lawyer",
            favorite_policy: "Algorithmic Law",
            industries: "Consulting, Life Coaching",
            alignment: "libertarian"
          },
          {
            id: 8,
            title: "VHEMT",
            description: "A radical environmentalist organization founded in the early 1990s by Les U. Knight, VHEMT stands for the 'Voluntary Human Extiniction Movement'. As society has grown more dystopian, many people have began supporting VHEMT as the best way to increase global  welfare, declaring that the death of humanity is the only sensible choice in a insensible world.",
            pro_quote: "Q: Is this another one of those suicide cults? A: Seems as if our entire industralized civilization is one big suicide cult. ... [V]oluntary human extiniction offers a healthy cure to humanity's collective death wish.---VHEMT Q&A"
            anti_quote: "The logic is as absurd as it's unassailable. Yes, indeed, if there are no more children, there will be no more child tragedies. Or child triumphs, for that matter, or much reason to think childless humanity will spend its dying days as serenely as Knight predicts. ---Brian Bethune, journalist"
            industries: "Environmental Services",
            alignment: "left"
          },
          {
            id: 9,
            title: "Liberal Crime Squad"
            description: "A leftist terrorist group that previously wanted to establish an 'Elite Liberal Utopia'. The leadership soon realized that it would be far easier to plug people into a 'simulation' of an Elite Liberal utopia instead. They now adopt a policy of utter hedonism, and only leave the VR sims to raise funds and preach their agenda to the masses.",
            pro_quote: "Only by abandoning 'Conservative Reality' can humanity be awakened to its True Liberal Nature and be able to enjoy happy, productive lives.---Chris Horsa, Liberal Crime Squad Founder",
            anti_quote: "The LCS agents sleep soundly in their virtual pods, and dream of fighting their war against Conservative society. But I notice that they never really dream what happens after they win.---Leobwin Sansone, former LCS employee",
            industries: "Virtual Reality",
            alignment: "left"
          },
          {
            id: 10,
            title: "Daemon Hunters",
            description: "Wackos and conspiracy theorists who believe that they are living in a computer simulation ('MMO') controlled by cruel daemons ('players'). These daemons regularly pay 'subscription fees' for the chance to beat up and cruelly torture 'NPCs' (us). The Demon Hunters seek to purge the daemonic element from human society, but have a hard time distingushing between the NPCs and the daemons.",
            pro_quote: "Friend or foe? Paranoia imperative. Galaxy purely casual, individualism is a statistical anomaly - Nada is an error. Trust Nada? Trust you?---Priest Entity Nada, CTO of Daemon Hunters",
            anti_quote: "If I was a daemon, the first thing I'd do is to create a faction to grief other daemons. Read between the lines.---Argyros Naevius, former journalist",
            alignment: "right",
            industries: "Space Exploration, Food Production"
          }
        ]
  }
  })
// Other Corps To Add?

// Uber/On-Demand Startups?
// Conservative Crime Squad?
// Social Media?
// "Weyland Corps" could be an interesting addition, and it would introduce the standard 'evil corp' back into the picture, since most of the corps here seem to make more sense as rebellious scum than as multitrillion-dollar megacorps. (Weyland appears to be a pro-"human supremacy" organization that does care for the environment and believe mankind to be like gods.) The biggest hurdle for Weyland Corps is two-folds
// One...the existence of the Daemon Hunters already mean you have a faction dedicated to interacting with 'extraterrestial entities' (the Demons), although the Daemon Hunters 'officially' wants to purge demons, not use them as weaponry.
// Two...the Weyland Corps' techno-utopianism is already reflected in Cenaturs Incorporated and Singularility LLC, and actually made more explicit. Their environmentalism is radicalized in the form of VHEMT. In the dystopian world of The Regulator, the Weylands are just too...conventional. Too boring.

// Peter Weyland's speech: http://lybio.net/peter-weylands-2023-ted-talk/people/
// Even though Peter believed mankind to be god, in the movie Prometheus, he had to beg to the Creators themselves...gods who are theorized to have made mankind solely as breeding vessels for the greatest biological weapons ever...the Xenomorphs

// Possible 'Enemy Faction' To Include If Tyranny is too High
// If so, provide hints that the HFSE exist in the Lore before launching them
// I like this faction but it appears to be a non-violent version of PAGAD,
// so it can't really be used
// {
//   id: 11,
//   title: "Human Flesh Search Engine",
//   description: "Established in the early 21st century as a loose-knit collection of Chinese vigilantes seeking to punish corruption and immorality through public shaming and doxxing, it has since absorbed other crowd-sourced intelligence gathering entities to become a major international force. The HFSE uses harrassment and death threats to push the vague and shifting views of the Internet mob, and tends to target both the strong and the weak fairly equally.",
//   pro_quote: "Righteousness is one of the five virtues in the Confucian tradition. With the convenience of the internet, and in the case of non-responsive law, the righteous people took matters into their own hands.---Xujun Eberlein, Chinese-American writer",
//   anti_quote: "The human-flesh search has unimaginable power. First it was a lot of phone calls every day. Then people painted red characters on his parents’ froxnt door, which said things like, ‘You caused your wife’s suicide, so you should pay.’---Zhang Yanfeng, lawyer representing Wang Fei, a husband accused of cheating on his wife. Wang Fei went into hiding to evade the HFSE",
//   alignment: "right?"
// }

// The HFSE is a place that you can periodically monitor to check people's opinions about you. If you engage in too much tyranny, the HFSE will turn against you, and you will go against their wrath (which includes threatening attacks as well as stronger Corporations.)
// When you start the game, you log onto the HFSE to get your job.<commit_msg>Create a new political faction<commit_after>app.service('corporations', function($http) {
  this.information = function(){
    return [
          {
            id: 1,
            title: 'CreativeAI',
            description: 'This post-modernist ad agency uses the latest in artifical intelligence to develop highly-targeted messages to reach consumers. They are experts at manipulating culture and human emotion to convince people to do horrible things. The only humans CreativeAI hires are "data scientists"; all of their other employees are algorithms.',
            industries: "Public Relations, Advertising, Entertainment",
            pro_quote: "[The noises from video compression] are more beautiful to me than most things deliberately made by humans.--Loren Schmidt, Human Co-Founder",
            anti_quote: "CreativeAI's work is...decent. Not as good as a human, of course. But the corporations don't care about quality. They care about cost. And a computer is much cheaper than a human.---Argyros Naevius, former journalist",
            favorite_policy: "Transperancy Mandate",
            alignment: "left"
          },
          {
            id: 2,
            title: 'Vanguard',
            description: "A left-wing organization dedicated to leading a People's Revolution to overthrow capitalism. To raise funds for its lofty goal, Vanguard sells its 'espionage' and 'security' services to the other corporations. Vanguard has been linked to many high-profile assassinations of corporate executives...all of them paid for by other corporate executives.",
            pro_quote: "Remember that we do not want our sons and daughters to live in this cursed hell. We will fight for their sake.---Dori Iodocus, CEO",
            anti_quote: "It is cliche to point out that the Vanguard leadership lives in skyscrapers and mansions while their employees are dirt-poor, expendable cannon fooder. But at least the Vanguard leadership recognizes the irony and pretends to cry about it.---Argyros Naevius, former journalist",
            favorite_policy: "E-Democracy",
            industries: "Corporate Espionage, Military",
            alignment: "left"
          },
          {
            id: 3,
            title: 'Centaurs Incorporated',
            description: "Humans who have decided to 'upgrade' themselves by merging with their machines, turning into a weird hybrid of 'artifical intelligence' and 'natural intelligence'. They are the workforce that are responsible for manufacturing most of the goods that the other corporations repackage and sell to other people. They are strong advocates for uplifting other people to the 'next stage of human evolution', and will happily kidnap and brainwash those who refuses upliftment.",
            pro_quote: "I am unable to see why if AI becomes effective and productive it would result in anything other than an age of practical abundance.--friendsie, Vice-President of Marketing",
            anti_quote: "In the past, we humans used technology. Now, technology uses us, and is using us for some greater, unfathomable purpose.---Yamato Izz al-Din, former Centaur employee",
            favorite_policy: "Basic Income",
            industries: "Industrial Automation, Research and Development"
            alignment: "libertarian"
          },
          {
            id: 4,
            title: "Baudrillard Associates",
            description: "An alliance of rogue financial traders and bankers who had given up pretending to comply with arbitrary government regulations and appeasing corrupt financial regulators. The white collar crime may be boring, but the pay is more than worth it. Currently the most popular corporation in the city, due to their reluctance to use violence to settle disputes.",
            industries: "Financial Services, Investment Banking, Accounting",
            anti_quote: "There is no evidence that the Baudrillard Associates even *exists*. Either the leadership has hidden themselves very well, or these bankers invented up the organization just to give themselves an excuse to do what they always wanted to do.---Tadeo Waldobert, Police Officer",
            pro_quote: "When the government treats the law as a pliable instrument to be used creatively, it tends to encourage citizens to treat it the same way. ... [The corporations] treated the law as a game to be played, a puzzle to be solved as aggressively as possible, rather than a moral obligation. THE JUSTICE DEPARTMENT DOES TOO.---Matt Levine, Senior Vice President of Public Relations",
            favorite_policy: "Deregulation",
            alignment: "libertarian"
          },
          {
            id: 5,
            title: "PAGAD",
            description: "The 'People Against Gangsterism and Drugs' movement had its roots in the chaotic violence in 1990s South Africa. It has since spread throughout the world as an anti-globalization political force. Members of PAGAD use car bombings, intimidation, and extortion in its eternal crusade against corporate crime, in the hopes of bringing sanity to an often insane world. Despite its supposedly secular nature, PAGAD has attracted its fair share of religious zealots.",
            industries: "Security & Investigations, Law Enforcement",
            favorite_policy: "Vigilante Legalization",
            anti_quote: "They believe they can go against the law if it means ridding the area of a drug dealer or gangster. How are they any better than the criminals when they resort to criminal tactics?---John Davids, South African Civilian",
            pro_quote: "If you do not mobilise yourselves, no one will do it for you. Drugs and gangsterism is destroying our society and everyone is affected.---Haroun Orrie, PAGAD spokesperson",
            alignment: "rightist"
          },
          {
            id: 6,
            title: "Room 39",
            description: "A criminal organization that was founded in the late 1970s with explicit purpose of securing funding for the North Korean dictatorship, through the use of criminal activities such as drug smuggling and weapons trafficking.  After the fall of the North Korean dictatorship, Room 39 went 'legit' in return for legal immunity for its previous crimes. Room 39 is slowly and gradually adjusting to the capitalist system.",
            pro_quote: "Ideologies are like clothing; when one is worn out, it's time to buy a new one.---Ji-Hun Yeong-Ho, Room 39 agent",
            anti_quote: "It's a mockery of our laws that a criminal gang is able to freely reinvent themselves as a honorable corporation. And they probably haven't given up on the crime yet.---Argyros Naevius, former journalist",
            favorite_policy: "Slush Fund",
            industries: "Pharmaceuticals, Weapon Production",
            alignment: "rightist"
          },
          {
            id: 7,
            title: "Singularity LLC",
            description: "Radical political activists who (after being repeatedly disappointed at the failure of human politicans and regulators to solve problems) are attempting to build an Artifical General Intelligence that will control human society. They sometimes rent their experiments as 'consultants' to the other corporations to help raise revenue.",
            pro_quote: "People are superstitios [sic] about self-modifying code because once you employ this for solving usual engineering problems, you will often find it to be difficult to trace down the reasons for your program's behavior and that the ability of a program to modify itself can be exploited to gain access / information by people / other programs they not allowed to have. However, if these aren't problematic, then any Lisp or Prolog is a safe bet. Something that speaks to broader audience: Python, JavaScript, Lua.---wvxvw, Singularity LLC employee",
            anti_quote: "Humans *don't* agree on how to run our society! Why should we trust a computer to know any better?---Bassam Petru, lawyer",
            favorite_policy: "Algorithmic Law",
            industries: "Consulting, Life Coaching",
            alignment: "libertarian"
          },
          {
            id: 8,
            title: "VHEMT",
            description: "A radical environmentalist organization founded in the early 1990s by Les U. Knight, VHEMT stands for the 'Voluntary Human Extiniction Movement'. As society has grown more dystopian, many people have began supporting VHEMT as the best way to increase global  welfare, declaring that the death of humanity is the only sensible choice in a insensible world.",
            pro_quote: "Q: Is this another one of those suicide cults? A: Seems as if our entire industralized civilization is one big suicide cult. ... [V]oluntary human extiniction offers a healthy cure to humanity's collective death wish.---VHEMT Q&A"
            anti_quote: "The logic is as absurd as it's unassailable. Yes, indeed, if there are no more children, there will be no more child tragedies. Or child triumphs, for that matter, or much reason to think childless humanity will spend its dying days as serenely as Knight predicts. ---Brian Bethune, journalist"
            industries: "Environmental Services",
            alignment: "left"
          },
          {
            id: 9,
            title: "Liberal Crime Squad"
            description: "A leftist terrorist group that previously wanted to establish an 'Elite Liberal Utopia'. The leadership soon realized that it would be far easier to plug people into a 'simulation' of an Elite Liberal utopia instead. They now adopt a policy of utter hedonism, and only leave the VR sims to raise funds and preach their agenda to the masses.",
            pro_quote: "Only by abandoning 'Conservative Reality' can humanity be awakened to its True Liberal Nature and be able to enjoy happy, productive lives.---Chris Horsa, Liberal Crime Squad Founder",
            anti_quote: "The LCS agents sleep soundly in their virtual pods, and dream of fighting their war against Conservative society. But I notice that they never really dream what happens after they win.---Leobwin Sansone, former LCS employee",
            industries: "Virtual Reality",
            alignment: "left"
          },
          {
            id: 10,
            title: "Daemon Hunters",
            description: "Wackos and conspiracy theorists who believe that they are living in a computer simulation ('MMO') controlled by cruel daemons ('players'). These daemons regularly pay 'subscription fees' for the chance to beat up and cruelly torture 'NPCs' (us). The Demon Hunters seek to purge the daemonic element from human society, but have a hard time distingushing between the NPCs and the daemons.",
            pro_quote: "Friend or foe? Paranoia imperative. Galaxy purely casual, individualism is a statistical anomaly - Nada is an error. Trust Nada? Trust you?---Priest Entity Nada, CTO of Daemon Hunters",
            anti_quote: "If I was a daemon, the first thing I'd do is to create a faction to grief other daemons. Read between the lines.---Argyros Naevius, former journalist",
            alignment: "right",
            industries: "Space Exploration, Food Production"
          },
          {
            id: 11,
            title: "The Firemen",
            description: "Journalists, academics, and political activists hoping to modify society's entertainment to promote proper moral conduct. Entertainment, while providing a mandatory dose of fun in a person's life, also negatively affects social norms and behaviors. They're fine with the media brainwashing people...it just have to brainwash people in the *right* manner. Endorses social justice and ethics in video game journalism.",
            pro_quote: "The murders of innocents every day? The constant arson and torture allegations? The media didn't start the fire, true. But the media fueled it, by glorifying the criminals on the street and justifying their every misdeed! All we're doing is throwing water onto the fire.---Nikon Pytheid, Populist Commander of the Firemen",
            anti_quote: "We run to media to AVOID the cold reality of politics. If even the media must be politicized by these Firemen, then...where do we run to next?---Argyros Naevius, former journalist",
            industries: "Media, Academia"
          }
        ]
  }
  })
// Other Corps To Add?

// Uber/On-Demand Startups?
// Conservative Crime Squad?
// Social Media?
// "Weyland Corps" could be an interesting addition, and it would introduce the standard 'evil corp' back into the picture, since most of the corps here seem to make more sense as rebellious scum than as multitrillion-dollar megacorps. (Weyland appears to be a pro-"human supremacy" organization that does care for the environment and believe mankind to be like gods.) The biggest hurdle for Weyland Corps is two-folds
// One...the existence of the Daemon Hunters already mean you have a faction dedicated to interacting with 'extraterrestial entities' (the Demons), although the Daemon Hunters 'officially' wants to purge demons, not use them as weaponry.
// Two...the Weyland Corps' techno-utopianism is already reflected in Cenaturs Incorporated and Singularility LLC, and actually made more explicit. Their environmentalism is radicalized in the form of VHEMT. In the dystopian world of The Regulator, the Weylands are just too...conventional. Too boring.

// Peter Weyland's speech: http://lybio.net/peter-weylands-2023-ted-talk/people/
// Even though Peter believed mankind to be god, in the movie Prometheus, he had to beg to the Creators themselves...gods who are theorized to have made mankind solely as breeding vessels for the greatest biological weapons ever...the Xenomorphs

// Possible 'Enemy Faction' To Include If Tyranny is too High
// If so, provide hints that the HFSE exist in the Lore before launching them
// I like this faction but it appears to be a non-violent version of PAGAD,
// so it can't really be used
// {
//   id: 11,
//   title: "Human Flesh Search Engine",
//   description: "Established in the early 21st century as a loose-knit collection of Chinese vigilantes seeking to punish corruption and immorality through public shaming and doxxing, it has since absorbed other crowd-sourced intelligence gathering entities to become a major international force. The HFSE uses harrassment and death threats to push the vague and shifting views of the Internet mob, and tends to target both the strong and the weak fairly equally.",
//   pro_quote: "Righteousness is one of the five virtues in the Confucian tradition. With the convenience of the internet, and in the case of non-responsive law, the righteous people took matters into their own hands.---Xujun Eberlein, Chinese-American writer",
//   anti_quote: "The human-flesh search has unimaginable power. First it was a lot of phone calls every day. Then people painted red characters on his parents’ froxnt door, which said things like, ‘You caused your wife’s suicide, so you should pay.’---Zhang Yanfeng, lawyer representing Wang Fei, a husband accused of cheating on his wife. Wang Fei went into hiding to evade the HFSE",
//   alignment: "right?"
// }

// The HFSE is a place that you can periodically monitor to check people's opinions about you. If you engage in too much tyranny, the HFSE will turn against you, and you will go against their wrath (which includes threatening attacks as well as stronger Corporations.)
// When you start the game, you log onto the HFSE to get your job.<|endoftext|>


<commit_before>
google.load('search', '1');
var i = 0;
var canvas = $('#seeker').get(0);
function player_init(){
  var width = (($(document).width())>1280? 1280: $(document).width());
  canvas = $('#seeker').get(0);
  $.app.ctx = canvas.getContext('2d');
  $('body').css('width', width);
  $.app.playerAction = 'play';

  $('#player_wrapper #album_artwork').attr('src', '/images/nothumb.png');
  google.search.Search.getBranding('google_branding');
}

function loadMusic(files) {
  var musicFiles = _(files).select(function (file) {
    var path = file.webkitRelativePath || file.mozFullPath;
    var fileName = file.fileName;
    var size = file.fileSize;
    var lpath = path.toLowerCase();
    return !/\.$/.test(lpath) &&
      (/\.mp3$/.test(lpath)) ||
      (/\.ogg$/.test(lpath)) ||
      (/\.m4a$/.test(lpath))
  });

  var total = musicFiles.length, progress = 0;

  function incProgress() {
    progress++;
    $('#addmusic').html(progress+' / '+total);
    if(progress == total) {
      $.app.Storage.save();
    } else {
      newMuFile(musicFiles[progress]);
    }
  }

  $.app.liveFiles = {};

  function newMuFile(f) {
    $.app.liveFiles[f.webkitRelativePath] = f;
    var muFile = new $.app.MuFile(f, incProgress);
  }

  newMuFile(musicFiles[progress]);
}

function getPrettySongName(muFile) {
  var name = muFile.name.length > muFile.title.length ?
    muFile.name : muFile.title;
  return name.replace(/\.\w+$/,'');
}

function getYoutubeSearchURL(muFile) {
  var name = getPrettySongName(muFile);
  return 'http://www.youtube.com/results?search_query='+
    name.split(/\s+/).join('+')+'+'+
    muFile.artist.split(/\s+/).join('+');
}

function getLyricsSearchURL(muFile) {
  var name = getPrettySongName(muFile);
  return 'http://www.google.com/search?q='+
    name.split(/\s+/).join('+')+'+'+
    muFile.artist.split(/\s+/).join('+')+'+lyrics';
}

function getArtistWikipediaURL(muFile) {
  return 'http://en.wikipedia.org/w/index.php?search='+
          muFile.artist.split(/\s+/).join('+');
}

function getAmazonLink(muFile) {
  return 'http://www.amazon.com/s?ie=UTF8&x=0&ref_=nb_sb_noss&y=0&field-keywords='+encodeURI(muFile.artist)+'&url=search-alias%3Ddigital-music&_encoding=UTF8&tag=myfreq-20&linkCode=ur2&camp=1789&creative=390957'
}

function getSongEntryHtml(muFile, asSearchResult) {
  var name = getPrettySongName(muFile);
  var entryHTML = '
'+
    '  '+
    ''+getPrettySongName(muFile)+''+
    '  '+
    ''+muFile.album+''+
    '  '+
    ''+muFile.artist+''+
    '  '+
    (asSearchResult ?
      '+' :
      '-'+
      '>')+
  '
';
  var entry = $(entryHTML);

  entry
    .hover(
      function () { $(this).addClass('focused_entry'); },
      function () { $(this).removeClass('focused_entry'); }
    )
    .find('.entry_action').data('muFile',muFile);

  return entry;
}

function getObjectURL(path) {
  if($.app.liveFiles) {
    var liveFile = $.app.liveFiles[path];
    return liveFile ? window.webkitURL.createObjectURL(liveFile) : null;
  } else {
    return null;
  }
}

function searchImage(query, callback) {
  function onComplete() {
    if (imageSearch.results && imageSearch.results.length > 0) {
      var results = imageSearch.results;
      callback(results[0].tbUrl);
    }
  }

  var imageSearch = new google.search.ImageSearch();
  imageSearch.setSearchCompleteCallback(this, onComplete, null);
  imageSearch.execute(query);
}

function updateSongInfo(muFile){
  var songInfo = $('#player_column #player_controls #song_info');
  $('#title', songInfo).text(muFile.title);
  $('#artist', songInfo).text(muFile.artist);
  $('#album', songInfo).text(muFile.album);
}

var currentPlaying = null;
$.app.nextSong = function () {
  var nextDiv = currentPlaying.next();
  if(nextDiv.length == 0) {
    nextDiv = currentPlaying.parent().children().first();
  }
  play(nextDiv);
}

function pause() {
  $('#player').get(0).pause();
}

function animateSeeker() {
  if(i<360){
    $.app.ctx.beginPath();
    $.app.ctx.clearRect(0,0,canvas.width, canvas.height);
    $.app.ctx.strokeStyle = 'rgba(00, 194, 256, 0.9)';
    $.app.ctx.lineWidth = 15;
    $.app.ctx.arc(76,75,65,Math.PI*(270/180),Math.PI*(++i+270)/180);
    $.app.ctx.shadowOffsetX = 0;
    $.app.ctx.shadowOffsetY = 0;
    $.app.ctx.shadowBlur = 5;
    $.app.ctx.shadowColor = 'rgba(170,170,170,0.7)';
    $.app.ctx.stroke();

    $.app.ctx.closePath();
    window.webkitRequestAnimationFrame(animateSeeker);
  } else {
    window.webkitCancelRequestAnimationFrame(animateSeeker);
  }
}

function play(div, resumeFlag) {
  if(!div){
    if($('#playlist', '#playlist_wrapper').is(':empty')){
      alert('No selction made.');
      return;
    } else {
      div = $('.entry', '#playlist').first();
      resumeFlag = false;
    }
  }
  var muFile = div.find('.entry_action').data('muFile');
  var url = getObjectURL(muFile.path);

  if(url) {
    if(!resumeFlag) { $('#player').get(0).src = url; }

    $('#player').get(0).play();
    currentPlaying = div;
    currentPlaying.parent().children().removeClass('active_entry');
    currentPlaying.addClass('active_entry');
    searchImage(muFile.album+' '+muFile.artist,function (tbUrl) {
      $('#player_wrapper #album_artwork').attr('src',tbUrl);
    });
    updateSongInfo(muFile);
  } else {
    alert('Add music again');
  }
}

$(document).ready(function () {
  player_init();
  $.app.Storage.load();

  $('#addmusic').click(function () {
    $('input[name=actual_addmusic]').click();
  });

  $('#play', '#player_column')
    .hover(
      function () {
        $('img', this)
          .attr('src', '/images/'+$.app.playerAction+'_hover.png');
      },
      function () {
        $('img', this)
          .attr('src', '/images/'+$.app.playerAction+'.png');
      }
    )
    .click(function () {
      if($.app.playerAction == 'play'){
        play(currentPlaying, true);
      } else {
        pause();
      }
    });

  $('#player', '#player_column')
    .bind('play', function () {
      $.app.playerAction = 'pause';
      $('img', '#play').attr('src', '/images/pause.png');
    })
    .bind('pause', function () {
      $.app.playerAction = 'play';
      $('img', '#play').attr('src', '/images/play.png');
    });

  $('input[name=search]').keyup(function (e) {

    var divResults = $('#search_results');
    divResults.empty();
    var text = $(this).val();

    if(!text || (text && text.length < 4)) { return; }

    var results = $.app.Storage.search($(this).val());
    _(results).each(function (muFile) {
      divResults.append(getSongEntryHtml(muFile, true));
    });

    divResults.find('.entry_action')
      .click(function () {
        var muFile = $(this).data('muFile');
        var player_entry = getSongEntryHtml(muFile, false);
        player_entry.find('.entry_action').click(function () {
          play($(this).parent());
        });
        player_entry.find('.remove_action').click(function () {
          play($(this).parent().remove());
        });
        $('#playlist_wrapper #playlist').append(player_entry);
      });

  })
  .focus(function (e){
    $(this).val('');
  })
  .focusout(function (e){
    if($(this).val() == ''){
      $(this).val('Search...');
    }
  });
});

<commit_msg>renaming play to playMedia for better read and find<commit_after>
google.load('search', '1');
var i = 0;
var canvas = $('#seeker').get(0);
function player_init(){
  var width = (($(document).width())>1280? 1280: $(document).width());
  canvas = $('#seeker').get(0);
  $.app.ctx = canvas.getContext('2d');
  $('body').css('width', width);
  $.app.playerAction = 'play';

  $('#player_wrapper #album_artwork').attr('src', '/images/nothumb.png');
  google.search.Search.getBranding('google_branding');
}

function loadMusic(files) {
  var musicFiles = _(files).select(function (file) {
    var path = file.webkitRelativePath || file.mozFullPath;
    var fileName = file.fileName;
    var size = file.fileSize;
    var lpath = path.toLowerCase();
    return !/\.$/.test(lpath) &&
      (/\.mp3$/.test(lpath)) ||
      (/\.ogg$/.test(lpath)) ||
      (/\.m4a$/.test(lpath))
  });

  var total = musicFiles.length, progress = 0;

  function incProgress() {
    progress++;
    $('#addmusic').html(progress+' / '+total);
    if(progress == total) {
      $.app.Storage.save();
    } else {
      newMuFile(musicFiles[progress]);
    }
  }

  $.app.liveFiles = {};

  function newMuFile(f) {
    $.app.liveFiles[f.webkitRelativePath] = f;
    var muFile = new $.app.MuFile(f, incProgress);
  }

  newMuFile(musicFiles[progress]);
}

function getPrettySongName(muFile) {
  var name = muFile.name.length > muFile.title.length ?
    muFile.name : muFile.title;
  return name.replace(/\.\w+$/,'');
}

function getYoutubeSearchURL(muFile) {
  var name = getPrettySongName(muFile);
  return 'http://www.youtube.com/results?search_query='+
    name.split(/\s+/).join('+')+'+'+
    muFile.artist.split(/\s+/).join('+');
}

function getLyricsSearchURL(muFile) {
  var name = getPrettySongName(muFile);
  return 'http://www.google.com/search?q='+
    name.split(/\s+/).join('+')+'+'+
    muFile.artist.split(/\s+/).join('+')+'+lyrics';
}

function getArtistWikipediaURL(muFile) {
  return 'http://en.wikipedia.org/w/index.php?search='+
          muFile.artist.split(/\s+/).join('+');
}

function getAmazonLink(muFile) {
  return 'http://www.amazon.com/s?ie=UTF8&x=0&ref_=nb_sb_noss&y=0&field-keywords='+encodeURI(muFile.artist)+'&url=search-alias%3Ddigital-music&_encoding=UTF8&tag=myfreq-20&linkCode=ur2&camp=1789&creative=390957'
}

function getSongEntryHtml(muFile, asSearchResult) {
  var name = getPrettySongName(muFile);
  var entryHTML = '
'+
    '  '+
    ''+getPrettySongName(muFile)+''+
    '  '+
    ''+muFile.album+''+
    '  '+
    ''+muFile.artist+''+
    '  '+
    (asSearchResult ?
      '+' :
      '-'+
      '>')+
  '
';
  var entry = $(entryHTML);

  entry
    .hover(
      function () { $(this).addClass('focused_entry'); },
      function () { $(this).removeClass('focused_entry'); }
    )
    .find('.entry_action').data('muFile',muFile);

  return entry;
}

function getObjectURL(path) {
  if($.app.liveFiles) {
    var liveFile = $.app.liveFiles[path];
    return liveFile ? window.webkitURL.createObjectURL(liveFile) : null;
  } else {
    return null;
  }
}

function searchImage(query, callback) {
  function onComplete() {
    if (imageSearch.results && imageSearch.results.length > 0) {
      var results = imageSearch.results;
      callback(results[0].tbUrl);
    }
  }

  var imageSearch = new google.search.ImageSearch();
  imageSearch.setSearchCompleteCallback(this, onComplete, null);
  imageSearch.execute(query);
}

function updateSongInfo(muFile){
  var songInfo = $('#player_column #player_controls #song_info');
  $('#title', songInfo).text(muFile.title);
  $('#artist', songInfo).text(muFile.artist);
  $('#album', songInfo).text(muFile.album);
}

var currentPlaying = null;
$.app.nextSong = function () {
  var nextDiv = currentPlaying.next();
  if(nextDiv.length == 0) {
    nextDiv = currentPlaying.parent().children().first();
  }
  playMedia(nextDiv);
}

function animateSeeker() {
  if(i<360){
    $.app.ctx.beginPath();
    $.app.ctx.clearRect(0,0,canvas.width, canvas.height);
    $.app.ctx.strokeStyle = 'rgba(00, 194, 256, 0.9)';
    $.app.ctx.lineWidth = 15;
    $.app.ctx.arc(76,75,65,Math.PI*(270/180),Math.PI*(++i+270)/180);
    $.app.ctx.shadowOffsetX = 0;
    $.app.ctx.shadowOffsetY = 0;
    $.app.ctx.shadowBlur = 5;
    $.app.ctx.shadowColor = 'rgba(170,170,170,0.7)';
    $.app.ctx.stroke();

    $.app.ctx.closePath();
    window.webkitRequestAnimationFrame(animateSeeker);
  } else {
    window.webkitCancelRequestAnimationFrame(animateSeeker);
  }
}

function pauseMedia() {
  $('#player').get(0).pause();
}

function playMedia(div, resumeFlag) {
  if(!div){
    if($('#playlist', '#playlist_wrapper').is(':empty')){
      alert('No selction made.');
      return;
    } else {
      div = $('.entry', '#playlist').first();
      resumeFlag = false;
    }
  }
  var muFile = div.find('.entry_action').data('muFile');
  var url = getObjectURL(muFile.path);

  if(url) {
    if(!resumeFlag) { $('#player').get(0).src = url; }

    $('#player').get(0).play();
    currentPlaying = div;
    currentPlaying.parent().children().removeClass('active_entry');
    currentPlaying.addClass('active_entry');
    searchImage(muFile.album+' '+muFile.artist,function (tbUrl) {
      $('#player_wrapper #album_artwork').attr('src',tbUrl);
    });
    updateSongInfo(muFile);
  } else {
    alert('Add music again');
  }
}

$(document).ready(function () {
  player_init();
  $.app.Storage.load();

  $('#addmusic').click(function () {
    $('input[name=actual_addmusic]').click();
  });

  $('#play', '#player_column')
    .hover(
      function () {
        $('img', this)
          .attr('src', '/images/'+$.app.playerAction+'_hover.png');
      },
      function () {
        $('img', this)
          .attr('src', '/images/'+$.app.playerAction+'.png');
      }
    )
    .click(function () {
      if($.app.playerAction == 'play'){
        playMedia(currentPlaying, true);
      } else {
        pauseMedia();
      }
    });

  $('#player', '#player_column')
    .bind('play', function () {
      $.app.playerAction = 'pause';
      $('img', '#play').attr('src', '/images/pause.png');
    })
    .bind('pause', function () {
      $.app.playerAction = 'play';
      $('img', '#play').attr('src', '/images/play.png');
    });

  $('input[name=search]').keyup(function (e) {

    var divResults = $('#search_results');
    divResults.empty();
    var text = $(this).val();

    if(!text || (text && text.length < 4)) { return; }

    var results = $.app.Storage.search($(this).val());
    _(results).each(function (muFile) {
      divResults.append(getSongEntryHtml(muFile, true));
    });

    divResults.find('.entry_action')
      .click(function () {
        var muFile = $(this).data('muFile');
        var player_entry = getSongEntryHtml(muFile, false);
        player_entry.find('.entry_action').click(function () {
          playMedia($(this).parent());
        });
        player_entry.find('.remove_action').click(function () {
          playMedia($(this).parent().remove());
        });
        $('#playlist_wrapper #playlist').append(player_entry);
      });

  })
  .focus(function (e){
    $(this).val('');
  })
  .focusout(function (e){
    if($(this).val() == ''){
      $(this).val('Search...');
    }
  });
});

<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies
 */
var Color = require('famous-utilities').Color;
var helpers = require('famous-utilities').helpers;

/**
 * Light Component
 */
var Light = function Light(dispatch) {
    this.dispatch = dispatch;
    this._id = dispatch.addComponent(this);
    this.queue = [];
    this._color = new Color();
    this.commands = { color: '' };
};

Light.toString = function toString() {
    return 'Light';
};

Light.prototype.setColor = function setColor() {
    this.dispatch.dirtyComponent(this._id);
    var values = helpers.flattenArguments(arguments);

    if (values[0] instanceof Color) {
        this._color = materialExpression[0];
    }

    this._color.set(values);
    this.queue.push(this.commands.color);
    var color = this._color.getNormalizedRGB();
    this.queue.push(color[0]);
    this.queue.push(color[1]);
    this.queue.push(color[2]);
    return this;
};

Light.prototype.getColor = function getColor(option) {
    return this._color.getColor(option);
};

Light.prototype.clean = function clean() {
    var path = this.dispatch.getRenderPath();

    this.dispatch
        .sendDrawCommand('WITH')
        .sendDrawCommand(path);

    var i = this.queue.length;
    while (i--) {
        this.dispatch.sendDrawCommand(this.queue.shift());
    }

    if (this._color.isActive()) {
        this.dispatch.sendDrawCommand(this.commands.color);
        var color = this._color.getNormalizedRGB();
        this.dispatch.sendDrawCommand(color[0]);
        this.dispatch.sendDrawCommand(color[1]);
        this.dispatch.sendDrawCommand(color[2]);
        return true;
    }

    return false;
};

/**
 * Expose
 */
module.exports = Light;
<commit_msg>Clean: Remove helper function<commit_after>'use strict';

/**
 * Module dependencies
 */
var Color = require('famous-utilities').Color;

/**
 * Light Component
 */
var Light = function Light(dispatch) {
    this.dispatch = dispatch;
    this._id = dispatch.addComponent(this);
    this.queue = [];
    this._color = new Color();
    this.commands = { color: '' };
};

Light.toString = function toString() {
    return 'Light';
};

Light.prototype.setColor = function setColor() {
    this.dispatch.dirtyComponent(this._id);
    var values = Color.flattenArguments(arguments);

    if (values[0] instanceof Color) {
        this._color = materialExpression[0];
    }

    this._color.set(values);
    this.queue.push(this.commands.color);
    var color = this._color.getNormalizedRGB();
    this.queue.push(color[0]);
    this.queue.push(color[1]);
    this.queue.push(color[2]);
    return this;
};

Light.prototype.getColor = function getColor(option) {
    return this._color.getColor(option);
};

Light.prototype.clean = function clean() {
    var path = this.dispatch.getRenderPath();

    this.dispatch
        .sendDrawCommand('WITH')
        .sendDrawCommand(path);

    var i = this.queue.length;
    while (i--) {
        this.dispatch.sendDrawCommand(this.queue.shift());
    }

    if (this._color.isActive()) {
        this.dispatch.sendDrawCommand(this.commands.color);
        var color = this._color.getNormalizedRGB();
        this.dispatch.sendDrawCommand(color[0]);
        this.dispatch.sendDrawCommand(color[1]);
        this.dispatch.sendDrawCommand(color[2]);
        return true;
    }

    return false;
};

/**
 * Expose
 */
module.exports = Light;
<|endoftext|>


<commit_before>"use strict";

const fs = require("fs-extra");
const path = require("path");

const cliRunner = require("@lerna-test/cli-runner");
const gitAdd = require("@lerna-test/git-add");
const gitCommit = require("@lerna-test/git-commit");
const cloneFixture = require("@lerna-test/clone-fixture")(
  path.resolve(__dirname, "../commands/publish/__tests__")
);

const env = {
  // never actually upload when calling `npm install`
  npm_config_dry_run: true,
  // skip npm package validation, none of the stubs are real
  LERNA_INTEGRATION: "SKIP",
};

test("lerna publish lifecycle scripts stop on non-zero exit", async () => {
  const { cwd } = await cloneFixture("lifecycle");
  const args = ["publish", "minor", "--yes", "--no-verify-registry"];

  const rootManifest = path.join(cwd, "package.json");
  const json = await fs.readJson(rootManifest);

  json.scripts.preversion = "echo boom && exit 123";

  await fs.writeJson(rootManifest, json);
  await gitAdd(cwd, rootManifest);
  await gitCommit(cwd, "update root prepack");

  try {
    await cliRunner(cwd, env)(...args);
  } catch (err) {
    expect(err.code).toBe(123);
    expect(err.stdout).toMatchInlineSnapshot(`

Changes:
 - package-1: 1.0.0 => 1.1.0
 - package-2: 1.0.0 => 1.1.0

> lifecycle@0.0.0-monorepo preversion __TEST_ROOTDIR__
> echo boom && exit 123

boom

`);
    expect(err.stderr).toMatchInlineSnapshot(`
lerna notice cli __TEST_VERSION__
lerna info current version 1.0.0
lerna info Looking for changed packages since initial commit.
lerna info auto-confirmed
lerna info lifecycle lifecycle@0.0.0-monorepo~preversion: lifecycle@0.0.0-monorepo
lerna info lifecycle lifecycle@0.0.0-monorepo~preversion: Failed to exec preversion script
lerna ERR! lifecycle "preversion" errored in "lifecycle", exiting 123

`);
  }
});
<commit_msg>test(integration): Avoid inexplicable snapshot comparison errors on Windows<commit_after>"use strict";

const fs = require("fs-extra");
const path = require("path");

const cliRunner = require("@lerna-test/cli-runner");
const gitAdd = require("@lerna-test/git-add");
const gitCommit = require("@lerna-test/git-commit");
const cloneFixture = require("@lerna-test/clone-fixture")(
  path.resolve(__dirname, "../commands/publish/__tests__")
);

const env = {
  // never actually upload when calling `npm install`
  npm_config_dry_run: true,
  // skip npm package validation, none of the stubs are real
  LERNA_INTEGRATION: "SKIP",
};

test("lerna publish lifecycle scripts stop on non-zero exit", async () => {
  const { cwd } = await cloneFixture("lifecycle");
  const args = ["publish", "minor", "--yes", "--no-verify-registry"];

  const rootManifest = path.join(cwd, "package.json");
  const json = await fs.readJson(rootManifest);

  json.scripts.preversion = "echo boom && exit 123";

  await fs.writeJson(rootManifest, json);
  await gitAdd(cwd, rootManifest);
  await gitCommit(cwd, "update root prepack");

  try {
    await cliRunner(cwd, env)(...args);
  } catch (err) {
    expect(err.code).toBe(123);

    if (process.platform !== "win32") {
      // windows can go pound sand, i'm done debugging this shit
      expect(err.stdout).toMatchInlineSnapshot(`

Changes:
 - package-1: 1.0.0 => 1.1.0
 - package-2: 1.0.0 => 1.1.0

> lifecycle@0.0.0-monorepo preversion __TEST_ROOTDIR__
> echo boom && exit 123

boom

`);
      expect(err.stderr).toMatchInlineSnapshot(`
lerna notice cli __TEST_VERSION__
lerna info current version 1.0.0
lerna info Looking for changed packages since initial commit.
lerna info auto-confirmed
lerna info lifecycle lifecycle@0.0.0-monorepo~preversion: lifecycle@0.0.0-monorepo
lerna info lifecycle lifecycle@0.0.0-monorepo~preversion: Failed to exec preversion script
lerna ERR! lifecycle "preversion" errored in "lifecycle", exiting 123

`);
    }
  }
});
<|endoftext|>


<commit_before>import React from 'react';
import autoBind from 'react-autobind';
import alertify from 'alertifyjs';
import Select from 'react-select';
import ToggleSwitch from 'js/components/common/toggleSwitch';
import TextBox from 'js/components/common/textBox';
import {actions} from 'js/actions';
import {bem} from 'js/bem';
import {renderLoading} from './modalHelpers';
import {
  truncateFile,
  truncateString,
} from '../../utils';

const MAX_DISPLAYED_STRING_LENGTH = 30;

/*
 * Modal for connecting project data
 */
class ConnectProjects extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isInitialised: false,
      isLoading: false,
      // `data_sharing` is an empty object if never enabled before
      isShared: props.asset.data_sharing?.enabled || false,
      attachedParents: [],
      sharingEnabledAssets: null,
      newParent: null,
      newFilename: '',
      fieldsErrors: {},
    };

    autoBind(this);
  }

  /*
   * Setup
   */

  componentDidMount() {
    actions.dataShare.attachToParent.completed.listen(
      this.refreshAttachmentList
    );
    actions.dataShare.attachToParent.failed.listen(
      this.onAttachToParentFailed
    );
    actions.dataShare.detachParent.completed.listen(
      this.refreshAttachmentList
    );
    actions.dataShare.getSharingEnabledAssets.completed.listen(
      this.onGetSharingEnabledAssetsCompleted
    );
    actions.dataShare.getAttachedParents.completed.listen(
      this.onGetAttachedParentsCompleted
    );
    actions.dataShare.toggleDataSharing.completed.listen(
      this.onToggleDataSharingCompleted
    );

    this.refreshAttachmentList();
    actions.dataShare.getSharingEnabledAssets();
  }

  /*
   * `actions` Listeners
   */

  onAttachToParentFailed(response) {
    this.setState({
      isLoading: false,
      fieldsErrors: response.responseJSON || {},
    });
  }
  onGetAttachedParentsCompleted(response) {
    this.setState({
      isInitialised: true,
      isLoading: false,
      attachedParents: response,
    });
  }
  onGetSharingEnabledAssetsCompleted(response) {
    this.setState({sharingEnabledAssets: response});
  }
  onToggleDataSharingCompleted(response) {
    this.setState({isShared: response.data_sharing.enabled});
  }
  refreshAttachmentList() {
    this.setState({
      newParent: null,
      newFilename: '',
    });
    actions.dataShare.getAttachedParents(this.props.asset.uid);
  }

  /*
   * UI Listeners
   */

  confirmAttachment(evt) {
    evt.preventDefault();

    let parentUrl = this.state.newParent?.url;
    let filename = this.state.newFilename;
    if (filename !== '' && parentUrl) {
      this.setState({
        isLoading: true,
        fieldsErrors: {},
      });

      var data = JSON.stringify({
        parent: parentUrl,
        fields: [],
        filename: filename,
      });
      actions.dataShare.attachToParent(this.props.asset.uid, data);
    } else {
      if (!parentUrl) {
        this.setState({
          fieldsErrors: Object.assign(
            this.state.fieldsErrors, {emptyParent: t('No project selected')}
          )
        });
      }
      if (filename === '') {
        this.setState({
          fieldsErrors: Object.assign(
            this.state.fieldsErrors, {emptyFilename: t('Field is empty')}
          )
        });
      }
    }
  }
  onParentChange(newVal) {
    this.setState({
      newParent: newVal,
      fieldsErrors: {},
    });
    this.generateAutoname(newVal);
  }
  onFilenameChange(newVal) {
    this.setState({
      newFilename: newVal,
      fieldsErrors: {},
    });
  }
  removeAttachment(newVal) {
    this.setState({isLoading: true})
    actions.dataShare.detachParent(newVal);
  }
  toggleSharingData() {
    var data = JSON.stringify({
      data_sharing: {
        enabled: !this.state.isShared
      }
    });

    if (!this.state.isShared) {
      let dialog = alertify.dialog('confirm');
      let opts = {
        title: `${t('Privacy Notice')}`,
        message: t('This will attach the full dataset from \"##ASSET_NAME##\" as a background XML file to this form. While not easily visible, it is technically possible for anyone entering data to your form to retrieve and view this dataset. Do not use this feature if \"##ASSET_NAME##\" includes sensitive data.').replaceAll('##ASSET_NAME##', this.props.asset.name),
        labels: {ok: t('Acknowledge and continue'), cancel: t('Cancel')},
        onok: (evt, value) => {
          actions.dataShare.toggleDataSharing(this.props.asset.uid, data);
          dialog.destroy();
        },
        oncancel: () => {
          dialog.destroy();
        }
      };
      dialog.set(opts).show();
    } else {
      actions.dataShare.toggleDataSharing(this.props.asset.uid, data);
    }
  }

  /*
   * Utilities
   */

  // Generates a filename for the selected parent, done so by taking the first
  // 30 characters, turning them lowercase and replacing spaces with underscores
  generateAutoname(newParent) {
    if (newParent) {
      let autoname = newParent.name;
      autoname = autoname.toLowerCase().substring(0, MAX_DISPLAYED_STRING_LENGTH).replace(/(\ |\.)/g, '_');
      this.setState({newFilename: autoname});
    }
  }
  generateFilteredAssetList() {
    let attachedParentUids = [];
    this.state.attachedParents.forEach((item) => {
      attachedParentUids.push(item.parentUid)
    });

    // Filter displayed asset list based on unattached projects
    return (
      this.state.sharingEnabledAssets.results.filter(
        item => !attachedParentUids.includes(item.uid)
      )
    );
  }

  /*
   * Rendering
   */

  renderSwitchLabel() {
    let switchLabel = this.state.isShared
      ? t('Data sharing enabled')
      : t('Data sharing disabled');

    return (
      <ToggleSwitch
        onChange={this.toggleSharingData.bind(this)}
        label={switchLabel}
        checked={this.state.isShared}
      />
    );
  }
  renderSelect() {
    // Don't crash the page before `actions.dataShare.sharingEnabledAssets` finishes
    if (this.state.sharingEnabledAssets !== null) {
      let sharingEnabledAssets = this.generateFilteredAssetList();

      const selectClassNames = ['kobo-select__wrapper'];
      if (this.state.fieldsErrors.emptyParent || this.state.fieldsErrors.parent) {
        selectClassNames.push('kobo-select__wrapper--error');
      }

      return(

            <Select
              placeholder={t('Select a different project to import data from')}
              options={sharingEnabledAssets}
              value={this.state.newParent}
              isLoading={(!this.state.isInitialised || this.state.isLoading || !sharingEnabledAssets)}
              getOptionLabel={option => option.name}
              getOptionValue={option => option.url}
              noOptionsMessage={() => {return t('No projects to connect')}}
              onChange={this.onParentChange}
              className='kobo-select'
              classNamePrefix='kobo-select'
            />

              {this.state.fieldsErrors.emptyParent || this.state.fieldsErrors.parent}

          <TextBox
            placeholder={t('Give a unique name to the import')}
            value={this.state.newFilename}
            onChange={this.onFilenameChange}
            errors={this.state.fieldsErrors.emptyFilename ||
                    this.state.fieldsErrors.filename}
          />

          <bem.KoboButton m='blue'>
            {t('Import')}
          </bem.KoboButton>

      );
    } else {
      return null;
    }
  }

  render() {
    return (
      <bem.FormModal__form
        className='project-settings project-settings--upload-file connect-projects'
        onSubmit={this.confirmAttachment}
      >
        {/* Enable data sharing */}
        <bem.FormModal__item m='data-sharing'>

{t('Share data with other project forms')}

            {t('Enable data sharing to allow other forms to import and use dynamic data from this project. Learn more about dynamic data attachments')}
            {t(' ' + 'here')}

          {this.renderSwitchLabel()}
        </bem.FormModal__item>

        {/* Attach other projects data */}
        <bem.FormModal__item m='import-data'>

{t('Import other project data')}

            {t('Connect with other project(s) to import dynamic data from them into this project. Learn more about dynamic data attachments')}
            {t(' ' + 'here')}

          {this.renderSelect()}

          {/* Display attached projects */}

            {t('Imported')}
            {(!this.state.isInitialised || this.state.isLoading) &&

                {renderLoading(t('Loading imported projects'))}

            }
            {!this.state.isLoading && this.state.attachedParents.length == 0 &&

                {t('No data imported')}

            }
            {!this.state.isLoading && this.state.attachedParents.length > 0 &&
                this.state.attachedParents.map((item, n) => {
                  return (

                          {truncateFile(item.filename, MAX_DISPLAYED_STRING_LENGTH)}

                          {truncateString(item.parentName, MAX_DISPLAYED_STRING_LENGTH)}

                       this.removeAttachment(item.attachmentUrl)}
                      />

                  );
                })
            }

        </bem.FormModal__item>

      </bem.FormModal__form>
    );
  }
}

export default ConnectProjects;
<commit_msg>PR Changes: remove useless guard<commit_after>import React from 'react';
import autoBind from 'react-autobind';
import alertify from 'alertifyjs';
import Select from 'react-select';
import ToggleSwitch from 'js/components/common/toggleSwitch';
import TextBox from 'js/components/common/textBox';
import {actions} from 'js/actions';
import {bem} from 'js/bem';
import {renderLoading} from './modalHelpers';
import {
  truncateFile,
  truncateString,
} from '../../utils';

const MAX_DISPLAYED_STRING_LENGTH = 30;

/*
 * Modal for connecting project data
 */
class ConnectProjects extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isInitialised: false,
      isLoading: false,
      // `data_sharing` is an empty object if never enabled before
      isShared: props.asset.data_sharing?.enabled || false,
      attachedParents: [],
      sharingEnabledAssets: null,
      newParent: null,
      newFilename: '',
      fieldsErrors: {},
    };

    autoBind(this);
  }

  /*
   * Setup
   */

  componentDidMount() {
    actions.dataShare.attachToParent.completed.listen(
      this.refreshAttachmentList
    );
    actions.dataShare.attachToParent.failed.listen(
      this.onAttachToParentFailed
    );
    actions.dataShare.detachParent.completed.listen(
      this.refreshAttachmentList
    );
    actions.dataShare.getSharingEnabledAssets.completed.listen(
      this.onGetSharingEnabledAssetsCompleted
    );
    actions.dataShare.getAttachedParents.completed.listen(
      this.onGetAttachedParentsCompleted
    );
    actions.dataShare.toggleDataSharing.completed.listen(
      this.onToggleDataSharingCompleted
    );

    this.refreshAttachmentList();
    actions.dataShare.getSharingEnabledAssets();
  }

  /*
   * `actions` Listeners
   */

  onAttachToParentFailed(response) {
    this.setState({
      isLoading: false,
      fieldsErrors: response.responseJSON || {},
    });
  }
  onGetAttachedParentsCompleted(response) {
    this.setState({
      isInitialised: true,
      isLoading: false,
      attachedParents: response,
    });
  }
  onGetSharingEnabledAssetsCompleted(response) {
    this.setState({sharingEnabledAssets: response});
  }
  onToggleDataSharingCompleted(response) {
    this.setState({isShared: response.data_sharing.enabled});
  }
  refreshAttachmentList() {
    this.setState({
      newParent: null,
      newFilename: '',
    });
    actions.dataShare.getAttachedParents(this.props.asset.uid);
  }

  /*
   * UI Listeners
   */

  confirmAttachment(evt) {
    evt.preventDefault();

    let parentUrl = this.state.newParent?.url;
    let filename = this.state.newFilename;
    if (filename !== '' && parentUrl) {
      this.setState({
        isLoading: true,
        fieldsErrors: {},
      });

      var data = JSON.stringify({
        parent: parentUrl,
        fields: [],
        filename: filename,
      });
      actions.dataShare.attachToParent(this.props.asset.uid, data);
    } else {
      if (!parentUrl) {
        this.setState({
          fieldsErrors: Object.assign(
            this.state.fieldsErrors, {emptyParent: t('No project selected')}
          )
        });
      }
      if (filename === '') {
        this.setState({
          fieldsErrors: Object.assign(
            this.state.fieldsErrors, {emptyFilename: t('Field is empty')}
          )
        });
      }
    }
  }
  onParentChange(newVal) {
    this.setState({
      newParent: newVal,
      fieldsErrors: {},
    });
    this.generateAutoname(newVal);
  }
  onFilenameChange(newVal) {
    this.setState({
      newFilename: newVal,
      fieldsErrors: {},
    });
  }
  removeAttachment(newVal) {
    this.setState({isLoading: true})
    actions.dataShare.detachParent(newVal);
  }
  toggleSharingData() {
    var data = JSON.stringify({
      data_sharing: {
        enabled: !this.state.isShared
      }
    });

    if (!this.state.isShared) {
      let dialog = alertify.dialog('confirm');
      let opts = {
        title: `${t('Privacy Notice')}`,
        message: t('This will attach the full dataset from \"##ASSET_NAME##\" as a background XML file to this form. While not easily visible, it is technically possible for anyone entering data to your form to retrieve and view this dataset. Do not use this feature if \"##ASSET_NAME##\" includes sensitive data.').replaceAll('##ASSET_NAME##', this.props.asset.name),
        labels: {ok: t('Acknowledge and continue'), cancel: t('Cancel')},
        onok: (evt, value) => {
          actions.dataShare.toggleDataSharing(this.props.asset.uid, data);
          dialog.destroy();
        },
        oncancel: () => {
          dialog.destroy();
        }
      };
      dialog.set(opts).show();
    } else {
      actions.dataShare.toggleDataSharing(this.props.asset.uid, data);
    }
  }

  /*
   * Utilities
   */

  // Generates a filename for the selected parent, done so by taking the first
  // 30 characters, turning them lowercase and replacing spaces with underscores
  generateAutoname(newParent) {
    if (newParent) {
      let autoname = newParent.name;
      autoname = autoname.toLowerCase().substring(0, MAX_DISPLAYED_STRING_LENGTH).replace(/(\ |\.)/g, '_');
      this.setState({newFilename: autoname});
    }
  }
  generateFilteredAssetList() {
    let attachedParentUids = [];
    this.state.attachedParents.forEach((item) => {
      attachedParentUids.push(item.parentUid)
    });

    // Filter displayed asset list based on unattached projects
    return (
      this.state.sharingEnabledAssets.results.filter(
        item => !attachedParentUids.includes(item.uid)
      )
    );
  }

  /*
   * Rendering
   */

  renderSwitchLabel() {
    let switchLabel = this.state.isShared
      ? t('Data sharing enabled')
      : t('Data sharing disabled');

    return (
      <ToggleSwitch
        onChange={this.toggleSharingData.bind(this)}
        label={switchLabel}
        checked={this.state.isShared}
      />
    );
  }
  renderSelect() {
    // Don't crash the page before `actions.dataShare.sharingEnabledAssets` finishes
    if (this.state.sharingEnabledAssets !== null) {
      let sharingEnabledAssets = this.generateFilteredAssetList();

      const selectClassNames = ['kobo-select__wrapper'];
      if (this.state.fieldsErrors.emptyParent || this.state.fieldsErrors.parent) {
        selectClassNames.push('kobo-select__wrapper--error');
      }

      return(

            <Select
              placeholder={t('Select a different project to import data from')}
              options={sharingEnabledAssets}
              value={this.state.newParent}
              isLoading={(!this.state.isInitialised || this.state.isLoading)}
              getOptionLabel={option => option.name}
              getOptionValue={option => option.url}
              noOptionsMessage={() => {return t('No projects to connect')}}
              onChange={this.onParentChange}
              className='kobo-select'
              classNamePrefix='kobo-select'
            />

              {this.state.fieldsErrors.emptyParent || this.state.fieldsErrors.parent}

          <TextBox
            placeholder={t('Give a unique name to the import')}
            value={this.state.newFilename}
            onChange={this.onFilenameChange}
            errors={this.state.fieldsErrors.emptyFilename ||
                    this.state.fieldsErrors.filename}
          />

          <bem.KoboButton m='blue'>
            {t('Import')}
          </bem.KoboButton>

      );
    } else {
      return null;
    }
  }

  render() {
    return (
      <bem.FormModal__form
        className='project-settings project-settings--upload-file connect-projects'
        onSubmit={this.confirmAttachment}
      >
        {/* Enable data sharing */}
        <bem.FormModal__item m='data-sharing'>

{t('Share data with other project forms')}

            {t('Enable data sharing to allow other forms to import and use dynamic data from this project. Learn more about dynamic data attachments')}
            {t(' ' + 'here')}

          {this.renderSwitchLabel()}
        </bem.FormModal__item>

        {/* Attach other projects data */}
        <bem.FormModal__item m='import-data'>

{t('Import other project data')}

            {t('Connect with other project(s) to import dynamic data from them into this project. Learn more about dynamic data attachments')}
            {t(' ' + 'here')}

          {this.renderSelect()}

          {/* Display attached projects */}

            {t('Imported')}
            {(!this.state.isInitialised || this.state.isLoading) &&

                {renderLoading(t('Loading imported projects'))}

            }
            {!this.state.isLoading && this.state.attachedParents.length == 0 &&

                {t('No data imported')}

            }
            {!this.state.isLoading && this.state.attachedParents.length > 0 &&
                this.state.attachedParents.map((item, n) => {
                  return (

                          {truncateFile(item.filename, MAX_DISPLAYED_STRING_LENGTH)}

                          {truncateString(item.parentName, MAX_DISPLAYED_STRING_LENGTH)}

                       this.removeAttachment(item.attachmentUrl)}
                      />

                  );
                })
            }

        </bem.FormModal__item>

      </bem.FormModal__form>
    );
  }
}

export default ConnectProjects;
<|endoftext|>


<commit_before>var http = require('http'),
    env  = process.env,
    server = http.createServer(function(req, res) {
      res.writeHead(200);
      res.end('Process ' + process.pid + ' says hi (node ' + process.version + ')!');
    });

server.listen(
  env.NODE_PORT || 3000,
  env.NODE_IP || 'localhost',
  function() {
    console.log('Application worker ' + process.pid + ' started...');
  }
);
<commit_msg>delete app.js<commit_after><|endoftext|>


<commit_before>/* LANGUAGE
 ================================================== */
if (typeof VMM != "undefined") {
	VMM.Language = {
		lang:"ru",
		api:{
			wikipedia:"ru"
		},
		date:{
			month:["Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь"],
			month_abbr:["Янв.", "Фев.", "Март", "Апр.", "Май", "Июнь", "Июль", "Авг.", "Сент.", "Окт.", "Нояб.", "Дек."],
			day:["Воскресенье", "Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота"],
			day_abbr:["Вск.", "Пн.", "Вт.", "Ср.", "Чт.", "Пт.", "Сб."]
		},
		dateformats:{
			year:"yyyy",
			month_short:"mmm",
			month:"mmmm yyyy",
			full_short:"mmm d",
			full:"mmmm d',' yyyy",
			time_no_seconds_short:"h:MM TT",
			time_no_seconds_small_date:"h:MM TT'
'mmmm d',' yyyy''",
			full_long:"mmm d',' yyyy 'at' hh:MM TT",
			full_long_small_date:"hh:MM TT'
mmm d',' yyyy''"
		},
		messages:{
			loading_timeline:"Загрузка... ",
			return_to_title:"Вернуться к заголовку",
			expand_timeline:"Увеличить",
			contract_timeline:"Уменьшить",
			wikipedia:"Из Wikipedia",
			loading_content:"Загрузка контента"
		}
	}
};<commit_msg>Github merge cleanup. Argh<commit_after>/* LANGUAGE
 ================================================== */
if (typeof VMM != "undefined") {
	VMM.Language = {
		lang:"ru",
		api:{
			wikipedia:"ru"
		},
		date:{
			month:["Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь"],
			month_abbr:["Янв.", "Фев.", "Март", "Апр.", "Май", "Июнь", "Июль", "Авг.", "Сент.", "Окт.", "Нояб.", "Дек."],
			day:["Воскресенье", "Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота"],
			day_abbr:["Вск.", "Пн.", "Вт.", "Ср.", "Чт.", "Пт.", "Сб."]
		},
		dateformats:{
			year:"yyyy",
			month_short:"mmm",
			month:"mmmm yyyy",
			full_short:"mmm d",
			full:"mmmm d',' yyyy",
			time_no_seconds_short:"h:MM TT",
			time_no_seconds_small_date:"h:MM TT'
'mmmm d',' yyyy''",
			full_long:"mmm d',' yyyy 'at' hh:MM TT",
			full_long_small_date:"hh:MM TT'
mmm d',' yyyy''"
		},
		messages:{
			loading_timeline:"Загрузка... ",
			return_to_title:"Вернуться к заголовку",
			expand_timeline:"Увеличить",
			contract_timeline:"Уменьшить",
			wikipedia:"Из Wikipedia",
			loading_content:"Загрузка контента",
			loading: "Загрузка"
		}
	}
};<|endoftext|>


<commit_before>/*eslint no-console: ["error", { allow: ["log"] }] */

var assert = require('chai').assert;
var after = require('mocha').after;
var validate = require('../index.js');
var request = require('sync-request');
var fs = require('fs');
var AdmZip = require('adm-zip');
var path = require('path');
var Test = require("mocha/lib/test");
var test_version = "1.0.0-rc3u5";

function getDirectories(srcpath) {
    return fs.readdirSync(srcpath).filter(function(file) {
        return fs.statSync(path.join(srcpath, file)).isDirectory();
    });
}

var missing_session_files = ['7t_trt', 'ds006', 'ds007', 'ds008', 'ds051', 'ds052', 'ds105', 'ds108', 'ds109', 'ds113b'];

function assertErrorCode(errors, expected_error_code) {
    var matchingErrors = errors.filter(function (error) {
        return error.code === expected_error_code;
    });
    assert(matchingErrors.length >= 0);
}

var suite = describe('BIDS example datasets ', function() {
    this.timeout(100000);

    before(function(done) {
        if (!fs.existsSync("tests/data/BIDS-examples-" + test_version + "/")) {
            console.log('downloading test data');
            var response = request("GET", "http://github.com/INCF/BIDS-examples/archive/" + test_version + ".zip");
            if (!fs.existsSync("tests/data")) {
                fs.mkdirSync("tests/data");
            }
            fs.writeFileSync("tests/data/examples.zip", response.body);
            var zip = new AdmZip("tests/data/examples.zip");
            console.log('unzipping test data');
            zip.extractAllTo("tests/data/", true);
        }

        var datasetDirectories = getDirectories("tests/data/BIDS-examples-" + test_version + "/");

        datasetDirectories.forEach(function testDataset(path){
            suite.addTest(new Test(path, function (isdone){
                var options = {ignoreNiftiHeaders: true};
                validate.BIDS("tests/data/BIDS-examples-" + test_version + "/" + path + "/", options, function (issues) {
                    var errors = issues.errors;
                    var warnings = issues.warnings;
                    assert.deepEqual(errors, []);
                    var session_flag = false;
                    for (var warning in warnings) {
                        if (warnings[warning]['code'] === '38') {
                            session_flag = true;
                            break;
                        }
                    }
                    if (missing_session_files.indexOf(path) === -1) {
                        assert.deepEqual(session_flag, false);
                    } else {
                        assert.deepEqual(session_flag, true);
                    }
                    isdone();
                });
            }));
        });
        done();
    });

    // we need to have at least one non-dynamic test
    it('validates path without trailing backslash', function(isdone) {
        var options = {ignoreNiftiHeaders: true};
        validate.BIDS("tests/data/BIDS-examples-" + test_version + "/ds001", options, function (issues, summary) {
            var errors = issues.errors;
            var warnings = issues.warnings;
            assert(summary.sessions.length === 0);
            assert(summary.subjects.length === 16);
            assert.deepEqual(summary.tasks, ['balloon analog risk task']);
            assert.deepEqual(summary.modalities, ['T1w', 'inplaneT2', 'bold']);
            assert(summary.totalFiles === 133);
            assert(summary.size === 803546);
            assert.deepEqual(errors, []);
            assert(warnings.length === 1 && warnings[0].code === '13');
            isdone();
        });
    });

    // we need to have at least one non-dynamic test
    it('validates dataset with valid nifti headers', function(isdone) {
        var options = {ignoreNiftiHeaders: false};
        validate.BIDS("tests/data/valid_headers", options, function (issues, summary) {
            var errors = issues.errors;
            var warnings = issues.warnings;
            assert(summary.sessions.length === 0);
            assert(summary.subjects.length === 1);
            assert.deepEqual(summary.tasks, ['rhyme judgment']);
            assert.deepEqual(summary.modalities, ['T1w', 'bold']);
            assert(summary.totalFiles === 8);
            assert(summary.size === 481793);
            assert(errors[0].code === '60');
            assert(warnings.length === 1 && warnings[0].code === '13');
            isdone();
        });
    });

    // test for illegal characters used in acq and task name
    it('validates dataset with illegal characters in task name', function(isdone) {
        var options = {ignoreNiftiHeaders: false};
        validate.BIDS("tests/data/valid_filenames", options, function (issues) {
            assertErrorCode(issues.errors, '58');
            isdone();
        });
    });

    // test for illegal characters used in sub name
    it('validates dataset with illegal characters in sub name', function(isdone) {
        var options = {ignoreNiftiHeaders: false};
        validate.BIDS("tests/data/valid_filenames", options, function (issues) {
            assertErrorCode(issues.errors, '64');
            isdone();
        });
    });

    // Catch some browser specific iteration issues with for .. in loops
    describe('with enumerable array prototype methods', function() {
        before(function () {
            // Patch in a potentially iterable prototype
            Array.prototype.broken = function () { /* custom extension */ };
        });
        after(function () {
            // Unpatch the above
            delete Array.prototype.broken;
        });
        it('validates dataset with illegal characters in task name', function (isdone) {
            var options = {ignoreNiftiHeaders: false};
            validate.BIDS("tests/data/valid_filenames", options, function (issues) {
                assertErrorCode(issues.errors, '58');
                isdone();
            });
        });
    });

    it('checks for subjects with no valid data', function (isdone) {
        var options = {ignoreNiftiHeaders: true};
        validate.BIDS("tests/data/no_valid_data", options, function (issues) {
            assertErrorCode(issues.errors, '67');
            isdone();
        });
    });

    // test for directory path not existing
    it('checks for non-existing directory', function (isdone) {
        var options = {ignoreNiftiHeaders: false};
        validate.BIDS("path/does/not/exist", options).then((issues) => {
            assertErrorCode(issues.errors, '68');
            isdone();
        }).catch(isdone);
    });
});
<commit_msg>Add test for directory check fix<commit_after>/*eslint no-console: ["error", { allow: ["log"] }] */

var assert = require('chai').assert;
var after = require('mocha').after;
var validate = require('../index.js');
var request = require('sync-request');
var fs = require('fs');
var AdmZip = require('adm-zip');
var path = require('path');
var Test = require("mocha/lib/test");
var test_version = "1.0.0-rc3u5";

function getDirectories(srcpath) {
    return fs.readdirSync(srcpath).filter(function(file) {
        return fs.statSync(path.join(srcpath, file)).isDirectory();
    });
}

var missing_session_files = ['7t_trt', 'ds006', 'ds007', 'ds008', 'ds051', 'ds052', 'ds105', 'ds108', 'ds109', 'ds113b'];

function assertErrorCode(errors, expected_error_code) {
    var matchingErrors = errors.filter(function (error) {
        return error.code === expected_error_code;
    });
    assert(matchingErrors.length >= 0);
}

var suite = describe('BIDS example datasets ', function() {
    this.timeout(100000);

    before(function(done) {
        if (!fs.existsSync("tests/data/BIDS-examples-" + test_version + "/")) {
            console.log('downloading test data');
            var response = request("GET", "http://github.com/INCF/BIDS-examples/archive/" + test_version + ".zip");
            if (!fs.existsSync("tests/data")) {
                fs.mkdirSync("tests/data");
            }
            fs.writeFileSync("tests/data/examples.zip", response.body);
            var zip = new AdmZip("tests/data/examples.zip");
            console.log('unzipping test data');
            zip.extractAllTo("tests/data/", true);
        }

        var datasetDirectories = getDirectories("tests/data/BIDS-examples-" + test_version + "/");

        datasetDirectories.forEach(function testDataset(path){
            suite.addTest(new Test(path, function (isdone){
                var options = {ignoreNiftiHeaders: true};
                validate.BIDS("tests/data/BIDS-examples-" + test_version + "/" + path + "/", options, function (issues) {
                    var errors = issues.errors;
                    var warnings = issues.warnings;
                    assert.deepEqual(errors, []);
                    var session_flag = false;
                    for (var warning in warnings) {
                        if (warnings[warning]['code'] === '38') {
                            session_flag = true;
                            break;
                        }
                    }
                    if (missing_session_files.indexOf(path) === -1) {
                        assert.deepEqual(session_flag, false);
                    } else {
                        assert.deepEqual(session_flag, true);
                    }
                    isdone();
                });
            }));
        });
        done();
    });

    // we need to have at least one non-dynamic test
    it('validates path without trailing backslash', function(isdone) {
        var options = {ignoreNiftiHeaders: true};
        validate.BIDS("tests/data/BIDS-examples-" + test_version + "/ds001", options, function (issues, summary) {
            var errors = issues.errors;
            var warnings = issues.warnings;
            assert(summary.sessions.length === 0);
            assert(summary.subjects.length === 16);
            assert.deepEqual(summary.tasks, ['balloon analog risk task']);
            assert.deepEqual(summary.modalities, ['T1w', 'inplaneT2', 'bold']);
            assert(summary.totalFiles === 133);
            assert(summary.size === 803546);
            assert.deepEqual(errors, []);
            assert(warnings.length === 1 && warnings[0].code === '13');
            isdone();
        });
    });

    // we need to have at least one non-dynamic test
    it('validates dataset with valid nifti headers', function(isdone) {
        var options = {ignoreNiftiHeaders: false};
        validate.BIDS("tests/data/valid_headers", options, function (issues, summary) {
            var errors = issues.errors;
            var warnings = issues.warnings;
            assert(summary.sessions.length === 0);
            assert(summary.subjects.length === 1);
            assert.deepEqual(summary.tasks, ['rhyme judgment']);
            assert.deepEqual(summary.modalities, ['T1w', 'bold']);
            assert(summary.totalFiles === 8);
            assert(summary.size === 481793);
            assert(errors[0].code === '60');
            assert(warnings.length === 1 && warnings[0].code === '13');
            isdone();
        });
    });

    // test for illegal characters used in acq and task name
    it('validates dataset with illegal characters in task name', function(isdone) {
        var options = {ignoreNiftiHeaders: false};
        validate.BIDS("tests/data/valid_filenames", options, function (issues) {
            assertErrorCode(issues.errors, '58');
            isdone();
        });
    });

    // test for illegal characters used in sub name
    it('validates dataset with illegal characters in sub name', function(isdone) {
        var options = {ignoreNiftiHeaders: false};
        validate.BIDS("tests/data/valid_filenames", options, function (issues) {
            assertErrorCode(issues.errors, '64');
            isdone();
        });
    });

    // Catch some browser specific iteration issues with for .. in loops
    describe('with enumerable array prototype methods', function() {
        before(function () {
            // Patch in a potentially iterable prototype
            Array.prototype.broken = function () { /* custom extension */ };
        });
        after(function () {
            // Unpatch the above
            delete Array.prototype.broken;
        });
        it('validates dataset with illegal characters in task name', function (isdone) {
            var options = {ignoreNiftiHeaders: false};
            validate.BIDS("tests/data/valid_filenames", options, function (issues) {
                assertErrorCode(issues.errors, '58');
                isdone();
            });
        });
    });

    it('checks for subjects with no valid data', function (isdone) {
        var options = {ignoreNiftiHeaders: true};
        validate.BIDS("tests/data/no_valid_data", options, function (issues) {
            assertErrorCode(issues.errors, '67');
            isdone();
        });
    });

    // test for directory path not existing
    it('checks for non-existing directory', function (isdone) {
        var options = {ignoreNiftiHeaders: false};
        validate.BIDS("path/does/not/exist", options).then(function(issues){
            assertErrorCode(issues.errors, '68');
            isdone();
        }).catch(isdone);
    });
});
<|endoftext|>