text
stringlengths 7
3.69M
|
|---|
export { Range } from './Range'
|
//悬浮框
$(".floatBox li").hover(function(){
$(this).find('img').show();
},function(){
$(this).find('img').hide();
});
|
import React from "react";
class Images extends React.Component {
render() {
const props = this.props;
let imgClassName = (props.isCenter ? "block" : "");
return (
<li className={imgClassName}>
<img src={props.url} alt={props.filename} />
</li>
);
}
}
export default Images;
|
var $ = prop => document.querySelector(prop);
var fRand = num => Math.floor(Math.random() * num);
var fR = (min, max) => min + Math.floor(Math.random() * (max - min));
var Rand = (min, max) => min + Math.random() * (max - min);
var randP = num => Math.floor(Math.random() * num) / 100;
function say(str) {
$("#log").innerHTML += str + "<br>";
res = true;
}
function c_s(str, color) {
return `<span style='color:${color}'>${str}</span>`;
}
function ind(arr, e) {
return arr.indexOf(e);
}
function rem(arr, e) {
arr.splice(arr.indexOf(e), 1);
}
function search(arr, e) {
for (var i = 0; i < arr.length; i++) {
if (e === arr[i]) {
return true;
}
}
}
function gramarr(arr) {
var result = "";
var reg = /a|e|i|o|u/i;
for (var i = 0; i < arr.length; i++) {
if (arr.length > 1) {
if (i < arr.length - 1) {
if (reg.test(arr[i].split('')[0])) {
result += "an " + arr[i] + ", ";
} else {
result += "a " + arr[i] + ", ";
}
} else {
if (reg.test(arr[i].split('')[0])) {
result += "and an " + arr[i];
} else {
result += "and a " + arr[i];
}
}
} else {
if (reg.test(arr[i].split('')[0])) {
result += "an " + arr[i];
} else {
result += "a " + arr[i];
}
}
}
return result;
}
function matchEl(arr, e) {
for (var i = 0; i < arr.length; i++) {
if (arr[i].includes(e)) {
return arr[i];
}
}
}
function getEl(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
function random(_min, _max) {
var min = _min;
var max = _max;
if (_min > _max) {
min = _max;
max = _min;
}
return min + Math.random() * (max - min);
}
function parseColors() {
var txt = $("#log").innerHTML;
var parsedTxt = txt
//regexp parsing
.replace(/[(]\w\w+[)]/g, (a) => c_s(a, "rgb(255,200,0)"))
.replace(/\[\w.+\]/g, (a) => c_s(a, "rgb(0,100,200)"))
.replace(/["](\w|\s)+["]/g, (a) => c_s(a, "rgb(0,175,0)"))
.replace(/…/g, c_s("…", "rgb(0,0,0)"))
.replace(/[≤]/ig, (a) => "<div style='text-align:center'>")
.replace(/[≥]/ig, (a) => "</div>")
.replace(/\n/g, "<br>")
.replace(/\ᚭ-/g, (a) => `<span style="color:rgb(150,150,150)">` + a)
.replace(/-\ᚮ/g, (a) => `${a}</span>`)
//very light blue
.replace(/Armor Points|Damage Bonus|Attack Speed Bonus|Bonus Critical Chance|Bonus Block Chance|Bonus Dodge Chance|Health Regeneration Bonus|Slot|Replenishes|Fills\(Bonus Health\)|crystal/g, (a) => c_s(a, "rgb(150, 200, 200)"))
//light red
.replace(/mist of blood|gash|\Wcut\W|chop|stab|cough up|health|squirting/ig, (a) => c_s(a, "rgb(255, 100, 100)"))
//dark red
.replace(/blood|gore|guts|gut|pain| red|splattering|splatter/ig, (a) => c_s(a, "rgb(200,0,0)"))
//light brown/coffee bone color
.replace(/bones|bone|ribcage|rib|skull|exoskeleton|skeleton|crunch/ig, (a) => c_s(a, "rgb(205,205,150)"))
//multi-colored words
.replace(/bandits/ig, c_s("ba", "rgb(150,50,0)") + c_s("n", "rgb(200,0,0)") + c_s("d", "rgb(200,150,0)") + c_s("it", "rgb(150,100,0)") + c_s("s", "rgb(125,75,0)"))
.replace(/bandit/ig, c_s("ba", "rgb(150,50,0)") + c_s("n", "rgb(200,0,0)") + c_s("d", "rgb(200,150,0)") + c_s("it", "rgb(150,100,0)"))
.replace(/bandit's/ig, c_s("ba", "rgb(150,50,0)") + c_s("n", "rgb(200,0,0)") + c_s("d", "rgb(200,150,0)") + c_s("it's", "rgb(150,100,0)"))
.replace(/knives|knife|weapon|crowbar|shiv|scales|scale|dagger|gunfire|shield|robotic|robot|carbon/ig, (a) => c_s(a, "rgb(150,150,150)"))
.replace(/metal|sword|steel|fiber|armor/ig, (a) => {
return c_s(a[0], "rgb(150,150,150)") +
c_s(a[1], "rgb(200,200,200)") +
c_s(a[2], "rgb(255,255,255)") +
c_s(a[3], "rgb(200,200,200)") +
c_s(a[4], "rgb(150,150,150)")
})
//light blue
.replace(/water|elixir|\Wwar\W/ig, (a) => c_s(a, "rgb(0,150,200)"))
//lighter blue
.replace(/xorox|cytotron|aliens|alien/ig, (a) => c_s(a, "rgb(0,200,255)"))
//white with a blue text glow
.replace(/electrocute|electricity|electric|glowing|\Wglow\W/ig, (a) => `<span style="color:white;text-shadow: 0 0 2px rgb(0,200,255);">${a}</span>`)
//almost white, yellowish light
.replace(/photon|lightning|\Wlight\W|consiousness/ig, (a) => `<span style="color:white;text-shadow: 0 0 2px rgb(255,255,200);">${a}</span>`)
//human flesh color
.replace(/kicks|punches|kick|punch|stomach|wrist|face|nose|head|flesh|body|bodies|bread/ig, (a) => c_s(a, "rgb(194, 167, 124)"))
//venom green
.replace(/creeps|creep|entity's|entity|grimace|battle-hardened/ig, (a) => c_s(a, "rgb(200,255,200)"))
//white
.replace(/smog|bottle|dodges|dodge|slams|slam|throwing|throw|survivor|survive|artifacts|artifact/ig, (a) => c_s(a,"rgb(255,255,255)"))
//dark grey
.replace(/lurking|lurk/ig, (a) => c_s(a, "rgb(75,75,75)"))
$("#log").innerHTML = parsedTxt;
}
//the items are literally all objects. There might be a couple thousand lines of code just for objects :O
var Items = {
/****************************************
* Food & Drink Items
****************************************/
"moldy piece of bread": {
d: "The moldy piece of bread is dry, stale, and covered with splotches of mold. It won't taste good, but it'll sustain you for a bit.",
//how much health it heals
healthG: 15,
//how much hunger it satisfies
hungerG: 25,
//how much thirst it satisfies
thirstG: -5,
//item type
type: "food",
},
"water bottle": {
d: "The plastic water bottle is about three-quarters full. The water in it isn't very clean, but it will keep you alive.",
//how much health it heals
healthG: 5,
//how much hunger it satisfies
hungerG: 2,
//how much thirst it satisfies
thirstG: 25,
//item type
type: "drink",
},
"xor candy": {
d: "What the humans call Xor Candies are actually the aliens' source of food. It is like glass that glows with a blue light. It is edible and tastes uniquely like nothing on earth.",
//how much health it heals
healthG: 25,
//how much hunger it satisfies
hungerG: 22,
//how much thirst it satisfies
thirstG: 25,
//item type
type: "food",
},
/****************************************
* Equipment (armor & weapons)
****************************************/
//daggers
"photon dagger": {
apts: 0,
dpts: 10,
asp: 20,
chance: [0.05, 0, 0, 0],
slot: "weapon",
type: "eq",
desc: "The photon Dagger is engraved with markings in which flow massive amounts of photons.",
attacks: ["stab", "slash"],
},
"antimatter dagger": {
apts: 0,
dpts: 10,
asp: 100,
chance: [0.03, 0, 0, 0],
slot: "weapon",
type: "eq",
desc: "The antimatter dagger weighs next to nothing. It's blade, made from pure antimatter cuts through anything including Light, Air, and Aliens.",
attacks: ["stab", "slash", "gash"],
},
"arcanium dagger": {
apts: 0,
dpts: 20,
asp: 0,
chance: [0.03, 0.1, 0, 0],
slot: "weapon",
type: "eq",
desc: "The arcanium dagger has the ability to enhance your attack power and gives you extra dexterity to dodge attacks.",
attacks: ["stab", "slash"],
},
"slit dagger": {
apts: 0,
dpts: 5,
asp: 15,
chance: [0.025, 0, 0, 0],
slot: "weapon",
type: "eq",
desc: "The steel Light Intensification Titancrush (SLIT) dagger is decorated with futuristic engravements, glowing with powerfully bright beams of blue laser.",
attacks: ["stab", "slash"],
},
"bloodshed dagger": {
apts: 0,
dpts: 25,
asp: 10,
chance: [0.03, 0, 0, 0],
slot: "weapon",
type: "eq",
desc: "The BLOODSHED dagger is made of a combination of titanium, arcanium, and antimatter.",
attacks: ["stab", "slash", "gash"],
},
"soulsmiter shortsword": {
apts: 0,
dpts: 20,
asp: 10,
chance: [0.03, 0, 0.075, 0],
slot: "weapon",
type: "eq",
desc: "the SoulSmiter Shortsword is Titanium in the structure of a diamond -- the most unbreakable element in the universe.",
attacks: ["stab", "slash", "gash"],
},
//swords
"steel sword": {
apts: 0,
dpts: 10,
asp: -1,
//crit, dodge, block, healthRegen
chance: [0.05, 0, 0.05, 0],
slot: "weapon",
type: "eq",
desc: "The shiny steel sword is beautifully decorated with futuristic markings and in it flow blue lines of power.",
attacks: ["slash", "stab", "hiltslam"],
},
"steel katana": {
apts: 0,
dpts: 10,
asp: 7,
//crit, dodge, block, healthRegen
chance: [0.05, 0, 0.025, 0],
slot: "weapon",
type: "eq",
desc: "The steel Katana is a durable, lightweight weapon capable of piercing almost anything.",
attacks: ["slash", "stab"],
},
"steel machete": {
apts: 0,
dpts: 20,
asp: -5,
//crit, dodge, block, healthRegen
chance: [0.05, 0, 0.025, 0],
slot: "weapon",
type: "eq",
desc: "The steel Machete is a heavyweight weapon, but its weight adds on to momentum, enhancing its power.",
attacks: ["slash", "gash", "chop"],
},
"photon sword": {
apts: 0,
dpts: 15,
asp: 5,
chance: [0.025, 0, 0.05, 0],
slot: "weapon",
type: "eq",
desc: "The photon sword is a very lightweight titanium sword outlined with a layer of powerful cutting laser.",
attacks: ["stab", "slash", "hiltslam", "gash"],
},
"photon katana": {
apts: 0,
dpts: 15,
asp: 10,
chance: [0.025, 0, 0.075, 0],
slot: "weapon",
type: "eq",
desc: "The photon Katana is a super lightweight titanium weapon with powerful cutting abilities.",
attacks: ["stab", "slash", "hiltslam", "gash"],
},
"photon machete": {
apts: 0,
dpts: 30,
asp: -5,
//crit, dodge, block, healthRegen
chance: [0.05, 0, 0.075, 0],
slot: "weapon",
type: "eq",
desc: "The photon Machete is heavy weapon whose power is to be reckoned with.",
attacks: ["slash", "gash", "chop"],
},
"antimatter sword": {
apts: 0,
dpts: 20,
asp: 10,
chance: [0.05, 0, -0.05, -1],
slot: "weapon",
type: "eq",
desc: "The antimatter sword is a super lightweight weapon that is fast and weighs next to nothing. The antimatter does emit radiation which drains your Health Regeneration slightly.",
attacks: ["stab", "slash", "hiltslam", "gash"],
},
"antimatter katana": {
apts: 0,
dpts: 20,
asp: 20,
chance: [0.05, 0, -0.075, -1],
slot: "weapon",
type: "eq",
desc: "The antimatter Katana is one of the lightest weapons ever. It has super powerful cutting abilities, but emits dangerous radiation which drains your Health Regeneration slightly.",
attacks: ["stab", "slash", "hiltslam", "gash"],
},
"antimatter machete": {
apts: 0,
dpts: 40,
asp: 0,
//crit, dodge, block, healthRegen
chance: [0, 0, -0.075, -2],
slot: "weapon",
type: "eq",
desc: "The antimatter Machete weighs nothing and is super powerful. The large antimatter blade emits dangerous radiation which drains your Health Regeneration slightly.",
attacks: ["slash", "gash"],
},
"arcanium sword": {
apts: 0,
dpts: 15,
asp: 0,
chance: [0.025, 0.05, 0.05, 1],
slot: "weapon",
type: "eq",
desc: "The arcanium Sword is slightly heavier than a photon Sword but offers higher dexterity and health regeneration.",
attacks: ["stab", "slash", "hiltslam", "gash"],
},
"arcanium katana": {
apts: 0,
dpts: 15,
asp: 5,
chance: [0.025, 0.05, 0.075, 1.5],
slot: "weapon",
type: "eq",
desc: "The arcanium Katana is a lightweight weapon with powerful abilities which offers higher dexterity and health regeneration.",
attacks: ["stab", "slash", "hiltslam", "gash"],
},
"arcanium machete": {
apts: 0,
dpts: 30,
asp: -10,
//crit, dodge, block, healthRegen
chance: [0.05, 0.05, 0.075, 2],
slot: "weapon",
type: "eq",
desc: "The arcanium Machete weighs a lot, deals a lof of damage, and offers higher dexterity and health regeneration.",
attacks: ["slash", "gash", "chop"],
},
"golden cytotron machete": {
apts: 0,
dpts: 50,
asp: -100,
//crit, dodge, block, healthRegen
chance: [0.05, 0.05, 0.075],
slot: "weapon",
type: "eq",
desc: "The cytotron golden machete is an extremely heavy weapon, but its power is more than any other weapon.",
attacks: ["slash", "gash", "chop"],
},
//axes
"steel battle axe": {
apts: 0,
dpts: 20,
asp: -10,
//crit, dodge, block, healthRegen
chance: [0.1, 0, 0, 0],
slot: "weapon",
type: "eq",
desc: "The steel axe is engraved with technological runes that glow with green light. It is heavy, but its weight enhances its power.",
attacks: ["chop", "gash", "knockout"],
},
"photon battle axe": {
apts: 0,
dpts: 20,
asp: -5,
//crit, dodge, block, healthRegen
chance: [0.1, 0, 0, 0],
slot: "weapon",
type: "eq",
desc: "The photon axe glows with a green light and weighs very light. It isn't super powerful, but it is a durable weapon.",
attacks: ["chop", "gash", "knockout", "axe throw"],
},
"antimatter battle axe": {
apts: 0,
dpts: 25,
asp: 0,
//crit, dodge, block, healthRegen
chance: [0.1, 0, 0, 0],
slot: "weapon",
type: "eq",
desc: "The antimatter axe weighs next to nothing and cuts through virtually anything. Its power is very high and is to be reckoned with.",
attacks: ["chop", "gash", "knockout", " axe throw"],
},
//sticks/staffs
"steel staff": {
apts: 0,
dpts: 10,
asp: 100,
//crit, dodge, block, healthRegen
chance: [0, 0, 0.05, 0],
slot: "weapon",
type: "eq",
desc: "The steel staff is engraved with red power lines that transfer energy throughout the weapon. It is a light, deadly weapon.",
attacks: ["stab", "strike"],
},
"stunshock staff": {
apts: 0,
dpts: 10,
asp: 50,
//crit, dodge, block, healthRegen
chance: [0.05, 0, 0.05, 0],
slot: "weapon",
type: "eq",
desc: "The stunshock staff has a tazor on each end of it",
attacks: ["stab", "strike", "electrocute"],
},
"titancrush staff": {
apts: 0,
dpts: 50,
asp: -100,
//crit, dodge, block, healthRegen
chance: [0.05, 0, 0.05, 0],
slot: "weapon",
type: "eq",
desc: "The titancrush staff is made of pure Osmium which is the heaviest metal in the universe. It is a pain to lift, but its power is amazing.",
attacks: ["stab", "strike"],
},
//technological devices
"bolt tazor": {
apts: 0,
dpts: 15,
asp: 200,
//crit, dodge, block, healthRegen
chance: [0, 0.05, 0, 0],
slot: "weapon",
type: "eq",
desc: "The handheld BOLT tazor is lightweight, fast, and discharges tons of voltage into its target.",
attacks: ["electrocute"],
},
"short range phaser": {
apts: 0,
dpts: 25,
asp: -50,
//crit, dodge, block, healthRegen
chance: [0, 0.05, 0, 0],
slot: "weapon",
type: "eq",
desc: "The handheld phaser can hit enemies at a short range. It also has a small 1-foot-long bayonette-type knife on it.",
attacks: ["shoot", "stab"],
},
"25 kilowatt laser beam blaster": {
apts: 0,
dpts: 15,
asp: -10,
//crit, dodge, block, healthRegen
chance: [0, 0.05, 0, 0],
slot: "weapon",
type: "eq",
desc: "The kilowatt laser blaster has a long barrel, about 1.5ft long, and unlimited ammo. It is powered by compressed photons and has a small knife on its hilt.",
attacks: ["shoot", "stab", "gash"],
},
//other weapons
"magnorok throwing hammer": {
apts: 0,
dpts: 35,
asp: -50,
//crit, dodge, block, healthRegen
chance: [0, 0.05, 0, 0],
slot: "weapon",
type: "eq",
desc: "The magnorok throwing hammer is a side weapon used by cytotron sentries. It is a very powerful artifact of war.",
attacks: ["throw", "strike", "pound"],
},
"baseball bat": {
apts: 0,
dpts: 5,
asp: 0,
//crit, dodge, block, healthRegen
chance: [0.025, 0, 0.025, 0],
slot: "weapon",
type: "eq",
desc: "The baseball bat is made of old, decaying wood. Not a very good weapon, but it's enough.",
attacks: ["strike", "pound"],
},
"shiv": {
apts: 0,
dpts: 5,
asp: 10,
//crit, dodge, block, healthRegen
chance: [0.025, 0.05, 0, 0],
slot: "weapon",
type: "eq",
desc: "The shiv is made of what seems two sheets of metal hammered together.",
attacks: ["stab", "slash"],
},
"crowbar": {
apts: 0,
dpts: 10,
asp: -10,
//crit, dodge, block, healthRegen
chance: [0.05, -0.025, 0, 0],
slot: "weapon",
type: "eq",
desc: "The shiv is made of what seems two sheets of metal hammered together.",
attacks: ["strike", "stab", "pound"],
},
"proton gauntlets": {
apts: 5,
dpts: 10,
asp: 150,
//crit, dodge, block, healthRegen
chance: [0, 0.15, 0, 5],
slot: "weapon",
type: "eq",
desc: "The proton gauntlets are an amazingly light, fast, and powerful weapon. They come with electric fist tazors that zap your opponent on punch.",
attacks: ["punch", "electrocute"],
},
//armor
"guardian helmet": {
apts: 5,
dpts: 0,
asp: 0,
//crit, dodge, block, healthRegen
chance: [0, 0, 0, 0],
slot: "helmet",
type: "eq",
desc: "The guardian helmet is made of steel and microlattice and engraved with glowing lines of power.",
attacks: ["punch"],
},
"cytotron helmet": {
apts: 10,
dpts: 0,
asp: 5,
//crit, dodge, block, healthRegen
chance: [0, 0.05, 0, 0],
slot: "helmet",
type: "eq",
desc: "The bronze-like cytotron helmet is engraved with glowing technological runes.",
attacks: ["punch"],
},
"refractor helmet": {
apts: 15,
dpts: 0,
asp: 10,
//crit, dodge, block, healthRegen
chance: [0, 0, 0, 0.05],
slot: "helmet",
type: "eq",
desc: "The refractor helmet is a very strong piece of armor that protects with attack-deflecting nanotechnology.",
attacks: ["punch"],
},
"checkered cap": {
apts: 2,
dpts: 0,
asp: 0,
//crit, dodge, block, healthRegen
chance: [0, 0, 0, 0],
slot: "helmet",
type: "eq",
desc: "The checkered cap is made of fabric. Not a very good equipment item.",
attacks: ["punch"],
},
"aeroguard armor": {
apts: 20,
dpts: 0,
asp: 10,
//crit, dodge, block, healthRegen
chance: [0, 0.05, 0, 0],
slot: "armor",
type: "eq",
desc: "The aeroguard armor is a self-morphing armor powered by nanotechnology. It can predict where hits will land and strengthen certain areas. It also uses air pressure and resistance to shield from blows.",
attacks: ["punch"],
},
"cytotron armor": {
apts: 25,
dpts: 0,
asp: 10,
//crit, dodge, block, healthRegen
chance: [0, 0, 0, 0],
slot: "armor",
type: "eq",
desc: "The cytotron armor is made of a bronze-like substance engraved with orange firey runes. You can't really understand what they say, but you can get \"defense\" out of what's written.",
attacks: ["punch"],
},
"refractor armor": {
apts: 35,
dpts: 0,
asp: 20,
//crit, dodge, block, healthRegen
chance: [0, 0, 0, 0.05],
slot: "armor",
type: "eq",
desc: "The refractor armor is made of a strong silver alloy and is engraved with purple lines of power in a geometric arrangement.",
attacks: ["punch"],
},
"t-shirt": {
apts: 3,
dpts: 0,
asp: 0,
//crit, dodge, block, healthRegen
chance: [0, 0, 0, 0],
slot: "armor",
type: "eq",
desc: "the t-shirt is, well was white and is now stained with many blotches of dirty stuff.",
attacks: ["punch"],
},
"alien exoskeleton armor": {
apts: 10,
dpts: 0,
asp: -5,
//crit, dodge, block, healthRegen
chance: [0, 0, 0, 0.5],
slot: "armor",
type: "eq",
desc: "The alien exoskeleton armor is a very advanced nanotechnology armor. It can morph to fit a human, an alien, or an animal or almost any size. It's made of a carbon-fiber-like substance with a metalic sheen.",
attacks: ["punch"],
},
"aeroguard boots": {
apts: 10,
dpts: 0,
asp: 10,
//crit, dodge, block, healthRegen
chance: [0, 0, 0.025, 0],
slot: "shoes",
type: "eq",
desc: "The lightweight cytotron boots provide lots of dexterity and protect your feet from deadly attacks.",
attacks: ["punch"],
},
"cytotron boots": {
apts: 12,
dpts: 0,
asp: -15,
//crit, dodge, block, healthRegen
chance: [0, 0, 0.05, 0],
slot: "shoes",
type: "eq",
desc: "The heavyweight cytotron boots limit your speed by a large amount but offer lots of powerful protection. Best of all, you can sometimes block attacks with your feet.",
attacks: ["punch"],
},
"refractor boots": {
apts: 15,
dpts: 5,
asp: -20,
//crit, dodge, block, healthRegen
chance: [0, 0, 0.075, 0.05],
slot: "shoes",
type: "eq",
desc: "The refractor boots are heavy, but allow you to block attacks with your feet and kick with powerful force.",
attacks: ["punch"],
},
"pair of sneakers": {
apts: 3,
dpts: 0,
asp: 0,
//crit, dodge, block, healthRegen
chance: [0, 0, 0, 0],
slot: "shoes",
type: "eq",
desc: "The pair of rubber sneakers is, well, not very good as armor, but enough to prevent your feet from getting sore.",
attacks: ["punch"],
},
"pair of jeans": {
apts: 3,
dpts: 0,
asp: 0,
//crit, dodge, block, healthRegen
chance: [0, 0, 0, 0],
slot: "pants",
type: "eq",
desc: "The blue jeans have holes torn in them. Nothing special.",
attacks: ["punch"],
},
"restoration accelerator": {
apts: 0,
dpts: 0,
asp: 0,
//crit, dodge, block, healthRegen
chance: [0, 0, 0, 5],
slot: "accelerator",
type: "eq",
desc: "The restoration accelerator is a ring with a pulsing bluish-purple gemstone. It is a healing device that injects life through your veins.",
attacks: ["punch"],
},
"reaction accelerator": {
apts: 0,
dpts: 0,
asp: 50,
//crit, dodge, block, healthRegen
chance: [0, 0.1, 0.1, 0],
slot: "accelerator",
type: "eq",
desc: "The flashflare accelerator is an accelerator that makes your movement speed and reactions much faster. It is a glowing blue gemstone ring.",
attacks: ["punch"],
},
"iris accelerator": {
apts: 0,
dpts: 0,
asp: 25,
//crit, dodge, block, healthRegen
chance: [0.15, 0, 0.05, 0],
slot: "accelerator",
type: "eq",
desc: "The iris accelerator enhances your vision and your chance to hit enemies and score critical hits. It is a golden ring with a green gemstone on it.",
attacks: ["punch"],
},
"leviathan accelerator": {
apts: 25,
dpts: 25,
asp: 0,
//crit, dodge, block, healthRegen
chance: [0, 0, 0, 0],
slot: "accelerator",
type: "eq",
desc: "The leviathan accelerator is a glowing orange gemstone on a ring that enhances your damage and armor percentage.",
attacks: ["punch"],
},
"deflection accelerator": {
apts: 0,
dpts: 0,
asp: 0,
//crit, dodge, block, healthRegen
chance: [0, 0, 0.25, 1],
slot: "accelerator",
type: "eq",
desc: "The deflection accelerator is a ring with an infinitely black gemstone that increases block chance and a bit of health regen.",
attacks: ["punch"],
},
"battlecry accelerator": {
apts: 15,
dpts: 15,
asp: 20,
//crit, dodge, block, healthRegen
chance: [0.1, 0.1, 0.1, 2],
slot: "accelerator",
type: "eq",
desc: "The battlecry accelerator is a bright white gemstone, pulsing with a blinding light. It increases a bit of everything.",
attacks: ["punch"],
},
"carbonshield accelerator": {
apts: 15,
dpts: 5,
asp: 0,
//crit, dodge, block, healthRegen
chance: [0, 0, 0.05, 1],
slot: "accelerator",
type: "eq",
desc: "The carbonshield accelerator is a black gemstone glowing with a purple light. It turns the outer layer of your skin to solid carbon at almost the strength of a diamond.",
attacks: ["punch"],
},
//shields
"cytotron shield": {
apts: 5,
dpts: 0,
asp: 0,
//crit, dodge, block, healthRegen
chance: [0, 0, 0.15, 0],
slot: "shield",
type: "eq",
desc: "The Cytotron shield is made of a polished bronze-like alloy. engraved with technological runes.",
attacks: ["punch"],
},
"morphatory shield": {
apts: 10,
dpts: 0,
asp: 0,
//crit, dodge, block, healthRegen
chance: [0, 0, 0.15, 0],
slot: "shield",
type: "eq",
desc: "The morphatory shield is made of aluminum in the same structure of a diamond. It is super light and just as hard as the clear gemstones.",
attacks: ["punch"],
},
"stasis particle shield": {
apts: 15,
dpts: 0,
asp: 20,
//crit, dodge, block, healthRegen
chance: [0, 0, 0.15, 0],
slot: "shield",
type: "eq",
desc: "The stasis particle shield can absorb hundreds of thousands of tons of force and shatter it by using light and sound waves. Better yet, it's made of the lightest metal in the world - Microlattice.",
attacks: ["punch"],
},
"alien exoskeleton shield": {
apts: 10,
dpts: 0,
asp: 10,
//crit, dodge, block, healthRegen
chance: [0, 0, 0.15, 0],
slot: "shield",
type: "eq",
desc: "The alien exoskeleton shield is made of some type of carbonfiber-like material. It's light, but has a metalic feel to it.",
attacks: ["punch"],
},
/****************************************
* One-time use items (grenades, etc)
****************************************/
"grenade": {
desc: "The grenade is a lumpy ellipsoid full of explosives.",
use: "You remove the lock ring from the grenade and throw it at your opponent. The grenade blasts open in a blast of flame, scorching and seriously wounding your opponent.",
damage: 75,
heal: 0,
type: "one-use",
},
"throwing knives (5)": {
desc: "You hold five silver throwing knives in your hand. They can deal lots of damage when used together.",
use: "You hold three knives in one hand and three in the other. When your opponent gets close enough, five knifes slash them, giving them some nasty wounds.",
damage: 25,
heal: 0,
type: "one-use",
},
"health shot": {
desc: "The health shot syringe contains emergency oxygen, energy, and compressed atoms that can heal your body almost instantly.",
use: "You inject the syringe into yourself and a sharp pain pierces through your body. It goes away after a split second and you feel much better.",
damage: 0,
heal: 50,
type: "one-use",
},
"neutron pulsar cannon": {
desc: "The neutron pulsar cannon is a one-shot hand cannon capable of doing tons of destruction.",
use: "You fire off the neutron pulsar cannon and the fast-moving bulvar smashes into your opponent at the speed of light!",
damage: 100,
heal: 0,
type: "one-use",
},
"nuclear Fusion sniper": {
desc: "The nuclear fusion sniper is a one-shot sniper tool that shoots at the speed of light.",
use: "A flash of blinding light flashes and your opponent is on the floor, covered in blood.",
damage: 200,
heal: 0,
type: "one-use",
},
"acid grenade": {
desc: "The acid grenade will hook onto its target and inject powerful acid into their body.",
use: "You throw the acid grenade at your opponent. Immediately, it locks onto their skin on contact and injects a very powerful acid into them. They writhe in pain and vomit up large amounts of blood as the acid destroys their body.",
damage: 75,
heal: 0,
type: "one-use",
},
"phosphorus grenade": {
desc: "The super flammable phosphorus grenade is like a throwing knife with a large spherical core.",
use: "You throw the fire grenade at your opponent and its blade flies and roots into their flesh. It then blasts out in a firey explosion, roasting them and slightly burning you.",
damage: 75,
heal: -10,
type: "one-use",
},
/****************************************
* Misc
****************************************/
"silver coin": {
d: "The silver coin is very shiny and has the picture of a globe on it. International currency.",
value: 10,
type: "misc"
},
"xorox alien scale": {
d: "This tough element comes from a xorox alien. You can't really do a lot with it, but it could come in useful.",
value: 5,
type: "misc"
},
"steel xorox scale": {
d: "This steel scale came from a xorox alien. It's not much, but it could turn in useful.",
value: 7,
type: "misc"
},
"cytotron plate": {
d: "This metal plate came from a cytotron trooper's armor. It looks very smooth but slightly satisfying. Alien design.",
value: 7,
type: "misc"
},
"xorox crystal": {
d: "The xorox crystal is a beautiful transparent blue one about one ounce in weight. It glows with a faint blue light and seems to be an energy accelerator. You don't know how to use it.",
value: 10,
type: "misc"
},
"human femur": {
d: "The human femur has some rotting flesh on it and smells detestable. This was probably for the study of humans back at the aliens' base.",
value: 1,
type: "misc"
},
"severed hand": {
d: "Ew, a severed hand. The aliens were probably trying to study humans.",
value: 1,
type: "misc"
},
"twig": {
d: "The brown wooden twig is slightly cracked and all the leaves on it are dead.",
value: 1,
type: "misc"
},
/****************************************
* Useable Items
****************************************/
"bandage": {
type: "useable",
d: "The bandage is a long strip of cloth for bandaging up wounds. Type 'use bandage' to heal yourself.",
use: function(){
if(player.health < player.maxHealth-10){
player.health += 10;
} else {
player.health = player.maxHealth;
}
},
}
};
/*
This is what most of the DreamForger Engine was made of. I developed the engine on my local server and brought it here.
The DreamForger engine was made before primavera as mentioned above, but not the story, items, etc.
*/
var past = ">";
var npcs = [];
var res = false;
var rooms = [];
var creatures = [];
var objects = [];
var humans = [];
var spawnPoints = [1, 1];
var myInt;
var population = 100;
var words = {
"north": ["north", "n", "go north", "go n"],
"south": ["south", "s", "go south", "go s"],
"east": ["east", "e", "go east", "go e"],
"west": ["west", "w", "go west", "go w"],
"fight": ["fight", "attack", "kill", "provoke", "tease", "mock"],
"look": ["look", "examine", "see", "study", "read"],
"inv": ["inv", "inventory", "i"],
"eq": ["equipment", "eq"],
"craft": ["craft", "make", "create", "invent", "construct"],
"buy": ["buy", "purchase"],
"sell": ["sell", "donate"],
"take": ["take", "loot", "pick up"],
"drop": ["drop", "throw", "toss", "abandon"],
"give": ["give", "offer"],
"talk": ["say", "shout", "scream"],
"communicate": ["chat", "talk", "communicate", "ask"],
"open": ["open"],
"wear": ["wear", "equip", "put on"],
"remove": ["remove", "unequip", "take off"],
"eat": ["eat", "chew", "gulp"],
"drink": ["drink", "swallow"],
"flee": ["run", "flee", "escape"],
"clear": ["clear", "empty", "blank", "erase"],
"help": ["help", "guide"],
"all": ["all", "everything"],
"use": ["use", "make use of", "interact"],
"quests": ["quests", "jobs", "tasks", "work"],
"scan": ["scan","survey","gaze"],
"list": ["list","items","stock"]
};
var phrasesNotAllowed = ["Huh?", "You can't do that.", "That's not a valid command. Please try again.", "What?", "I don't know what you are trying to accomplish.", "That command doesn't do anything."];
var WPS = {
"sword": ["sword", "saber", "blade", "katana", "scimitar"],
"axe": ["axe", "cleaver", "tomahawk", "battleaxe"],
"spear": ["spear"],
"knife": ["knife", "dagger"],
"club": ["club", "mace", "shillelagh"],
"staff": ["staff", "stick", "cane", "stick", 'bar']
};
var AMR = {
"helmet": ["headgear", "helmet", "cap"],
"armor": ["armor", "jacket", "coat", "chestplate", "breastplate"],
"shield": ["shield", "buckler"],
"ring": ["ring", "accelerator", "finger ring"],
"glove": ["glove", "gauntlet"],
"belt": ["belt", "girdle", "waistband", "sash"],
"armplate": ["armplate", "armlet"],
"shoulderguard": ["shoulderguard"],
"leggings": ["pants", "trousers", "leggings", "greaves"],
"legplate": ["legplate", "shinguard"],
"shoe": ["boot", "shoe", "sneaker"],
"necklace": ["accelerator", "necklace", "chain", "pendant", "locket"],
"bracelet": ["bracelet", "accelerator", "band", "bangle"]
};
var wtps = Object.keys(WPS);
var atps = Object.keys(AMR);
var canvas = $("canvas");
var ctx = canvas.getContext("2d");
/***********************
*
* @ > dead end (alley)
* - & | > alley sections
* g > scorched grass
* G > garage
* h > rundown house
* H > house (empty)
* = & " > roads
* + & # > cross intersections (alley & road)
* w > polluted water
* W > water spring
* r > rundown restaurant
* B > battlefield
* b > building (empty)
* : > turn
*
***********************/
var globalMap = [
' ',
' @-|-: AAAAAAAAA ',
' gG" ^^^^^^^^^^^^^ AaaaaaapA ',
' ghT====#====T=TT=gggdddddgd^BBBBBBBBBBBBtaaa AaaaaaaaA ',
' gg" " ggg" "" ggddHhgdgg^BBBBBBBBBBBB aaaaaaaaaaaa A©AAAAA©A ',
' @--|" w" gr=T "" gddgwWH==:^BBBBBBBBBBBBtaaa a a AAAAA f f AAAAAA ',
' gG" ww" ggg" "" gggwwhwgg"^BBBBBBBBBBBB aaaaaaaaaaaa ffffffff A ',
' gHT====T ggg" "" gggHhHddd"^BBBBBBBBBBBBtaaa a ©fffffffffffffffffffff A ',
' gg" ww" gb=T "" ggddddgdd"^BBBBBBBBBBBB aaaaaaaaaA f fffffffffffffffffffff A',
' @|--T w" ggg" ":==========T^BBBBBBBBBBBBtaaa a Aff fffffffffffffffffffff A',
' gG" " ggg" :======T====T^BBBBBBBBBBBB aaaaaaaaaA f fffffffffffffffffffff A',
' gH"====T gb=T ggggggg"gggg"^BBBBBBBBBBBBtaaa a ©fffffffffffffffffffff A ',
' gg" ww" ggg" g%%g$$$$$$$g"^BBBBBBBBBBBB aaaaaaaaaaaa fffffffffffffff A ',
' @-|-T ww" ggg" g%%$$$$$$$$g"^BBBBBBBBBBBBtaaa a a AAAAA f AAAAA ',
' gG" w" gr=T g%%g$$$$$$$g"^BBBBBBBBBBBB aaaaaaaaaaaa AAAAA©AAAA ',
' gh"====: ggg" g$ggggg$gggg"^BBBBBBBBBBBBtaaa f ',
' ggww gg " g!!!!g$$$g" ^^^^^^^^^^^^^ fffffff©AAAAAAAAAAA f AAAAAAAAAAA ',
' @--|T gG " g!!!!$$$$g" $$$$$$$$^ BBB f A f © A ',
' gH===T" g!!!!g$$$gT===!!!!$$$$^ BBBBBB f AAA A fffffffff f fffffffff A ',
' @--==T gggg " gggggggggg" !!!!$$$$^ BBBBBB f AfA A ff f ff A ',
' bbbbg" T===========T !!!!$$$$^ BBBBBB f A©A A fffffffff f fffffffff A ',
' @--==T gg "ghhHhHHHGGg" $$$$$$$$^ BB f f A ff f ff A ',
' bbbbg" gG "ggggh"hgggg" ^^^^"^^^^ ^^^ BB f f A fffffffff f fffffffff A ',
' @--==T gh===#=====T=T===T==" " "ggg^BB f f A ff f ff A ',
' bbbbg" gggg " "bbbb :====#====Tggg^BB f f A fffffffff f fffffffff A ',
' @--==T " g"bg T-|-@ "" "ggg^BB f f A ff f ff A ',
' bbbbg" " g"rg "bbbb "" ^^^ BB f f A fffff f fffff A ',
' @--==#========: g"rg T|-|@ "" BB f f AA fffffffffffffffff AA ',
' " g"bg "bbbb "" BBBBBB f f AAA fffffffffffff AAA ',
' " g"rg T--|@ "" BBBBBB f f AAA fffffff AAA ',
' " :====T===:bbbb "" BBBBBB f f AA AA ',
' " " "" BBBBBB f f AAAAAAAAAAAAA ',
' H H =================:: BBBBB A©A f ',
' BBBBB Af©fffiiiiiiiiiiiiiiiiiiiiiiiie ',
' AAA ',
' ',
];
var player = {
x: spawnPoints[0],
y: spawnPoints[1],
health: 100,
maxHealth: 100,
bonusHealth: 0,
xp: 0,
level: 1,
money: 0,
inv: [],
eq: ["pair of jeans", "t-shirt", "checkered cap", "pair of sneakers","baseball bat","leviathan accelerator","iris accelerator","restoration accelerator","reaction accelerator","carbonshield accelerator","deflection accelerator"],
attarr: ["punch", "kick"],
attacks: [],
//maximum stuff you can wear
wearLimit: {
//one helmet
"helmet": 0,
//one suit of armor
"armor": 0,
//one shield
"shield": 1,
//one weapon
"weapon": 1,
//one pair of pants
"pants": 0,
//two boots
"shoes": 0,
//accelerators
"accelerator": 6,
},
fighting: false,
//fighting stats
minDamage: 1,
maxDamage: 5,
damageBonus: 0,
//rate (milliseconds) for when you attack
attackRate: 3000,
bAttack: 0,
//special stuffses
dodgeChance: 0.05,
blockChance: 0,
critChance: 0.1,
bDodge: 0,
bBlock: 0,
bCrit: 0,
//the higher, the better. 100 is full, 0 is empty
hunger: 100,
thirst: 100,
//maximum hunger and thirst
maxH: 100,
maxT: 100,
//nothing to worry about
died: false,
isDead: false,
//health Regeneration
healthRegen: 2,
plusReg: 0,
quests: [],
qd: [],
};
var spawnLoc = {
"-": ["bandit","cobra gangster"],
"|": ["bandit","cobra gangster"],
"@": ["bandit","cobra gangster"],
"h": ["bandit","cobra gangster"],
"H": ["bandit","cobra gangster"],
"=": ["xorox trooper","bandit","cobra gangster"],
'"': ["xorox trooper","bandit","cobra gangster"],
"^": ["quasar trooper"],
"$": ["quasar trooper"],
"B": ["xorox entity","xorox trooper","quasar trooper","cytotron trooper"],
"g": ["xorox entity"],
"a": ["xorox entity"],
};
/****************************************
* PROTOTYPE CONSTRUCTORS
****************************************/
var rands = {
banditWeapons: ["baseball bat", "crowbar", "shiv"],
parts: ["jaw", "stomach", "gut", "ribcage", "nose"],
};
function Creature(t, x, y) {
this.int = false;
this.x = x;
this.y = y;
this.type = t;
this.fighting = false;
this.d = "";
this.ad = "";
this.dd = "The corpse of a dead " + this.type + " is empty, decayed, and disgusting."
this.aggr = false;
this.health = 0;
this.maxHealth = 0;
this.level = 0;
this.dead = false;
this.spawn = "";
switch (this.type) {
case "bandit": {
this.wpn = getEl(rands.banditWeapons);
this.ad = "A bandit runs up to you, wielding a " + this.wpn;
this.d = "A bandit is sitting on the floor, holding a " + this.wpn + ", looking very bored.";
this.minDamage = 1;
this.maxDamage = 10;
this.attackRate = 3000;
this.critChance = 0.05;
this.blockChance = 0;
this.dodgeChance = 0.2;
this.drops = ["throwing knives (5)", "silver coin","bandage", "water bottle", "moldy piece of bread", this.wpn];
this.aggr = true;
this.health = 20;
this.maxHealth = 20;
this.level = 2;
this.attacks = ["The bandit punches you in the " + getEl(rands.parts), "The bandit hits you with his weapon", "Your opponent hits you in the " + getEl(rands.parts) + " with his weapon.", "The bandit slams you down on the floor with a judo throw."];
} break;
case "quasar trooper": {
this.ad = "A quasar trooper runs over to you, ready to attack";
this.d = "A well-armed quasar trooper is behind a mounted Proton Quasar cannon, aiming to find a lurking alien.";
this.minDamage = 5;
this.maxDamage = 30;
this.attackRate = 3000;
this.critChance = 0.1;
this.blockChance = 0.1;
this.dodgeChance = 0.1;
this.drops = ["water bottle", "moldy piece of bread", "photon katana", "grenade","bandage", "short range phaser","bolt tazor","guardian helmet","short-range phaser"];
this.aggr = false;
this.health = 75;
this.maxHealth = 75;
this.level = 5;
this.attacks = ["The quasar trooper zaps you with a bolt tazor","The quasar trooper slashes you with a photon katana","The quasar trooper smashes you in the face with the hilt of a photon katana","The quasar trooper punches you in the stomach","The quasar trooper impales you with his sword."];
} break;
case "xorox entity": {
this.ad = "A xorox alien, covered in a carbonfiber-like armor jumps out at you.";
this.d = "A xorox entity walks around on six legs, searching for something to destroy.";
this.minDamage = 5;
this.maxDamage = 15;
this.attackRate = 2500;
this.critChance = 0.1;
this.blockChance = 0.1;
this.dodgeChance = 0;
this.drops = ["alien exoskeleton shield","photon dagger","human femur","severed hand","twig","xor candy","xor crystal","xorox alien scale","human femur","alien exoskeleton armor"];
this.aggr = true;
this.health = 50;
this.maxHealth = 50;
this.level = 3;
this.attacks = ["The xorox alien smashes its long stiff arm into the side of your head.","The xorox alien jumps on you and smashes you head into the floor","The alien jumps on you and bites your shoulder","The xorox entity smashes its heavy fist into your stomach","The alien smashes and breaks your nose, squirting blood everywhere."];
} break;
case "xorox trooper": {
this.ad = "A heavyweight alien about seven feet and covered in metal armor jumps out at you.";
this.d = "A heavyweight xorox trooper walks along, phaser in hand, searching for any less powerful being than you to destroy.";
this.minDamage = 10;
this.maxDamage = 60;
this.attackRate = 3500;
this.critChance = 0.1;
this.blockChance = 0;
this.dodgeChance = 0;
this.drops = ["alien exoskeleton shield","human femur","severed hand","twig","xor candy","xor crystal","arcanium sword","cytotron boots","steel xorox scale"];
this.aggr = true;
this.health = 150;
this.maxHealth = 150;
this.level = 7;
this.attacks = ["The xorox alien smashes its long stiff arm into the side of your head.","The xorox alien jumps on you and smashes you head into the floor","The alien jumps on you and bites your shoulder","The xorox entity smashes its heavy fist into your stomach","The alien smashes and breaks your nose, squirting blood everywhere."];
} break;
case "cytotron trooper": {
this.ad = "A very large bronze-colored alien invader walks over to you, ready to demolish you.";
this.d = "A large cytotron trooper is blasting deadly lasers at everything in its path, trying to deface the planet earth.";
this.minDamage = 15;
this.maxDamage = 75;
this.attackRate = 2500;
this.critChance = 0;
this.blockChance = 0.15;
this.dodgeChance = 0;
this.drops = ["cytotron helmet","cytotron armor","cytotron shield","cytotron boots","antimatter machete","cytotron plate"];
this.aggr = true;
this.health = 250;
this.maxHealth = 250;
this.level = 10;
this.attacks = ["The cytotron trooper smashes you with the hilt of a very large machete-like weapon.","The cytotron trooper gives you a large cut accross the face","The cytotron trooper sends you flying a large distance with one mighty kick","The cytotron trooper cracks your skull with a large metal fist.","The cytotron trooper dismounts a large gun from its back and just barely vaporizes you."];
} break;
case "cytotron sentry": {
this.ad = "A golden cytotron sentry removes a long golden machete from its sheath and runs at you, ready to tear you to pieces.";
this.d = "A golden cytotron sentry stands still, waiting for an invade to pass by.";
this.minDamage = 25;
this.maxDamage = 200;
this.attackRate = 3000;
this.critChance = 0.1;
this.blockChance = 0.15;
this.dodgeChance = 0;
this.drops = ["cytotron helmet","cytotron armor","cytotron shield","cytotron boots","magnorok throwing hammer","golden cytotron machete","cytotron plate"];
this.aggr = true;
this.health = 750;
this.maxHealth = 750;
this.level = 10;
this.attacks = ["The massive cytotron sentry swings a very large machete at you. It hits you in the side, breaking a couple of ribs.","The cytotron sentry removes a throwing hammer from its belt and smashes you in the face.","The powerful sentry smashes you in the stomach with its large metalic fist, forcing blood out of your mouth.","The cytotron sentry picks you up and smashes you against the nearest wall","The cytotron sentry dismounts a large gun from its back and blasts it at you. A small part of your body has been vaporized. Luckily, you're still alive."];
} break;
case "cobra gangster": {
this.ad = "A cobra gangster with an ouroboros (snake) tatoo on his forehead jumps out of nowhere and gives you a nasty surprise.";
this.d = "A cobra gangster is sitting on the floor and looking very bored. He has an ouroboros (snake) tatoo on his forehead.";
this.minDamage = 1;
this.maxDamage = 10;
this.attackRate = 2500;
this.critChance = 0.1;
this.blockChance = 0.1;
this.dodgeChance = 0.15;
this.drops = ["throwing knives (5)", "silver coin","bandage", "water bottle", "moldy piece of bread", "pair of sneakers","checkered cap","xorox crystal","grenade","shiv","stunshock staff"];
this.aggr = true;
this.health = 85;
this.maxHealth = 85;
this.level = 5;
this.attacks = ["The cobra gangster does a spinning-kick and smashes his foot into your face.","The cobra gangster throws five knives at you. You dodge most of them, but get cut a bit.","The cobra gangster throws a grenade at you. It hits you, bounces off of you, and explodes, burning you slightly.","The gangster rams his shoulder int your stomach.","The gangster slices at you with a shiv.","The gangster starts wielding a stunshock staff and smashes you with it.","The gangster karate-chops your neck."];
} break;
}
}
Creature.prototype.fight = function() {
if (this.fighting && player.fighting) {
clearInterval(this.int);
clearInterval(myInt);
this.int = setInterval(eAttack, this.attackRate);
myInt = setInterval(playerAttack, player.attackRate);
}
};
Creature.prototype.run = function() {
var c = $("#com").value.split('').splice(1, 10000).join('');
var c_br = c.split(' ');
if (this.x == player.x && this.y == player.y) {
if (!this.dead) {
if (!this.fighting) {
if (this.level >= player.level && this.aggr) {
this.fighting = true;
player.fighting = true;
} else {
if (search(words.fight, c_br[0]) && matchEl([this.type], c_br[1])) {
say("You reveal your weapon to the " + this.type + ", starting the fight.");
player.fighting = true;
this.fighting = true;
}
}
}
if (this.fighting) {
this.fight();
}
}
}
};
function Room(t, x, y) {
this.x = x;
this.y = y;
this.t = t;
this.d = "";
this.items = [];
switch (this.t) {
case "p":
this.d = "The room you enter glows with a very bright light. Power cords line the walls and mandelbrot patterns in the walls and floor flow.";
break;
case "f":
this.d = "You walk accross the floor in the aliens' base. Each tile is shaped like a mandelbrot-like swirl outlined with a glowing plasma-like substance. Occasionally, the mandelbrot tiles will shift positions, changing to a different recursive pattern.";
break;
case "©":
this.d = "You walk up to a large gate, made by the aliens. The design of the gate is super durable, full of self-regenerating nanotechnology, and is not guarded with any special weapons.";
break;
case "A":
this.d = "You walk over to a large metal gate made by the aliens. The gates, when fired at will regenerate itself to a lighter and stronger structure with nanotechnology. You can see slight vibrations moving when you look at the wall closely."
break;
case "a":
var nns = [
"Strange glowing runes are carved into the ground. Some elixir-like substance is flowing like a rive beneath your feet. Such power is emitted that static electricity makes your hair prick up a bit, or is it fear? You are in alien territory.",
"Your nearly silent footsteps soundly touch the ground. Strange glowing patterns are carved into the ground. The ground is very smooth and in the glowing patterns is a neverending river of a plasma-like substance.",
"You look down on the ground and see a glowing alien XOR matrix. XOR matrices are proton accelerators - a new techology discovered by humans about a year before aliens arrived. XORs have the ability to increment or decrement the number of protons in an object. You are in alien territory.",
"The ground under you is completely transparent. You stare through the glass floor and underneath is a flowing river of pure energy. You are in alien territory."
];
this.d = c_s(getEl(nns), "rgb(75,100,225)");
break;
case "t":
this.d = c_s("You cross an area with a smoothened-out floor. Lines of elixir flow through transparent veins cut in the ground. The massive amoutn of energy flowing beneath your feet creates some static electricity, pricking your hair up.", "rgb(100,100,200)");
break;
case "i":
this.d = c_s("You walk down a nearly invisible underground hallway. It seems to have been carved by alien hands as there are claw marks everywhere. ", "rgb(200,200,200)");
break;
case "e":
this.d = c_s("You walk into a bright white room. " + "!gge retsae eht dnuof uoY".split('').reverse().join('') + " Paste this code in the T&T for proof: xorMatrix[your username]" + Math.floor(Math.random() * 1000) + "Cytotron", "rgb(255,255,255)");
break;
case "T":
this.d = c_s("You reach a t-shaped intersection. Everything around is lifeless and broken. A thick smog fills the air and the sound of gunfire and screaming echoes in the distance. An uncomfortable feeling creeps up your spine. Anything could be lurking around waiting to jump out at you.", "rgb(100,100,100)");
break;
case ":":
this.d = c_s("You reach a turn. Everything around is lifeless and broken. A thick smog fills the air and the sound of gunfire and screaming echoes in the distance. An uncomfortable feeling creeps up your spine. Anything could be lurking around waiting to jump out at you.", "rgb(100,100,100)");
break;
case "@":
this.d = c_s("You've reached a dead end in an alley. Pieces of trash line the walls and a thick smog smelling of death fills the air. An occasional rat scurries out of nowhere. Anything can jump out of you out of nowhere. Your eyes flicker back and forth watching for something that might kill you.", "rgb(100,100,100)");
break;
case "-":
this.d = c_s("You stand in a shady abandoned alley. Everything around is lifeless and broken. A thick smog fills the air and the sound of gunfire and screaming echoes in the distance. An uncomfortable feeling creeps up your spine. Anything could be lurking around waiting to jump out at you.", "rgb(150,150,150)");
break;
case "|":
this.d = c_s("You walk into a sinister, shaded alley. Trash lines the sides of the alley and a thick, smelly fog fills the air. Gunfire and screaming sounds echo in the distance. Not much to see around here. Anything could jump out at you at any given moment.", "rgb(150,150,150)");
break;
case '"':
this.d = c_s("You walk up an abandoned street. Many flying cars used to travel this route. Now there is nothing. Anything could jump out at you at any given moment. The smell of burning rotten corpses streams through your nose, giving off a sickly feeling.", "rgb(175,175,175)");
break;
case '=':
this.d = c_s("You enter an abandoned road. So many flying cars used to populate the streets. It was a good life before, but now?\nLife is hard trying to survive in the war with aliens. The sound of gunfire and the smell of dead bodies turn your stomach.", "rgb(175,175,175)");
break;
case '+':
this.d = c_s("You enter a cross-shaped area. Four directions to choose from. Buildings tower around you in four directions. The smell of burning corpses, smoke, and gas make you feel sick. Sounds of gunfire and warfare echo in the distance. Terrible.", "rgb(125,125,125)");
break;
case '#':
this.d = c_s("You enter a road intersection. Four directions to choose from. Broken traffic lights, empty ammo rounds, and trash line the streets. An occasional rat scurries out from the drain systems. A thick smog smelling of burning corpses fills the air while gunfire sounds off in the distance.", "rgb(125,125,125)");
break;
case 'g':
this.d = c_s("You walk accross a patch of scorched grass. The grass crumbles into ash as you step on it. The once green patch has been destroyed by firepower and life-elimitating aliens. You hear flamethrowers and guns blasting in the distance.", "rgb(100,150,100)");
break;
case 'h':
this.d = c_s("You enter a crumbled-down house. Some people used to live in it, but now they are probably dead. You can't find much of anything in the thick rubble and all the remaining items of the house seem to have been burnt up. The smell of a rotting corpse wafts out of somewhere.", "rgb(175,150,125)");
break;
case 'b':
this.d = c_s("You enter an abandoned building. Almost all of its items have been looted previously and the inside of the building seems to have been scorched by flame. Such a broken world. So sad.", "rgb(175,150,100)");
break;
case 'B':
var descs = [
"You walk over the grounds of a battlefield. All the grass is scorched and empty ammo shells and broken weapons line the ground. Some flames try their best to consume the remaining living grass. Even fire has a hard time surviving. Such a broken world.",
"You gaze accross the darkened face of a battlefield. All the grass is scorched. Almost no life remains here. War, death, evil, and starvation all come together. Some little bugs and rodents scurry accross the area, searching for food.",
"Grey clouds cover the battlefield you stand on. Almost no life is left here. Death is everywhere. In an alien invasion, everything is desolated more than in a normal war on earth."
];
this.d = c_s(getEl(descs), "rgb(80,80,80)");
break;
case 'H':
this.d = c_s("You enter a house that is still standing, but the inside has been looted and broken. Vines grow along the walls, desperately trying to cling to something and mould drips from gaps in the wall and roof.", "rgb(200,175,150)");
break;
case 'r':
this.d = c_s("You enter what used to be a restaurant. Virtually nothing remains. A few rats scurry around the room, trying their best to loot some remaining food. Spatters of blood appear periodically. Maybe starving people killing to survive.", "rgb(175,175,125)");
break;
case 'G':
this.d = c_s("You enter what seems to have been a garage. Almost nothing is here. Even the tools such as hammer and wrenches have been taken for self-defense. This is what war is. The smell of a rotting corpse comes out of nowhere.", "rgb(100,80,80)");
break;
case 'w':
this.d = c_s("You wade accross an area of polluted water. Nothing is really over here at all. All the fish in it have died and the water is undrinkable.", "rgb(125,125,175)");
break;
case 'W':
this.d = c_s("You found a spring of water. It is one of the only freshwater sources that remain. Clear water slowly drips out of a hole in the ground, ready to be consumed. If your thirst level is below 50, you can replenish it at a spring.", "rgb(50,75,200)");
break;
case 'd':
this.d = c_s("You walk over an empty patch of dirt. All the vegetation seems to have dried up. A few scorpions race between clumps of dry earth while hardworking ants scurry around, looking for food.", "rgb(175,100,0)");
break;
case "!":
this.d = c_s("Your footsteps echo through an empty stone room. A few empty rounds of ammo, broken guns, and smashed magazines lay accross the floor. It seems as though this was a military arsenal before.", "rgb(200,200,225)");
break;
case "$":
this.d = c_s("Your footsteps echo as you walk through an abandoned piece of a military base. Almost everything in it has been looted except for an occaional empty bulvar shell or broken gun.", "rgb(50,150,0)");
break;
case "%":
this.d = c_s("You tramp through some soft dirt. Wheel tracks are printed into the floor by once powerful tanks. Almost everything in this room has been destroyed. Trash and ashes lay everywhere.", "rgb(150,75,0)");
break;
case "^":
this.d = c_s("You walk over a fence of barbed wire and broken metal fences. This used to be a restricted area but now, since everything is broken, anyone can go through.", "rgb(100,125,100)");
break;
}
}
Room.prototype.run = function() {
//special features of different landscape types
if (this.x === player.x && this.y === player.y) {
if (player.thirst < 50 && this.t === "W") {
say("You drink some of the clear spring water to soothe your dry, parched throat.");
player.thirst = player.maxT;
}
}
};
Room.prototype.spawnC = function() {
var chance = Math.random();
if (spawnLoc[this.t] && this.x !== spawnPoints[0] && this.y !== spawnPoints[1]) {
if (chance < 0.2) {
creatures.push(new Creature(getEl(spawnLoc[this.t]), this.x, this.y));
}
}
if(this.t == "©"){
creatures.push(new Creature("cytotron sentry", this.x,this.y))
}
};
var attackPower = {
"punch": 0.5,
"kick": 0.6,
"strike": 0.7,
"slash": 0.8,
"gash": 1,
"hiltslam": 0.8,
"chop": 1.2,
"knockout": 1.5,
"electrocute": 1.75,
"shoot": 2,
"throw": 1.25,
"pound": 1,
"stab": 1.75,
};
var randomPhrases = [
"with your weapon, splattering blood everywhere",
"with your weapon, splattering gore everywhere",
"with your weapon, enshrouding them in a mist of blood",
"with your weapon, forcing blood out of their mouth",
", causing them to grimace in pain",
"with your weapon, causing them to cough up some blood",
"with your weapon, staining red your weapon",
];
var randomPhrases2 = [
", temporarily stunning them",
", knocking the breath out of them",
", causing a satisfying Crunch",
", causing them to grimace in pain",
", making them lose consiousness for a split second",
", cracking one of their bones",
]
function playerAttack() {
setPlayerPos();
parseColors();
function PTurn(target) {
var name = target.type;
var rollChance = Math.random();
var attackType = getEl(player.attacks);
var dmg = random(player.minDamage, player.maxDamage * attackPower[attackType]);
var status = "attack";
if (rollChance > 0 && rollChance < player.critChance) {
dmg *= 2;
say(c_s("You score a Critical Hit!<br>", "rgb(0,200,0)"));
}
if (target.fighting && target.x === player.x && target.y === player.y && target.health > 0) {
if (rollChance > player.critChance && rollChance < target.blockChance + player.critChance) {
say("The " + target.type + " blocks your attack");
status = "miss";
}
if (rollChance > player.critChance + target.blockChance && rollChance < target.blockChance + player.critChance + target.dodgeChance) {
say("The " + target.type + " dodges your attack");
status = "miss";
}
}
if (status == "attack") {
if ((attackType == "slash" || attackType == "gash" || attackType == "stab" || attackType == "throw" || attackType == "chop" || attackType == "shoot"))
say(c_s("-" + c_s(Math.floor(dmg), "rgb(0,200,0)") + "- | " + name + "'s health: " + target.health + " | " + "- You " + attackType + " the " + target.type + " " + getEl(randomPhrases), "rgb(175,175,175)"))
else
say(c_s("-" + c_s(Math.floor(dmg), "rgb(0,200,0)") + "- | " + name + "'s health: " + target.health + " | " + "- You " + attackType + " the " + target.type + "" + getEl(randomPhrases2), "rgb(175,175,175)"))
target.health -= Math.floor(dmg);
}
if (target.health < 0 || target.health === 0) {
clearInterval(target.int);
target.int = false;
target.fighting = false;
player.fighting = false;
var overallXP = Math.round((target.level / player.level * 100) * Rand(0.5, 1));
say(c_s("<br>You killed the " + name + "!", "rgb(0,200,0)"));
player.xp += overallXP;
say("You got " + c_s("+" + overallXP + "XP", "rgb(0,200,0)") + "!");
var dropChance = Math.random();
var dropNum = fR(1, 4);
var regex1 = /(a|e|i|o|u)/i;
if (dropChance > 0.2) {
for (var q = 0; q < dropNum; q++) {
var fetchedEl = getEl(target.drops);
if(player.inv.length < 20){
player.inv.push(fetchedEl);
if (regex1.test(fetchedEl)) {
say("You take a " + fetchedEl + " from the " + name);
} else {
say("You take an " + fetchedEl + " from the " + name);
}
} else{
say("You can't carry any more.")
}
parseColors();
}
}
target.dead = true;
}
say("");
}
for (var i = 0; i < creatures.length; i++) {
if (creatures[i].fighting && creatures[i].x === player.x && creatures[i].y === player.y && !creatures[i].dead && player.fighting) {
PTurn(creatures[i]);
}
}
parseColors();
setPlayerPos();
}
function eAttack() {
if (player.fighting) {
setPlayerPos();
parseColors();
for (var i = 0; i < creatures.length; i++) {
var u = creatures[i];
if (u.fighting && u.x === player.x && u.y === player.y) {
player.fighting = true;
var attacks = u.attacks;
var dmg = random(u.minDamage, u.maxDamage);
var fd = Math.floor(dmg);
var rollChance = Math.random();
var status = "attack";
if (rollChance > 0 && rollChance < u.critChance) {
dmg = random(u.minDamage, u.maxDamage) * 2;
say("The " + u.type + " got a Critical Hit!")
}
if (rollChance > u.critChance && rollChance < u.critChance + player.blockChance) {
var blocks = [
"You block the " + u.type + "'s attack.",
"The " + u.type + "'s attack thuds against your shield",
"The " + u.type + "'s attack is shielded by your armor",
];
say(getEl(blocks))
status = "miss";
}
if (rollChance > u.critChance + player.blockChance && rollChance < u.critChance + player.blockChance + player.dodgeChance) {
say("You dodge the " + u.type + "'s attack.")
status = "miss";
}
if (status == "attack"&&u.health > 0) {
say(" -" + c_s(fd, "rgb(200,50,50)") + "- | " + u.type + "'s health: " + u.health + " | " + c_s(getEl(attacks), "rgb(175,175,175)"));
player.health -= fd;
}
if (player.health < 0 || player.health === 0) {
player.fighting = false;
u.fighting = false;
clearInterval(myInt);
clearInterval(u.int);
u.int = false;
playerDie();
}
say("")
if (u.health < 0 || u.health === 0) {
clearInterval(u.int);
u.fighting = false;
player.fighting = false;
var overallXP = Math.round((u.level / player.level * 100) * Rand(0.5, 1));
say(c_s("<br>You killed the " + u.type + "!", "rgb(0,200,0)"));
player.xp += overallXP;
say("You got " + c_s("+" + overallXP + "XP", "rgb(0,200,0)") + "!");
var dropChance = Math.random();
var dropNum = fR(1, 3);
var regex1 = /(a|e|i|o|u)/i;
if (dropChance > 0.2) {
for (var q = 0; q < dropNum; q++) {
var fetchedEl = getEl(u.drops);
if(player.inv.length < 20) {
player.inv.push(fetchedEl);
if (regex1.test(fetchedEl)) {
say("You take a " + fetchedEl + " from the " + u.type);
} else {
say("You take an " + fetchedEl + " from the " + u.type);
}
} else{
say("You can't carry any more.")
}
parseColors();
}
}
say("");
u.dead = true;
}
}
}
parseColors();
setPlayerPos();
}
}
function Obj(x, y, t) {
this.x = x;
this.y = y;
this.d = "";
this.type = t;
this.spec = [];
this.spec2 = [];
this.useFunc = function() {};
switch (this.type) {
case "alien turret":
this.d = "The alien turret is a massive structure, weighing a few thousand tons. One blast could cause so much destruction--more power than a human weapon could ever discharge.";
this.useFunc = function() {
say("You don't know how to use the turret.<br>")
}
break;
case "emf cannon":
this.d = "The Electro Magnetic Force Cannon is a weapon made by humans that can crush metal. Its huge base covers about 64 square feet and is made of solid titanium. Large hoses and wires supply it with extreme power.";
this.useFunc = function() {
say("You don't know how to use an emf turret<br>")
}
break;
case "portal":
this.d = "The large hexagonal portal seems to be off. Thick hoses and cords feed glowing energy into the portal. Type 'use portal' to use it if you are ready.";
this.useFunc = function() {
if(
search(player.eq, "leviathan accelerator") &&
search(player.eq, "iris accelerator") &&
search(player.eq, "restoration accelerator") &&
search(player.eq, "deflection accelerator") &&
search(player.eq, "reaction accelerator") &&
search(player.eq, "carbonshield accelerator")
){
$("#log").innerHTML = "";
say("You stick each accelerator from your fingers into the portal's slots. The portal lights up and activates. As it turns on, it blasts out a surge of power and you are sucked into it. You are on your way to Saudi Arabia to defeat the aliens.<br><br>≤-----To Be Continued-----≥");
}else {
say("You don't have the right accelerators to open the portal.");
}
}
break;
}
}
Obj.prototype.run = function() {
var c = $("#com").value.split('').splice(1, 10000).join('');
var c_br = c.split(' ');
if (this.x === player.x && this.y === player.y) {
if (search(words.look, c_br[0]) && matchEl([this.type], c_br[1])) {
say(this.d + "<br>");
}
if (search(words.use, c_br[0]) && matchEl([this.type], c_br[1])) {
this.useFunc();
}
if(this.type == "shop"){
if(search(words.list, c_br[0])){
}
}
}
};
function NPC(x, y, t) {
this.x = x;
this.y = y;
this.type = t;
this.wants = [];
this.satisfied = false;
this.d = "";
this.rewardFunc = function() {};
this.midQuest = "";
this.greetFunc = function() {};
this.quest = "";
this.dead = false;
this.d2 = "";
this.qd = "";
switch (this.type) {
case "don the battle-hardened survivor":{
this.qd = "Get three Xorox Alien Scales for don."
this.d2 = 'A skinny battle-hardened survivor of the war named Don has a robotic hand and seems to be building something out of xorox alien scales.';
this.quest = "Xorox 3";
this.wants = ["xorox alien scale", "xorox alien scale", "xorox alien scale"];
this.d = "Don is a scarred warrior and survivor. He isn't a big guy, but he's a deadly fighter when in action. Glowing tatoos stretch from the backs of his hands to his biceps."
this.greetFunc = function() {
player.quests.push(this.quest);
player.qd.push(this.qd)
say('"Hello, I\'m Don," Says the man, "Would you mind getting three pieces of Xorox Alien Scales for me? If you do, I\'ll give you artifacts of war."');
};
this.midQuest = '"Please come back to me once you get the three xorox alien scales," says Don.';
this.rewardFunc = function() {
player.inv.push("grenade");
player.inv.push("acid grenade");
player.inv.push("health shot");
player.inv.push("health shot");
player.xp += 400;
say('"Thanks a lot, my friend. Here are two grenades and two health shots. Use them while you fight."');
say(c_s("You got two grenades, two health shots, and +400xp!", "rgb(0,200,0)"))
say("Type \"use [item]\" (e.g. \"use grenade\") in a fight to deal large amounts of damage to your opponent.");
}
}break;
case "james":{
this.qd = "Get two water bottles for james."
this.d2 = 'An barely-alive old man named James is staring into the distance, drained mostly of his life. His eyes are an intense green color, showing that he is more than what he appears.';
this.quest = "Thirst Charge";
this.wants = ["water bottle","water bottle"];
this.d = "James is a drained old man who seems to be older than 70 years. Old age line his face but his intense green eyes tell you he's more than just that."
this.greetFunc = function() {
player.quests.push(this.quest);
player.qd.push(this.qd)
say('"Hello, stranger, please help me. I\'m dying of thirst," Says the old man, "Please get me two water bottles so I can go on living a little longer. I will give you what nobody can."');
};
this.midQuest = '"If I cannot live, I cannot reward you."';
this.rewardFunc = function() {
player.inv.push("carbonshield accelerator");
player.xp += 300;
say('"Thank you for helping me," says James as he quenches his thirst with the water. He stands up and says "Here, I have given you a carbonshield accelerator ring. Put it on your finger and your body will be shielded with a layer of solid carbon."');
say(c_s("You got a carbonshield accelerator and +300xp!", "rgb(0,200,0)"))
say("Equip the accelerator to start using it.");
}
}break;
case "sandra":{
this.qd = "Get five xorox crystals for sandra"
this.d2 = 'A young woman named Sandra is drawing a geometric pattern on the floor, and placing some heavyweight magnets around it. She seems to be working on something big.';
this.quest = "Crystalization";
this.wants = ["xorox crystal","xorox crystal","xorox crystal","xorox crystal","xorox crystal"];
this.d = "Sandra is a small, thin woman who looks quite wasted from the war. She stares into your eyes with an intese glare that shows that she wants to live on for a reason."
this.greetFunc = function() {
player.quests.push(this.quest);
player.qd.push(this.qd)
say('"Hello," says Sandra, "Would you mind getting me five xorox crystals? I\'m trying to find a way to unleash their power, but I can\'t fight the aliens."');
};
this.midQuest = '"Do you have all five xorox crystals?", says Sandra. "No? Okay, come back to me when you have them."';
this.rewardFunc = function() {
player.inv.push("carbonshield accelerator");
player.xp += 300;
say('"Thank you for helping me," says James as he quenches his thirst with the water. He stands up and says "Here, I have given you a carbonshield accelerator ring. Put it on your finger and your body will be shielded with a layer of solid carbon."');
say(c_s("You got a carbonshield accelerator and +300xp!", "rgb(0,200,0)"))
say("Equip the accelerator to start using it.");
}
}break;
case "ignatius the quasar trooper":{
this.qd = "Get a bandage for Ignatius"
this.d2 = 'A seriously wounded Quasar trooper named Ignatius is laying on the floor, soaked with blood. His left arm is torn off and his shirt is spattered with blood.';
this.quest = "Hurt and the Healer";
this.wants = ["bandage"];
this.d = "Ignatius seems to be about forty years old. His face is scarred from war and his expression is twisted with pain. His left arm has been torn off."
this.greetFunc = function() {
player.quests.push(this.quest);
player.qd.push(this.qd)
say('"Please," Says the trooper, "I need a bandage for my arm to stop the bleeding or I\'ll bleed to death. Please, if you do this for me, I\'ll give you a stasis particle shield."');
};
this.midQuest = '"If I cannot live, I cannot reward you."';
this.rewardFunc = function() {
player.inv.push("stasis particle shield");
player.xp += 200;
say('"Thank you so much," says Ignatius as he wraps his injured shoulder with the bandage. He takes a small cylinder out of his pocket and expands it to become a stasis particle shield. "Here, it\'s for you".');
say(c_s("You got a stasis particle shield and +200xp!", "rgb(0,200,0)"))
say("Equip the shield to start using it.");
}
}break;
case "maglor the sorcerer":{
this.qd = "Get six human femurs for Maglor"
this.d2 = 'Maglor is a very old, but strong man. His logn grey beard reaches down to his chest and his body is covered in black tatoos that seem to be some runic letters and geometric patterns. His eyes are a glowing golden yellow color and on his finger is a ring with a glowing blue gemstone on it.';
this.quest = "Human Bone";
this.wants = ["human femur","human femur","human femur","human femur","human femur","human femur"];
this.d = "Ignatius is wearing a long white robe and a golden belt around his waist. On the robe are glowing blue runes and patterns–probably accelerators for his sorcery."
this.greetFunc = function() {
player.quests.push(this.quest);
player.qd.push(this.qd)
say('"Hello young stranger, says Maglor, "I have a simple request to ask you. Please get for me six human femurs and I will reward you greatly. A lot of people don\'t believe in magic, but they should."');
};
this.midQuest = '"Please return once you have all six human femurs."';
this.rewardFunc = function() {
player.inv.push("reaction accelerator");
player.xp += 600;
say('"Thank you, my friend," says Maglor. He aligns the six femurs in a hexagon, scratches a hexagon into the floor within the bones, draws a circle and triangle outside of them and puts his hands on the drawing. Water springs forth from the ground and surrounds him in a vortex. After a moment, he comes out of the spinning fury of water, completely unharmed and tatoos glowing. "Here is your reward, my friend," he says as he hands you his ring. "Search for five of the other warlocks at the six corners of the earth. Then you will be able to face the great darkness that invades the world."',);
say(c_s("You got a reaction accelerator and +600xp!", "rgb(0,200,0)"))
say("Equip the accelerator to start using it.");
npcs.push(new NPC(5, 1, "narada the warlock"))
}
}break;
case "narada the warlock":{
this.qd = "Get six Photon Daggers for Narada"
this.d2 = 'Narada is a Warlock and appears to be very young. Runic symbols and tatoos run up and down her from the palms of her hands to her neck. She has a ring on her finger with a glowing green gemstone on it.';
this.quest = "Photon Six";
this.wants = ["photon dagger","photon dagger","photon dagger","photon dagger","photon dagger","photon dagger"];
this.d = "Narada is dressed in a long red robe with glowing green runic patterns and letters. She appears to be very young, but who knows how old a Warlock could be?"
this.greetFunc = function() {
player.quests.push(this.quest);
player.qd.push(this.qd)
say('"Hello young stranger, says Narada, "I have a simple request to ask you. Please get for me six photon daggers and I will reward you greatly. A lot of people don\'t believe in magic, but they should."');
};
this.midQuest = '"Please return once you have all six photon daggers."';
this.rewardFunc = function() {
player.inv.push("iris accelerator");
player.xp += 600;
say('"Thank you my friend," says Narada. She draws a circle, then inside of it a hexagon. Two triangles are also drawn in the hexagon. She stabs the six daggers on each point of the hexagon. When she activates it, ancient roots spring from the ground and wrap around her body completely. After a moment, she comes out of the entanglement, completely unharmed and tatoos glowing. "Here, take my ring. Find the rest of the warlocks on the six corners of the earth."',);
say(c_s("You got an iris accelerator and +600xp!", "rgb(0,200,0)"))
say("Equip the accelerator to start using it.");
npcs.push(new NPC(30, 2, "magloroth the warlock"))
}
}break;
case "magloroth the warlock":{
this.qd = "Get six xorox crystals for Magloroth"
this.d2 = 'Magloroth is a young powerful warlock. You see six runic tatoos on him. Two on the palms of his hands, two in his eyes, and two on his feet. Six, what an interesting number with the warlocks. He has a ring on his finger with a glowing orange stone.';
this.quest = "Xorox Gems";
this.wants = ["xorox crystal","xorox crystal","xorox crystal","xorox crystal","xorox crystal","xorox crystal"];
this.d = "Magloroth is dressed in a dark grey robe with glowing orange runes and patterns on it. He has a ring on his finger with a glowing orange stone."
this.greetFunc = function() {
player.quests.push(this.quest);
player.qd.push(this.qd)
say('"Hello young stranger, says Magloroth, "I have but a small request to ask you. Please get for me six xorox crystals and I will reward you greatly. A lot of people don\'t believe in magic, but they should."');
};
this.midQuest = '"Please return once you have all six xorox crystals."';
this.rewardFunc = function() {
player.inv.push("leviathan accelerator");
player.xp += 600;
say('"Thank you my friend," says Magloroth. He links all the six crystals together in a pattern, holds the linked structure in his hands, and compresses it between his palms. The floor under him opens up and a rift is torn in the sky. Fire comes down from the sky while magma rushes out of the earth over him. After a minute or so of intense heat, he comes out of the magma and fire, completely unharmed and tatoos glowing. "Here, take my ring," he says. "Search the six corners of the earth."');
say(c_s("You got a Leviathan accelerator and +600xp!", "rgb(0,200,0)"))
say("Equip the accelerator to start using it.");
npcs.push(new NPC(64, 6, "endrithor the warlock"))
}
}break;
case "endrithor the warlock":{
this.qd = "Get six steel xorox scales for Endrithor"
this.d2 = 'Endrithor is one of the warlocks, but has a hood over his face so that you cannot see. You can see that his robe and body have the warlock tatoos and runes on them and that his hand has a very dark accelerator on it.';
this.quest = "Steel Armor";
this.wants = ["steel xorox scale","steel xorox scale","steel xorox scale","steel xorox scale","steel xorox scale","steel xorox scale"];
this.d = "Endrithor is dressed in a black robe with glowing white runes and patterns on it. He has a ring on his finger with a seemingly infinitely black stone."
this.greetFunc = function() {
player.quests.push(this.quest);
player.qd.push(this.qd)
say('"Hello young stranger, says Endrithor, "I have but a small request to ask you. Please get for me six steel xorox scales and I will reward you greatly. A lot of people don\'t believe in magic, but they should. You\'ve come this far into the alien base already. Continue your mission to save the world."');
};
this.midQuest = '"Please return once you have all six steel xorox plates."';
this.rewardFunc = function() {
player.inv.push("deflection accelerator");
player.xp += 600;
say('"Thank you my friend," says Endrithor. He stabs each xorox plate into the floor in a hexagonal pattern, draws some more marks in the floor, and activates it in a warlock formation. The ground opens up under him and the darkness below covers him completely. Lightning flashes around the dark area he is in. From the darkness comes a bright white light. His tatoos are glowing. "Here, take my ring," he says. "Search the six corners of the earth."');
say(c_s("You got a Deflection accelerator and +600xp!", "rgb(0,200,0)"))
say("Equip the accelerator to start using it.");
npcs.push(new NPC(81, 16, "leanora the warlock"))
}
}break;
case "leanora the warlock":{
this.qd = "Get six grenades for Leanora"
this.d2 = 'Leanora looks as though she is the most celestial of all the warlocks. Her eyes glow purple and her skin is covered in a purple glow.';
this.quest = "Warlock Explosives";
this.wants = ["grenade","grenade","grenade","grenade","grenade","grenade"];
this.d = "Leanora is dressed in a purple robe with bright purple glowing runes on it. Instead of having the warlock tatoos all over her body, her right hand, which has six fingers, has them–one on each finger. From her skin is emitted a purpleish glow."
this.greetFunc = function() {
player.quests.push(this.quest);
player.qd.push(this.qd)
say('"Hello young stranger, says Leanora, "I have but a small request to ask you. Please get for me six grenades and I will reward you greatly. A lot of people don\'t believe in magic, but they should."');
};
this.midQuest = '"Please return once you have all six grenades."';
this.rewardFunc = function() {
player.inv.push("resortation accelerator");
player.xp += 600;
say('"Thank you my friend," says Leanora. She carefully removes each safety pin from the grenades. Next, the grenades are placed around in a hexagonal shape (again). She then reveals her six-fingered hand and places it in the middle of the six grenades. Ice spikes break out of the ground and destroy her body. It then dissapears. "Here, take my ring," says Leanora\'s voice from through the air. "I have deconstructed my body because you will need me again. Go now an conquer the great evil the invades the earth. I am the last of the warlocks you needed to find. Go to the Portal and activate it."' );
say(c_s("You got a Restoration accelerator and +600xp!", "rgb(0,200,0)"))
say("Equip the accelerator to start using it.");
}
}break;
}
}
NPC.prototype.run = function() {
var c = $("#com").value.split('').splice(1, 10000).join('');
var c_br = c.split(' ');
var count = 0;
for (var i = 0; i < player.inv.length; i++) {
if (player.inv[i] === (this.wants[count])) {
count++;
}
}
if (this.x === player.x && this.y === player.y) {
if (search(words.look, c_br[0]) && matchEl([this.type], c_br[c_br.length - 1])) {
say(this.d);
}
if (search(words.communicate, c_br[0]) && matchEl([this.type], c_br[c_br.length - 1])) {
if (!this.satisfied) {
if (search(player.quests, this.quest)) {
if (count >= this.wants.length) {
this.satisfied = true;
var count = 0;
rem(player.quests, this.quest)
rem(player.qd, this.qd)
for (var j = 0; j < this.wants.length; j++) {
for (var i = 0; i < player.inv.length; i++) {
if (player.inv[i] === (this.wants[count])) {
count++;
rem(player.inv, this.wants[count]);
}
}
}
this.rewardFunc();
} else {
say(this.midQuest);
}
} else {
this.greetFunc();
say(c_s("You got a new quest, \"" + this.quest + "\". Type 'quests' anytime to view your quests.<br>", "rgb(255,200,0)"));
}
} else {
var phrases = ["smiles at you", "nods at you", "thanks you for your help", "motions for you to go away", "looks at you then turns away"];
say(this.type + " " + getEl(phrases) + ".")
}
}
}
};
objects = [
new Obj(43, 3, "alien turret"),
new Obj(43, 5, "alien turret"),
new Obj(43, 7, "alien turret"),
new Obj(43, 9, "alien turret"),
new Obj(43, 11, "alien turret"),
new Obj(43, 13, "alien turret"),
new Obj(43, 15, "alien turret"),
new Obj(31, 3, "emf cannon"),
new Obj(31, 5, "emf cannon"),
new Obj(31, 7, "emf cannon"),
new Obj(31, 9, "emf cannon"),
new Obj(31, 11, "emf cannon"),
new Obj(31, 13, "emf cannon"),
new Obj(31, 15, "emf cannon"),
new Obj(71, 2, "portal"),
]
npcs = [
new NPC(1,9,"don the battle-hardened survivor"),
new NPC(1, 5,"james"),
new NPC(13, 8, "sandra"),
new NPC(36, 7, "ignatius the quasar trooper"),
new NPC(14, 32, "maglor the sorcerer")
]
/****************************************
* MISCALLENEOUS FUNCTIONS
****************************************/
function setRooms() {
for (var i = 0; i < globalMap.length; i++) {
for (var j = 0; j < globalMap[i].length; j++) {
rooms.push(new Room(globalMap[i][j], j, i));
}
}
for (var r = 0; r < rooms.length; r++) {
rooms[r].run();
rooms[r].spawnC();
}
}
function locStats() {
for (var r = 0; r < rooms.length; r++) {
var R = rooms[r];
R.run();
if (R.x === player.x && R.y === player.y) {
say(R.d);
if (R.items.length > 0) {
var itemStr = R.items;
var regex1 = /(a|e|i|o|u)/i;
var result = "";
if (itemStr.length > 1) {
for (var w = 0; w < itemStr.length; w++) {
if ((itemStr[w].split('')[0]).match(regex1)) {
if (w > 0 && w < itemStr.length - 1) {
result += ", an " + itemStr[w];
} else if (w === itemStr.length - 1) {
result += ", and an " + itemStr[w];
} else {
result += " an " + itemStr[w];
}
} else {
if (w > 0 && w < itemStr.length - 1) {
result += ", a " + itemStr[w];
} else if (w === itemStr.length - 1) {
result += ", and a " + itemStr[w];
} else {
result += " a " + itemStr[w];
}
}
}
}
if (itemStr.length === 1) {
if (regex1.test(itemStr[0].split('')[0])) {
result = ("an " + itemStr);
} else {
result = "a " + itemStr;
}
}
if (itemStr.length !== 0) {
say(c_s("You can see " + result + ".", "rgb(0,200,150)"));
}
}
}
}
for (var n = 0; n < npcs.length; n++) {
if (npcs[n].x === player.x && npcs[n].y === player.y && !npcs[n].dead) {
say(npcs[n].d2);
}
}
for (var d = 0; d < objects.length; d++) {
var G = objects[d];
if (G.x === player.x && G.y === player.y) {
var reg = /a|e|i|o|u/i
if (reg.test(G.type.split('')[0])) {
say("an " + G.type + " is here.");
} else {
say("a " + G.type + " is here.");
}
}
}
var exitRes = [];
if (player.y !== 0 && globalMap[player.y - 1][player.x] !== " ") {
exitRes.push("North");
}
if (player.x !== globalMap[player.y].length && globalMap[player.y][player.x + 1] !== " ") {
exitRes.push("East");
}
if (player.y !== globalMap.length && globalMap[player.y + 1][player.x] !== " ") {
exitRes.push("South");
}
if (player.x !== 0 && globalMap[player.y][player.x - 1] !== " ") {
exitRes.push("West");
}
say(c_s("Obvious Exits: " + exitRes.join(', '), "rgb(200,150,0)"));
for (var i = 0; i < creatures.length; i++) {
var cr = creatures[i];
if (cr.x === player.x && cr.y === player.y) {
if (!cr.dead) {
if (cr.level < player.level || !cr.aggr) {
say(cr.d);
} else {
say(cr.ad);
}
} else {
var reg001 = /a|e|i|o|u/i;
if (reg001.test(cr.type.split('')[0])) {
say("The decaying corpse of an " + cr.type + " is here")
} else {
say("The decaying corpse of a " + cr.type + " is here")
}
}
}
}
say('');
}
function playerDie() {
for (var i = 0; i < creatures.length; i++) {
if (creatures[i].int) {
clearInterval(creatures[i].int);
}
}
$("#log").innerHTML = "";
player.fighting = false;
if (player.thirst == 2) {
say("You died of thirst!")
}
if (player.hunger == 2) {
say("You died of starvation!")
}
if (player.health == 2) {
say("You died!")
}
say(`Unfortunately, you have died. Died temporarily. The modern technology nowadays allows for the reviving of humans. Someone revived you for a reason. You were meant to live. Type "respawn" or "revive" to try again (you still keep your current progress).`);
}
/****************************************
* Canvas Map
****************************************/
var setPlayerPos = function() {
ctx.fillStyle = "rgb(25,25,25)";
ctx.fillRect(0, 0, 200, 200);
ctx.save();
ctx.translate(-player.x * 20 + 100, -player.y * 20 + 100);
for (var i = 0; i < rooms.length; i++) {
var R = rooms[i];
ctx.strokeStyle = "rgba(0,0,0,0)";
switch (R.t) {
case "f":
ctx.fillStyle = "rgb(150,100,200)";
ctx.strokeStyle = "rgb(75,100,255)";
break;
case "a":
ctx.fillStyle = `rgb(${random(25,75)},${random(50,100)},${random(75,125)},${random(0.1,0.9)})`;
ctx.strokeStyle = "rgb(75,100,225)";
break;
case "t":
ctx.fillStyle = "rgb(100,100,200)";
break;
case "A":
ctx.fillStyle = "rgb(100,100,150)";
break;
case "©":
ctx.fillStyle = "rgb(150,175,200)";
ctx.strokeStyle = "rgb(100,100,200)";
break;
case "i":
ctx.fillStyle = "rgb(27,27,27)";
break;
case "e":
ctx.fillStyle = "rgb(255,255,255)";
break;
case "T":
case ":":
case "@":
ctx.fillStyle = "rgb(100,100,100)";
break;
case "-":
case "|":
ctx.fillStyle = "rgb(150,150,150)";
break;
case "+":
case "#":
ctx.fillStyle = "rgb(125,125,125)";
break;
case "\"":
case "=":
ctx.fillStyle = "rgb(175,175,175)";
break;
case "g":
ctx.fillStyle = "rgb(100,150,100)";
break;
case "h":
ctx.fillStyle = "rgb(175,150,125)";
break;
case "b":
ctx.fillStyle = "rgb(175,150,100)";
break;
case "B":
ctx.fillStyle = "rgb(50,50,50)";
break;
case "H":
ctx.fillStyle = "rgb(200,175,150)";
break;
case "r":
ctx.fillStyle = "rgb(175,175,125)";
break;
case "G":
ctx.fillStyle = "rgb(100,80,80)";
break;
case "w":
ctx.fillStyle = "rgb(150,150,175)";
break;
case "W":
ctx.fillStyle = "rgb(50,75,255)";
break;
case " ":
ctx.fillStyle = "rgb(25,25,25)";
break;
case "d":
ctx.fillStyle = "rgb(175,100,0)";
break;
case "!":
ctx.fillStyle = "rgb(200,200,225)";
break;
case "$":
ctx.fillStyle = "rgb(50,150,0)";
break;
case "%":
ctx.fillStyle = "rgb(150,75,0)";
break;
case "^":
ctx.fillStyle = "rgb(100,125,100)";
break;
}
ctx.fillRect(R.x * 20, R.y * 20, 20, 20);
ctx.strokeRect(R.x * 20, R.y * 20, 20, 20);
ctx.stroke();
}
for (var j = 0; j < creatures.length; j++) {
var Cr = creatures[j];
if (!Cr.dead) {
ctx.beginPath();
ctx.arc(Cr.x * 20 + 10 + (Math.random() * 10 - 5), Cr.y * 20 + 10 + (Math.random() * 10 - 5), 2.5, 0, Math.PI * 2);
ctx.fillStyle = "rgb(150,0,0)";
ctx.fill();
}
}
for (var j = 0; j < objects.length; j++) {
var Cr = objects[j];
if (!Cr.dead) {
ctx.beginPath();
ctx.arc(Cr.x * 20 + 10, Cr.y * 20 + 10, 4, 0, Math.PI * 2);
ctx.fillStyle = "rgb(100,100,100)";
ctx.strokeStyle = "black";
ctx.stroke();
ctx.fill();
}
}
for (var k = 0; k < npcs.length; k++) {
var n = npcs[k];
if (!n.dead) {
if (!n.satisfied) {
ctx.beginPath();
ctx.arc(n.x * 20 + 5, n.y * 20 + 5, 2.5, 0, Math.PI * 2);
ctx.fillStyle = "rgb(255,200,0)";
ctx.strokeStyle = "rgb(0,0,0)";
ctx.stroke();
ctx.fill();
}
if (n.satisfied) {
ctx.beginPath();
ctx.arc(n.x * 20 + 5, n.y * 20 + 5, 2.5, 0, Math.PI * 2);
ctx.fillStyle = "rgb(100,100,100)";
ctx.strokeStyle = "rgb(0,0,0)";
ctx.stroke();
ctx.fill();
}
}
}
ctx.beginPath();
ctx.strokeStyle = "black";
ctx.arc(player.x * 20 + 10, player.y * 20 + 10, 2.5, 0, Math.PI * 2);
ctx.fillStyle = "rgb(0,200,255)";
ctx.stroke();
ctx.fill();
ctx.restore();
};
$("#log").innerHTML = "";
say(`
≤…_____………___………_…………………___……___……___…_____……_____…__………__
/……__…\\…/…_…\\…|…|……………/…_…\\…|……\\/……||_………_||_………_|\\…\\…/…/
|…/……\\//…/_\\…\\|…|…………/…/_\\…\\|….…….…|……|…|…………|…|………\\…V…/…
|…|…………|……_……||…|…………|……_……||…|\\/|…|……|…|…………|…|…………\\…/……
|…\\__/\\|…|…|…||…|____|…|…|…||…|……|…|…_|…|_………|…|…………|…|……
…\\____/\\_|…|_/\\_____/\\_|…|_/\\_|……|_/…\\___/………\\_/…………\\_/……≥
`.replace(/\|/g, (a) => c_s(a, "rgb(0,200,255)")).replace(/\/…/g, c_s("/…", "rgb(100,100,100)")).replace(/\\/g, c_s("\\", "rgb(125,125,125)")).replace(/_/g, c_s("_", "rgb(100,150,200)")))
say(`Aliens have invaded earth and are destroying as many life forms as they can. Even the most powerful weapons made by humans cannot harm them. You must survive and destroy their ship which lies in Saudi Arabia.
The ship is so massive that it covers 25% of the country. Break the core and break the aliens.
You must fight your way to survive as well. Battle aliens, sneaky robbers, fufill quests, and destroy your enemies.
Type "help" anytime to learn how to play the game.
≤--------------------------------------------≥`)
setRooms();
locStats();
parseColors();
setPlayerPos();
/****************************************
* COMMAND HANDLING
****************************************/
function commands() {
var c = $("#com").value.split('').splice(1, 10000).join('');
var c_br = c.split(' ');
if(window.innerWidth < 700){
if(c == "!scnsht"){
$("#log").innerHTML = "";
parseColors();
say(`
___________________________________________________________
≤…_____………___………_…………………___……___……___…_____……_____…__………__
/……__…\\…/…_…\\…|…|……………/…_…\\…|……\\/……||_………_||_………_|\\…\\…/…/
|…/……\\//…/_\\…\\|…|…………/…/_\\…\\|….…….…|……|…|…………|…|………\\…V…/…
|…|…………|……_……||…|…………|……_……||…|\\/|…|……|…|…………|…|…………\\…/……
|…\\__/\\|…|…|…||…|____|…|…|…||…|……|…|…_|…|_………|…|…………|…|……
…\\____/\\_|…|_/\\_____/\\_|…|_/\\_|……|_/…\\___/………\\_/…………\\_/……≥
……………………………………__
…………………………………/…/
__…………………………|…|_______________________________
/……\\_______/…………………………………………………………………………………………\\
|………_______………()--()--()--()--()--()--()--()--->
\\__/…………………\\……________________________________/
………………………………|…|
…………………………………\\_\\
___________________________________________________________
`.replace(/\|/g, (a) => c_s(a, "rgb(0,200,255)")).replace(/\/…/g, c_s("/…", "rgb(100,100,100)")).replace(/\\/g, c_s("\\", "rgb(125,125,125)")).replace(/_/g, c_s("_", "rgb(100,150,200)")));
parseColors();
}else{
var a = window.open("","");
a.document.open();
a.document.write(
"<DOCTYPE html>"+document.documentElement.outerHTML.replaceAll("KAInfiniteLoopProtect();","")
);
}
} else{
try {
setPlayerPos();
res = false;
if (!player.isDead) {
//moving
{
if (search(words.flee, c)) {
if (player.fighting) {
var exitRes = [];
if (player.y !== 0 && globalMap[player.y - 1][player.x] !== " ")
exitRes.push("North");
if (player.x !== globalMap[player.y].length && globalMap[player.y][player.x + 1] !== " ")
exitRes.push("East");
if (player.y !== globalMap.length && globalMap[player.y + 1][player.x] !== " ")
exitRes.push("South");
if (player.x !== 0 && globalMap[player.y][player.x - 1] !== " ")
exitRes.push("West");
var rollChance = Math.random();
if (rollChance < 0.5) {
say("You fail to escape the fight!")
} else {
player.fighting = false;
clearInterval(myInt);
for (var i = 0; i < creatures.length; i++) {
if (creatures[i].fighting) {
clearInterval(creatures[i].int);
creatures[i].fighting = false;
}
}
var dir = getEl(exitRes);
if (dir == "North") {
player.y--;
} else if (dir == "East") {
player.x++;
} else if (dir == "South") {
player.y++;
} else {
player.x--;
}
say("You manage to escape the fight. You flee " + dir);
}
} else {
say("You can't flee if you are not in a fight.")
}
}
//
if (search(words.north, c)) {
if (!player.fighting) {
if (player.y !== 0) {
if (globalMap[player.y - 1][player.x] !== " ") {
player.y--;
say("You go north");
locStats();
} else {
say("You can't go north");
}
} else {
say("You can't go north");
}
} else {
say("You are in the middle of a fight!")
}
}
if (search(words.south, c)) {
if (!player.fighting) {
if (player.y !== globalMap.length) {
if (globalMap[player.y + 1][player.x] !== " ") {
player.y++;
say("You go south");
locStats();
} else {
say("You can't go south");
}
} else {
say("You can't go south");
}
} else {
say("You are in the middle of a fight!")
}
}
if (search(words.east, c)) {
if (!player.fighting) {
if (player.x !== globalMap[player.y].length - 1) {
if (globalMap[player.y][player.x + 1] !== " ") {
player.x++;
say("You go east");
locStats();
} else {
say("You can't go east");
}
} else {
say("You can't go east");
}
} else {
say("You are in the middle of a fight!")
}
}
if (search(words.west, c)) {
if (!player.fighting) {
if (player.x !== 0) {
if (globalMap[player.y][player.x - 1] !== " ") {
player.x--;
say("You go west");
locStats();
} else {
say("You can't go west");
}
} else {
say("You can't go west");
}
} else {
say("You are in the middle of a fight!")
}
}
}
//examining stuff
{
if (search(words.look, c_br[0]) && !c_br[1]) {
locStats();
}
if (search(words.look, c_br[0]) && c_br[1]) {
var matchedEl = matchEl(player.inv, c.split(' ').splice(1, 10000).join(' '));
if (matchedEl) {
var IM = Items[matchedEl];
if (IM.type === "food" || IM.type === "drink") {
say(`≤ᚭ---------------${matchedEl}---------------ᚮ≥\n` + Items[matchedEl].d + `
- Replenishes ${Items[matchedEl].healthG} Health
- Fills ${Items[matchedEl].hungerG} Hunger
- Fills ${Items[matchedEl].thirstG} Thirst
≤ᚭ----------------------------------------ᚮ≥`);
}
if (IM.type === "one-use") {
say(`≤ᚭ---------------${matchedEl}---------------ᚮ≥\n` + Items[matchedEl].desc + `
- Replenishes ${Items[matchedEl].heal} Health
- Deals ${Items[matchedEl].damage} Damage (to opponent)
≤ᚭ----------------------------------------ᚮ≥`);
}
if (IM.type === "eq") {
say(`≤ᚭ---------------${matchedEl}---------------ᚮ
${Items[matchedEl].desc}
Armor Points (Bonus Health): ${IM.apts}
Damage Bonus: ${IM.dpts}
Attack Speed Bonus: ${IM.asp}
Bonus Critical Chance: ${IM.chance[0]*100}%
Bonus Block Chance: ${IM.chance[1]*100}%
Bonus Dodge Chance: ${IM.chance[2]*100}%
Health Regeneration Bonus: ${IM.chance[3]}
Slot: ${IM.slot}
ᚭ----------------------------------------ᚮ≥`);
}
if (IM.type === "misc"||IM.type === "useable") {
say(`≤ᚭ---------------${matchedEl}---------------ᚮ≥ <br> ${Items[matchedEl].desc}<br><br> ≤ᚭ----------------------------------------ᚮ≥`);
}
}
}
}
//interacting (eat, take, drop, wear, etc)
{
if (player.fighting) {
if (search(words.use, c_br[0])) {
if (c_br[1]) {
var ml = matchEl(player.inv, c_br[1]);
if(ml){
if (Items[ml].type == "one-use") {
for (var i = 0; i < creatures.length; i++) {
if (creatures[i].fighting && creatures[i].x === player.x && creatures[i].y === player.y && !creatures[i].dead && player.fighting) {
creatures[i].health -= Items[ml].damage;
player.health += Items[ml].heal;
}
}
say(Items[ml].use);
setTimeout(function() {
rem(player.inv, ml);
}, 100)
}
}else{
say("You don't have that.")
}
} else {
say("What do you want to use?")
}
}
}
//equipping equippable equipment
if (search(words.wear, c_br[0])) {
var matchedEld = matchEl(player.inv, c.split(' ').splice(1, 10000).join(' '));
if (c_br[1]) {
if (matchedEld) {
if (Items[matchedEld].type === "eq") {
if (player.wearLimit[Items[matchedEld].slot] > 0) {
rem(player.inv, matchedEld)
player.eq.push(matchedEld);
player.wearLimit[Items[matchedEld].slot]--;
player.health += Items[matchedEld].apts;
say("Equipped.")
} else {
var remItem = "";
for (var d = 0; d < player.eq.length; d++) {
if (Items[player.eq[d]].slot === Items[matchedEld].slot) {
remItem = player.eq[d];
}
}
say("You will have to remove a/an " + remItem + " before you equip that.");
}
} else {
say("You can't equip that.")
}
} else {
say("You don't have that")
}
} else {
say("What do you want to equip?")
}
}
//removing removable removableItems
if (search(words.remove, c_br[0])) {
if (search(words.all, c_br[1])) {
for (var m = 0; m < player.eq.length; m++) {
player.inv.push(player.eq[m]);
}
player.eq = [];
player.wearLimit = {
//one helmet
"helmet": 1,
//one suit of armor
"armor": 1,
//one shield
"shield": 1,
//one weapon
"weapon": 1,
//one pair of pants
"pants": 1,
//two boots
"shoes": 1,
//accelerators
"accelerator": 5,
};
say("All Equipment Removed.");
say("You aren't wearing anything. Quick, hide before someone sees you!<br>")
} else {
var matchedElc = matchEl(player.eq, c.split(' ').splice(1, 10000).join(' '));
if (c_br[1]) {
if (matchedElc) {
player.bonusHealth -= Items[matchedElc].apts;
player.wearLimit[Items[matchedElc].slot]++;
rem(player.eq, matchedElc);
player.inv.push(matchedElc);
say("Removed.");
} else {
say("You aren't wearing that")
}
} else {
say("What do you want to remove?")
}
}
}
//look at your inventory
if (search(words.inv, c)) {
if (player.inv.length > 0) {
say("You are carrying (" + (player.inv.length) + "/20):")
for (var z = 0; z < player.inv.length; z++) {
say((z + 1) + ". " + player.inv[z]);
}
say("");
} else {
say("You aren't carrying anything.<br>")
}
}
//look at your equipment
if (search(words.eq, c)) {
if (player.eq.length !== 0) {
say("You are wearing: ");
for (var f = 0; f < player.eq.length; f++) {
say("[" + Items[player.eq[f]].slot + "] " + player.eq[f]);
}
say("")
} else {
say("You are not wearing anything. Quick! Hide before someone sees you!")
}
}
//taking things
for (var v = 0; v < rooms.length; v++) {
var R = rooms[v];
if (player.x === R.x && player.y === R.y) {
var matchedElg = matchEl(R.items, c.split(' ').splice(1, 10000).join(' '));
if (search(words.take, c_br[0]) && c_br[1] && matchedElg) {
if(player.inv.length < 20){
rem(R.items, matchedElg);
player.inv.push(matchedElg);
say("Taken.<br>");
} else{
say("You can't carry any more.")
}
}
if (search(words.take, c_br[0]) && c_br[1] && !matchedElg) {
if (search(words.all, c_br[1])) {
for (var a = 0; a < R.items.length; a++) {
if(player.inv.length < 20){
player.inv.push(R.items[a]);
} else{
say("You can't carry any more.")
}
}
R.items = [];
say("All Items Taken.")
} else {
say("That isn't here.<br>")
}
}
if (search(words.take, c_br[0]) && !c_br[1]) {
say("What do you want to take?<br>")
}
}
}
//dropping things
for (var h = 0; h < rooms.length; h++) {
var Ro = rooms[h];
if (player.x === Ro.x && player.y === Ro.y) {
var matchedElv = matchEl(player.inv, c.split(' ').splice(1, 10000).join(' '));
if (search(words.drop, c_br[0]) && c_br[1] && matchedElv) {
rem(player.inv, matchedElv);
Ro.items.push(matchedElv);
say("Dropped.<br>");
}
if (search(words.drop, c_br[0]) && c_br[1] && !matchedElv) {
if (search(words.all, c_br[1])) {
for (var b = 0; b < player.inv.length; b++) {
Ro.items.push(player.inv[b]);
}
player.inv = [];
say("All Items Dropped")
} else {
say("You don't have that.<br>")
}
}
if (search(words.drop, c_br[0]) && !c_br[1]) {
say("What do you want to drop?<br>")
}
}
}
//eating things
if (search(words.eat, c_br[0]) && c_br[1]) {
var matchedElx = matchEl(player.inv, c.split(' ').splice(1, 10000).join(' '));
if (matchedElx) {
if (Items[matchedElx].type === "food") {
player.health += Items[matchedElx].healthG;
player.hunger += Items[matchedElx].hungerG;
player.thirst += Items[matchedElx].thirstG;
rem(player.inv, matchedElx);
say("Eaten.<br>");
} else {
say("You can't eat that.<br>")
}
} else {
say("You don't have that<br>")
}
}
if (search(words.drink, c_br[0]) && c_br[1]) {
var matchedEls = matchEl(player.inv, c.split(' ').splice(1, 10000).join(' '));
if (matchedEls) {
if (Items[matchedEls].type === "drink") {
player.health += Items[matchedEls].healthG;
player.hunger += Items[matchedEls].hungerG;
player.thirst += Items[matchedEls].thirstG;
rem(player.inv, matchedEls);
say("Drank.<br>");
} else {
say("You can't drink that.<br>")
}
} else {
say("You don't have that<br>")
}
}
}
//other commands (say, clear, help, etc)
{
if(search(words.scan, c_br[0])){
for(var i = 0; i < creatures.length; i++){
var c = creatures[i];
if(!c.dead){
if(c.x === player.x&&c.y < player.y&&Math.abs(c.y-player.y) < 4){
say("A "+c.type+" is "+Math.abs(c.y-player.y) + " spaces north of you.")
}
if(c.x === player.x&&c.y > player.y&&Math.abs(c.y-player.y) < 4){
say("A "+c.type+" is "+Math.abs(c.y-player.y) + " spaces south of you.")
}
if(c.y === player.y&&c.x < player.x&&Math.abs(c.x-player.x) < 4){
say("A "+c.type+" is "+Math.abs(c.x-player.x) + " spaces west of you.")
}
if(c.y === player.y&&c.x > player.x&&Math.abs(c.x-player.x) < 4){
say("A "+c.type+" is "+Math.abs(c.x-player.x) + " spaces east of you.")
}
}
}
}
if (search(words.quests, c_br[0])) {
if (player.quests.length !== 0) {
say("Your Quests (" + player.quests.length + "):");
for (var i = 0; i < player.quests.length; i++) {
say(`- ${player.quests[i]} : ${player.qd[i]}`)
}
} else {
say("You don't have any quests.")
}
}
if (search(words.talk, c_br[0])) {
say("You say, \"" + c.split(' ').splice(1, 10000).join(' ') + "\" to yourself.<br>")
}
if (search(words.clear, c)) {
$("#log").innerHTML = "";
locStats();
}
}
for (var y = 0; y < creatures.length; y++) {
creatures[y].run();
}
for (var ob = 0; ob < objects.length; ob++) {
objects[ob].run();
}
for (var n = 0; n < npcs.length; n++) {
npcs[n].run();
}
setPlayerPos();
}
if (player.isDead) {
if (search(['respawn', 'revive'], c)) {
say("You feel a sudden sharp pain like lightning pierce your body. Your eyes open and your lungs fill with air. Your soul attaches itself to your body and you are back in the world, alive again.<br>")
player.x = spawnPoints[0];
player.y = spawnPoints[1];
player.isDead = false;
player.died = false;
player.health = player.maxHealth;
player.hunger = player.maxH;
player.thirst = player.maxT;
setPlayerPos();
locStats();
} else {
say('Type "respawn" to revive yourself');
}
}
if (!res) {
say(getEl(phrasesNotAllowed) + "<br>");
}
if (search(words.help, c_br[0])) {
if (!c_br[1]) {
say(`<div class="-sec">
<div>Help Options</div>
Welcome to the help options menu! There are a series of guides that you can read. Here is a list of tutorials that you can read:
1. Moving
2. Examining things
3. Item Interaction
4. Fighting
5. Interacting with NPCs
Start one of the tutorials by typing "help [tutorial number]" e.g. "help 1"
</div>`);
}
if (c_br[1]) {
if (c_br[1] === "1") {
say(`<div class="-sec">
<div>Help Options > Moving</div>
Moving is the most basic thing in an interactive fiction game.
In Interactive Fiction games, you can move north, south, east, west, and sometimes up and down. Here are a list of commands for moving:
${c_s("Moving North","rgb(0,200,0)")}:
'go north', 'north', 'go n', 'n'
${c_s("Moving South","rgb(0,200,0)")}:
'go south', 'south', 'go s', 's'
${c_s("Moving East","rgb(0,200,0)")}:
'go east', 'east', 'go e', 'e'
${c_s("Moving West","rgb(0,200,0)")}:
'go west', 'west', 'go w', 'w'
As you can see, there are shorthand words for moving. The easiest way to move would be by just using the shortest commands.
If you need to see these commands again, just type 'help 1' at any time.
</div>`)
}
if (c_br[1] === "2") {
say(`<div class="-sec">
<div>Help Options > Examining Things</div>
Examining things is probably the most important thing in a text adventure that you will have to use.
Type "look" to examine the location you are in.
Type "look [object/item]" to examine an object (like a bed) that is in the same location you are in or an item in your inventory.
Looking at an armor or weapon will show you it's stats. Looking at a food or drink item will show how much health, hunger, and/or thirst it replenishes. You can also examine NPCs and Enemies. To scan your surroundings for enemies, type 'scan' to see what type of enemies are close by you.
</div>`)
}
if (c_br[1] === "3") {
say(`<div class="-sec">
<div>Help Options > Item Interaction</div>
Item interaction includes eating, drinking, equipping, taking, dropping, and more. If you want to become more powerful, you have to keep looting items and upgrading yourself.
${c_s("Taking Items","rgb(0,200,0)")}
Let's say you are in a location and there is an apple there. All you have to do is type 'take apple' and it will be added into your inventory. If you want to take any item, type 'take <item>'.
${c_s("Dropping Items","rgb(0,200,0)")}
If you don't want something in your inventory (some items are classified as useless), type 'drop <item>'. It will be removed from your inventory and placed in the location you are currently in.
${c_s("Equipping Armor & Weapons","rgb(0,200,0)")}
If you have a weapon or a piece of armor in your inventory, type 'equip <item>'. The item will then be removed from your inventory and placed on your body.
${c_s("Removing Equipment","rgb(0,200,0)")}
Sometimes, you will be prompted to remove a piece of armor before you equip another type. Simply type 'remove <item>' and the item will be taken from your equipment and placed in your inventory.
Don't forget that you can come back any time by typing 'help 3'.
</div>`)
}
if (c_br[1] === "4") {
say(`<div class="-sec">
<div>Help Options > Fighting</div>
Combat is probably the most fun part of playing an Interactive Fiction game. It's pretty simple as well as all you do is wait and watch to see who dies.
${c_s("Starting a Fight","rgb(0,200,0)")}
Starting a fight is very simple. Some creatures are aggresive. That means that they will attack you if you enter their territory and if your level is lower than theirs. If a mob is passive, that means that they will not fight you. You will have to type 'fight [creature]' if you want to fight them.
${c_s("Why Fight?","rgb(0,200,0)")}
If you kill a creature, most of the time, they will drop items for you to take. You can get anywhere from useless items to top-notch weapons.
${c_s("Combat Tips","rgb(0,200,0)")}
Usually, eating food and drinking water heals you. You can eat and drink when you are fighting. Also, if you have an item like a Grenade, type "use grenade" to use up that item. Keep an eye on your health bar as you fight. If you don't think you can win the fight, type 'flee' to run away. Sometimes you will manage to escape while other times, you will fail. If you die, you will still keep your inventory, level, xp and all, but you will start at your spawn point again.
Don't forget that you can come back and view this again by typing 'help 4'
</div>`)
}
if (c_br[1] === "5") {
say(`<div class="-sec">
<div>Help Options > Interacting with NPCs</div>
NPCs (Non-Player Characters) can give you quests and send you on wild adventures. Rewards can be armor, weapons, XP, money, or more. Type 'talk <character>' to interact with them. If they have a quest for you, they will give it to you. Once the quest is fufilled, you will get your reward.
</div>`);
}
}
}
if (c == "attacks") {
say(player.attarr);
}
console.log(player.x, player.y)
parseColors();
} catch (err) {
say(err);
console.log(err);
}
}
}
/****************************************
* KEYUP EVENT LISTENER
****************************************/
$("#com").addEventListener("keyup", function(e) {
if (!$("#com").value.includes(">") || $("#com").value[0] !== ">") {
var s = $("#com").value.replaceAll(">", "");
$("#com").value = ">" + s;
}
if (e.keyCode === 38) {
$("#com").value = past;
}
if (e.keyCode === 13 && $("#com").value !== ">") {
commands()
past = ($("#com").value);
$("#com").select();
}
})
/****************************************
* Player Stats
****************************************/
//update player every tenth of a second
setInterval(function() {
var highestDamage = 0;
var pws = player.attarr;
for(var i = 0; i < pws.length; i++){
if(attackPower[pws[i]] > highestDamage){
highestDamage = attackPower[pws[i]];
}
}
player.maxHealth = 100 + player.bonusHealth;
player.maxDamage = (5 + player.damageBonus) * (1.1 ** player.level);
player.healthRegen = 2 + player.plusReg;
player.blockChance = 0 + player.bBlock;
player.critChance = 0.05 + player.bCrit;
player.dodgeChance = 0 + player.bDodge;
player.attackRate = 3000 - (player.bAttack * 10);
player.attarr = ["punch", "kick"];
var overallA = 0,
overallD = 0,
overallHR = 0,
overallBlock = 0,
overallCrit = 0,
overallDodge = 0,
overallSpeed = 0,
attackArr = [];
for (var i = 0; i < player.eq.length; i++) {
overallA += Items[player.eq[i]].apts;
overallD += Items[player.eq[i]].dpts;
overallHR += Items[player.eq[i]].chance[3];
overallCrit += Items[player.eq[i]].chance[0];
overallBlock += Items[player.eq[i]].chance[2];
overallDodge += Items[player.eq[i]].chance[1];
overallSpeed += Items[player.eq[i]].asp;
attackArr.push(Items[player.eq[i]].attacks);
}
for (var q = 0; q < attackArr.length; q++)
for (var p = 0; p < attackArr[q].length; p++)
if (attackArr[q][p])
player.attarr.push(attackArr[q][p]);
player.attacks = [...new Set(player.attarr)];
if (overallCrit > 0.35) {
overallCrit = 0.35;
}
if (overallBlock > 0.2) {
overallBlock = 0.2;
}
if (overallDodge > 0.2) {
overallDodge = 0.2;
}
if (player.attackRate < 500) {
player.attackRate = 500;
}
player.bonusHealth = overallA;
player.damageBonus = overallD;
player.plusReg = overallHR;
player.bBlock = overallBlock;
player.bCrit = overallCrit;
player.bDodge = overallDodge;
player.bAttack = overallSpeed;
player.minDamage = (player.maxDamage/2);
$("#mainStats").innerHTML = `
Health: ${Math.round(player.health)}/${player.maxHealth}<br>
Hunger: ${Math.round(player.hunger)}/${player.maxH}<br>
Thirst: ${Math.round(player.thirst)}/${player.maxT}<br>
XP: ${player.xp}<br>
Level: ${player.level}<br>
Damage: ${Math.floor(player.minDamage)}-${Math.floor(player.maxDamage*highestDamage)}<br>
Attack Rate: ${player.attackRate/1000}s<br>
Dodge Chance: ${Math.floor(player.dodgeChance*100)}%<br>
Block Chance: ${Math.floor(player.blockChance*100)}%<br>
Critical Chance: ${Math.floor(player.critChance*100)}%<br>`;
if (player.health < player.maxHealth) {
player.health += player.healthRegen / 100;
}
if (player.health >= player.maxHealth) {
player.health = player.maxHealth;
}
if (player.hunger >= player.maxH) {
player.hunger = player.maxH;
}
if (player.thirst >= player.maxT) {
player.thirst = player.maxT;
}
if (!player.isDead) {
player.thirst -= 0.01;
player.hunger -= 0.005;
}
if (player.thirst < 1) {
player.died = true;
}
if (player.hunger < 1) {
player.died = true;
}
if (player.health < 1) {
player.died = true;
}
if (player.died) {
if (player.health < 1) {
player.health = 2;
}
if (player.thirst < 1) {
player.thirst = 2;
}
if (player.hunger < 1) {
player.hunger = 2;
}
playerDie();
player.died = false;
player.isDead = true;
}
for (var b = 0; b < creatures.length; b++) {
if (creatures[b].health < 0 || creatures[b].health === 0) {
creatures[b].dead = true;
}
}
if (player.critChance >= 0.2) {
player.critChance = 0.2;
}
if (player.critChance >= 0.2) {
player.critChance = 0.2;
}
if (player.dodgeChance >= 0.15) {
player.critChance = 0.15;
}
if (player.blockChance >= 0.15) {
player.blockChance = 0.15;
}
if (player.xp >= (500+(100*player.level))) {
var diffOut = player.xp - (500+(100*player.level));
player.level++;
player.minDamage += 0.5
say(c_s("You leveled up to level " + player.level, "rgb(0,200,0)"));
player.xp = diffOut;
}
//save the player
localStorage.setItem("playerstats", JSON.stringify(player));
//clear part of the log so that the game still keeps a high FPS rate
var logSplit = $("#log").innerHTML.split('<br>');
if (logSplit.length > 35) {
logSplit.shift();
$("#log").innerHTML = logSplit.join('<br>');
}
}, 100);
|
// Build a function my_max() which takes an array and returns the maximum number.
var array = [1,4,7,3,8,3,5,0,1,2];
function my_max(arr) {
var max = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
console.log(max);
}
my_max(array);
// Build a function vowel_count() which takes a string and returns the number of vowels (AEIOUY).
var string = "wa hello yabu dybi";
var vowels = "aeiouy";
function vowel_count(str) {
var counter = 0;
for (var i = 0; i < str.length; i++) {
if (vowels.split("").includes(str[i])) {
counter += 1;
}
}
console.log(counter);
}
vowel_count(string);
// Build a function reverse() which takes a string and returns all the characters in the opposite position, e.g. reverse("this is a string") // "gnirts a si siht"
var testString = "test string for test";
function reverse(str) {
var strReversed = "";
for (var i = str.length - 1; i > 0; i--) {
strReversed += str[i];
}
console.log(strReversed);
}
reverse(testString);
|
//存储了actionCreator的type, 保证调用正确 不因为字符错误出错
export const DYNAMIC_CHANGE_TIME = 'header/dynamicChangeTime';
export const GET_WEATHER = 'header/getWeather';
export const LOGIN_OUT = 'header/loginOut';
|
const mongoose = require("mongoose");
const productModel = require("../models/product.model");
const createProduct = (req, res) => {
const { name, category, isActive, details } = req.body;
const product = new productModel({
name,
category,
isActive,
details,
});
product.save((error, result) => {
if (error) return res.status(400).json({ error });
res.status(201).json({ result });
});
};
const getProducts = (req, res) => {
productModel
.find({})
.then((products) => {
res.send(products);
})
.catch((error) => res.status(500).json({ error }));
};
const getProduct = (req, res) => {
const { id } = req.params;
productModel.findById(id, (error, result) => {
if (error) {
return res.status(400).json({ error });
}
if (!result) {
return res.status(404).send("Wrong ID");
}
res.json({ result });
});
};
const getActiveProducts = (req, res) => {
productModel
.find({ isActive: true })
.then((products) => {
res.send(products);
})
.catch((error) => res.status(500).json({ error }));
};
const getProductsByPriceRange = (req, res) => {
const { min, max } = req.body;
productModel
.find({ "details.price": { $gte: min, $lte: max } })
.then((products) => {
res.send(products);
})
.catch((error) => res.status(500).json({ error }));
};
module.exports = {
create: createProduct,
getAll: getProducts,
getOne: getProduct,
getAllActive: getActiveProducts,
getAllInRange: getProductsByPriceRange,
};
|
import React from 'react'
import st from './index.css'
const Page = (props) => {
return (
<div className={st.subRoot}>
<props.header />
<props.content />
</div>
)
}
export default Page
|
// Simple date selector
// Component API:
// Pass in any (all optional) of the following props to affect certain aspects
// @initDay - sets the initial value of the day picker (value should be [1-31]). Default is 1
// @initMonth - sets the initial value of the month picker (value should be [1-12]). Default is 1
// @initYear - sets the initial value of the year picker. Default is 2010.
// @minYear - sets the floor of the year picker. Default is 2010. The maximum year is the current year.
import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet, Picker } from 'react-native';
import RNPickerSelect from 'react-native-picker-select';
const CurrentYear = new Date().getFullYear();
const Years = []; for(let i = 2010; i <= CurrentYear; i++) Years.push(i);
const DaysPerMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
const Months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
export default function SelectDate(props) {
// update hook located in props.update
let [day, setDay] = useState(props.initDay || 1);
let [month, setMonth] = useState(props.initMonth || 1);
let [year, setYear] = useState(props.initYear || props.minYear || 2010);
useEffect(() => {
let y = year % 100;
props.update(parseInt(`${y < 10 ? `0${y}` : y}${month < 10 ? `0${month}` : month}${day < 10 ? `0${day}` : day}`));
}, [day, month, year]);
return (
<View style={styles.container}>
{/* Month Picker */}
<RNPickerSelect style={pickerStyle}
placeholder={{}}
InputAccessoryView={() => null}
onValueChange={val => setMonth(parseInt(val))}
items={Months.map((month, i) => (
{label: `${month}`, value: i + 1}
))}
value={month}/>
{/* Day Picker */}
<RNPickerSelect style={pickerStyle}
placeholder={{}}
InputAccessoryView={() => null}
onValueChange={val => setDay(parseInt(val))}
items={[...Array(year % 4 === 0 && month === 2 ? 29 : DaysPerMonth[month - 1])].map((_, i) => ({label: `${i + 1}`, value: i + 1}))}
value={day}/>
{/* Year Picker */}
<RNPickerSelect style={pickerStyle}
placeholder={{}}
InputAccessoryView={() => null}
onValueChange={val => setYear(parseInt(val))}
items={[...Array(CurrentYear - (props.minYear || 2010) + 1)].map((_, i) => ({label: `${i + (props.minYear || 2010)}`, value: i + (props.minYear || 2010)}))}
value={year}/>
</View>
)
}
const styles = StyleSheet.create({
container: {
flexDirection: "row",
justifyContent: "space-around",
},
});
// Styles copied from the react-native-picker-select sample snack, with some modifications
// https://snack.expo.io/@lfkwtz/react-native-picker-select
const pickerStyle = StyleSheet.create({
inputIOS: {
fontSize: 16,
paddingVertical: 7,
paddingHorizontal: 5,
borderWidth: 1,
borderColor: 'gray',
borderRadius: 4,
color: 'black',
marginHorizontal: 2,
},
inputAndroid: { // Covers Android & Web platforms
paddingVertical: 7,
paddingHorizontal: 5,
borderWidth: 0.5,
borderColor: 'gray',
borderRadius: 8,
color: 'black',
marginHorizontal: 2,
},
});
|
'use strict';
const myApp = require('../app/Oop');
describe('Laptop Class Test', function () {
describe('Verify Laptop is an Object and is a Constructor Object', function () {
it("Should be an Object", function () {
let Dell = new myApp.Laptop('Dell', 'Inspiron', 'windows', 'Black');
expect(typeof Dell).toEqual(typeof {});
});
it("Should be an instance of Laptop", function () {
let Dell = new myApp.Laptop('Dell', 'Inspiron', 'Windows', 'Black');
expect(Dell instanceof myApp.Laptop).toBeTruthy();
});
});
describe('Create a New Laptop and Call Some of its Methods', () => {
it("Should return generic Laptop Motto", () => {
let Dell = new myApp.Laptop('Dell', 'Inspiron', 'Windows', 'Black');
let motto = Dell.getBrandMotto();
expect(motto).toEqual("Dell..., World's Best");
});
it("should return manufacturing date", () => {
let Dell = new myApp.Laptop('Dell', 'Inspiron', 'Windows', 'Black');
let manufacturingDate = Dell.getProductionDate();
expect(manufacturingDate).toEqual(Dell.getProductionDate());
});
it("should change Laptop Color", () => {
let Dell = new myApp.Laptop('Dell', 'Inspiron', 'Windows', 'Black');
let newColor = Dell.setColor('purple');
expect(Dell.color).toEqual('purple');
});
it("should return basic information of the Laptop", () => {
let Dell = new myApp.Laptop('Dell', 'Inspiron', 'Windows', 'Black');
let laptopInfo = Dell.getLaptopInfo();
expect(laptopInfo).toEqual('Dell Inspiron running on Windows operating system');
});
it("should return basic startup message", () => {
let Dell = new myApp.Laptop('Dell', 'Inspiron', 'Windows', 'Black');
let startLaptop = Dell.startLaptop();
expect(startLaptop).toEqual('Dell Inspiron is starting up !!!');
});
});
describe(" Dell Instance of Laptop Tests", () => {
it("Should be an Object", () => {
let Dell = new myApp.Dell('Dell', 'Inspiron', 'windows', 'Black');
let motto = Dell.getBrandMotto();
expect(motto).toEqual("Dell, Purely You");
});
})
});
|
// interaction/communication with database
const connection = require("./connection");
class DB {
constructor(connection) {
this.connection = connection;
}
findAllEmployees() {
return this.connection.query(
"SELECT * FROM Employee"
);
}
createEmployee(employee) {
return this.connection.query("INSERT INTO employees SET ?", employee);
}
updateEmp
findAllRoles() {
return this.connection.query(
"select * from roles"
);
}
createRole(role) {
return this.connection.query("INSERT INTO role SET ?" ,
role
);
}
findAllDepartments() {
return this.connection.query(
"SELECT * FROM Department"
);
}
createDepartment(departmentId) {
return this.connection.query(
"INSERT INTO department SET ?",
departmentId
);
}
updateEmployee(employeeId) {
return this.connection.query(
"UPDATE employee SET ? WHERE ?",
employeeId
);
}
}
module.exports = new DB(connection);
|
var socket = io();
let username;
let busy = false;
var incallwith = "";
const localVideoEl = $('#localVideo');
const remoteVideosEl = $('#remoteVideos');
const chatlist = $('.chatlist');
let remoteVideosCount = 0;
let webrtc;
const chatTemplate = Handlebars.compile($('#chat-template').html());
const chatContentTemplate = Handlebars.compile($('#chat-content-template').html());
const chatEl = $('#chat');
const messages = [];
let user_list = [];
let user_count = 0;
let join = false;
let openchat;
// Hide cameras until they are initialized
localVideoEl.hide();
const swrtc = () => {
webrtc = new SimpleWebRTC({
// the id/element dom element that will hold "our" video
localVideoEl: 'localVideo',
// the id/element dom element that will hold remote videos
remoteVideosEl: 'remoteVideos',
// immediately ask for camera access
autoRequestMedia: true,
debug: false,
detectSpeakingEvents: true,
autoAdjustMic: false,
});
// We got access to local camera
webrtc.on('localStream', () => {
localVideoEl.show();
});
}
function user_login() {
var login = document.getElementById('login').value;
username = login;
socket.send({
type: "login",
name: username
})
}
function call_user() {
var callerID = document.getElementById('callerID').value;
if (callerID == "") {
alert('Please enter caller ID');
} else {
//const roomid = username+"-"+callerID;
//join(roomid);
swrtc();
createCall(username);
var callerIDContainer = document.getElementById('callerIDContainer');
callerIDContainer.parentElement.removeChild(callerIDContainer);
busy = true;
incallwith = callerID;
socket.send({
type: "call_user",
name: callerID,
callername: username
})
}
}
function onAnswer(data) {
if (busy == false) {
busy = true
incallwith = data.callername
var res = confirm(data.callername + " is calling you");
if (res == true) {
console.log("call accepted");
swrtc();
joinCall(data.callername);
// code
socket.send({
type: "call_accepted",
callername: data.callername,
from: username
})
} else {
console.log("call rejected");
socket.send({
type: "call_rejected",
callername: data.callername,
from: username
})
busy = false
incallwith = ""
}
} else {
console.log("call busy");
socket.send({
type: "call_busy",
callername: data.callername,
from: username
})
}
}
const chatlistcomponent = (object) => {
let d = document.createElement('ul');
d.className = 'cl';
for(var i in object){
d.innerHTML += '<li><a class="openchat notclickyet" href="#">' + i + '</a></li>';
user_count++;
}
chatlist.html(d);
openchat = $('.openchat');
openchat.click((e)=>{
if ($(e.target).hasClass("notclickyet")) {
$(e.target).removeClass( 'notclickyet' );
createRoom($(e.target).text());
}else{
joinRoom($(e.target).text());
}
}
);
}
// Update Chat Messages
const updateChatMessages = (chatMessage,room) => {
console.log(chatMessage);
const html = chatContentTemplate({ chatMessage });
const chatContentEl = $('#chat-content-'+room);
chatContentEl.append(html);
// automatically scroll downwards
const scrollHeight = chatContentEl.prop('scrollHeight');
chatContentEl.animate({ scrollTop: scrollHeight }, 'slow');
};
// Post Local Message
const postMessage = (message,room,join) => {
const chatMessage = {
type: "chat_message",
from: username,
to: room,
message: message,
join:join,
postedOn: new Date().toLocaleString('id-ID'),
};
// Send to all peer messages
socket.send(chatMessage)
// Update messages locally
updateChatMessages(chatMessage,room);
};
// Display Chat Interface
const showChatRoom = (room) => {
const html = chatTemplate({ room });
chatEl.append(html);
$('.'+room+' #post-btn').on('click', () => {
const message = $('.'+room+' #post-message').val();
postMessage(message,room,join=false);
$('.'+room+' #post-message').val('');
});
$('.'+room+' #post-message').on('keyup', (event) => {
if (event.keyCode === 13) {
console.log(room);
const message = $('.'+room+' #post-message').val();
postMessage(message,room,join=false);
$('.'+room+' #post-message').val('');
}
});
};
// Register new Chat Room
const createRoom = (roomName) => {
console.log(`Creating new room: ${roomName}`);
showChatRoom(roomName);
postMessage(`${username} created chatroom`,roomName,join=true);
};
//Call user
const createCall = (roomName) => {
// Remote video was added
webrtc.on('videoAdded', (video, peer) => {
console.log("ini videoadded");
// eslint-disable-next-line no-console
let d = document.createElement('div');
d.className = 'videoContainer';
d.id = 'container_' + webrtc.getDomId(peer);
d.appendChild(video);
if (remoteVideosCount === 0) {
remoteVideosEl.html(d);
} else {
remoteVideosEl.append(d);
}
remoteVideosCount += 1;
});
webrtc.createRoom(roomName, null);
// webrtc.createRoom(roomName, (err, name) => {
// showChatRoom(name);
// postMessage(`${username} created chatroom`);
// });
};
// Join call
const joinCall = (roomName) => {
// Remote video was added
webrtc.on('videoAdded', (video, peer) => {
console.log("ini videoadded");
// eslint-disable-next-line no-console
let d = document.createElement('div');
d.className = 'videoContainer';
d.id = 'container_' + webrtc.getDomId(peer);
d.appendChild(video);
if (remoteVideosCount === 0) {
remoteVideosEl.html(d);
} else {
remoteVideosEl.append(d);
}
remoteVideosCount += 1;
});
webrtc.joinRoom(roomName);
}
// Join existing Chat Room
const joinRoom = (data) => {
console.log(`Joining Room: ${data.from}`);
showChatRoom(data.from);
postMessage(`${username} joined chatroom`,data.from,join=false);
};
function onResponse(data) {
switch (data.response) {
case "accepted":
incallwith = data.responsefrom;
console.log('pembuat room', data.callername);
console.log("Call accepted by :" + data.responsefrom);
break;
case "rejected":
console.log("Call rejected by :" + data.responsefrom);
busy = false;
incallwith = ""
break;
case "busy":
console.log(data.responsefrom + " call busy");
busy = false;
incallwith = ""
break;
default:
console.log(data.responsefrom + " is offline");
busy = false;
incallwith = ""
}
}
const chat = (data) => {
if(data.type == 'chat_message'){
updateChatMessages(data,data.from);
}
}
socket.on('connect', function (data) {
console.log('connect');
});
//when a user logs in
function onLogin(data) {
if (data.success === false) {
alert("oops...try a different username");
} else {
var loginContainer = document.getElementById('loginContainer');
loginContainer.parentElement.removeChild(loginContainer);
username = data.username;
console.log("Login Successfull");
console.log("logged in as :" + username);
console.log(data.userlist);
chatlistcomponent(data.userlist);
console.log('total user :',user_count);
user_count = 0;
}
}
socket.on('roommessage', function (message) {
var data = message;
switch (data.type) {
case "login":
console.log("New user : " + data.username);
console.log(data.userlist);
chatlistcomponent(data.userlist);
console.log('total user :',user_count);
user_count = 0;
break;
case "disconnect":
console.log("User disconnected : " + data.username);
chatlistcomponent(data.userlist);
console.log('total user :',user_count);
user_count = 0;
break;
// case "chat_message":
// console.log(data.message)
// chat(data);
// break;
default:
break;
}
});
socket.on('privatechat', function(message) {
var data = message;
console.log(data);
switch (data.type) {
case "chat_message":
console.log(data.message);
join = true;
chat(data);
break;
default:
break;
}
});
socket.on('message', function (message) {
var data = message;
switch (data.type) {
case "login":
onLogin(data);
break;
case "answer":
console.log("getting called");
onAnswer(data);
break;
case "call_response":
onResponse(data);
break;
case "chat_message":
console.log(data.message);
if (data.join) {
openchat.each(function()
{
if ($(this).text() == data.from) {
$(this).removeClass('notclickyet');
}
});
joinRoom(data);
}else{
updateChatMessages(data,data.from);
}
break;
default:
break;
}
});
|
$(document).ready(function() {
var topics = ["LA Dodgers", "LA Clippers", "LA Kings", "Pittsburgh Steelers"];
function renderButtons() {
$('#buttons').empty();
for (var i = 0; i < topics.length; i++) {
var teamBtn = $('<button>');
teamBtn.addClass('team-button team-button-color');
teamBtn.attr('data-team', topics[i]);
teamBtn.appendTo('#buttons');
teamBtn.text(topics[i]);
$('.team-button').on('click', displayGifs);
}
};
//Function to create button for user input
$("#add-team").on("click", function (event) {
event.preventDefault();
var input = $('#team-input').val();
topics.push(input);
$('#add-team').empty();
renderButtons();
});
renderButtons();
//Function to display GIFs
function displayGifs() {
$('#gifs-appear-here').empty();
var team = $(this).attr('data-team');
console.log(team);
var queryURL = "https://api.giphy.com/v1/gifs/search?q=" + team + "&api_key=4lKQIGcIqYJp4vgYepvwYkHdb28Gf6q3&limit=10";
//AJAX Call
$.ajax({
url: queryURL,
method: "GET"
}).then(function (response) {
console.log(response.data);
var results = response.data;
for (var i = 0; i < results.length; i++) {
var teamDiv = $('<div>');
var p = $('<p>');
p.text('Rating: ' + results[i].rating);
var teamImage = $('<img>')
teamImage.addClass('team-image');
teamImage.attr('src', results[i].images.fixed_height.url);
teamImage.attr('data-still', results[i].images.fixed_height_still.url);
teamImage.attr('data-animate', results[i].images.fixed_height.url);
console.log(results[i].images);
teamImage.attr('data-state', "still");
teamDiv.append(p);
teamDiv.append(teamImage);
$('#gifs-appear-here').prepend(teamDiv);
}
$('#gifs-appear-here').on("click", ".team-image", function (event) {
console.log(this);
event.preventDefault()
var state = $(this).attr("data-state");
console.log(state);
if (state === "still") {
$(this).attr("src", $(this).attr("data-animate"));
$(this).attr("data-state", "animate");
} else {
$(this).attr("src", $(this).attr("data-still"));
$(this).attr("data-state", "still");
}
});
});
};
});
|
angular.module('entraide').controller('FooterCtrl', function ($scope, $meteor) {
console.log("footer-view Ctrl");
});
|
import React from "react";
import { useHistory } from "react-router-dom";
import logo from "./logo.png";
import back from "./back.png";
function AddressKYC() {
const history = useHistory();
const handleRoute3 = () => {
history.push("/otp");
};
return (
<div className="AddressPage">
<div className="topbar">
<div className="back">
<img src={back} alt="back" onClick={handleRoute3} />
</div>
<div className="homeName">Address KYC</div>
<div className="logo">
<img src={logo} alt="logo" />
</div>
</div>
<button className="scanDocBtn">CLICK HERE TO SCAN YOUR DOCUMENT</button>
<div className="addressForm">
<p className="formText">
Make sure all your information is correct before join with us
</p>
<form>
<div className="firstName">
<label for="firstName" className="firstNameLabel">
First Name
</label>
<input type="text" className="firstNameInput" />
</div>
<div className="lastName">
<label for="lastName" className="lastNameLabel">
Last Name
</label>
<input type="text" className="lastNameInput" />
</div>
<div className="address">
<label for="address" className="addressLabel">
Address
</label>
<textarea className="addressInput"></textarea>
</div>
</form>
<button type="button" class="scanBtn">
SCAN AGAIN
</button>
<button type="button" class="confirmBtn">
CONFIRM
</button>
</div>
</div>
// <div className="container-fluid">
// <div class="row justify-content-between headerRow">
// <div class="col-6">
// <h4 className="text-light">Address KYC</h4>
// </div>
// <div class="col-6">
// <img src={logo} alt="logo" width="150" />
// </div>
// </div>
// <div className="row justify-content-evenly text-center">
// <div className="col">
// <button className="btn btn-primary rounded-0 m-2">
// CLICK HERE TO SCAN YOUR DOCUMENT
// </button>
// <p>Make sure all your information is correct before join with us</p>
// </div>
// </div>
// <div className="row justify-content-evenly">
// <div className="col">
// <form>
// <div className="mb-3">
// <label for="firstName" className="form-label">
// First Name
// </label>
// <input type="text" className="form-control" />
// <label for="lastName" className="form-label">
// Last Name
// </label>
// <input type="text" className="form-control" />
// <label for="address" className="form-label">
// Address
// </label>
// <textarea className="form-control" cols="30" rows="7"></textarea>
// </div>
// </form>
// </div>
// </div>
// <div class="container bg-light">
// <div class="col-12 text-center">
// <button type="button" class="btn btn-primary rounded-0 m-3">
// SCAN AGAIN
// </button>
// <button type="button" class="btn btn-primary rounded-0 m-3">
// CONFIRM
// </button>
// </div>
// </div>
// </div>
);
}
export default AddressKYC;
|
import React from 'react';
import {
StyleSheet,
Text,
View,
Image,
TextInput,
TouchableOpacity,
} from 'react-native';
import { LinearGradient } from 'expo-linear-gradient';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
num: ' ',
op: ' ',
op2: ' ',
a: ' ',
b: ' ',
ans: '0',
};
}
input(num) {
switch (num) {
case '1':
this.setState({ a: this.state.a + '1' });
this.setState({ ans: this.state.a + '1' });
break;
case '2':
this.setState({ a: this.state.a + '2' });
this.setState({ ans: this.state.a + '2' });
break;
case '3':
this.setState({ a: this.state.a + '3' });
this.setState({ ans: this.state.a + '3' });
break;
case '4':
this.setState({ a: this.state.a + '4' });
this.setState({ ans: this.state.a + '4' });
break;
case '5':
this.setState({ a: this.state.a + '5' });
this.setState({ ans: this.state.a + '5' });
break;
case '6':
this.setState({ a: this.state.a + '6' });
this.setState({ ans: this.state.a + '6' });
break;
case '7':
this.setState({ a: this.state.a + '7' });
this.setState({ ans: this.state.a + '7' });
break;
case '8':
this.setState({ a: this.state.a + '8' });
this.setState({ ans: this.state.a + '8' });
break;
case '9':
this.setState({ a: this.state.a + '9' });
this.setState({ ans: this.state.a + '9' });
break;
case '0':
this.setState({ a: this.state.a + '0' });
this.setState({ ans: this.state.a + '0' });
break;
case '.':
this.setState({ a: this.state.a + '.' });
this.setState({ ans: this.state.a + '.' });
break;
}
}
clear() {
this.setState({ ans: '0', a: ' ', b: ' ' });
}
operation(op) {
if (op == '=') {
switch (this.state.op2) {
case '+':
this.setState({ a: Number(this.state.b) + Number(this.state.a) });
this.setState({ ans: Number(this.state.b) + Number(this.state.a) });
break;
case '-':
this.setState({ a: Number(this.state.b) - Number(this.state.a) });
this.setState({ ans: Number(this.state.b) - Number(this.state.a) });
break;
case '*':
this.setState({ a: Number(this.state.b) * Number(this.state.a) });
this.setState({ ans: Number(this.state.b) * Number(this.state.a) });
break;
case '/':
this.setState({ a: Number(this.state.b) / Number(this.state.a) });
this.setState({ ans: Number(this.state.b) / Number(this.state.a) });
break;
}
} else {
this.setState({ b: this.state.a });
this.setState({ a: ' ' });
this.setState({ op2: op });
}
}
render() {
return (
<LinearGradient
colors={['#000000', '#000000', '#000000']}
style={{ flex: 1 }}>
<View style={{ flex: 1 }}>
<View style={{ flex: 1 }} />
<View
style={{ flex: 1, flexDirection: 'row', justifyContent: 'center' }}>
<Text style={styles.container5}>{this.state.ans}</Text>
</View>
<View
style={{
flex: 1.1,
flexDirection: 'row',
justifyContent: 'center',
}}>
<TouchableOpacity
style={styles.container4}
onPress={() => this.clear()}>
<Text style={styles.text2}>AC</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.container4}>
<Text style={styles.text2}>+/-</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.container4}>
<Text style={styles.text2}>%</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.container3}
onPress={() => this.operation('/')}>
<Text style={styles.text}>/</Text>
</TouchableOpacity>
</View>
<View
style={{
flex: 1.1,
flexDirection: 'row',
justifyContent: 'center',
}}>
<TouchableOpacity
style={styles.container}
onPress={() => this.input('7')}>
<Text style={styles.text}>7</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.container}
onPress={() => this.input('8')}>
<Text style={styles.text}>8</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.container}
onPress={() => this.input('9')}>
<Text style={styles.text}>9</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.container3}
onPress={() => this.operation('*')}>
<Text style={styles.text}>x</Text>
</TouchableOpacity>
</View>
<View
style={{
flex: 1.1,
flexDirection: 'row',
justifyContent: 'center',
}}>
<TouchableOpacity
style={styles.container}
onPress={() => this.input('4')}>
<Text style={styles.text}>4</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.container}
onPress={() => this.input('5')}>
<Text style={styles.text}>5</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.container}
onPress={() => this.input('6')}>
<Text style={styles.text}>6</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.container3}
onPress={() => this.operation('-')}>
<Text style={styles.text}>-</Text>
</TouchableOpacity>
</View>
<View
style={{
flex: 1.1,
flexDirection: 'row',
justifyContent: 'center',
}}>
<TouchableOpacity
style={styles.container}
onPress={() => this.input('1')}>
<Text style={styles.text}>1</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.container}
onPress={() => this.input('2')}>
<Text style={styles.text}>2</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.container}
onPress={() => this.input('3')}>
<Text style={styles.text}>3</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.container3}
onPress={() => this.operation('+')}>
<Text style={styles.text}>+</Text>
</TouchableOpacity>
</View>
<View
style={{
flex: 1.1,
flexDirection: 'row',
justifyContent: 'center',
}}>
<TouchableOpacity
style={styles.container2}
onPress={() => this.input('0')}>
<Text style={styles.text}>0</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.container}
onPress={() => this.input('.')}>
<Text style={styles.text}>.</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.container3}
onPress={() => this.operation('=')}>
<Text style={styles.text}>=</Text>
</TouchableOpacity>
</View>
</View>
</LinearGradient>
);
}
}
const styles = StyleSheet.create({
text: {
color: 'white',
fontSize: 25,
},
text2: {
color: 'black',
fontSize: 25,
},
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#222222',
borderRadius: 100,
height: 60,
padding: 8,
margin: 9,
},
container2: {
flex: 2.4,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#222222',
borderRadius: 100,
height: 60,
padding: 8,
margin: 9,
},
container3: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#FFA500',
borderRadius: 100,
height: 60,
padding: 8,
margin: 9,
},
container4: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#BEBEBE',
borderRadius: 100,
height: 60,
padding: 8,
margin: 9,
},
container5: {
flex: 1,
backgroundColor: '#000000',
color: 'white',
fontSize: 60,
textAlign: 'right',
},
});
|
var URL = require('url'),
http = require('http'),
util = require('util');
var cityArray = ['suzhou', 'changshu', 'kunshan', 'nantong', 'zhongshan', 'shaoxing', 'wujiang'],
mapUrls = ['http://www.subicycle.com/map.asp','http://www.csbike01.com/map.asp', 'http://www.ksbike01.com/map2.asp', 'http://www.ntbike.com/map.asp',
'http://www.zsbicycle.com/zsbicycle/map.asp', 'http://www.sxbicycle.com/map1.asp', 'http://www.wjbicycle.com/wjbicycle/map.asp'],
allBicyclesUrl = ['http://www.subicycle.com/szmap/ibikestation.asp' ,'http://www.csbike01.com/csmap/ibikestation.asp', 'http://www.ksbike01.com/ksmap/ibikestation.asp',
'http://www.ntbike.com/ntmap/ibikestation.asp','http://www.zsbicycle.com/zsbicycle/zsmap/ibikestation.asp',
'http://www.sxbicycle.com/sxmap/ibikestation.asp', 'http://www.wjbicycle.com/wjbicycle/wjmap/ibikestation.asp'],
singleBicycleUrl = ['http://www.subicycle.com/szmap/ibikestation.asp?id=', 'http://www.csbike01.com/csmap/ibikestation.asp?id=', 'http://www.ksbike01.com/ksmap/ibikestation.asp?id=',
'http://www.ntbike.com/ntmap/ibikestation.asp?id=', 'http://www.zsbicycle.com/zsbicycle/zsmap/ibikestation.asp?id=',
'http://www.sxbicycle.com/sxmap/ibikestation.asp?id=', 'http://www.wjbicycle.com/wjbicycle/wjmap/ibikestation.asp?id='],
cookieArray = [null, null, null, null, null, null, null];
function redirect(req, res){
var pathUrl = req.url;
if(pathUrl == '/favicon.ico'){
return;
}
var pathObj = URL.parse(pathUrl, true);
var paramObj = pathObj.query;
var city = paramObj.city;
var id = paramObj.id;
// console.log('redirect city = ' + city + ', id = ' + id);
var index = getIndex(city);
// console.log('redirect index = ' + index);
console.log('time = ' + new Date().toGMTString());
if(!cookieArray[index]){
console.log('===========================New Cookie==================================');
getCookie(index, id, res);
}else{
console.log('===========================Old Cookie==================================');
console.log('city = ' + city + ', id = ' + id);
getBicycleInfo(index, id, res);
}
// getCookie(index, id, res);
}
function getIndex(city){
var index = -1;
for(var i in cityArray){
if(cityArray[i] == city){
index = i;
break;
}
}
return index;
}
function getCookie(index, id, res){
var mapUrl = mapUrls[index];
var options = URL.parse(mapUrl);
options.headers = {
Connection : 'keep-alive',
Host : options.host
};
// options.port = '80';
var req = http.get(options, function(response) {
response.setEncoding('utf8');
response.on('end', function(){
var cookie = response.headers['set-cookie'][0].split('\\;');
console.log('getCookie cookie = ' + cookie);
cookieArray[index] = cookie;
getBicycleInfo(index, id, res);
// keepSessinTask(index);
});
});
req.on('error', function(){
res.writeHeader(404, "404");
res.end('404');
});
}
function getBicycleInfo(index, id, res){
var bicycleOption = URL.parse(getBicycleUrl(index, id));
bicycleOption.headers = {
Connection : 'keep-alive',
Host : bicycleOption.host,
cookie : cookieArray[index]
}
http.get(bicycleOption, function(response) {
response.setEncoding('utf8');
var data = '';
response.on('data', function(chunck) {
data += chunck;
});
response.on('end', function(){
if(data){
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(data);
}
});
});
}
function refreshCookieTask(){
console.log('----------------------refreshCookieTask------------------------------');
for(var i = 0; i < 1; i++){
//first get cookie
getCookieTask(i);
//then refresh cookie every 5 minutes
setInterval(getCookieTask, 300000, [i]);
//keep session in every 2 minutes
// keepSessinTask(i);
}
}
function getCookieTask(index){
console.log('****************Refresh City ' + cityArray[index] +' cookie ****************')
var mapUrl = mapUrls[index];
var options = URL.parse(mapUrl);
options.headers = {
Connection : 'close',
Host : options.host
};
// options.port = '80';
http.get(options, function(response) {
response.on('end', function() {
// var cookie = response.headers['set-cookie'][0].split('\\;');
// console.log('-----------Refresh Cookie city = ' + cityArray[index] + ', cookie = ' + cookie + ', time = ' + new Date().toGMTString());
// cookieArray[index] = cookie;
var newOptions = options;
newOptions.headers.Connection = 'keep-alive';
http.get(options, function(res) {
res.on('end', function() {
var cookieHeader = response.headers['set-cookie'];
if(cookieHeader != null && cookieHeader.length > 0) {
var cookie = response.headers['set-cookie'][0].split('\\;');
cookieArray[index] = cookie;
console.log('-----------Refresh Cookie city = ' + cityArray[index] + ', cookie = ' + cookie + ', time = ' + new Date().toGMTString());
}
});
});
});
});
}
function keepSessinTask(index){
console.log('-------------start time = ' + new Date().toString());
setInterval(getBicycleInfoTask, 300000, [index]);
}
function getBicycleInfoTask(index){
console.log('================getBicycleInfoTask=========== index = ' + index);
var bicycleOption = URL.parse(getBicycleUrl(index, 1));
bicycleOption.headers = {
Connection : 'keep-alive',
Host : bicycleOption.host,
cookie : cookieArray[index]
}
http.get(bicycleOption, function(response){
response.on('data', function(chunck){
console.log('************bicycle info = ' + chunck);
if(chunck.length < 20){
console.log('-------------end time = ' + new Date().toGMTString());
}
});
});
}
function getBicycleUrl(index, id){
var url = "";
if(id){
url = singleBicycleUrl[index] + id;
}else{
url = allBicyclesUrl[index];
}
return url;
}
exports.redirect = redirect;
exports.refreshCookieTask = refreshCookieTask;
|
export const SET_CURRENT_WEEK = 'SET_CURRENT_WEEK';
export const setCurrentWeek = data => ({
type: SET_CURRENT_WEEK,
payload: { data }
});
export const SET_OVERALL_TOTAL_MINUTES = 'SET_OVERALL_TOTAL_MINUTES';
export const setOverallTotalMinutes = data => ({
type: SET_OVERALL_TOTAL_MINUTES,
payload: { data }
});
export const SET_TIMEOUTS_IN_MINUTES = 'SET_TIMEOUTS_IN_MINUTES';
export const setTimeoutsInMinutes = data => ({
type: SET_TIMEOUTS_IN_MINUTES,
payload: { data }
});
export const SET_LOG_TIME = 'SET_LOG_TIME';
export const setLogTime = data => ({
type: SET_LOG_TIME,
payload: { data }
});
export const RESET_DATA = 'RESET_DATA';
export const resetData = data => ({
type: RESET_DATA,
payload: { data }
});
export const SET_OPTIONS = 'SET_OPTIONS';
export const setOptions = data => ({
type: SET_OPTIONS,
payload: { data }
});
|
if (!Object.values) {
Object.values = function (o) {
return Object.keys(o).map(function (k) {
return o[k];
});
};
}
|
import React from 'react';
import Dash from './Dashboard.css';
export default function Dashboard() {
return (
<div className="container">
<div className="dashboard">
<div className="search">
<div>
<label>Name</label>
<input name="Search Name"/><br/>
</div>
<div>
<label>Last Name</label>
<input name="Search Last Name"/>
</div>
<div>
<label>Email</label>
<input name="Search Email"/>
</div>
<div>
<label>Phone</label>
<input name="Phone"/>
</div>
<div>
<label>Faculty</label>
<select name="faculty"/>
</div>
<div>
<label>Group</label>
<select name="group"/>
</div>
</div>
</div>
</div>
)
}
|
const express = require('express');
const app = express();
app.set('port', process.env.PORT || 3000);
// Homepage:
app.get('', function(req, res) {
res.type('text/plain');
res.send('Meadwork Travel');
});
// About page:
app.get('/about', function(req, res) {
res.type('text/plain');
res.send('About Meadwork Travel');
});
// Page 404:
app.use(function(req, res) {
res.type('text/plain');
res.status(404);
res.send('Nothing founded');
});
// Page 500:
app.use(function(err, req, res, next) {
console.error(err.stack);
res.type('text/plain');
res.status(500);
res.send('500 - Server error');
});
app.listen(app.get('port'), function() {
console.log('Сервер запущен на localhost: 3000: ' + app.get('port') + '. Нажмите Ctrl + C для завершения...');
});
|
let vieuxBtn = document.getElementById("vieux");
let multipleBtn = document.getElementById("multiple");
let tableauBtn = document.getElementById("tableau");
let commandeBtn = document.getElementById("commande");
// calcul nombre de jeune et de vieux
const vieux = () => {
window.alert("Cette fonction classe les âges que vous rentrer en 3 catégories, \ninférieur a 20 ans (jeunes), \nentre 20 et 40 ans (adultes) \net les plus de 40 ans (vieux) \ncette fonction s'arrête dès lors que l'âge que vous donner dépasse 100 ans.")
let age = 0;
let nb_jeune = 0;
let nb_adulte = 0;
let nb_vieux = 0;
while (age < 100) {
age = parseInt(prompt("Entrez un âge celui de votre choix pour le classer dans l'une des 3 catégorie\n(la saisie s'arrête lorsque vous saisissez un âge supérieur ou egale 100 ans \nvous pouvez aussi cliquer sur annuler, mais cela contera un vieux en plus.)"));
if (age < 20) {
nb_jeune++;
} else if (age >= 20 && age <= 40) {
nb_adulte++;
} else {
nb_vieux++;
}
}
window.alert("il y a tant de jeunes : " + nb_jeune + "\n il y a tant d'adulte : " + nb_adulte + "\n et il y a tant de vieux : " + nb_vieux)
}
// table de multiplication
function multiple() {
window.alert("Cette fonction vous affiche la table de multiplication que vous voulez \n(Veuillez s'il vous plaît réactualiser la page avant de recommencer.)");
let N = Number(window.prompt("Veuillez entrez votre table de multiplication", ""));
while (isNaN(N)) {
N = Number(window.prompt("ERREUR : Valeur invalide, veuillez entrez votre table de multiplication", ""));
};
let X = Number(window.prompt("Veuillez entrez le nombre jusqu'ou la table doit aller", ""));
while (isNaN(X)) {
X = Number(window.prompt("ERREUR : Valeur invalide, Veuillez entrez le nombre jusqu'ou la table doit aller", ""));
};
for (let i = 1; i <= X; i++) {
document.getElementById("table").innerHTML += `${i}x${N}=${i * N} <br>`;
}
}
// nom dans le tableau
const tableau = () => {
window.alert("Cette fonction est un tableau dans lequel il y a des noms une fois qu'un de ses noms a était rentré il est supprimé du tableau qui sera alors afficher dans la console de votre navigateur visible en appuyant sur la touche F12 de votre clavier")
let tab = ["audrey", "aurelien", "flavien", "jeremy", "laurent", "melik", "nouara", "salem", "samuel", "stephane"];
let saisie = window.prompt(`
Veuillez choisir un prénom. parmi : "audrey", "aurelien", "flavien", "jeremy", "laurent", "melik", "nouara", "salem", "samuel", "stephane"
`)
if (tab.includes(saisie)) {
console.log(tab);
tab.splice(tab.indexOf(saisie), 1);
tab.push(" ");
console.log(tab);
} else {
alert("erreur réessayer");
saisie = window.prompt(`
Veuillez choisir un prénom parmi : "audrey", "aurelien", "flavien", "jeremy", "laurent", "melik", "nouara", "salem", "samuel", "stephane"
`)
}
if (tab.includes(saisie)) {
console.log(tab);
tab.splice(tab.indexOf(saisie), 1);
tab.push(" ");
console.log(tab);
}
}
// calcul prix de la commande
const commande = () => {
window.alert("Cette fonction calcul pour vous le prix d'une commande avec ses remises et ses frais de port\n(Port gratuit si supérieur a 500 € \nen dessous le port est égale à 2 % du total et un minimum de 6 €; \nremise de 5 % si total compris entre 100 € et 200 € \npas de remise en dessous et remise de 10 % au-dessus).")
let PU = parseFloat(prompt('Prix unitaire'));
let QTECOM = parseInt(prompt('Quantité commandée'));
let TOT = PU * QTECOM;
let PORT = 0.02 * TOT;
let REM5 = TOT * 0.05;
let REM10 = TOT * 0.1;
let PAP = 0;
if (isNaN(PU && QTECOM)) {
alert('Erreur, saisissez des nombres');
} else {
if (TOT > 500) {
PAP = TOT - REM10;
alert('Le prix à payer sera de ' + PAP + '€.');
} else if (TOT > 200 && TOT <= 500) {
if (PORT < 6) {
PORT = 6;
} else {
PORT = 0.02 * TOT;
}
PAP = TOT - REM10 + PORT;
alert('Le prix à payer sera de ' + PAP + '€.');
} else if (TOT <= 200 && TOT >= 100) {
PAP = TOT - REM5 + 6;
alert('Le prix à payer sera de ' + PAP + '€.');
} else {
PAP = TOT + 6;
alert('Le prix à payer sera de ' + PAP.toFixed(2) + '€.');
}
}
}
vieuxBtn.onclick = vieux;
multipleBtn.onclick = multiple;
tableauBtn.onclick = tableau;
commandeBtn.onclick = commande;
|
import styled from 'styled-components';
const StyledNav = styled.div`
font-family: 'Gilroy', 'Nunito', sans-serif;
a {
color: white;
text-decoration: none;
}
a:hover {
color: #d0d0d0;
}
.fas {
font-family: 'Font Awesome 5 Free';
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Gilroy', 'Nunito', sans-serif;
}
.logo {
width: auto;
height: 100%;
}
.inner-header {
background-color: #004495;
padding: 1em 2em;
color: white;
display: flex;
flex-direction: row;
justify-content: space-between;
<<<<<<< HEAD
padding: 0rem 4rem;
align-items: center;
background: blue;
max-height: 5rem;
=======
>>>>>>> 7cea36aa0066d65444e782074ccb4b4b2e89421e
}
.menu {
display: flex;
flex-wrap: wrap;
align-content: center;
}
header ul li {
display: inline-block;
font-family: 'Gilroy';
font-size: 18px;
line-height: 27px;
width: 100px;
text-align: center;
}
.button {
background: white;
width: 130px;
padding: 10px;
outline: none;
color: #004495;
text-align: center;
border-radius: 4px;
cursor: pointer;
a {
color: #004296;
}
}
.mobile-menu {
display: none;
}
.mobile-sign {
display: none;
}
.toggle-btn {
display: none;
}
@media only screen and (max-width: 968px) {
.menu li {
font-size: 1.1em;
line-height: 5em;
}
.sign li {
line-height: 2em;
}
.logo {
width: auto;
height: auto;
}
header {
position: unset;
}
.toggle-btn {
display: block;
position: absolute;
top: 0.5rem;
right: 2rem;
cursor: pointer;
}
.inner-header {
display: flex;
width: 100%;
justify-content: space-around;
}
.menu {
display: none;
}
.desktop-sign {
display: none;
}
/* .menu {
display: unset;
} */
.mobile-menu {
background: #fff;
padding: 1rem;
flex-direction: column;
margin-top: 1em;
display: ${({ openNav }) => (openNav ? 'flex' : 'none')};
transition: transform 0.3s ease-in-out;
transform: ${({ openNav }) =>
openNav ? 'translateX(0)' : 'translateX(-100%)'};
ul {
display: flex;
flex-direction: column;
li {
color: #004296;
font-size: 1.1em;
}
}
/* background: #fff; */
}
.mobile-sign {
display: flex;
justify-content: center;
align-items: center;
ul {
display: flex;
flex-direction: column;
li {
color: #004296;
}
.mobile-button {
background: #004296;
color: #fff;
}
}
}
.inner-header {
padding: 1em;
display: block;
text-align: center;
}
}
`;
export default StyledNav;
|
//[COMMENTS]
/*
Instructions
Add the equality operator to the indicated line so that the function will return "Equal" when val is equivalent to 12
testEqual(10) should return "Not Equal"
testEqual(12) should return "Equal"
testEqual("12") should return "Equal"
You should use the == operator
*/
//[COMMENTS]
// Setup
function testEqual(val) {
if (val == 12) { // Change this line
return "Equal";
}
return "Not Equal";
}
// Change this value to test
testEqual(10);
|
module.exports.run = async (bot, message, args) => {
let xp = require("./xp.json");
let xpAdd = Math.floor(Math.random() * 7) + 8
console.log(xpAdd);
if(!xp[message.author.id]){
xp[message.author.id] = {
xp:0,
level:1
};
}
let curXp = xp[message.author.id].xp;
let curLvl = xp[message.author.id].level;
let nxtLvl = xp[message.author.id].level * 300;
xp[message.author.id].xp = curXp + xpAdd;
if(nxtLvl <= xp[message.author.id]){
xp[message.author.id].level = curLvl + 1;
}
fs.writeFile("./xp.json", JSON.stringify(xp), (err) => {
if (err) console.log(err)
});
}
module.exports.help = {
name: "level"
}
|
let T = {}
T.locale = null
T.locales = {}
// T.langCode=['zh', 'en']
// let index = 1
T.registerLocale = function (locales) {
T.locales = locales;
}
T.setLocale = function (code) {
T.locale = code
}
// T.setLocaleByIndex = function (index) {
// lastLangIndex = index;
// T.setLocale(T.langCode[index]);
// setTabBarLang(index);
// }
// T.getLanguage = function () {
// console.log(T.locales[T.locale])
// return T.locales[T.locale];
// }
let navigationBarTitles = [
"泛函科技",
'Fanhan Tech'
]
T.setNavigationBarTitle = function() {
wx.setNavigationBarTitle({
title: navigationBarTitles[index]
})
}
T._ = function (line, data) {
const locale = T.locale
const locales = T.locales
if (locale && locales[locale] && locales[locale][line]) {
line = locales[locale][line]
}
return line
}
// export default T
module.exports = {
T: T
}
|
$(function() {
Filterometry.Photo = Backbone.Model.extend({
idAttribute: 'id'
});
Filterometry.PhotoStrip = Backbone.Collection.extend({
model: Filterometry.Photo,
fetchNewItems: function () {
var that = this;
var id = 1944086551;
this.fetch({data: {'id': id},
success: function(resp) {
console.log(resp);
}
});
},
parse: function (resp) {
return resp.data;
},
url: '/api/photos'
});
Filterometry.Photos = new Filterometry.PhotoStrip();
Filterometry.PhotoView = Backbone.View.extend({
tagName: 'li',
className: 'photo',
template: _.template($('#filmstrip-template').html()),
initialize: function() {
this.model.bind('change', this.render, this);
this.model.bind('destroy', this.remove, this);
},
render: function() {
$(this.el).html(this.template(this.model.toJSON()));
this.setContent();
return this;
},
setContent: function() {
var url = this.model.get('images').standard_resolution.url;
this.$('a').css("background-image", "url(" + url + ")");
},
clear: function() {
this.model.destroy();
}
});
Filterometry.AppView = Backbone.View.extend({
el: $('#film'),
initialize: function() {
Filterometry.Photos.bind('add', this.addOne, this);
Filterometry.Photos.bind('all', this.render, this);
Filterometry.Photos.fetchNewItems();
},
addOne: function(photo) {
var view = new Filterometry.PhotoView({model: photo});
this.$('ul').append(view.render().el);
}
});
Filterometry.App = new Filterometry.AppView();
});
|
const path= require('path');
const express= require('express');
const socketIO= require('socket.io');
const http= require('http');
const moment= require ('moment');
const {Users}=require('./users');
const app= express(); //server side..(on cmd)
const port= process.env.PORT || 8000;
//defining path for public directory
const publicPath= path.join(__dirname, '../public');
app.use(express.static(publicPath));
//creating socket webserver
const server= http.createServer(app);
const io= socketIO(server);
const users= new Users();
io.on('connection',(socket)=> {
console.log('New user connected');
// when client is connected..it notifies server that new
// user is connected.(inside cmd)
let time= moment();
time.add(330, 'minutes');
socket.on('join', (params)=>{
socket.join(params.room);
users.removeUser(socket.id);
users.addUser(socket.id, params.name, params.room);
io.to(params.room).emit('updateUsersList', users.getUsersList(params.room));
socket.emit('newMessage',{
from:'Server',
text:`Welcome to chat app, ${params.name}`,
createdAt:moment(time).format('h:mm:ss a')
})
socket.broadcast.to(params.room).emit('newMessage',{
from:'Server',
text:`${params.name} joined group`,
createdAt:moment(time).format('h:mm:ss a')
})
})
socket.on('createMessage',(message)=> {
let time= moment();
time.add(330, 'minutes');
const user= users.getUser(socket.id);
console.log('createMessage', message);
io.to(user.room).emit('newMessage',{
from:message.from,
text:message.text,
createdAt:moment(time).format('h:mm:ss a')
})
})
socket.on('disconnect',()=> {
const user= users.removeUser(socket.id);
let time= moment();
time.add(330, 'minutes');
if(user){
console.log(`${user.name} disconnected`);
io.to(user.room).emit('updateUsersList', users.getUsersList(user.room));
socket.broadcast.to(user.room).emit('newMessage', {
from:'Server',
text:`${user.name} left group.`,
createdAt:moment(time).format('h:mm:ss a')
})
}
})
// when client is disconnected..it notifies server that
// user is disconnected.(inside cmd)
})
server.listen(port, ()=> {
console.log(`local server is started at ${port}`);
})
// socket.on('createLocationMessage',(message)=>{
// let time= moment();
// time.add(330, 'minutes');
//
// io.emit('newLocationMessage',{
// from:'Admin',
// url:`https://www.google.com/maps?q=${message.latitude},${message.longitude}`,
// createdAt:moment(time).format('h:mm:ss a')
//
// })
// })
|
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
* @jest-environment node
*/
runPlaceholderTests('ReactSuspensePlaceholder (mutation)', () =>
require('react-noop-renderer'),
);
runPlaceholderTests('ReactSuspensePlaceholder (persistence)', () =>
require('react-noop-renderer/persistent'),
);
function runPlaceholderTests(suiteLabel, loadReactNoop) {
let React;
let ReactTestRenderer;
let ReactFeatureFlags;
let ReactCache;
let Suspense;
let TextResource;
let textResourceShouldFail;
describe(suiteLabel, () => {
beforeEach(() => {
jest.resetModules();
ReactFeatureFlags = require('shared/ReactFeatureFlags');
ReactFeatureFlags.debugRenderPhaseSideEffectsForStrictMode = false;
ReactFeatureFlags.replayFailedUnitOfWorkWithInvokeGuardedCallback = false;
React = require('react');
ReactTestRenderer = require('react-test-renderer');
ReactCache = require('react-cache');
Suspense = React.Suspense;
TextResource = ReactCache.unstable_createResource(([text, ms = 0]) => {
let listeners = null;
let status = 'pending';
let value = null;
return {
then(resolve, reject) {
switch (status) {
case 'pending': {
if (listeners === null) {
listeners = [{resolve, reject}];
setTimeout(() => {
if (textResourceShouldFail) {
ReactTestRenderer.unstable_yield(
`Promise rejected [${text}]`,
);
status = 'rejected';
value = new Error('Failed to load: ' + text);
listeners.forEach(listener => listener.reject(value));
} else {
ReactTestRenderer.unstable_yield(
`Promise resolved [${text}]`,
);
status = 'resolved';
value = text;
listeners.forEach(listener => listener.resolve(value));
}
}, ms);
} else {
listeners.push({resolve, reject});
}
break;
}
case 'resolved': {
resolve(value);
break;
}
case 'rejected': {
reject(value);
break;
}
}
},
};
}, ([text, ms]) => text);
textResourceShouldFail = false;
});
function Text(props) {
ReactTestRenderer.unstable_yield(props.text);
return props.text;
}
function AsyncText(props) {
const text = props.text;
try {
TextResource.read([props.text, props.ms]);
ReactTestRenderer.unstable_yield(text);
return text;
} catch (promise) {
if (typeof promise.then === 'function') {
ReactTestRenderer.unstable_yield(`Suspend! [${text}]`);
} else {
ReactTestRenderer.unstable_yield(`Error! [${text}]`);
}
throw promise;
}
}
it('times out children that are already hidden', () => {
class HiddenText extends React.PureComponent {
render() {
const text = this.props.text;
ReactTestRenderer.unstable_yield(text);
return <span hidden={true}>{text}</span>;
}
}
function App(props) {
return (
<Suspense maxDuration={500} fallback={<Text text="Loading..." />}>
<HiddenText text="A" />
<span>
<AsyncText ms={1000} text={props.middleText} />
</span>
<span>
<Text text="C" />
</span>
</Suspense>
);
}
// Initial mount
const root = ReactTestRenderer.create(<App middleText="B" />, {
unstable_isConcurrent: true,
});
expect(root).toFlushAndYield(['A', 'Suspend! [B]', 'C', 'Loading...']);
expect(root).toMatchRenderedOutput(null);
jest.advanceTimersByTime(1000);
expect(ReactTestRenderer).toHaveYielded(['Promise resolved [B]']);
expect(root).toFlushAndYield(['A', 'B', 'C']);
expect(root).toMatchRenderedOutput(
<React.Fragment>
<span hidden={true}>A</span>
<span>B</span>
<span>C</span>
</React.Fragment>,
);
// Update
root.update(<App middleText="B2" />);
expect(root).toFlushAndYield(['Suspend! [B2]', 'C', 'Loading...']);
// Time out the update
jest.advanceTimersByTime(750);
expect(root).toFlushAndYield([]);
expect(root).toMatchRenderedOutput('Loading...');
// Resolve the promise
jest.advanceTimersByTime(1000);
expect(ReactTestRenderer).toHaveYielded(['Promise resolved [B2]']);
expect(root).toFlushAndYield(['B2', 'C']);
// Render the final update. A should still be hidden, because it was
// given a `hidden` prop.
expect(root).toMatchRenderedOutput(
<React.Fragment>
<span hidden={true}>A</span>
<span>B2</span>
<span>C</span>
</React.Fragment>,
);
});
it('times out text nodes', async () => {
function App(props) {
return (
<Suspense maxDuration={500} fallback={<Text text="Loading..." />}>
<Text text="A" />
<AsyncText ms={1000} text={props.middleText} />
<Text text="C" />
</Suspense>
);
}
// Initial mount
const root = ReactTestRenderer.create(<App middleText="B" />, {
unstable_isConcurrent: true,
});
expect(root).toFlushAndYield(['A', 'Suspend! [B]', 'C', 'Loading...']);
expect(root).toMatchRenderedOutput(null);
jest.advanceTimersByTime(1000);
expect(ReactTestRenderer).toHaveYielded(['Promise resolved [B]']);
expect(root).toFlushAndYield(['A', 'B', 'C']);
expect(root).toMatchRenderedOutput('ABC');
// Update
root.update(<App middleText="B2" />);
expect(root).toFlushAndYield(['A', 'Suspend! [B2]', 'C', 'Loading...']);
// Time out the update
jest.advanceTimersByTime(750);
expect(root).toFlushAndYield([]);
expect(root).toMatchRenderedOutput('Loading...');
// Resolve the promise
jest.advanceTimersByTime(1000);
expect(ReactTestRenderer).toHaveYielded(['Promise resolved [B2]']);
expect(root).toFlushAndYield(['A', 'B2', 'C']);
// Render the final update. A should still be hidden, because it was
// given a `hidden` prop.
expect(root).toMatchRenderedOutput('AB2C');
});
});
}
|
//per site tinyMCE_config
if(typeof($) === "undefined" && typeof(django.jQuery) != "undefined"){var $ = django.jQuery; var jQuery = $;}
if (typeof(site_mce_config) == 'undefined'){
var site_mce_config = {}
}
var extra_styles = site_mce_config.extra_styles || "Grey text=grey"; // TODO make configurable
var extra_classes = site_mce_config.extra_classes || "class<grey"; // TODO make configurable
var content_width = site_mce_config.content_width || 690; // TODO this should relate to site's content width to give accurate idea of line lengths
var table_controls = site_mce_config.table_controls || ", tablecontrols";
var extra_plugins = site_mce_config.extra_plugins || ", table";
var table_elements = site_mce_config.table_elements || ",table,tr,th,#td,thead,tbody";
function fix_banner() { //TODO this is specific to my admin CSS which has a position:fixed header
// Bigger offset if two toolbars are visible
if ($('.mceToolbarRow1:visible').length) {
if ($('.mceToolbarRow2:visible').length) {
offset = '153px';
} else {
offset = '123px';
}
} else {
offset = '88px';
}
$('#content').css('margin-top', offset);
}
function cleanup_html(element_id, html, body) {
html = html.replace(/<!--[\s\S]+?-->/gi,'');//remove Word comments like conditional comments etc
content = $(html)
content.find('a[href]').each(function(){
// remove empty links
// if there is nothing left after removing <br />, and whitespace characters then the a tag is empty
if ($(this).html().replace(/<br>/g,'').replace(/\s+/g,'').replace(/ /g,'')==''){
$(this).replaceWith($(this).html());
}
});
return $('<div>').append(content.clone()).html();
}
function CustomFileBrowser(field_name, url, type, win) {
var cmsURL = "/admin/filebrowser/browse/?pop=2&dir=images";
cmsURL = cmsURL + "&type=" + type;
tinyMCE.activeEditor.windowManager.open({
file: cmsURL,
width: 820, // Your dimensions may differ - toy around with them!
height: 500,
resizable: "yes",
scrollbars: "yes",
inline: "yes", // This parameter only has an effect if you use the inlinepopups plugin!
close_previous: "no"
}, {
window: win,
input: field_name,
editor_id: tinyMCE.selectedInstance.editorId
});
return false;
}
tinyMCE_config = {
mode : "none",
theme : "advanced",
skin : "thebigreason",
//skin_variant : "clean",
theme_advanced_resizing : true,
theme_advanced_resize_horizontal : false,
theme_advanced_path : false,
theme_advanced_statusbar_location : "bottom",
content_css : "/static/stylesheets/mcestyles.css?" + new Date().getTime(),
theme_advanced_styles : extra_styles,
theme_advanced_toolbar_location : "external",
theme_advanced_toolbar_align : "left",
theme_advanced_buttons1 : "formatselect,styleselect,removeformat,|,bold,italic,|,bullist,numlist,blockquote,|,undo,redo,|,link,unlink,anchor,|,image,fileBrowser,|,pdw_toggle",
theme_advanced_buttons2 : "charmap,hr,|,search,replace,|,code,visualchars,|"+table_controls,
theme_advanced_buttons3 : "",
theme_advanced_blockformats : "p,h2,h3",
width : content_width+18,
cleanup_on_startup : true,
convert_urls : false,
fix_list_elements : true,
fix_nesting : true,
fix_table_elements : true,
gecko_spellcheck : true,
use_native_selects: false,
external_image_list_url : "/admin/cms/imagelist.js",
external_link_list_url : "/admin/cms/linklist.js",
auto_cleanup_word : true,
//plugins : "inlinepopups, paste, searchreplace, advimagescale, visualchars, autoresize, pdw"+extra_plugins,
plugins : "inlinepopups, paste, searchreplace, advimagescale, visualchars, autoresize, noneditable, pdw"+extra_plugins,
valid_elements : ("-h2/h1[___],-h3/h4/h5[___],p[___],ul[___],-li,-ol,blockquote,br,-em/i,-strong/b,-span[!___],-div[!___],a[!name|!href|title|target],hr,img[src|class<left?right?center?floatleft?floatright|alt|title|height|width]"+table_elements).replace(/___/g, extra_classes),
paste_preprocess : function(pl, o) {
o.content = o.content.replace(/<!(?:--[\s\S]*?--\s*)?>\s*/g,'');
},
save_callback : cleanup_html,
// file_browser_callback: "CustomFileBrowser", //TODO
pdw_toggle_on : 1,
pdw_toggle_toolbars : "2",
setup : function(ed) {
ed.addButton('showWhitespace', {
title : 'Show Whitespace',
image : '/static/images/admin/show_whitespace.gif', // TODO make a proper icon
onclick : function() {
if (!tinyMCE.activeEditor.show_paragraphs) {
tinyMCE.activeEditor.dom.setStyle(tinyMCE.activeEditor.dom.select('p, h1, h2, h3, h4, ul, li, ol'), 'background-color', '#FFFFBB');
tinyMCE.activeEditor.dom.setStyle(tinyMCE.activeEditor.dom.select('p, h1, h2, h3, h4, ul, ol'), 'margin-bottom', '5px');
tinyMCE.activeEditor.dom.setStyle(tinyMCE.activeEditor.dom.select('a'), 'background-color', '#AAF');
tinyMCE.activeEditor.dom.setStyle(tinyMCE.activeEditor.dom.select('a'), 'border', '1px solid blue');
tinyMCE.activeEditor.dom.setStyle(tinyMCE.activeEditor.dom.select('a'), 'margin', '2px');
tinyMCE.activeEditor.dom.setStyle(tinyMCE.activeEditor.dom.select('a'), 'padding', '2px');
tinyMCE.activeEditor.show_paragraphs = true;
} else {
tinyMCE.activeEditor.dom.setStyle(tinyMCE.activeEditor.dom.select('p, h1, h2, h3, h4, ul, li, ol'), 'background-color', 'transparent');
tinyMCE.activeEditor.dom.setStyle(tinyMCE.activeEditor.dom.select('p, h1, h2, h3, h4, ul, ol'), 'margin-bottom', '0');
tinyMCE.activeEditor.dom.setStyle(tinyMCE.activeEditor.dom.select('a'), 'background-color', '#FFF');
tinyMCE.activeEditor.dom.setStyle(tinyMCE.activeEditor.dom.select('a'), 'border', 'none');
tinyMCE.activeEditor.dom.setStyle(tinyMCE.activeEditor.dom.select('a'), 'margin', '0');
tinyMCE.activeEditor.dom.setStyle(tinyMCE.activeEditor.dom.select('a'), 'padding', '0');
tinyMCE.activeEditor.show_paragraphs = false;
}
}
});
ed.addButton('fileBrowser', {
title : 'Open Filebrowser',
image : '/static/js/tiny_mce/themes/advanced/img/iframe.gif',
onclick : function() {
//window.open('/admin/filebrowser/browse/?pop=ixxy', 'Filebrowser', 'height=500,width=980,resizable=yes,scrollbars=yes');
//window.open('/admin/filebrowser/browse/?pop=tinymce', 'Filebrowser', 'height=500,width=980,resizable=yes,scrollbars=yes');
// if (!$('a#fancylink').length) {
// $('div:first').after('<a style="display: none" id="fancylink" class="iframe" href="/admin/filebrowser/browse/?pop=tinymce&dir=images"></a>');
// }
// $("a#fancylink")
// .fancybox({
// padding: 0,
// width: 820,
// height: 500,
// titleShow: false
// })
// .trigger("click");
tinyMCE.activeEditor.windowManager.open({
file: "/admin/filebrowser/browse/?pop=0",
//andyb mce filebrowser integration: file: "/admin/filebrowser/browse/?pop=2&ixxy=1&dir=images",
width: 820,
height: 500,
resizable: "yes",
scrollbars: "yes",
inline: "yes",
close_previous: "no"
}, {});
}
});
ed.onActivate.add(function(ed) {
fix_banner();
});
ed.onClick.add(function(ed) {
fix_banner();
});
ed.onPreInit.add(function(ed){
if(typeof(fontFaceCssTag) !== 'undefined') {
$(ed.contentDocument).find('head').append(fontFaceCssTag);
}
});
}
};
// Alternate config for HTML snippets
nonblocklevel_tinyMCE_config = $.extend(true, {}, tinyMCE_config);
nonblocklevel_tinyMCE_config['theme_advanced_blockformats'] = "p";
nonblocklevel_tinyMCE_config['theme_advanced_buttons1'] = "styleselect,removeformat,|,bold,italic,|,undo,redo,|,link,unlink,anchor,|,fileBrowser,|,pdw_toggle";
nonblocklevel_tinyMCE_config['theme_advanced_buttons2'] = "charmap,|,search,replace,|,code,showWhitespace,|";
nonblocklevel_tinyMCE_config['forced_root_block'] = '';
nonblocklevel_tinyMCE_config['force_br_newlines'] = true;
nonblocklevel_tinyMCE_config['force_p_newlines'] = false;
//per site tinyMCE_config
if (typeof(site_mce_config) != 'undefined'){
$.extend(tinyMCE_config, site_mce_config)
}
//Parse the per field conf parameter
//content = MCEField(blank=True, null=True, conf={'width':999})
function parseQuery ( query ) {
var Params = new Object ();
if ( ! query ) return Params; // return empty object
var Pairs = query.split(/[;&]/);
for ( var i = 0; i < Pairs.length; i++ ) {
var KeyVal = Pairs[i].split('=');
if ( ! KeyVal || KeyVal.length != 2 ) continue;
var key = unescape( KeyVal[0] );
var val = unescape( KeyVal[1] );
val = val.replace(/\+/g, ' ');
Params[key] = val;
}
return Params;
}
var scripts = document.getElementsByTagName('script');
var current_ccript = scripts[scripts.length - 1];
var query_string = current_ccript.src.replace(/^[^\?]+\??/,'');
var field_mce_conf = parseQuery(query_string);
for (attr in field_mce_conf){
tinyMCE_config[attr] = field_mce_conf[attr]
}
document.domain = document.domain.replace('www.', '').replace('static.', '');
tinyMCE.init(tinyMCE_config);
function process_inline_mce(){
$(".mce_fields").not('.empty-form .mce_fields').filter(':visible').not('[id*=__prefix__]').each(function(i) {
tinyMCE.execCommand("mceAddControl",true,this.id);
$(this).removeClass('mce_fields');
});
}
function mce_init(){
$(".mce_fields").not('.empty-form .mce_fields').not('.mce_inited').not('[id*=__prefix__]').each(function(i) {
tinyMCE.execCommand("mceAddControl",true,this.id);
$(this).removeClass('mce_fields').addClass('mce_inited');
});
$('.add-row').on('mouseup', 'a', function() {
setTimeout('process_inline_mce()', 200)
});
}
$(document).ready(function() {
mce_init()
});
|
import React from 'react'
const TopSearch = () => (
<div className="ui grid">
<div className="eight wide column">
<form className="ui form network-form" action="#" id="networkForm">
<div className="fields">
<div className="fourteen wide field">
<select className="ui fluid search dropdown" name="network">
<option value="">- Select Network for Analysis -</option>
<option value="steemit">SteemIt</option>
<option value="mastodon">Mastodon</option>
<option value="all">All</option>
</select>
</div>
<div className="two wide field">
<button type="submit" className="ui green button">Analyze</button>
</div>
</div>
</form>
</div>
</div>
)
export default TopSearch
|
__resources__["/explode.js"] = {meta: {mimetype: "application/javascript"}, data: function(exports, require, module, __filename, __dirname) {
var h = require("helper");
var m = require("model");
var p = require("particle")
var Particle = p.Particle;
var Emitter = p.Emitter;
var CircleModel = require("model").CircleModel;
var debug = require("debug");
var getSpacePstn = function(s)
{
var t = s.exec("getTransformSteps")[0];
debug.assert(!isNaN(t[1]) && typeof(t[1]) == "number" &&
!isNaN(t[2]) && typeof(t[2]) == "number", "logical error 1");
return {x:t[1], y:t[2]};
}
var setSpacePstn = function(s, x, y)
{
debug.assert(!isNaN(x) && typeof(x) == "number" &&
!isNaN(x) && typeof(x) == "number", "logical error 2" );
s.exec("translate", x, y);
}
function createExplode(createModel, duration, maxSpeed) {
emitterShape = CircleModel.create({
radius:5,
fill: "rgba(0, 255, 0, 0)", /*{r:255, g:0, b:0, a: 1},*/
//ratioAnchorPoint: {x: 0.5, y:0.5}
});
emitterShape = m.moveRelative(-0.5, -0.5, emitterShape);
particle = Particle.exec("clone", [],
{
updateDynamic: function (dt, owner, env)
{
var space = this.slot("space");
var pos = getSpacePstn(space);
var age = this.exec("age");
var life = this.exec("life");
var v = this.slot("velocity");
var radians = v.radians;
var speed = v.speed(age/life);
var vx = Math.cos(radians) * speed;
var vy = Math.sin(radians) * speed;
//var acceleration = this.slot("acceleration");
//var ax = acceleration.ax;
//var ay = acceleration.ay;
pos.x += vx*dt;
pos.y += vy*dt;
//pos.y = pos.y+dt*v.y+0.5*ay*dt*dt;
//pos.x = pos.x+dt*v.x+0.5*ax*dt*dt;
//alert([pos.x, pos.y, acceleration.ax, acceleration.ay]);
//space.position = pos;
setSpacePstn(space, pos.x, pos.y);
//v.x += ax*dt;
//v.y += ay*dt;
//this.slot("velocity", v);
//console.log(dt);
//console.log(v.x + "," + v.y + "," + ax*dt+ ","+ay*dt+","+dt);
var model = this.slot("model");
var fill = model.slot("fill");
// console.log(fill);
var strs = fill.split(",");
var rgba = "".concat(strs[0], ",", strs[1], ",", strs[2], ",", parseFloat((life-age)/life), ")");
//alert(rgba);
model.slot("fill", rgba);
//console.log(model.fill);
return true;
}
});
particle.exec("life", duration);
//particle.slot("model", createModel());
emitter = Emitter.exec("clone",
[],
{
initParticle: function (p, which, familyCount, env)
{
if(maxSpeed === undefined) {
maxSpeed = 300;
}
//var speed = 0 * (1 + Math.random());
//var a = 6000 * (1 + Math.random());
p.slot("model", createModel());
var radians = Math.random() * (2 * Math.PI);
//var x = Math.cos(radians) * speed;
//var ax = Math.cos(radians) * a;
//var y = Math.sin(radians) * speed;
//var ay = Math.sin(radians) * a;
//alert([which, familyCount]);
//alert([ax, ay]);
//particle.slot("velocity", {x: (Math.random() - 0.5) * 500, y: (Math.random() - 0.5) * 500});
var r = Math.random();
p.slot("velocity", {
radians: radians,
speed: function(x) {
var range = 1;
return Math.sin(Math.PI* ((1 - range) * 0.5 + x * range)) * (1 + r) * maxSpeed;
}});
//particle.slot("acceleration", {ax: ax, ay: ay});
//particle.slot("velocity", {x: x, y: y});
},
reset: function ()
{
this.execProto("reset");
var s = this.slot("space");
//s.position = {x: 0, y:0};
//setSpacePstn(s, 200, 200);
this.exec("life", duration);
return true;
}
});
var count = 15;
emitter.slot("particle", particle);
emitter.slot("bulletsPerShot", count);
emitter.slot("shotRate", 1);
emitter.exec("maxCount", count);
emitter.slot("model", emitterShape);
return emitter;
}
exports.createExplode = createExplode;
}};
|
/** @jsx React.DOM */
var React = require('react');
var AppActions = require('../actions/AppActions.jsx');
var AppStore = require('../stores/AppStore.jsx');
var getItemsFromStore = function () {
return {
items: AppStore.getItems()
};
}
var App = React.createClass({
getInitialState: function() {
return getItemsFromStore();
},
componentDidMount: function() {
AppStore.addChangeListener(this._onChange);
},
_onChange: function() {
this.setState(getItemsFromStore());
},
addNewItem: function() {
var newitem = this.refs.taskitem.getDOMNode().value.trim();
if(newitem.length !== 0) {
AppActions.addItem(newitem);
this.refs.taskitem.getDOMNode().value = '';
this.refs.taskitem.getDOMNode().focus();
}
else {
console.error('Please enter something. Input is empty');
}
},
removeItem: function(itemIndex) {
AppActions.removeItem(itemIndex);
},
render:function(){
return (
<div className="wrapper">
<input ref="taskitem" placeholder="Enter item" />
<button onClick={this.addNewItem}>Add task</button>
<div>
<ul>
{
this.state.items.map(function(item, i) {
var removeItemClick = this.removeItem.bind(this, i);
return (
<li key={item}>
<button onClick={removeItemClick}>
Remove task
</button>
{item}
</li>
)
}, this)
}
</ul>
</div>
</div>
)
}
});
module.exports = App;
|
let utils = require('./utils')
let webpack = require('webpack')
let config = require('../config')
let merge = require('webpack-merge')
let baseWebpackConfig = require('./webpack.base.conf')
let HtmlWebpackPlugin = require('html-webpack-plugin')
let FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
let VueLoaderPlugin = require('vue-loader/lib/plugin');
module.exports = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap })
},
// cheap-module-eval-source-map is faster for development
devtool: 'cheap-module-eval-source-map',
// add local server
devServer: {
contentBase: './dist',
hot: true,
},
plugins: [
new webpack.DefinePlugin({
'process.env': config.dev.env
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
}),
new FriendlyErrorsPlugin(),
new VueLoaderPlugin()
],
mode: 'development'
})
|
/* global G7 */
$(function() {
'use strict';
(function($, window, undefined) {
/**
* @name Utils
* @memberof G7
* @namespace Utils
* @description Utilities and Methods for the App
*/
G7.Utils = (function() {
/**
* @scope G7.Utils
* @description Exposed methods from the G7.Utils Module.
*/
return {
/**
* @name init
* @description G7.Utils Module Constructor.
*/
init: (function() {
})(),
/**
* @name getUrlParam
* @description Gets the selected param from the current URL.
* @param param
* @returns {*}
*/
getUrlParam: function(param) {
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++) {
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === param) {
return sParameterName[1];
}
}
}
};
}());
})(jQuery, window);
});
|
import React, { useEffect, useRef } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import {
BrowserRouter as Router,
Switch, Route, Link
} from 'react-router-dom';
import './App.css';
import Login from './components/Login';
import NameDisplay from './components/NameDisplay';
import BlogList from './components/BlogList';
import LogoutButton from './components/LogoutButton';
import AddBlogForm from './components/AddBlogForm';
import Notification from './components/Notification';
import Togglable from './components/Togglable';
import UserList from './components/UserList';
import UserDetails from './components/UserDetails';
import BlogDetails from './components/BlogDetails';
import loginService from './services/login';
import { initBlogs, createBlog, deleteBlog, likeBlog } from './reducers/blogReducer';
import { setNotificationMessage, clearNotificationMessage } from './reducers/notificationReducer';
import { setLoggedInUser, clearLoggedInUser } from './reducers/userReducer';
import Container from '@material-ui/core/Container';
import { Toolbar, Button, AppBar, Typography } from '@material-ui/core';
function App() {
const dispatch = useDispatch();
const blogs = useSelector(state => state.blogs);
const notification = useSelector(state => state.notification);
const user = useSelector(state => state.user);
const addBlogFormRef = useRef();
const showNotification = (msg, isError) => {
dispatch(setNotificationMessage({ msg, isError }));
setTimeout(function () {
dispatch(clearNotificationMessage());
}, 2000);
};
useEffect(() => {
async function tryGetUser() {
const maybeLoggedInUser = window.localStorage.getItem('loggedInUser');
if (maybeLoggedInUser) {
const storedUser = JSON.parse(maybeLoggedInUser);
dispatch(setLoggedInUser(storedUser));
dispatch(initBlogs(storedUser.token));
}
}
tryGetUser();
}, []);
const handleLogin = async (username, password) => {
try {
const loggedInUser = await loginService.login(username, password);
dispatch(setLoggedInUser(loggedInUser));
dispatch(initBlogs(loggedInUser.token));
window.localStorage.setItem('loggedInUser', JSON.stringify(loggedInUser));
} catch (err) {
showNotification('Incorrect username and/or password', true);
}
};
const handleLogout = () => {
window.localStorage.removeItem('loggedInUser');
dispatch(clearLoggedInUser(null));
};
const handleAddBlog = async (blog) => {
dispatch(createBlog(blog, user.token));
addBlogFormRef.current.toggleVisibility();
showNotification(`New blog added: ${blog.title} by ${blog.author}`, false);
};
const handleLike = async (blog) => {
dispatch(likeBlog(blog, user.token));
showNotification(`User ${user.name} liked blog ${blog.title}`, false);
};
const handleDelete = async (id) => {
if (window.confirm('Are you sure you want to delete this blog?')) {
dispatch(deleteBlog(id, user.token));
showNotification(`User ${user.name} deleted a blog`, false);
}
};
return (
<Container>
<Router>
{notification.msg && <Notification msg={notification.msg} isError={notification.isError} />}
<AppBar position="static">
<Toolbar>
<Button color="inherit" component={Link} to='/'>
Blogs
</Button>
<Button color="inherit" component={Link} to='/users/'>
Users
</Button>
<Typography style={{ 'margin-left': 'auto' }}>
{user && <NameDisplay fullName={user.name} />}
{user && <LogoutButton handleLogout={handleLogout} />}
</Typography>
</Toolbar>
</AppBar>
{!user && <Login handleLogin={handleLogin} />}
<Switch>
<Route path="/users/:id">
<UserDetails />
</Route>
<Route path="/users">
<UserList />
</Route>
<Route path="/blogs/:id">
<BlogDetails handleLike={handleLike} handleDelete={handleDelete} />
</Route>
<Route path="/">
<div>
{user && <BlogList blogs={blogs.sort((a, b) => { return a.likes > b.likes ? -1 : 1; })} />}
{user &&
<Togglable buttonLabel='new blog' ref={addBlogFormRef}>
<AddBlogForm handleAddBlog={handleAddBlog} />
</Togglable>}
</div>
</Route>
</Switch>
</Router>
</Container>
);
}
export default App;
|
const express = require('express');
const router = express.Router();
const { Posts, Likes,Comments,Users } = require("../models");
const { validateToken } = require("../middlewares/auth");
const multer = require("../middlewares/multer-config");
// recuperer tous les posts non signaller
router.get("/", validateToken, async (req, res) => {
const listOfPosts = await Posts.findAll({
attributes:['id','content','picture','usersLikes','createdAt'],
include: [
{
model: Users,
as:'author',
attributes: ['id','username','profile_picture']
},
{
model: Comments,
as: 'comments',
attributes: ['id','content',"user_id","createdAt"],
order:[
['createdAt','DESC']
],
include:[
{
model: Users,
as:'author',
attributes: ['id','username','profile_picture']
}
]
}
],
order:[
['createdAt','DESC']
],
}); //function qui go through the tables and generate the sql
res.json({ posts: listOfPosts});
});
// recuperer tous les posts signaler
router.get("/reported", validateToken, async (req, res) => {
const listOfPosts = await Posts.findAll({
attributes:['id','content','picture','usersLikes','createdAt'],
include: [
{
model: Users,
as:'author',
attributes: ['id','username','profile_picture']
},
{
model: Comments,
as: 'comments',
attributes: ['id','content',"user_id","createdAt"],
order:[
['createdAt','DESC']
],
include:[
{
model: Users,
as:'author',
attributes: ['id','username','profile_picture']
}
]
}
],
where:{postNotice:true},
order:[
['createdAt','DESC']
],
}); //function qui go through the tables and generate the sql
res.json({ posts: listOfPosts});
});
// recherche d'un post
router.get('/byId/:id', async (req, res) => {
const postId = req.params.id
const post = await Posts.findOne({
where:{id:postId},
include: [
{
model: Users,
as:'author',
attributes: ['id','username','profile_picture']
},
{
model: Comments,
as: 'comments',
attributes: ['id','content',"user_id"],
order:[
['createdAt','ASC']
],
include:[
{
model: Users,
as:'author',
attributes: ['id','username','profile_picture']
}
]
}
]
}) //(findByPk)=Pour dire a sequelize qu'on veut select un item specific, Pk=Primary key qu'on le trouve dans MySQL Table qu'on a créé
res.json(post);
});
// recherche des posts d'un utilisateur
router.get('/byuserId/:id', async (req, res) => {
const id = req.params.id
const listOfPosts = await Posts.findAll({
where: {user_id: id },
include: [
{
model: Users,
as:'author',
attributes: ['id','username','profile_picture']
},
{
model: Comments,
as: 'comments',
attributes: ['id','content',"user_id"],
include:[
{
model: Users,
as:'author',
attributes: ['id','username','profile_picture']
}
]
},
],
order:[
['createdAt','DESC']
],
});
res.json({posts:listOfPosts});
});
// creation d'un post
router.post("/", [validateToken,multer], async (req, res) => { //on met async/await pour etre sure que c'est entrer dans le database
const post = req.body;
let initial_likes = JSON.stringify([]) ; // on initialie le tableau vide
post.user_id = req.user.id;
post.picture = `images/${req.file.filename}`;
post.usersLikes = initial_likes ;
try{
let post_save = await Posts.create(post);
// je renvoie le post integrale avec les dependances
const postDetail = await Posts.findByPk(post_save.id,{
include: [
{
model: Users,
as:'author',
attributes: ['id','username','profile_picture']
},
{
model: Comments,
as: 'comments',
attributes: ['id','content',"user_id"],
include:[
{
model: Users,
as:'author',
attributes: ['id','username','profile_picture']
}
]
}
]
}) //(findByPk)=Pour dire a sequelize qu'on veut select un item specific, Pk=Primary key qu'on le trouve dans MySQL Table qu'on a créé
res.status(201).json({message:"post publier avec succes",post:postDetail});
}catch(error){
console.log(error)
res.status(500).json({message:"use erreur est survenue essayez plus tard"})
}
});
// supprimer un post
router.delete("/:postId", validateToken, async (req, res) => {
const postId = req.params.postId;
await Posts.destroy({
where: {
id: postId,
},
});
res.json({message:"post supprimer avec succes"});
});
// reporter un post
router.get("/report/:postId", validateToken, async (req, res) => {
const postId = req.params.postId;
await Posts.update( {postNotice: true}, {where: { id: postId},});
res.json({message:"post reporter avec succes"});
});
// like un post
router.post("/like/:postId",validateToken, async (req,res)=>{
// recuperer le post
let postId = req.params.postId
let opt = req.body.option
let userId = req.user.id ;
Posts.findOne({
where: { id: postId }
})
.then(post => {
if(post) {
if (opt == 1) {
let likes = JSON.parse(post.usersLikes)
if(!likes.includes(userId)) {
// si l'utilisateur pas encore liké
likes.push(userId) ;
likes = JSON.stringify(likes) ;
}
post.update({usersLikes:likes})
return res.status(200).json({ message: 'j\'aime',userId:userId,postId:postId});
}
else if (opt == -1 ) {
let likes = JSON.parse(post.usersLikes)
if(likes.includes(userId)) {
// si l'utilisateur a deja liké , on supprime
likes = likes.filter(item => item !=userId) ;
likes = JSON.stringify(likes) ;
}
post.update({ usersLikes:likes })
return res.status(200).json({ message: 'pas de préférence', userId:userId,postId:postId});
}
} else {
res.status(404).json({message:"pas de post"})
}
})
.catch(error => {
console.log(error)
res.status(500).json({ message: "une erreur est survenue , essayez plus tard" });
});
})
module.exports = router;
|
var users = [
{ id: 1, name: 'ID', age: 36 },
{ id: 2, name: 'BJ', age: 32 },
{ id: 3, name: 'JM', age: 32 },
{ id: 4, name: 'PJ', age: 27 },
{ id: 5, name: 'HA', age: 25 },
{ id: 6, name: 'JE', age: 26 },
{ id: 7, name: 'JI', age: 31 },
{ id: 8, name: 'MP', age: 23 },
]
// 1. 명령형 코드
// 1. 30세 이상인 users를 거른다.
var temp_users = [];
for (var i = 0; i < users.length; i++) {
if (users[i].age >= 30) {
temp_users.push(users[i]);
}
}
console.log(temp_users);
// 2. 30세 이상인 users의 names를 수집한다.
var names = [];
for (var i = 0; i < temp_users.length; i++) {
names.push(temp_users[i].name);
}
console.log(names);
// 3. 30세 미만인 users를 거른다.
var temp_users = [];
for (var i = 0; i < users.length; i++) {
if (users[i].age < 30) {
temp_users.push(users[i]);
}
}
console.log(temp_users);
// 4. 30세 미만인 users의 ages를 수집한다.
var ages = [];
for (var i = 0; i < temp_users.length; i++) {
names.push(temp_users[i].age);
}
console.log(ages);
// 2. _filter, _map으로 리팩토링.
function _filter(users, predi) {
// 인자를 조작하지 않고 필터링 된 새로운 값을 만든다
var new_list = [];
for (var i = 0; i < users.length; i++) {
// 함수에게 위임함
if (predi(users[i])) {
new_list.push(users[i]);
}
}
return new_list;
}
console.log(
_filter(users, function (user) { return user.age >= 30; })
)
console.log(
_filter(users, function (user) { return user.age < 30; })
)
console.log(
_filter([1, 2, 3, 4], function (num) { return num % 2; })
)
console.log(
_filter([1, 2, 3, 4], function (num) { return !(num % 2); })
)
var over_30 = _filter(users, function (user) { return user.age >= 30; });
var under_30 = _filter(users, function (user) { return user.age < 30; });
function _map(list, mapper) {
var new_list = [];
for (var i = 0; i < list.length; i++) {
new_list.push(mapper(list[i]));
}
return new_list;
}
var names = _map(over_30, function (user) {
return user.name;
});
var age = _map(under_30, function (user) {
return user.age;
});
console.log(names)
console.log(age)
_map(
_filter(users, function (user) { return user.age >= 30; }),
function (user) { return user.name; }
)
function _each(list, iter) {
for (var i = 0; i < list.length; i++) {
iter(list[i]);
}
return list;
}
// 개선된 버전
function _filter(users, predi) {
var new_list = [];
_each(list, function (val) {
new_list.push(predi(val));
})
return new_list;
}
function _map(list, mapper) {
var new_list = [];
_each(list, function (val) {
new_list.push(mapper(val));
})
return new_list;
}
[1, 2, 3].map(function (vale) {
return val * 2;
})
[1, 2, 3, 4].filter(function (vale) {
return val % 2;
})
// 커링
function _curry(fn) {
return function (a) {
return function (b) {
return fn(a, b);
}
}
}
// 일반적인 함수
var add = function (a, b) {
return a + b;
}
console.log(add(10, 5));
// _curry함수
var add = _curry(function (a, b) {
return a + b;
})
var add10 = add(10);
console.log(add10(5));
// 인자가 2개일 떄 _curry
function _curry(fn) {
return function (a, b) {
if (arguments.length == 2) return fn(a, b);
return function (b) {
return fn(a, b);
}
}
}
// 3항 연산자로 한단계 더 개선
function _curry(fn) {
return function (a, b) {
return arguments.length == 2 ?
fn(a, b) : function (b) { return fn(a, b); };
}
}
// 빼기
var sub = _curry(function (a, b) {
return a - b;
})
console.log(sub(10, 5));
var sub10 = sub(10);
console.log(sub10(5))
// curryr
function _curryr() {
return function (a, b) {
return arguments.length == 2 ? fn(a, b) : function (b) { return fn(b, a); };
}
}
function _get(obj, key) {
return obj == null ? undefined : obj[key];
}
var user1 = users[0];
console.log(user1.name);
console.log(_get(user1, 'name'));
var _get = _curryr(function (obj, key) {
return obj == null ? undefined : obj[key];
});
console.log(_get('name', user1));
// reduce
function _reduece(list, iter, memo) {
_each(list, function (val) {
memo = iter(memo, val);
})
return memo;
}
_reduece([1, 2, 3], function (a, b) {
return a + b;
}, 0)
// 3번째 인자를 생략
function _reduece(list, iter, memo) {
if (arguments.length == 2) {
memo = list[0];
list = list.slice(1);
}
_each(list, function (val) {
memo = iter(memo, val);
})
return memo;
}
//
var slice = Array.prototype.slice;
function _rest(list, num) {
return slice.call(list, num || 1);
}
function _reduece(list, iter, memo) {
if (arguments.length == 2) {
memo = list[0];
list = _rest(list);
}
_each(list, function (val) {
memo = iter(memo, val);
})
return memo;
}
// pipe
function _pipe() {
var fns = arguments;
return function (arg) {
return _reduece(fns, function (arg, fn) {
return fn(arg);
}, arg);
}
}
var f1 = _pipe(
function (a) { return a + 1 },
function (a) { return a * 2 },
function (a) { return a * a },
)
f1(1);
// go
function _go(arg) {
var fns = _rest(arguments);
return _pipe.apply(null, fns)(arg);
}
_go(1,
function (a) { return a + 1 },
function (a) { return a * 2 },
function (a) { return a * a },
console.log
)
// 다형성 높이기
// 이와 같은 상황에서는 에러가 발생
_each(null, console.log);
// get을 통해 null값을 처리해줌
var _length = _get('length');
function _each(list, iter) {
for (var i = 0, len = _length(list); i < len; i++) {
iter(list[i]);
}
return list;
}
// keys 만들기
|
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {boolean}
*/
var isSymmetric = function(root) {
if(!root)
return false;
if(!root.left && !root.right)
return true;
return root.left.data == root.right.data &&
mirror(root.left.left, root.right.right) &&
mirror(root.left.right, root.right.left);
};
var mirror = function(left, right){
if(!root.left && !root.right)
return true;
return left.data == right.data &&
mirror(left.left, right.right) &&
mirror(left.right, right.left);
}
|
"use strict"
//var setUpConnection = require('./utils/utils.js');
import setUpConnection from './utils/utils.js';
//var express = require('express');
import express from 'express';
//var cookieParser = require('cookie-parser');
import cookieParser from 'cookie-parser';
//var bodyParser = require('body-parser');
import bodyParser from 'body-parser';
//var session = require('express-session');
import session from 'express-session';
//var MongoStore = require('connect-mongo')(session);
import connectMongo from 'connect-mongo';
var MongoStore = connectMongo(session);
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
// APIs
var mongoose = require('mongoose');
var Books = require('./models/books.js');
var db = mongoose.connection;
db.on('error', console.error.bind(console, '# MongoDB - connection error: '));
setUpConnection(app.get('env'));
// --->> SETUP SESSION<<---
app.use(session({
secret: 'mySecretSessionWord',
saveUninitialized: false,
resave: false,
cookie: {maxAge: 1000*60*60*24*2},
store: new MongoStore({mongooseConnection: db, ttl: 60*60*24*2})
}))
// --->>END SETUP SESSION<<---
// --->>GET TO SESSION<<---
app.get('/cart', function(req, res){
if('undefined' !== typeof req.session.cart){
res.json(req.session.cart);
}else{
throw new Error('cart session not found');
}
});
// --->>END GET TO SESSION<<---
// --->>SAVE TO SESSION<<---
app.post('/cart', function(req, res){
var cart = req.body;
req.session.cart = cart;
req.session.save(function(err){
if(err){
throw err;
}
res.json(req.session.cart);
});
});
// --->>END SAVE TO SESSION<<---
// --->>GET BOOKS IMAGES API<<---
app.get('/images', function(req, res){
const imgFolder = __dirname + '/public/images/';
const fs = require('fs');
fs.readdir(imgFolder, function(err, files){
if(err){
throw err;
}
const filesArr = [];
files.map(function(file){
filesArr.push({name: file});
});
res.json(filesArr);
});
});
// --->>END GET BOOKS IMAGES API<<---
// --->>GET BOOKS<<---
app.get('/books', function(req, res){
var books = req.body;
Books.find(function(err, books){
if(err){
throw err;
}
res.json(books);
});
});
// --->>POST BOOKS<<---
app.post('/books', function(req, res){
var book = req.body;
Books.create(book, function(err, books){
if(err){
/*throw err;*/
console.log('# API Book posting ERROR - ', err);
}
res.json(books);
});
});
// --->>UPDATE BOOKS<<---
app.put('/books/:_id', function(req, res){
var query = {_id: req.params._id};
var book = req.body;
var update = {
'$set': {
title: book.title,
description: book.description,
image: book.image,
price: book.price
}
};
var options = {new: true};
Books.findOneAndUpdate(query, update, options, function(err, books){
if(err){
/*throw err;*/
console.log('# API Book updating ERROR - ', err);
}
res.json(books);
});
});
// --->>DELETE BOOKS<<---
app.delete('/books/:_id', function(req, res){
var query = {_id: req.params._id};
Books.remove(query, function(err, books){
if(err){
/*throw err;*/
console.log('# API Book deleting ERROR - ', err);
}
res.json(books);
});
});
// END APIs
app.listen(3001, function(err){
if(err){
return console.log(err);
}
console.log('API Sever is listening on http://localhost:3001');
});
|
import { useState } from 'react';
import { useSignIn } from 'react-auth-kit'
import axios from 'axios';
const SignIn = () => {
const signIn = useSignIn();
const [formData, setFormData] = useState({username: '', password: ''});
const onSubmit = async (e) => {
e.preventDefault();
try {
const res = await axios.post('http://localhost:8880/api/v1/auth', formData);
if (signIn({
token: res.data.bearer,
expiresIn:res.data.expSeconds,
tokenType: "Bearer",
authState: res.data.claims}))
{
console.log("User authenticated");
}
} catch (error) {
console.log(error.response.data.message);
}
}
return (
<form onSubmit={onSubmit}>
<p>
<input className="w-100" type={"text"} placeholder="Username" onChange={(e)=>setFormData({...formData, username: e.target.value})}/>
</p>
<p>
<input className="w-100"type={"password"} placeholder="Password" onChange={(e)=>setFormData({...formData, password: e.target.value})}/>
</p>
<p>
<button>Sign In</button>
</p>
</form>
);
};
export default SignIn;
|
import React from 'react';
import { FormGroup , Col,Row, ControlLabel} from 'react-bootstrap';
import DatePicker2 from 'react-bootstrap-datetimepicker';
let moment = require('moment');
export default class InputFecha extends React.Component{
constructor(){
super()
this.state={
min:moment(new Date()),
max:moment(new Date())
}
}
componentDidMount(){
this.refs.hasOwnProperty("data1") ? this.refs.data1.refs.datetimepicker.firstChild.disabled = true : null;
this.refs.hasOwnProperty("data2") ? this.refs.data2.refs.datetimepicker.firstChild.disabled = true : null;
}
changeDate1(e){
if(this.refs.hasOwnProperty("data2")){
this.setState({min:moment(parseInt(e,10))});
}
}
changeDate2(e){
this.setState({max:moment(parseInt(e,10))});
}
render(){
return(
<FormGroup controlId={this.props.id}>
<Col componentClass={ControlLabel} xs={12} sm={( typeof this.props.col == 'undefined' ? 2 : this.props.col.label)}>
{this.props.label}
</Col>
<Col xs={12} sm={( typeof this.props.col == 'undefined' ? 10 : this.props.col.input)}>
{(()=>{
if( typeof this.props.dual != 'undefined' && this.props.dual == "true"){
return <Row>
<Col xs={6}>
<DatePicker2 sm="sm" onChange={this.changeDate1.bind(this)} maxDate={this.state.max} ref="data1" mode="date" inputFormat={this.props.format} />
</Col>
<Col xs={6}>
<DatePicker2 sm="sm" onChange={this.changeDate2.bind(this)} minDate={this.state.min} ref="data2" mode="date" inputFormat={this.props.format} />
</Col>
</Row>
}else{
return <DatePicker2 ref="data1" mode="date" onChange={this.changeDate1.bind(this)} inputFormat={this.props.format}/>
}
})()}
</Col>
</FormGroup>
)
}
}
|
var user = {
name: "Spongebob Squarepants",
tweetCount: "50",
followerCount: "100",
followingCount: "120"
};
var discoverTweets = [
{
uname: "Patrick",
tweet: "Have you guys seen #TheWalkingDead finale yet?"
},
{
uname: "Squidward",
tweet: "#GossipGirl was great tonight"
},
{
uname: "Mr. Krabs",
tweet: "More money more problems #RIPBiggie"
}
];
function getUser(){
return user;
}
exports.getUser = getUser;
function getDiscoverTweets(){
return discoverTweets;
}
exports.getDiscoverTweets = getDiscoverTweets;
|
const scrapper = require('./scrapper.js');
(async () => {
const items = await scrapper.scrapItems('https://www.milanuncios.com/gatos-en-barcelona/adopcion.htm');
const filtered = items.filter(item => item !== undefined);
console.log('\n\n');
console.warn(JSON.stringify(filtered));
console.log('\n\n');
})();
|
App.HomeBooktabSingleitemRoute = Ember.Route.extend({
model: function(obj) {
var store = this.store;
return Ember.RSVP.hash({
bookingitem: store.find('bookingitem', obj.id), /// pass filter here to get correct data
booking: store.find('booking')/// pass filter here to get correct data ID HERE ONLY NEED BOOKINGS FOR THIS OBJECT
});
},
setupController: function(controller, models) {
controller.set("bookingitem", models.bookingitem);
// filter here for now. Should be moved to server !IMPORTANT
var filtered = models.booking.filter(function(item, index) {
for (var i = 0; i < models.bookingitem.get("bookings").length; i++) {
console.log(models.bookingitem.get("bookings").objectAt(i) + " = " + item.get("id"));
if (models.bookingitem.get("bookings").objectAt(i).toString() === item.get("id").toString()) {
return item;
}
}
});
controller.set("booking", filtered);
}
});
|
import React, { lazy, Suspense } from 'react';
import LoadElement from "../../UI/LoadElement/ImageLoadElement"
const LazyImage = lazy(() => import("./LazyImage"));
const LazyItem = (props) => {
return (<>
<Suspense fallback={<LoadElement />}>
<LazyImage src={props.src} alt={props.alt} />
</Suspense>
</>)
}
export default LazyItem;
|
/**
* Root Sagas
*/
import { all } from 'redux-saga/effects';
// sagas
import authSagas from './Auth';
import emailSagas from './Email';
import todoSagas from './Todo';
import feedbacksSagas from './Feedbacks';
export default function* rootSaga(getState) {
yield all([
authSagas(),
emailSagas(),
todoSagas(),
feedbacksSagas()
]);
}
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict
*/
import nodejsCustomInspectSymbol from './nodejsCustomInspectSymbol';
/**
* Used to print values in error messages.
*/
export default function inspect(value: mixed): string {
switch (typeof value) {
case 'string':
return JSON.stringify(value);
case 'function':
return value.name ? `[function ${value.name}]` : '[function]';
case 'object':
if (value) {
const customInspectFn = value[String(nodejsCustomInspectSymbol)];
if (typeof customInspectFn === 'function') {
return customInspectFn();
} else if (typeof value.inspect === 'function') {
return value.inspect();
} else if (Array.isArray(value)) {
return '[' + value.map(inspect).join(', ') + ']';
}
const properties = Object.keys(value)
.map(k => `${k}: ${inspect(value[k])}`)
.join(', ');
return properties ? '{ ' + properties + ' }' : '{}';
}
return String(value);
default:
return String(value);
}
}
|
//connecting to Sequelize
const Sequelize = require("sequelize");
// Option 1: Passing parameters separately
const sequelize = new Sequelize(
"heroku_3cead47d1b8797d",
"bb97fada1d29f8",
"7472d044",
{
host: "us-cdbr-iron-east-02.cleardb.net",
dialect: "mysql" /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */
}
);
//bb97fada1d29f8:7472d044@us-cdbr-iron-east-02.cleardb.net/heroku_3cead47d1b8797d?reconnect=true
//making sure connection works:
sequelize
.authenticate()
.then(() => {
// console.log("Connection has been established successfully.");
})
.catch(err => {
// console.error("Unable to connect to the database:", err);
});
const Burger = sequelize.define(
"burgers",
{
// attributes
burger_name: {
type: Sequelize.STRING,
allowNull: false
},
description: {
type: Sequelize.STRING
// allowNull defaults to true
},
devoured: {
type: Sequelize.BOOLEAN
// allowNull defaults to true
}
},
{
// options
}
);
Burger.sync({ force: true }).then(function(thing) {
// console.log("We managed to sync");
Burger.create({
burger_name: "Vegetarian",
description: "Product of Michael and Carla",
devoured: false
}).then(function(element) {
// console.log("The added row is: " + element);
});
Burger.create({
burger_name: "Classic",
description: "A burger like Grams used to make",
devoured: false
}).then(function(element) {
// console.log("The added row is: " + element);
});
Burger.create({
burger_name: "Baconator",
description: "The classic with bacon. Lots of bacon.",
devoured: false
}).then(function(element) {
// console.log("The added row is: " + element);
});
});
module.exports = {
Sequelize: Sequelize,
sequelize: sequelize,
Burger: Burger
};
|
const fs = require('fs');
const path = require('path');
const STATE_CONST = {
man: "чоловіча",
woman: "жіноча"
}
const AGE_CONST = {
stage1: "15-17",
stage2: "18-21",
stage3: "22-25",
stage4: "26-30",
stage5: "31-35",
stage6: "36-40",
stage7: "41-45",
stage8: "46-50"
}
const ALCOHOL_CONST = {
stage1: "alco 0",
stage2: "alco 0.2-0.5",
stage3: "alco 0.6-0.9",
stage4: "alco 1.0-1.5",
stage5: "alco 1.6-2.8"
}
const TIME_CONST = {
stage1: "ранок",
stage2: "обід",
stage3: "вечір",
stage4: "ніч"
}
const SEASON_CONST = {
summer: "літо",
autumn: "осінь",
winter: "зима",
spring: "весна",
}
const RESIDENCE = {
city: "місто",
village: "село"
}
const EDUCATION = {
hight: "вища",
medium: "середня",
low: "нижча"
}
const YEAR_RELEASE = {
stage1: "1-5",
stage2: "6-10",
stage3: "11-15",
stage4: "16-20"
}
const OWNER = {
stage1: "власник 1",
stage2: "власник 2",
stage3: "власник 3",
stage4: "власник 4+"
}
const COUNT_OF_PASSANGER = {
stage1: "пасажир 0",
stage2: "пасажири 1",
stage3: "пасажири 2",
stage4: "пасажири 3",
stage5: "пасажири 4",
stage6: "пасажири 4+",
}
const COLOR = {
white: "білий",
black: "чорний",
red: "червоний",
green: "зелений",
yellow: "жовтий",
}
fs.writeFile(path.join(__dirname, 'transactions.txt'), generate(), (err) => {
if (err) {
console.error(err.message);
}
});
function generate() {
const count = 1000000;
let result = "";
for (var i = 0; i < count; i++) {
result += `"${getState()}"`;
result += `"${getAge()}"`;
result += `"${getAlco()}"`;
result += `"${getTime()}"`;
result += `"${getColor()}"`;
result += `"${getEducation()}"`;
result += `"${getCountOfPassanger()}"`;
result += `"${getOwner()}"`;
result += `"${getYearRelease()}"`;
result += `"${getResidence()}"`;
result += `"${getSeason()}"\r\n`;
}
return result;
}
function getState() {
let number = Math.random() * 100;
if (number <= 65) {
return STATE_CONST.man;
} else {
return STATE_CONST.woman;
}
};
function getAge() {
let number = Math.random() * 100;
if (number <= 7) {
return AGE_CONST.stage1;
} else if (number <= 30) {
return AGE_CONST.stage2;
} else if (number <= 41) {
return AGE_CONST.stage3;
} else if (number <= 46) {
return AGE_CONST.stage4;
} else if (number <= 58) {
return AGE_CONST.stage5;
} else if (number <= 70) {
return AGE_CONST.stage6;
} else if (number <= 85) {
return AGE_CONST.stage7;
} else {
return AGE_CONST.stage8
}
}
function getAlco() {
let number = Math.random() * 100;
if (number <= 50) {
return ALCOHOL_CONST.stage5;
} else if (number <= 70) {
return ALCOHOL_CONST.stage4;
} else if (number <= 85) {
return ALCOHOL_CONST.stage3;
} else if (number <= 93) {
return ALCOHOL_CONST.stage2;
} else {
return ALCOHOL_CONST.stage1
}
}
function getTime() {
let number = Math.random() * 100;
if (number <= 30) {
return TIME_CONST.stage1;
} else if (number <= 60) {
return TIME_CONST.stage2;
} else if (number <= 80) {
return TIME_CONST.stage3;
} else {
return TIME_CONST.stage4
}
}
function getSeason() {
let number = Math.random() * 100;
if (number <= 42) {
return SEASON_CONST.winter;
} else if (number <= 55) {
return SEASON_CONST.summer;
} else if (number <= 80) {
return SEASON_CONST.autumn;
} else {
return SEASON_CONST.spring
}
}
function getResidence() {
let number = Math.random() * 100;
if (number <= 65) {
return RESIDENCE.city;
} else {
return RESIDENCE.village
}
}
function getEducation() {
let number = Math.random() * 100;
if (number <= 20) {
return EDUCATION.hight;
} else if (number <= 50) {
return EDUCATION.medium
} else {
return EDUCATION.low;
}
}
function getYearRelease() {
let number = Math.random() * 100;
if (number <= 15) {
return YEAR_RELEASE.stage1;
} else if (number <= 35) {
return YEAR_RELEASE.stage2;
} else if (number <= 70) {
return YEAR_RELEASE.stage3;
} else {
return YEAR_RELEASE.stage4;
}
}
function getColor() {
let number = Math.random() * 100;
if (number <= 40) {
return COLOR.black;
} else if (number <= 82) {
return COLOR.white;
} else if (number <= 88) {
return COLOR.red;
} else if (number <= 94) {
return COLOR.yellow;
} else {
return COLOR.green;
}
}
function getOwner() {
let number = Math.random() * 100;
if (number <= 20) {
return OWNER.stage1;
} else if (number <= 40) {
return OWNER.stage2;
} else if (number <= 70) {
return OWNER.stage3;
} else {
return OWNER.stage4;
}
}
function getCountOfPassanger() {
let number = Math.random() * 100;
if (number <= 30) {
return COUNT_OF_PASSANGER.stage1;
} else if (number <= 50) {
return COUNT_OF_PASSANGER.stage2;
} else if (number <= 60) {
return COUNT_OF_PASSANGER.stage3;
} else if (number <= 70) {
return COUNT_OF_PASSANGER.stage4;
} else if (number <= 85) {
return COUNT_OF_PASSANGER.stage5;
} else {
return COUNT_OF_PASSANGER.stage6;
}
}
|
import Configer from '../config/Configer';
import ShareUi from '../Gui/ShareUi';
class Share extends Phaser.State {
constructor () {
super();
}
init (obj) {
this.overlay = obj.overlay;
this.addMainBg();
this.resize();
this.hideOverlay();
}
create () {
this.shareModel = new ShareUi(this.game, this.world);
}
addMainBg () {
this.mainBg = this.game.add.image(0, 0, 'background', this.world);
}
resizeBg () {
this.mainBg.width = Configer.GAME_WIDTH + 1;
this.mainBg.height = Configer.GAME_HEIGHT + 1;
}
resize () {
this.resizeBg();
}
hideOverlay () {
this.hideLayTween = this.game.add.tween(this.overlay).to({
alpha: 0
}, 400, Phaser.Easing.Cubic.Out, !0);
this.hideLayTween.onComplete.addOnce(() => {
this.overlay.visible = !1;
});
}
}
export default Share;
|
// @flow
import React, { Component, Fragment } from "react";
import { connect } from "react-redux";
import {
type AsyncStatusType,
type NotificationType,
} from "shared/types/General";
import Loader from "components/loader";
import UpdateEmployeeForm from "./component/updateEmployeeForm";
import { ASYNC_STATUS } from "constants/async";
import { getEmployee, updateEmployee } from "action/employee";
import "./styles.scss";
type AdminUpdateEmployeePageProps = {
getEmployee: Function,
updateEmployee: Function,
status: AsyncStatusType,
notification: NotificationType,
employee: Object | null,
match: {
params: {
employeeId: number,
},
},
};
class AdminUpdateEmployeePage extends Component<AdminUpdateEmployeePageProps> {
componentDidMount() {
const {
match: {
params: { employeeId },
},
} = this.props;
this.props.getEmployee(employeeId);
}
render() {
const {
status,
notification,
updateEmployee,
employee,
match: {
params: { employeeId },
},
} = this.props;
if (status === ASYNC_STATUS.LOADING) {
return <Loader isLoading />;
}
return (
<Fragment>
{employee && employee.employeeId === employeeId && (
<UpdateEmployeeForm
notification={notification}
updateEmployee={updateEmployee}
employee={employee}
/>
)}
</Fragment>
);
}
}
function mapStateToProps(state) {
return {
status: state.employee.status,
notification: state.employee.notification,
employee: state.employee.employee,
};
}
const Actions = {
getEmployee,
updateEmployee,
};
export default connect(mapStateToProps, Actions)(AdminUpdateEmployeePage);
|
define(['jquery', 'underscore', 'backbone', 'fetchPolyfil'], function () {
var VehicleView = Backbone.View.extend({
tagName: 'li',
id: function () {
return 'vehicle-' + this.model.get('id');
},
events: {
'click .delete-btn': 'deleteElement',
'click .edit-btn': 'editElement'
},
isEdited: false,
initialize: function (data) {
//CALLBACK
//if (data && data.removeCallback) {
// this.removeCallback = data.removeCallback;
//}
if (data.eventPipe && data.eventPipe.trigger) {
this.eventPipe = data.eventPipe;
}
},
deleteElement: function () {
//CALLBACK
//this.removeCallback(this.model);
if (this.eventPipe) {
this.eventPipe.trigger('onRemove', this.model);
}
},
editElement: function () {
//POOR MANS UPDATE W/O BINDING
if (this.isEdited) {
this.model.set('name', this.$('.name-column')[0].innerText);
return this.model.save({}, {
success: function () {
this.isEdited = !this.isEdited;
this.render();
}.bind(this),
error: function (err) {
console.log(err);
}
})
}
this.isEdited = !this.isEdited;
this.render();
},
getTemplate: (function () {
var result;
return function getTemplate() {
if (result) {
var promise = new Promise(function (resolve, reject) {
setTimeout(function () {
if (result.error) {
return reject(result);
}
return resolve(result);
}, 0);
});
return promise;
}
return fetch('/templates/vehicleTemplate.html')
.then(function (data) {
if (data && data.text) {
return data.text();
}
})
.then(function (html) {
result = {
template: html
};
return result;
})
.catch(function (err) {
result = {
template: '',
error: err
}
});
}
})(),
render: function () {
this.getTemplate().then(function (result) {
var template = _.template(result.template);
var model = this.model.toJSON();
model.isEdited = this.isEdited;
var html = template(model);
this.$el.html(html);
}.bind(this));
return this;
}
});
return VehicleView;
});
|
function solve(input) {
let text = input.shift().split(' ');
for (let i = 0; i < input.length; i++) {
let tokens = input[i].split(' ');
let command = tokens[0];
if (command === 'Stop') {
break;
}else if (command === 'Swap') {
let firstWord = tokens[1];
let secondWord = tokens[2];
if (text.includes(firstWord) && text.includes(secondWord)) {
let indexOfFirstWord = getIndexOfWord(firstWord, text);
let indexOfSecondWord = getIndexOfWord(secondWord, text);
text[indexOfFirstWord] = secondWord;
text[indexOfSecondWord] = firstWord;
}
}else if (command === 'Delete') {
let indexToDelete = Number(tokens[1]) + 1;
if (isValidIndex(indexToDelete, text)) {
text.splice(indexToDelete, 1);
}
}else if (command === 'Replace'){
let firstWord = tokens[1];
let secondWord = tokens[2];
let secondWordIndex = getIndexOfWord(secondWord, text);
if (secondWordIndex > -1) {
text[secondWordIndex] = firstWord;
}
}else if (command === 'Put') {
let word = tokens[1];
let indexForNewWord = Number(tokens[2]) - 1;
if (indexForNewWord > 0 && indexForNewWord <= text.length) {
text.splice(indexForNewWord, 0, word);
}
}else if (command === 'Sort') {
text.sort((a, b) => b.localeCompare(a));
}
}
console.log(text.join(' '));
function getIndexOfWord(word, text) {
return text.indexOf(word);
}
function isValidIndex(index, arr){
return index >= 0 && index < arr.length;
}
}
solve(['Congratulations! You last also through the have challenge!',
'Swap have last',
'Replace made have',
'Delete 8',
'Put it 8',
'Stop']);
|
'use strict'
angular
.module('service.matter', [
'ngSanitize',
'ui.bootstrap',
'ui.tms',
'http.ui.xxt',
])
.provider('srvSite', function () {
var _siteId, _oSite, _aSns, _aMemberSchemas, _oTag
this.config = function (siteId) {
_siteId = siteId
}
this.$get = [
'$q',
'$uibModal',
'http2',
function ($q, $uibModal, http2) {
return {
getSiteId: function () {
return _siteId
},
getLoginUser: function () {
var defer, url
defer = $q.defer()
url = '/rest/pl/fe/user/get?_=' + new Date() * 1
http2.get(url).then(function (rsp) {
defer.resolve(rsp.data)
})
return defer.promise
},
get: function () {
var defer = $q.defer()
if (_oSite) {
defer.resolve(_oSite)
} else {
http2
.get('/rest/pl/fe/site/get?site=' + _siteId)
.then(function (rsp) {
_oSite = rsp.data
defer.resolve(_oSite)
})
}
return defer.promise
},
list: function () {
var defer = $q.defer()
http2.get('/rest/pl/fe/site/list').then(function (rsp) {
defer.resolve(rsp.data)
})
return defer.promise
},
update: function (prop) {
var oUpdated = {},
defer = $q.defer()
this.get().then(function (oSite) {
oUpdated[prop] = oSite[prop]
http2
.post('/rest/pl/fe/site/update?site=' + _siteId, oUpdated)
.then(function (rsp) {
defer.resolve(oSite)
})
})
return defer.promise
},
matterList: function (moduleTitle, site, page) {
if (!site) {
site = ''
} else {
site = site
}
if (!page) {
page = {
at: 1,
size: 10,
total: 0,
_j: function () {
return 'page=' + this.at + '&size=' + this.size
},
}
} else {
page.at++
}
var url,
title = moduleTitle,
defer = $q.defer()
switch (title) {
case 'subscribeSite':
url = '/rest/pl/fe/site/matterList'
break
case 'contributeSite':
url = '/rest/pl/fe/site/contribute/list'
break
case 'favorSite':
url = '/rest/pl/fe/site/favor/list'
break
}
url += '?' + page._j() + '&site=' + site
http2.get(url).then(function (rsp) {
page.total = rsp.data.total
defer.resolve({
matters: rsp.data.matters,
page: page,
})
})
return defer.promise
},
openGallery: function (options) {
var defer = $q.defer()
$uibModal
.open({
templateUrl: '/static/template/mattersgallery.html?_=1',
controller: [
'$scope',
'$http',
'$uibModalInstance',
function ($scope, $http, $mi) {
var fields = ['id', 'title']
$scope.filter = {}
$scope.matterTypes = options.matterTypes
$scope.singleMatter = options.singleMatter
$scope.p = {}
if ($scope.matterTypes && $scope.matterTypes.length) {
$scope.p.matterType = $scope.matterTypes[0]
}
if (options.mission) {
$scope.mission = options.mission
$scope.p.sameMission = 'Y'
$scope.p.onlySameMission =
options.onlySameMission || false
}
$scope.page = {
at: 1,
size: 10,
}
$scope.aChecked = []
$scope.doCheck = function (matter) {
if ($scope.singleMatter) {
$scope.aChecked = [matter]
} else {
var i = $scope.aChecked.indexOf(matter)
if (i === -1) {
$scope.aChecked.push(matter)
} else {
$scope.aChecked.splice(i, 1)
}
}
}
$scope.doSearch = function (pageAt) {
if (!$scope.p.matterType) return
var matter = $scope.p.matterType,
url = matter.url,
params = {}
pageAt && ($scope.page.at = pageAt)
params.byTitle = $scope.filter.byTitle
? $scope.filter.byTitle
: ''
/* 指定公共专题 */
if (matter.value === 'topic') {
url += '/enroll/' + matter.value + '/listPublicBySite'
} else {
url += '/' + matter.value + '/list'
}
url +=
'?site=' +
_siteId +
'&page=' +
$scope.page.at +
'&size=' +
$scope.page.size +
'&fields=' +
fields
/*指定记录活动场景*/
if (matter.value === 'enroll' && matter.scenario) {
url += '&scenario=' + matter.scenario
}
/*同一个项目*/
if ($scope.p.sameMission === 'Y') {
url += '&mission=' + $scope.mission.id
}
if ($scope.p.fromPlatform === 'Y') {
url += '&platform=Y'
}
$http.post(url, params).success(function (rsp) {
$scope.matters =
rsp.data.docs ||
rsp.data.apps ||
rsp.data.missions ||
rsp.data.topics
$scope.page.total = rsp.data.total
})
}
$scope.cleanFilter = function () {
$scope.filter.byTitle = ''
$scope.doSearch()
}
$scope.ok = function () {
$mi.close([
$scope.aChecked,
$scope.p.matterType
? $scope.p.matterType.value
: 'article',
])
}
$scope.cancel = function () {
$mi.dismiss('cancel')
}
$scope.createMatter = function () {
if ($scope.p.matterType.value === 'article') {
$http
.get(
'/rest/pl/fe/matter/article/create?site=' + _siteId
)
.success(function (rsp) {
$mi.close([[rsp.data], 'article'])
})
} else if ($scope.p.matterType.value === 'channel') {
$http
.get(
'/rest/pl/fe/matter/channel/create?site=' + _siteId
)
.success(function (rsp) {
$mi.close([[rsp.data], 'channel'])
})
}
}
$scope.$watch('p.matterType', function (nv) {
$scope.doSearch()
})
},
],
size: 'lg',
backdrop: 'static',
windowClass: 'auto-height mattersgallery',
})
.result.then(function (result) {
defer.resolve({
matters: result[0],
type: result[1],
})
})
return defer.promise
},
publicList: function () {
var defer = $q.defer()
http2.get('/rest/pl/fe/site/publicList').then(function (rsp) {
defer.resolve(rsp.data)
})
return defer.promise
},
friendList: function () {
var defer = $q.defer()
http2.get('/rest/pl/fe/site/friendList').then(function (rsp) {
defer.resolve(rsp.data)
})
return defer.promise
},
subscriberList: function (category, page) {
if (!page) {
page = {
at: 1,
size: 10,
total: 0,
_j: function () {
return 'page=' + this.at + '&size=' + this.size
},
}
} else {
page.at++
}
var defer = $q.defer()
http2
.get(
'/rest/pl/fe/site/subscriberList?site=' +
_siteId +
'&category=' +
category +
'&' +
page._j()
)
.then(function (rsp) {
page.total = rsp.data.total
defer.resolve({
subscribers: rsp.data.subscribers,
page: page,
})
})
return defer.promise
},
snsList: function (siteId) {
var defer = $q.defer()
if (!siteId && _aSns) {
defer.resolve(_aSns)
} else {
http2
.get('/rest/pl/fe/site/snsList?site=' + (siteId || _siteId))
.then(function (rsp) {
_aSns = rsp.data
if (_aSns) {
_aSns.names = Object.keys(_aSns)
_aSns.count = _aSns.names.length
} else {
_aSns = {
names: '',
count: 0,
}
}
defer.resolve(_aSns)
})
}
return defer.promise
},
tagList: function (subType) {
var subType = arguments[0] ? arguments[0] : 'M'
var defer = $q.defer()
if (_oTag) {
defer.resolve(_oTag)
} else {
http2
.get(
'/rest/pl/fe/matter/tag/listTags?site=' +
_siteId +
'&subType=' +
subType
)
.then(function (rsp) {
_oTag = rsp.data
defer.resolve(_oTag)
})
}
return defer.promise
},
memberSchemaList: function (oMatter, bOnlyMatter) {
var url,
defer = $q.defer()
if (_aMemberSchemas) {
defer.resolve(_aMemberSchemas)
} else {
url =
'/rest/pl/fe/site/member/schema/list?valid=Y&site=' + _siteId
if (oMatter && oMatter.id && oMatter.id !== '_pending') {
url += '&matter=' + oMatter.id + ',' + oMatter.type
if (bOnlyMatter) {
url += '&onlyMatter=Y'
}
}
http2.get(url).then(function (rsp) {
_aMemberSchemas = rsp.data
_aMemberSchemas.forEach(function (ms) {
var oSchema,
schemas = [],
schemasById = {},
mschemas = []
if (!ms.attrs.name.hide) {
oSchema = {
id: 'member.name',
title: '姓名',
type: 'shorttext',
format: 'name',
}
schemas.push(oSchema)
schemasById[oSchema.id] = oSchema
mschemas.push({
id: 'name',
title: '姓名',
type: 'address',
})
}
if (!ms.attrs.mobile.hide) {
oSchema = {
id: 'member.mobile',
title: '手机',
type: 'shorttext',
format: 'mobile',
}
schemas.push(oSchema)
schemasById[oSchema.id] = oSchema
mschemas.push({
id: 'mobile',
title: '手机',
type: 'address',
})
}
if (!ms.attrs.email.hide) {
oSchema = {
id: 'member.email',
title: '邮箱',
type: 'shorttext',
format: 'email',
}
schemas.push(oSchema)
schemasById[oSchema.id] = oSchema
mschemas.push({
id: 'email',
title: '邮箱',
type: 'address',
})
}
if (ms.extAttrs) {
ms.extAttrs.forEach(function (ea) {
var oSchema
oSchema = angular.copy(ea)
oSchema.id = 'member.extattr.' + oSchema.id
schemas.push(oSchema)
schemasById[oSchema.id] = oSchema
mschemas.push({
id: oSchema.id,
title: oSchema.title,
type: 'address',
})
})
}
ms._schemas = schemas
ms._schemasById = schemasById
ms._mschemas = mschemas
})
defer.resolve(_aMemberSchemas)
})
}
return defer.promise
},
chooseMschema: function (oMatter, $oMission) {
var _this = this
return $uibModal.open({
templateUrl:
'/views/default/pl/fe/_module/chooseMschema.html?_=1',
resolve: {
mschemas: function () {
if (oMatter && oMatter.id && oMatter.id !== '_pending') {
return _this.memberSchemaList(oMatter)
} else if ($oMission) {
return _this.memberSchemaList($oMission)
} else {
return _this.memberSchemaList()
}
},
},
controller: [
'$scope',
'$uibModalInstance',
'mschemas',
function ($scope2, $mi, mschemas) {
$scope2.mschemas = mschemas
$scope2.data = {}
if (mschemas.length) {
$scope2.data.chosen = mschemas[0]
}
$scope2.create = function () {
var url, proto, oNewSchema
url =
'/rest/pl/fe/site/member/schema/create?site=' + _siteId
proto = {
valid: 'Y',
}
if (oMatter && oMatter.id === '_pending') {
oNewSchema = {
id: '_pending',
title:
(oMatter.title
? oMatter.title + '-' + '通讯录'
: '通讯录') + '(待新建)',
}
mschemas.push(oNewSchema)
$scope2.data.chosen = oNewSchema
} else {
if (oMatter && oMatter.id) {
proto.matter_id = oMatter.id
proto.matter_type = oMatter.type
if (oMatter.title) {
proto.title = oMatter.title + '-' + '通讯录'
}
}
http2.post(url, proto).then(function (rsp) {
mschemas.push(rsp.data)
$scope2.data.chosen = rsp.data
})
}
}
$scope2.ok = function () {
$mi.close($scope2.data)
}
$scope2.cancel = function () {
$mi.dismiss()
}
},
],
backdrop: 'static',
}).result
},
}
},
]
})
.provider('srvTag', function () {
var _siteId
this.config = function (siteId) {
_siteId = siteId
}
this.$get = [
'$q',
'$uibModal',
'http2',
function ($q, $uibModal, http2) {
return {
_tagMatter: function (matter, oTags, subType) {
var oApp, oTags, tagsOfData, template, defer
defer = $q.defer()
oApp = matter
template = '<div class="modal-header">'
template += '<h5 class="modal-title">打标签 - {{tagTitle}}</h5>'
template += '</div>'
template += '<div class="modal-body">'
template +=
"<div class='list-group' style='max-height:300px;overflow-y:auto'>"
template +=
'<div class=\'list-group-item\' ng-repeat="tag in apptags">'
template += "<label class='checkbox-inline'>"
template +=
'<input type=\'checkbox\' ng-model="model.selected[$index]"> {{tag.title}}</label>'
template += '</div>'
template += '</div>'
template += "<div class='form-group'>"
template += "<div class='input-group'>"
template += '<input class=\'form-control\' ng-model="model.newtag">'
template += "<div class='input-group-btn'>"
template +=
'<button ng-disabled="model.newtag.length > 16" class=\'btn btn-default\' ng-click="createTag()" ><span class=\'glyphicon glyphicon-plus\'></span></button>'
template += '</div>'
template += '</div>'
template += '</div>'
template +=
'<div ng-show="model.newtag.length > 16" class=\'text-danger\'>标签最多支持16个字,已超过{{model.newtag.length - 16}}字</div>'
template += '</div>'
template += '<div class="modal-footer">'
template +=
'<button class="btn btn-default" ng-click="cancel()">关闭</button>'
template +=
'<button class="btn btn-primary" ng-click="ok()">设置标签</button>'
template += '</div>'
$uibModal.open({
template: template,
controller: [
'$scope',
'$uibModalInstance',
function ($scope2, $mi) {
var model
$scope2.apptags = oTags
if (subType === 'C') {
tagsOfData = oApp.matter_cont_tag
$scope2.tagTitle = '内容标签'
} else {
tagsOfData = oApp.matter_mg_tag
$scope2.tagTitle = '管理标签'
}
$scope2.model = model = {
selected: [],
}
if (tagsOfData) {
tagsOfData.forEach(function (oTag) {
var index
if (-1 !== (index = $scope2.apptags.indexOf(oTag))) {
model.selected[$scope2.apptags.indexOf(oTag)] = true
}
})
}
$scope2.createTag = function () {
var newTags
if ($scope2.model.newtag) {
newTags = $scope2.model.newtag.replace(/\s/, ',')
newTags = newTags.split(',')
http2
.post(
'/rest/pl/fe/matter/tag/create?site=' +
oApp.siteid +
'&subType=' +
subType,
newTags
)
.then(function (rsp) {
rsp.data.forEach(function (oNewTag) {
$scope2.apptags.push(oNewTag)
})
})
$scope2.model.newtag = ''
}
}
$scope2.cancel = function () {
$mi.dismiss()
defer.resolve()
}
$scope2.ok = function () {
var addMatterTag = []
model.selected.forEach(function (selected, index) {
if (selected) {
addMatterTag.push($scope2.apptags[index])
}
})
var url =
'/rest/pl/fe/matter/tag/add?site=' +
oApp.siteid +
'&resId=' +
oApp.id +
'&resType=' +
oApp.type +
'&subType=' +
subType
http2.post(url, addMatterTag).then(function (rsp) {
if (subType === 'C') {
matter.matter_cont_tag = addMatterTag
} else {
matter.matter_mg_tag = addMatterTag
}
})
$mi.close()
defer.resolve()
}
},
],
backdrop: 'static',
})
return defer.promise
},
}
},
]
})
.provider('srvQuickEntry', function () {
var siteId
this.setSiteId = function (id) {
siteId = id
}
this.$get = [
'$q',
'http2',
'noticebox',
function ($q, http2, noticebox) {
return {
get: function (taskUrl) {
var defer = $q.defer(),
url
url = '/rest/pl/fe/q/get?site=' + siteId
http2
.post(url, {
url: encodeURI(taskUrl),
})
.then(function (rsp) {
defer.resolve(rsp.data)
})
return defer.promise
},
add: function (taskUrl, title) {
var defer = $q.defer(),
url
url = '/rest/pl/fe/q/create?site=' + siteId
http2
.post(url, {
url: encodeURI(taskUrl),
title: title,
})
.then(function (rsp) {
defer.resolve(rsp.data)
})
return defer.promise
},
remove: function (taskUrl) {
var defer = $q.defer(),
url
url = '/rest/pl/fe/q/remove?site=' + siteId
http2
.post(url, {
url: encodeURI(taskUrl),
})
.then(function (rsp) {
defer.resolve(rsp.data)
})
return defer.promise
},
config: function (taskUrl, config) {
var defer = $q.defer(),
url
url = '/rest/pl/fe/q/config?site=' + siteId
http2
.post(url, {
url: encodeURI(taskUrl),
config: config,
})
.then(function (rsp) {
defer.resolve(rsp.data)
})
return defer.promise
},
update: function (code, data) {
var defer = $q.defer(),
url
url = '/rest/pl/fe/q/update?site=' + siteId + '&code=' + code
http2.post(url, data).then(function (rsp) {
defer.resolve(rsp.data)
})
return defer.promise
},
}
},
]
})
.provider('srvUserNotice', function () {
var _logs, _oPage
_logs = []
_oPage = {
at: 1,
size: 10,
j: function () {
return 'page=' + this.at + '&size=' + this.size
},
}
this.$get = [
'$q',
'http2',
function ($q, http2) {
return {
uncloseList: function () {
var defer = $q.defer(),
url
url = '/rest/pl/fe/user/notice/uncloseList?' + _oPage.j()
http2.get(url).then(function (rsp) {
_logs.splice(0, _logs.length)
rsp.data.logs.forEach(function (log) {
if (log.data) {
log._message = JSON.parse(log.data)
log._message = log._message.join('\n')
}
_logs.push(log)
})
_oPage.total = rsp.data.total
defer.resolve({
logs: _logs,
page: _oPage,
})
})
return defer.promise
},
closeNotice: function (log) {
var defer = $q.defer(),
url
url = '/rest/pl/fe/user/notice/close?id=' + log.id
http2.get(url).then(function (rsp) {
defer.resolve(rsp.data)
})
return defer.promise
},
}
},
]
})
.provider('srvTmplmsgNotice', function () {
this.$get = [
'$q',
'http2',
function ($q, http2) {
return {
init: function (sender, oPage, aBatches) {
this._sender = sender
// pagination
this._oPage = oPage
angular.extend(this._oPage, {
at: 1,
size: 30,
j: function () {
var p
p = '&page=' + this.at + '&size=' + this.size
return p
},
})
// records
this._aBatches = aBatches
},
list: function (_appId, page) {
var that = this,
defer = $q.defer(),
url
this._aBatches.splice(0, this._aBatches.length)
url =
'/rest/pl/fe/matter/tmplmsg/notice/list?sender=' +
this._sender +
this._oPage.j()
http2.get(url).then(function (rsp) {
that._oPage.total = rsp.data.total
rsp.data.batches.forEach(function (batch) {
that._aBatches.push(batch)
})
defer.resolve(that._aBatches)
})
return defer.promise
},
detail: function (batch) {
var defer = $q.defer(),
url
url = '/rest/pl/fe/matter/tmplmsg/notice/detail?batch=' + batch.id
http2.get(url).then(function (rsp) {
defer.resolve(rsp.data.logs)
})
return defer.promise
},
}
},
]
})
.controller('ctrlSetChannel', [
'$scope',
'http2',
'srvSite',
function ($scope, http2, srvSite) {
$scope.$on('channel.xxt.combox.done', function (event, aSelected) {
var i,
j,
existing,
aNewChannels = [],
relations = {},
matter = $scope.$parent[$scope.matterObj]
for (i in aSelected) {
existing = false
for (j in matter.channels) {
if (aSelected[i].id === matter.channels[j].id) {
existing = true
break
}
}
!existing && aNewChannels.push(aSelected[i])
}
relations.channels = aNewChannels
relations.matter = {
id: matter.id,
type: $scope.matterType,
}
http2
.post(
'/rest/pl/fe/matter/channel/addMatter?site=' + srvSite.getSiteId(),
relations
)
.then(function () {
matter.channels = matter.channels.concat(aNewChannels)
})
})
$scope.$on('channel.xxt.combox.link', function (event, clicked) {
location.href =
'/rest/pl/fe/matter/channel?site=' +
$scope.editing.siteid +
'&id=' +
clicked.id
})
$scope.$on('channel.xxt.combox.del', function (event, removed) {
var matter = $scope.$parent[$scope.matterObj],
param = {
id: matter.id,
type: $scope.matterType,
}
http2
.post(
'/rest/pl/fe/matter/channel/removeMatter?site=' +
srvSite.getSiteId() +
'&id=' +
removed.id,
param
)
.then(function (rsp) {
matter.channels.splice(matter.channels.indexOf(removed), 1)
})
})
http2
.get(
'/rest/pl/fe/matter/channel/list?site=' +
srvSite.getSiteId() +
'&cascade=N&page=1&size=999'
)
.then(function (rsp) {
$scope.channels = rsp.data.docs
})
},
])
.provider('srvInvite', function () {
var _matterType, _matterId
this.config = function (matterType, matterId) {
_matterType = matterType
_matterId = matterId
}
this.$get = [
'$q',
'http2',
function ($q, http2) {
return {
get: function () {
var defer = $q.defer(),
url
url =
'/rest/pl/fe/invite/get?matter=' + _matterType + ',' + _matterId
http2.get(url).then(function (rsp) {
defer.resolve(rsp.data)
})
return defer.promise
},
make: function () {
var defer = $q.defer(),
url
url =
'/rest/pl/fe/invite/create?matter=' +
_matterType +
',' +
_matterId
http2.get(url).then(function (rsp) {
defer.resolve(rsp.data)
})
return defer.promise
},
addCode: function (oInvite) {
var defer = $q.defer()
http2
.get('/rest/pl/fe/invite/code/add?invite=' + oInvite.id)
.then(function (rsp) {
defer.resolve(rsp.data)
})
return defer.promise
},
}
},
]
})
.provider('srvMemberPicker', function () {
this.$get = [
'$q',
'http2',
'$uibModal',
'noticebox',
function ($q, http2, $uibModal, noticebox) {
return {
open: function (oMatter, oMschema) {
var defer = $q.defer()
$uibModal
.open({
templateUrl: '/views/default/pl/fe/_module/memberPicker.html',
resolve: {
action: function () {
return {
label: '加入',
execute: function (members, schemas) {
var ids, defer
defer = $q.defer()
if (members.length) {
ids = []
members.forEach(function (oMember) {
oMember.checkedId =
oMatter.type == 'mschema'
? oMember.userid
: oMember.id
ids.push(oMember.checkedId)
})
schemas && schemas.length
? schemaUser(schemas, 0)
: matterUser()
}
function schemaUser(schemas, rounds) {
http2
.post(
'/rest/pl/fe/site/member/schema/importSchema?site=' +
oMatter.siteid +
'&id=' +
oMatter.id +
'&rounds=' +
rounds,
{
schemas: schemas,
users: ids,
}
)
.then(function (rsp) {
if (rsp.data.state !== 'end') {
var group = parseInt(rsp.data.group) + 1
noticebox.success(
'已导入用户' +
rsp.data.plan +
'/' +
rsp.data.total
)
schemaUser(schemas, group)
} else {
defer.resolve(rsp.data)
noticebox.success(
'已导入用户' +
rsp.data.plan +
'/' +
rsp.data.total
)
}
})
}
function matterUser() {
http2
.post(
'/rest/pl/fe/matter/group/record/addByApp?app=' +
oMatter.id,
ids
)
.then(function (rsp) {
noticebox.success(
'加入【' + rsp.data + '】个用户'
)
defer.resolve(rsp.data)
})
}
return defer.promise
},
}
},
},
controller: [
'$scope',
'$timeout',
'$uibModalInstance',
'http2',
'tmsSchema',
'action',
function (
$scope2,
$timeout,
$mi,
http2,
tmsSchema,
_oAction
) {
var _oPage, _oRows, _bAdded, _oMschema, doSearch
$scope2.tableReady = 'N'
$scope2.action = _oAction
$scope2.searchBys = []
oMschema.attr_name[0] == 0 &&
$scope2.searchBys.push({
n: '姓名',
v: 'name',
})
oMschema.attr_mobile[0] == 0 &&
$scope2.searchBys.push({
n: '手机号',
v: 'mobile',
})
oMschema.attr_email[0] == 0 &&
$scope2.searchBys.push({
n: '邮箱',
v: 'email',
})
$scope2.page = _oPage = {
at: 1,
size: 30,
keyword: '',
searchBy: $scope2.searchBys[0].v,
}
// 选中的记录
$scope2.rows = _oRows = {
schemas: {},
selected: {},
count: 0,
impschemaId: '',
change: function (index) {
this.selected[index] ? this.count++ : this.count--
},
reset: function () {
this.selected = {}
this.count = 0
},
}
function doSchemas() {
http2
.get(
'/rest/pl/fe/site/member/schema/listImportSchema?site=' +
oMschema.siteid +
'&id=' +
oMschema.id
)
.then(function (rsp) {
$scope2.importSchemas = rsp.data
_oRows.impschemaId = rsp.data[0].id
rsp.data.forEach(function (oSchema) {
_oRows.schemas[oSchema.id] = oSchema
})
doSearch(1)
})
}
$scope2.doSearch = doSearch = function (pageAt) {
let url, filter, selectedSchemaId
pageAt && (_oPage.at = pageAt)
filter = ''
selectedSchemaId = _oRows.impschemaId
? _oRows.impschemaId
: oMschema.id
$scope2.mschema = _oMschema =
oMatter.type == 'mschema'
? _oRows.schemas[selectedSchemaId]
: oMschema
if (_oPage.keyword !== '') {
filter = '&kw=' + _oPage.keyword
filter += '&by=' + _oPage.searchBy
}
url = `/rest/pl/fe/site/member/list?site=${oMschema.siteid}&schema=${selectedSchemaId}`
url += `&page=${_oPage.at}&size=${_oPage.size}${filter}&contain=total`
http2.get(url).then((rsp) => {
let members
members = rsp.data.members
if (members.length) {
if (_oMschema.extAttrs.length) {
members.forEach((oMember) => {
oMember._extattr =
tmsSchema.member.getExtattrsUIValue(
_oMschema.extAttrs,
oMember
)
})
}
}
$scope2.members = members
_oPage.total = rsp.data.total
_oRows.reset()
$timeout(() => ($scope2.tableReady = 'Y'), 500)
})
}
$scope2.cancel = function () {
_bAdded ? $mi.close() : $mi.dismiss()
}
$scope2.execute = function (bClose) {
var schemas, pickedMembers
if (_oRows.impschemaId) {
schemas = []
schemas.push(_oRows.impschemaId)
}
if (_oRows.count) {
pickedMembers = []
for (var i in _oRows.selected) {
pickedMembers.push($scope2.members[i])
}
_oAction
.execute(pickedMembers, schemas)
.then(function () {
if (bClose) {
$mi.close()
} else {
_bAdded = true
}
})
}
}
oMatter.type == 'mschema' ? doSchemas() : doSearch(1)
},
],
size: 'lg',
backdrop: 'static',
windowClass: 'auto-height mattersgallery',
})
.result.then(function () {
defer.resolve()
})
return defer.promise
},
}
},
]
})
/* 选取访客账号 */
.service('tkAccount', [
'$q',
'http2',
'$uibModal',
function ($q, http2, $uibModal) {
this.pick = function (oSite, oConfig) {
var defer = $q.defer()
http2
.post('/rest/script/time', {
html: {
picker: '/views/default/pl/fe/_module/accountPicker',
},
})
.then(function (oTemplateTimes) {
$uibModal
.open({
templateUrl:
'/views/default/pl/fe/_module/accountPicker.html?_=' +
oTemplateTimes.data.html.picker.time,
controller: [
'$scope',
'$uibModalInstance',
'http2',
function ($scope2, $mi, http2) {
var _oPage, _oRows, _fnSearch
$scope2.config = oConfig || {}
$scope2.page = _oPage = {
size: 30,
}
$scope2.rows = _oRows = {
change: function (index) {
this.selected[index] ? this.count++ : this.count--
},
reset: function () {
this.selected =
$scope2.config.single === true ? '-1' : {}
this.count = 0
},
}
_oRows.reset()
$scope2.doSearch = _fnSearch = function (pageAt) {
var url
pageAt && (_oPage.at = pageAt)
url =
'/rest/pl/fe/site/user/account/list?site=' + oSite.id
http2
.post(
url,
{},
{
page: _oPage,
}
)
.then(function (rsp) {
$scope2.users = rsp.data.users
})
}
$scope2.cancel = function () {
$mi.dismiss()
}
$scope2.execute = function () {
var pickedAccounts
if ($scope2.config.single === true) {
if (
_oRows.selected >= 0 &&
$scope2.users[_oRows.selected]
) {
$mi.close($scope2.users[_oRows.selected])
}
} else {
if (_oRows.count) {
pickedAccounts = []
for (var i in _oRows.selected) {
pickedAccounts.push($scope2.users[i])
}
}
$mi.close(pickedAccounts)
}
}
_fnSearch(1)
},
],
size: 'lg',
backdrop: 'static',
windowClass: 'auto-height',
})
.result.then(function (accounts) {
defer.resolve(accounts)
})
})
return defer.promise
}
},
])
/* 通讯录用户通用服务 */
.service('tkMember', [
'$q',
'http2',
'$uibModal',
function ($q, http2, $uibModal) {
this.create = function (oMschema, oProto) {
var defer = $q.defer()
http2
.post('/rest/script/time', {
html: {
editor: '/views/default/pl/fe/_module/memberEditor',
},
})
.then(function (oTemplateTimes) {
$uibModal
.open({
templateUrl:
'/views/default/pl/fe/_module/memberEditor.html?_=' +
oTemplateTimes.data.html.editor.time,
controller: [
'$uibModalInstance',
'$scope',
function ($mi, $scope2) {
$scope2.schema = oMschema
$scope2.member = oProto ? angular.copy(oProto) : {}
$scope2.close = function () {
$mi.dismiss()
}
$scope2.ok = function () {
http2
.post(
'/rest/pl/fe/site/member/create?schema=' +
oMschema.id,
$scope2.member
)
.then(function (rsp) {
$mi.close(rsp.data)
})
}
},
],
backdrop: 'static',
})
.result.then(function (oNewMember) {
defer.resolve(oNewMember)
})
})
return defer.promise
}
this.edit = function (oMschema, oMember) {
var defer = $q.defer()
http2
.post('/rest/script/time', {
html: {
editor: '/views/default/pl/fe/_module/memberEditor',
},
})
.then(function (oTemplateTimes) {
$uibModal
.open({
templateUrl:
'/views/default/pl/fe/_module/memberEditor.html?_=' +
oTemplateTimes.data.html.editor.time,
controller: [
'$uibModalInstance',
'$scope',
function ($mi, $scope2) {
$scope2.schema = oMschema
$scope2.member = angular.copy(oMember)
$scope2.close = function () {
$mi.dismiss()
}
$scope2.ok = function () {
$mi.close({
action: 'update',
data: $scope2.member,
})
}
$scope2.remove = function () {
$mi.close({
action: 'remove',
})
}
},
],
backdrop: 'static',
})
.result.then(function (rst) {
if (rst.action === 'update') {
var data = rst.data,
oUpdated = {
verified: data.verified,
name: data.name,
mobile: data.mobile,
email: data.email,
email_verified: data.email_verified,
extattr: data.extattr,
}
http2
.post(
'/rest/pl/fe/site/member/update?id=' + oMember.id,
oUpdated
)
.then(function (rsp) {
angular.extend(oMember, oUpdated)
defer.resolve({
action: 'update',
})
})
} else if (rst.action === 'remove') {
http2
.get('/rest/pl/fe/site/member/remove?id=' + oMember.id)
.then(function () {
defer.resolve({
action: 'remove',
})
})
}
})
})
return defer.promise
}
},
])
.controller('ctrlStat', [
'$scope',
'http2',
'noticebox',
function ($scope, http2, noticebox) {
var page, criteria, time1, time2, app
time1 = (function () {
var t
t = new Date()
t.setHours(8)
t.setMinutes(0)
t.setMilliseconds(0)
t.setSeconds(0)
t = parseInt(t / 1000)
return t
})()
time2 = (function () {
var t = new Date()
t = new Date(t.setDate(t.getDate() + 1))
t.setHours(8)
t.setMinutes(0)
t.setMilliseconds(0)
t.setSeconds(0)
t = parseInt(t / 1000)
return t
})()
$scope.page = page = {
at: 1,
size: 30,
_j: function () {
return '&page=' + this.at + '&size=' + this.size
},
}
$scope.criteria = criteria = {
startAt: '',
endAt: '',
byEvent: '',
}
$scope.events = [
{
id: 'read',
value: '阅读',
},
{
id: 'shareT',
value: '分享',
},
{
id: 'shareF',
value: '转发',
},
]
$scope.operation = {
read: '阅读',
shareT: '分享',
shareF: '转发',
}
$scope.list = function () {
var url
url =
`/rest/pl/fe/matter/${app.type}/log/matterActionLog?site=${app.siteid}&appId=${app.id}` +
page._j()
http2.post(url, criteria).then(function (rsp) {
$scope.logs = rsp.data.logs
page.total = rsp.data.total
})
}
$scope.renewNickname = function () {
if (app.type === 'link') {
let url = `/rest/pl/fe/matter/link/log/renewNickname?&appId=${app.id}`
http2.post(url, criteria).then((rsp) => {
noticebox.success(`完成【${rsp.data.length}】个用户数据更新`)
$scope.list()
})
}
}
$scope.export = function () {
let url = `/rest/pl/fe/matter/${app.type}/log/exportMatterActionLog?site=${app.siteid}&appId=${app.id}`
url += `&startAt=${criteria.startAt}&endAt=${criteria.endAt}&byEvent=${criteria.byEvent}`
window.open(url)
}
$scope.$watch('editing', function (nv) {
if (!nv) return
app = nv
criteria.startAt = time1
criteria.endAt = time2
$scope.list()
})
},
])
/**
* 轮次生成规则
*/
.service('tkRoundCron', [
'$rootScope',
'$q',
'$uibModal',
'http2',
function ($rootScope, $q, $uibModal, http2) {
var _aCronRules, _$scope
this.editing = {
modified: false,
}
this.mdays = []
while (this.mdays.length < 28) {
this.mdays.push('' + (this.mdays.length + 1))
}
this.init = function (oMatter) {
this.matter = oMatter
this.editing.rules = _aCronRules = oMatter.roundCron
? angular.copy(oMatter.roundCron)
: []
_$scope = $rootScope.$new(true)
_$scope.editing = this.editing
_$scope.$on('xxt.tms-datepicker.change', function (event, oData) {
oData.obj[oData.state] = oData.value
})
_$scope.$watch(
'editing.rules',
function (newRules, oldRules) {
if (newRules !== oldRules) {
_$scope.editing.modified = true
}
},
true
)
return this
}
this.example = function (oRule) {
http2
.post('/rest/pl/fe/matter/' + this.matter.type + '/round/getCron', {
roundCron: oRule,
})
.then(function (rsp) {
oRule.case = rsp.data
})
}
this.addPeriod = function () {
var oNewRule
oNewRule = {
purpose: 'C',
pattern: 'period',
period: 'D',
hour: '8',
notweekend: true,
enabled: 'N',
}
_aCronRules.push(oNewRule)
}
this.changePeriod = function (oRule) {
switch (oRule.period) {
case 'W':
!oRule.wday && (oRule.wday = '1')
break
case 'M':
!oRule.mday && (oRule.mday = '1')
break
}
!oRule.hour && (oRule.hour = '8')
}
this.addInterval = function () {
var oNewRule
var now = new Date()
now.setMinutes(0, 0)
oNewRule = {
purpose: 'C',
pattern: 'interval',
start_at: parseInt((now * 1) / 1000),
enabled: 'N',
}
_aCronRules.push(oNewRule)
}
this.removeRule = function (oRule) {
_aCronRules.splice(_aCronRules.indexOf(oRule), 1)
}
this.choose = function (oMatter) {
var defer = $q.defer()
http2
.post('/rest/script/time', {
html: {
picker: '/views/default/pl/fe/_module/chooseRoundCron',
},
})
.then(function (oTemplateTimes) {
$uibModal
.open({
templateUrl:
'/views/default/pl/fe/_module/chooseRoundCron.html?_=' +
oTemplateTimes.data.html.picker.time,
controller: [
'$uibModalInstance',
'$scope',
function ($mi, $scope2) {
$scope2.roundCron = oMatter.roundCron
$scope2.data = {}
$scope2.cancel = function () {
$mi.dismiss()
}
$scope2.ok = function () {
$mi.close($scope2.data.chosen)
}
},
],
backdrop: 'static',
})
.result.then(function (oRule) {
if (oRule) defer.resolve(oRule)
})
})
return defer.promise
}
},
])
/**
* 定时通知
*/
.service('srvTimerNotice', [
'$rootScope',
'$parse',
'$q',
'$timeout',
'http2',
'tkRoundCron',
function ($rootScope, $parse, $q, $timeout, http2, tkRoundCron) {
function fnDbToLocal(oDb, oLocal) {
;[
'pattern',
'task_expire_at',
'task_model',
'enabled',
'notweekend',
'offset_matter_type',
'offset_matter_id',
'offset_mode',
].forEach(function (prop) {
oLocal.task[prop] = oDb[prop]
})
;[
'min',
'hour',
'wday',
'mday',
'mon',
'offset_min',
'offset_hour',
].forEach(function (prop) {
oLocal.task[prop] = '' + oDb[prop]
})
oLocal.task.task_arguments = oDb.task_arguments
? oDb.task_arguments
: {
page: '',
}
if (oDb.name !== undefined) oLocal.name = oDb.name
}
function fnAppendLocal(oDbTimer, oMatter) {
var oLocalTimer
oLocalTimer = {
id: oDbTimer.id,
task: {},
}
if (oMatter) {
oLocalTimer.matter = oMatter
/* 参照轮次规则 */
if (
oDbTimer.offset_matter_type === 'RC' &&
oDbTimer.offset_matter_id
) {
if (oMatter.roundCron && oMatter.roundCron.length) {
for (var i = 0, ii = oMatter.roundCron.length; i < ii; i++) {
if (oMatter.roundCron[i].id === oDbTimer.offset_matter_id) {
$parse('surface.offset.matter').assign(oLocalTimer, {
name: oMatter.roundCron[i].name,
})
break
}
}
}
}
}
fnDbToLocal(oDbTimer, oLocalTimer)
oWatcher['t_' + oLocalTimer.id] = oLocalTimer
$scope.$watch(
'watcher.t_' + oLocalTimer.id,
function (oUpdTask, oOldTask) {
if (oUpdTask && oUpdTask.task) {
if (!angular.equals(oUpdTask.task, oOldTask.task)) {
oUpdTask.modified = true
if (
oUpdTask.task.offset_matter_type !==
oOldTask.task.offset_matter_type
) {
switch (oUpdTask.task.offset_matter_type) {
case 'RC':
!oUpdTask.task.offset_mode &&
(oUpdTask.task.offset_mode = 'AS')
oUpdTask.task.offset_hour = '0'
oUpdTask.task.offset_min = '0'
break
}
}
}
}
},
true
)
return oLocalTimer
}
var $scope, oWatcher // 监控数据的变化情况
$scope = $rootScope.$new(true)
$scope.watcher = oWatcher = {}
var fnBeforeSaves = [] // 保存数据前进行处理
/* 添加定时任务 */
this.add = function (oMatter, timers, model, oArgs, oTimerProto) {
var oConfig, defer
oConfig = {
matter: {
id: oMatter.id,
type: oMatter.type,
},
task: {
model: model,
},
}
defer = $q.defer()
oArgs && (oConfig.task.arguments = oArgs)
oTimerProto && (oConfig.timer = oTimerProto)
http2
.post('/rest/pl/fe/matter/timer/create', oConfig)
.then(function (rsp) {
var oNewTimer
oNewTimer = fnAppendLocal(rsp.data, oMatter)
timers && angular.isArray(timers) && timers.push(oNewTimer)
defer.resolve(oNewTimer)
})
return defer.promise
}
/* 保存定时任务设置 */
this.save = function (oTimer) {
function fnOne(i) {
if (i < fnBeforeSaves.length) {
fnBeforeSaves[i](oTimer).then(function () {
fnOne(++i)
})
} else {
http2
.post(
'/rest/pl/fe/matter/timer/update?id=' + oTimer.id,
oTimer.task
)
.then(function (rsp) {
fnDbToLocal(rsp.data, oTimer)
oTimer.modified = false
})
}
}
if (fnBeforeSaves.length) {
fnOne(0)
} else {
http2
.post(
'/rest/pl/fe/matter/timer/update?id=' + oTimer.id,
oTimer.task
)
.then(function (rsp) {
fnDbToLocal(rsp.data, oTimer)
$timeout(function () {
oTimer.modified = false
})
})
}
}
/* 保存前进行处理 */
this.onBeforeSave = function (fnHandler) {
fnBeforeSaves.push(fnHandler)
}
/* 删除定时任务 */
this.del = function (timers, index) {
var oTimer
if (window.confirm('确定删除定时规则?')) {
oTimer = timers[index]
http2
.get('/rest/pl/fe/matter/timer/remove?id=' + oTimer.id)
.then(function (rsp) {
timers.splice(index, 1)
})
}
}
this.update = function (oTimer) {
var defer = $q.defer()
http2
.post('/rest/pl/fe/matter/timer/update?id=' + oTimer.id, oTimer.task)
.then(function (rsp) {
defer.resolve()
})
return defer.promise
}
this.remove = function (oTimer, bJumpConfirm) {
var defer = $q.defer()
if (bJumpConfirm || window.confirm('确定删除定时规则?')) {
http2
.get('/rest/pl/fe/matter/timer/remove?id=' + oTimer.id)
.then(function (rsp) {
defer.resolve()
})
}
return defer.promise
}
/* 设置偏移的素材 */
this.setOffsetMatter = function (oTimer) {
if (oTimer.task.offset_matter_type === 'RC') {
tkRoundCron.choose(oTimer.matter).then(function (oRule) {
oTimer.task.offset_matter_id = oRule.id
$parse('surface.offset.matter').assign(oTimer, {
name: oRule.name,
})
})
}
}
/* 根据id获得定时任务 */
this.timerById = function (id) {
return oWatcher[id]
}
/* 定时任务列表 */
this.list = function (oMatter, model, taskArguments) {
var defer = $q.defer(),
oPosted = {}
taskArguments && (oPosted.taskArguments = taskArguments)
http2
.post(
'/rest/pl/fe/matter/timer/byMatter?type=' +
oMatter.type +
'&id=' +
oMatter.id +
'&model=' +
model,
oPosted
)
.then(function (rsp) {
var timers = []
rsp.data.forEach(function (oTask) {
var oNewTimer
oNewTimer = fnAppendLocal(oTask, oMatter)
timers.push(oNewTimer)
})
defer.resolve(timers)
})
return defer.promise
}
},
])
/**
* data schema
*/
.service('tkDataSchema', [
'$q',
'$uibModal',
'http2',
function ($q, $uibModal, http2) {
this.toObject = function (schemas, fnFilter, bOnlyFirst) {
if (!schemas || schemas.length === 0) {
return false
}
var oSchema, oResult
oResult = {
length: 0,
array: [],
}
for (var i = schemas.length - 1; i >= 0; i--) {
oSchema = schemas[i]
if (!fnFilter || fnFilter(oSchema)) {
oResult[oSchema.id] = oSchema
oResult.length++
oResult.array.push(oSchema)
if (bOnlyFirst) break
}
}
return oResult
}
},
])
/**
* enroll
*/
.service('tkEnrollApp', [
'$q',
'$uibModal',
'http2',
function ($q, $uibModal, http2) {
function _fnMakeApiUrl(oApp, action) {
var url
url =
'/rest/pl/fe/matter/enroll/' +
action +
'?site=' +
oApp.siteid +
'&app=' +
oApp.id
return url
}
this.get = function (id) {
var defer = $q.defer()
http2
.get('/rest/pl/fe/matter/enroll/get?app=' + id)
.then(function (rsp) {
defer.resolve(rsp.data)
})
return defer.promise
}
this.update = function (oApp, oModifiedData) {
var defer = $q.defer()
http2
.post(_fnMakeApiUrl(oApp, 'update'), oModifiedData)
.then(function (rsp) {
defer.resolve(rsp.data)
})
return defer.promise
}
this.choose = function (oApp, oOptions) {
var defer
defer = $q.defer()
http2
.post('/rest/script/time', {
html: {
enrollApp: '/views/default/pl/fe/_module/chooseEnrollApp',
},
})
.then(function (rsp) {
return $uibModal
.open({
templateUrl:
'/views/default/pl/fe/_module/chooseEnrollApp.html?_=' +
rsp.data.html.enrollApp.time,
controller: [
'$scope',
'$uibModalInstance',
'http2',
function ($scope2, $mi, http2) {
var _oResult, _oPage
$scope2.app = oApp
$scope2.result = _oResult = {}
$scope2.page = _oPage = {}
oApp.mission && ($scope2.result.sameMission = 'Y')
$scope2.doSearch = function () {
var url
url = '/rest/pl/fe/matter/enroll/list'
if (oApp.mission && _oResult.sameMission === 'Y')
url += '?mission=' + oApp.mission.id
http2
.post(
url,
{
byTitle: _oResult.title,
},
{
page: _oPage,
}
)
.then(function (rsp) {
$scope2.apps = rsp.data.apps
if ($scope2.apps.length)
_oResult.app = $scope2.apps[0]
})
}
$scope2.cancel = function () {
$mi.dismiss()
}
$scope2.ok = function () {
if (_oResult.app) $mi.close(_oResult.app)
}
$scope2.doSearch()
},
],
backdrop: 'static',
})
.result.then(function (oApp) {
defer.resolve(oApp)
})
})
return defer.promise
}
},
])
/**
* group app
*/
.service('tkGroupApp', [
'$q',
'$uibModal',
'http2',
function ($q, $uibModal, http2) {
this.choose = function (oMatter, bMultiple) {
var defer
defer = $q.defer()
http2
.post('/rest/script/time', {
html: {
groupApp:
'/views/default/pl/fe/matter/enroll/component/chooseGroupApp.html',
},
})
.then(function (rsp) {
return $uibModal
.open({
templateUrl:
'/views/default/pl/fe/matter/enroll/component/chooseGroupApp.html?_=' +
rsp.data.html.groupApp.time,
controller: [
'$scope',
'$uibModalInstance',
function ($scope2, $mi) {
var _oData, _oTeamsById
$scope2.app = oMatter
$scope2.data = _oData = {
app: null,
}
$scope2.multiple = !!bMultiple
if (bMultiple) _oData.teams = []
else _oData.team = null
oMatter.mission && (_oData.sameMission = 'Y')
$scope2.cancel = function () {
$mi.dismiss()
}
$scope2.ok = function () {
if (bMultiple && _oData.teams.length) {
var teams = []
_oData.teams.forEach(function (teamId) {
teams.push(_oTeamsById[teamId])
})
_oData.teams = teams
}
$mi.close(_oData)
}
$scope2.$watch('data.app', function (oGrpApp) {
if (oGrpApp) {
var url =
'/rest/pl/fe/matter/group/team/list?app=' +
oGrpApp.id +
'&teamType='
http2.get(url).then(function (rsp) {
if (bMultiple) {
_oTeamsById = {}
rsp.data.forEach(function (oTeam) {
_oTeamsById[oTeam.team_id] = oTeam
})
}
$scope2.teams = rsp.data
})
}
})
var url =
'/rest/pl/fe/matter/group/list?site=' +
oMatter.siteid +
'&size=999'
oMatter.mission && (url += '&mission=' + oMatter.mission.id)
http2.get(url).then(function (rsp) {
$scope2.apps = rsp.data.apps
})
},
],
backdrop: 'static',
})
.result.then(function (oResult) {
defer.resolve(oResult)
})
})
return defer.promise
}
},
])
/**
* 素材进入规则
*/
.factory('tkEntryRule', [
'$rootScope',
'noticebox',
'http2',
'srvSite',
'tkEnrollApp',
'tkGroupApp',
function ($rootScope, noticebox, http2, srvSite, tkEnrollApp, tkGroupApp) {
var RelativeProps = ['scope', 'member', 'group', 'enroll', 'sns']
/**
* bNoSave 不对修改进行保存,直接修改传入的原始数据
*/
function TK(oMatter, oSns, bNoSave, aExcludeRules) {
var _self, _oRule, _bJumpModifyWatch, $scope
$scope = $rootScope.$new(true)
this.noSave = !!bNoSave
this.excludeRules = aExcludeRules || []
this.matter = oMatter
this.sns = oSns
this.rule =
_oRule =
$scope.rule =
this.noSave ? oMatter.entryRule : angular.copy(oMatter.entryRule)
_self = this
if (!this.noSave) {
this.originalRule = $scope.originalRule = oMatter.entryRule
this.modified = false
_bJumpModifyWatch = false
$scope.$watch(
'rule',
function (nv, ov) {
if (nv && nv !== ov) {
if (_bJumpModifyWatch === false) {
_self.modified = true
}
_bJumpModifyWatch = false
}
},
true
)
$scope.$watch(
'originalRule',
function (nv, ov) {
if (nv && nv !== ov) {
http2.merge(_oRule, nv, RelativeProps)
_bJumpModifyWatch = true
}
},
true
)
}
this.chooseMschema = function () {
srvSite
.chooseMschema(oMatter, oMatter.mission)
.then(function (oResult) {
if (!_oRule.member) {
_oRule.member = {}
}
_oRule.member[oResult.chosen.id] = {
entry: 'Y',
title: oResult.chosen.title,
}
})
}
this.removeMschema = function (mschemaId) {
if (
!_oRule ||
!_oRule.member ||
!angular.isObject(_oRule.member) ||
Object.keys(_oRule.member).length === 0
)
return true
if (!mschemaId) mschemaId = Object.keys(_oRule.member)[0]
if (mschemaId && _oRule.member[mschemaId]) {
if (oMatter.dataSchemas && oMatter.dataSchemas.length) {
/* 取消题目和通讯录的关联 */
var aAssocSchemas = []
oMatter.dataSchemas.forEach(function (oSchema) {
if (oSchema.mschema_id && oSchema.mschema_id === mschemaId) {
aAssocSchemas.push(oSchema.title)
}
})
if (aAssocSchemas.length) {
noticebox.warn(
'已经有题目<b style="color:red">' +
aAssocSchemas.join(',') +
'</b>和通讯录关联,请解除关联后再删除进入规则'
)
return false
}
}
delete _oRule.member[mschemaId]
}
if (_oRule.optional) {
delete _oRule.optional.member
}
return true
}
this.chooseGroupApp = function () {
tkGroupApp.choose(oMatter).then(function (oResult) {
if (oResult.app) {
_oRule.group = {
id: oResult.app.id,
title: oResult.app.title,
}
if (oResult.team) {
_oRule.group.team = {
id: oResult.team.team_id,
title: oResult.team.title,
}
}
}
})
}
this.removeGroupApp = function () {
if (_oRule.group && _oRule.group.id) {
/* 取消题目和通讯录的关联 */
if (oMatter.dataSchemas && oMatter.dataSchemas.length) {
var aAssocSchemas = []
oMatter.dataSchemas.forEach(function (oSchema) {
if (oSchema.fromApp && oSchema.fromApp === _oRule.group.id) {
aAssocSchemas.push(oSchema.title)
}
})
if (aAssocSchemas.length) {
noticebox.warn(
'已经有题目<b style="color:red">' +
aAssocSchemas.join(',') +
'</b>和分组活动关联,请解除关联后再删除进入规则'
)
return false
}
}
delete _oRule.group
if (_oRule.optional) {
delete _oRule.optional.group
}
}
return true
}
this.chooseEnrollApp = function () {
tkEnrollApp.choose(oMatter).then(function (oTargetApp) {
_oRule.enroll = {
id: oTargetApp.id,
title: oTargetApp.title,
}
})
}
this.removeEnrollApp = function () {
if (_oRule.enroll && _oRule.enroll.id) {
/* 取消题目和通讯录的关联 */
if (oMatter.dataSchemas && oMatter.dataSchemas.length) {
var aAssocSchemas = []
oMatter.dataSchemas.forEach(function (oSchema) {
if (oSchema.fromApp && oSchema.fromApp === _oRule.enroll.id) {
aAssocSchemas.push(oSchema.title)
}
})
if (aAssocSchemas.length) {
noticebox.warn(
'已经有题目<b style="color:red">' +
aAssocSchemas.join(',') +
'</b>和记录活动关联,请解除关联后再删除进入规则'
)
return false
}
}
delete _oRule.enroll
if (_oRule.optional) {
delete _oRule.optional.enroll
}
}
return true
}
this.changeUserScope = function (userScope) {
switch (userScope) {
case 'member':
if (_oRule.scope.member === 'Y') {
if (!_oRule.member || Object.keys(_oRule.member).length === 0) {
this.chooseMschema()
}
} else {
if (false === this.removeMschema()) {
_oRule.scope.member = 'Y'
}
}
break
case 'sns':
if (_oRule.scope.sns === 'Y') {
if (!_oRule.sns) {
_oRule.sns = {}
}
if (oSns.count === 1) {
_oRule.sns[oSns.names[0]] = {
entry: 'Y',
}
}
} else {
delete _oRule.sns
}
break
case 'group':
if (_oRule.scope.group === 'Y') {
if (!_oRule.group) {
this.chooseGroupApp()
}
} else {
if (false === this.removeGroupApp()) {
_oRule.scope.group = 'Y'
}
}
break
case 'enroll':
if (_oRule.scope.enroll === 'Y') {
if (!_oRule.enroll) {
this.chooseEnrollApp()
}
} else {
if (false === this.removeEnrollApp()) {
_oRule.scope.enroll = 'Y'
}
}
break
}
}
this.save = function () {
http2
.post(
'/rest/pl/fe/matter/updateEntryRule?matter=' +
oMatter.id +
',' +
oMatter.type,
_oRule
)
.then(function (rsp) {
if (true === http2.merge(_oRule, rsp.data)) {
_bJumpModifyWatch = true
}
_self.modified = false
oMatter.entryRule = _oRule
})
}
}
return TK
},
])
|
window.onhashchange = function (ev) {
HashMapper.MapInfo.invokeByHashCode();
};
/**
* @version 1.0.0.0
* @copyright Copyright © 2017
* @compiler Bridge.NET 15.7.0
*/
Bridge.assembly("HashMapper", function ($asm, globals) {
"use strict";
Bridge.define("HashMapper.MapInfo", {
statics: {
mappings: null,
autoAdd: false,
previousHashLocation: null,
currentHashLocation: null,
previousRanMapInfos: null,
hashSeperator: "-",
config: {
init: function () {
this.mappings = new (System.Collections.Generic.List$1(HashMapper.MapInfo))();
this.previousRanMapInfos = new (System.Collections.Generic.List$1(HashMapper.MapInfo))();
}
},
invokeByHashCode: function () {
var $t;
HashMapper.MapInfo.currentHashLocation = window.location.hash;
if (System.String.startsWith(HashMapper.MapInfo.currentHashLocation, "#")) {
HashMapper.MapInfo.currentHashLocation = HashMapper.MapInfo.currentHashLocation.substr(1);
}
var currentRunningMapInfos = new (System.Collections.Generic.List$1(HashMapper.MapInfo))();
var hashs = HashMapper.MapInfo.currentHashLocation.split(HashMapper.MapInfo.hashSeperator);
var i;
var y;
var hashLength = hashs.length;
var mapLength = HashMapper.MapInfo.mappings.getCount();
for (y = 0; y < mapLength; y = (y + 1) | 0) {
for (i = 0; i < hashLength; i = (i + 1) | 0) {
try {
if (System.String.startsWith(HashMapper.MapInfo.mappings.getItem(y)._hash, "#")) {
HashMapper.MapInfo.mappings.getItem(y)._hash = HashMapper.MapInfo.mappings.getItem(y)._hash.substr(1);
}
if (Bridge.referenceEquals(HashMapper.MapInfo.mappings.getItem(y)._hash, hashs[i])) {
var map = HashMapper.MapInfo.mappings.getItem(y);
if (!HashMapper.MapInfo.previousRanMapInfos.contains(map)) {
if (!Bridge.staticEquals(map.getOnNavigated(), null)) {
map.getOnNavigated()(map);
}
}
currentRunningMapInfos.add(map);
break;
}
}
catch ($e1) {
$e1 = System.Exception.create($e1);
}
}
}
$t = Bridge.getEnumerator(HashMapper.MapInfo.previousRanMapInfos);
while ($t.moveNext()) {
var item = $t.getCurrent();
if (!currentRunningMapInfos.contains(item)) {
if (!Bridge.staticEquals(item.getOnLeft(), null)) {
item.getOnLeft()(item);
}
}
}
HashMapper.MapInfo.previousRanMapInfos = currentRunningMapInfos;
HashMapper.MapInfo.previousHashLocation = window.location.hash;
}
},
_hash: null,
config: {
properties: {
OnNavigated: null,
OnLeft: null
}
},
$ctor1: function (hash, onNavigated, onLeft) {
this.$initialize();
this._hash = hash;
this.setOnNavigated(onNavigated);
this.setOnLeft(onLeft);
if (HashMapper.MapInfo.mappings == null) {
HashMapper.MapInfo.mappings = new (System.Collections.Generic.List$1(HashMapper.MapInfo))();
}
if (HashMapper.MapInfo.autoAdd) {
if (!HashMapper.MapInfo.mappings.contains(this)) {
HashMapper.MapInfo.mappings.add(this);
}
}
},
ctor: function (hash, onNavigated) {
HashMapper.MapInfo.$ctor1.call(this, hash, onNavigated, null);
},
getHash: function () {
return this._hash;
}
});
});
|
import React from 'react';
import { Redirect } from 'react-router-dom';
export const withPermission = (Component, requiredPermission) => {
const WithPermission = (props) => {
const currentRole = JSON.parse(localStorage.getItem('currentUserRole'));
// Check if the user has the required permission
const hasPermission =
currentRole &&
currentRole.role_permissions.some(
(permission) => permission.permission === requiredPermission
);
if (!hasPermission) {
// If the user doesn't have permission, redirect to a "permission denied" page
return <Redirect to="/permission-denied" />;
}
// If the user has permission, render the requested component
return <Component {...props} />;
};
return WithPermission;
};
|
var mongoose = require('mongoose'),
PermissionSchema = require('./permission').schema,
Schema = mongoose.Schema;
var roleSchema = new Schema({
name: { type:String, required: true, index:{ unique:true, dropDups: true }},
permissions: [ PermissionSchema ]
});
roleSchema.virtual('created').get(function () {
return this._id.getTimestamp();
});
mongoose.model('Role', roleSchema);
|
angular.module("logout", [])
// Logout controller
.controller("LogoutCtrl", function ($scope, $state, auth) {
// get all posts from services
auth.logout();
$state.go("login", {}, { location: "replace" });
});
|
class HomeController {
constructor($scope) {
$scope.items = [
{ title: 'Lorem' },
{ title: 'Ipsum' },
{ title: 'Dolor' },
{ title: 'Sit' },
{ title: 'Amet' }
];
$scope.addItem = function(title) {
$scope.items.push({ title: title });
$scope.newItemTitle = '';
};
$scope.removeItem = function(item) {
let index = $scope.items.indexOf(item);
if (-1 === index) {
return;
}
$scope.items.splice(index, 1);
};
}
}
HomeController.$inject = ['$scope'];
export default HomeController;
|
import React, { Component } from 'react';
import { View, Text, StyleSheet, Image, TouchableOpacity } from 'react-native';
import { Icon } from 'react-native-elements';
export class PlaceDetail extends Component {
constructor(props) {
super(props);
this.state = {
};
this.goToPlace = this.goToPlace.bind(this);
}
goToPlace(place) {
console.log("JOURNEY")
}
render() {
const place = this.props.place;
return (
<View style={styles.placeItem}>
<View style={styles.textContainer}>
<TouchableOpacity onPress={() => this.goToPlace(place)}>
<Text style={styles.text}>
{`${place.name}`}
</Text>
<Text style={styles.locationText}>
{`${place.city}`}
</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
placeItem: {
height: 55,
flexDirection: 'row',
marginTop: 7,
marginBottom: 5,
alignItems: 'stretch',
justifyContent: 'space-between'
},
textContainer: {
flex: 1,
marginLeft: 5,
marginTop: 10,
flexDirection: 'row',
alignSelf: 'flex-start'
},
text: {
marginLeft: 8,
fontSize: 16,
color: '#4296CC',
fontWeight: '500'
},
locationText: {
color: "gray",
marginLeft: 8,
fontSize: 12,
}
});
|
export function setLang(lang) {
return { type: "SET_LANG", lang }
};
|
import { Debug } from '../../core/debug.js';
import { TRACEID_VRAM_VB } from '../../core/constants.js';
import { BUFFER_STATIC } from './constants.js';
let id = 0;
/**
* A vertex buffer is the mechanism via which the application specifies vertex data to the graphics
* hardware.
*
* @category Graphics
*/
class VertexBuffer {
/**
* Create a new VertexBuffer instance.
*
* @param {import('./graphics-device.js').GraphicsDevice} graphicsDevice - The graphics device
* used to manage this vertex buffer.
* @param {import('./vertex-format.js').VertexFormat} format - The vertex format of this vertex
* buffer.
* @param {number} numVertices - The number of vertices that this vertex buffer will hold.
* @param {number} [usage] - The usage type of the vertex buffer (see BUFFER_*). Defaults to BUFFER_STATIC.
* @param {ArrayBuffer} [initialData] - Initial data.
*/
constructor(graphicsDevice, format, numVertices, usage = BUFFER_STATIC, initialData) {
// By default, vertex buffers are static (better for performance since buffer data can be cached in VRAM)
this.device = graphicsDevice;
this.format = format;
this.numVertices = numVertices;
this.usage = usage;
this.id = id++;
this.impl = graphicsDevice.createVertexBufferImpl(this, format);
// Calculate the size. If format contains verticesByteSize (non-interleaved format), use it
this.numBytes = format.verticesByteSize ? format.verticesByteSize : format.size * numVertices;
this.adjustVramSizeTracking(graphicsDevice._vram, this.numBytes);
// Allocate the storage
if (initialData) {
this.setData(initialData);
} else {
this.storage = new ArrayBuffer(this.numBytes);
}
this.device.buffers.push(this);
}
/**
* Frees resources associated with this vertex buffer.
*/
destroy() {
// stop tracking the vertex buffer
const device = this.device;
const idx = device.buffers.indexOf(this);
if (idx !== -1) {
device.buffers.splice(idx, 1);
}
if (this.impl.initialized) {
this.impl.destroy(device);
this.adjustVramSizeTracking(device._vram, -this.storage.byteLength);
}
}
adjustVramSizeTracking(vram, size) {
Debug.trace(TRACEID_VRAM_VB, `${this.id} size: ${size} vram.vb: ${vram.vb} => ${vram.vb + size}`);
vram.vb += size;
}
/**
* Called when the rendering context was lost. It releases all context related resources.
*
* @ignore
*/
loseContext() {
this.impl.loseContext();
}
/**
* Returns the data format of the specified vertex buffer.
*
* @returns {import('./vertex-format.js').VertexFormat} The data format of the specified vertex
* buffer.
*/
getFormat() {
return this.format;
}
/**
* Returns the usage type of the specified vertex buffer. This indicates whether the buffer can
* be modified once and used many times {@link BUFFER_STATIC}, modified repeatedly and used
* many times {@link BUFFER_DYNAMIC} or modified once and used at most a few times
* {@link BUFFER_STREAM}.
*
* @returns {number} The usage type of the vertex buffer (see BUFFER_*).
*/
getUsage() {
return this.usage;
}
/**
* Returns the number of vertices stored in the specified vertex buffer.
*
* @returns {number} The number of vertices stored in the vertex buffer.
*/
getNumVertices() {
return this.numVertices;
}
/**
* Returns a mapped memory block representing the content of the vertex buffer.
*
* @returns {ArrayBuffer} An array containing the byte data stored in the vertex buffer.
*/
lock() {
return this.storage;
}
/**
* Notifies the graphics engine that the client side copy of the vertex buffer's memory can be
* returned to the control of the graphics driver.
*/
unlock() {
// Upload the new vertex data
this.impl.unlock(this);
}
/**
* Copies data into vertex buffer's memory.
*
* @param {ArrayBuffer} [data] - Source data to copy.
* @returns {boolean} True if function finished successfully, false otherwise.
*/
setData(data) {
if (data.byteLength !== this.numBytes) {
Debug.error(`VertexBuffer: wrong initial data size: expected ${this.numBytes}, got ${data.byteLength}`);
return false;
}
this.storage = data;
this.unlock();
return true;
}
}
export { VertexBuffer };
|
var select = document.getElementById("sampleSelect");
async function ret(){
try{
await $.post('/post',
{
processing: 'Upload',
firstname: document.getElementById("firstname").value,
lastname: document.getElementById("lastname").value,
mailaddress: document.getElementById("mailaddress").value,
passward: document.getElementById("passward").value
},
'json')
.done(function(data) {alert('JSON Data was able to Upload by system');})
.fail(function() {alert('通信失敗')});
//.always(function() {alert('通信終了')});
}catch (err) {
await alert(err.message + "@cosmosdbHTMLControl@dataup");
}
//alert(typeof document.getElementById("firstname").value) 型判定
}
|
export default class BootScene extends Phaser.Scene {
constructor() {
super({
key: 'BootScene'
});
}
preload() {
this.load.tilemapTiledJSON('Home', 'assets/maps/home.json');
this.load.tilemapTiledJSON('Level1', 'assets/maps/level1.json');
this.load.image('tiles', 'assets/tilesets/tileset.png');
this.load.spritesheet('player', 'assets/sprites/player_sprites.png', { frameWidth: 32, frameHeight: 32 });
this.load.image('speed_potion', 'assets/img/speed_potion_icon.png');
this.load.image('vision_potion', 'assets/img/vision_potion_icon.png');
}
create() {
this.initRegistry();
this.loadAnims();
this.scene.launch('HUDScene');
this.scene.start('GameScene');
}
loadAnims() {
this.anims.create({
key: 'down',
frames: this.anims.generateFrameNumbers('player', {start: 0, end: 2}),
frameRate: 10,
repeat: -1
});
this.anims.create({
key: 'left',
frames: this.anims.generateFrameNumbers('player', {start: 3, end: 5}),
frameRate: 10,
repeat: -1
});
this.anims.create({
key: 'right',
frames: this.anims.generateFrameNumbers('player', {start: 6, end: 8}),
frameRate: 10,
repeat: -1
});
this.anims.create({
key: 'up',
frames: this.anims.generateFrameNumbers('player', {start: 10, end: 12}),
frameRate: 10,
repeat: -1
});
}
initRegistry() {
// The game registry provides a place accessible by all scenes to set and get data
// Example : this.registry.set('custom_value', 0);
}
}
|
/* jshint esversion: 6 */
const builder = require('botbuilder');
const { Provider, ConversationState } = require('./provider');
// dispatch messages between agent and user
function Router(bot, isAgent) {
'use strict';
const provider = new Provider();
const middleware = () => {
return {
botbuilder: (session, next) => {
if (session.message.type === 'message') {
if (isAgent(session)) {
routeAgentMessage(session);
} else {
routeUserMessage(session, next);
}
} else {
next();
}
}
};
};
const routeAgentMessage = (session) => {
const message = session.message;
const conversation = provider.findByAgentId(message.address.conversation.id);
// if the agent is not in conversation, no further routing is necessary
if (!conversation) {
return;
}
// send text that agent typed to the user they are in conversation with
bot.send(new builder.Message().address(conversation.user).text(message.text));
};
const routeUserMessage = (session, next) => {
const message = session.message;
const conversation = provider.findByConversationId(message.address.conversation.id) || provider.createConversation(message.address);
// the next action depends on the conversation state
switch (conversation.state) {
case ConversationState.ConnectedToBot:
// continue the normal bot flow
return next();
case ConversationState.WaitingForAgent:
// send a notification to the customer
session.send(`Connecting you to the next available human agent... please wait, there are ${pending()-1} users waiting.`);
return;
case ConversationState.ConnectedToAgent:
// send text that customer typed to the agent they are in conversation with
bot.send(new builder.Message().address(conversation.agent).text(message.text));
return;
}
};
const pending = () => {
return provider.currentConversations().filter((conv) => conv.state === ConversationState.WaitingForAgent).length;
};
return {
isAgent,
middleware,
pending,
provider,
bot
};
}
module.exports = Router;
|
//******************************** VARIABLES / REQUIRE ********************************/
//*************************************************************************************/
const knexConfig = require('../knexfile');
const ENV = process.env.ENV || "development";
const knex = require('knex')(knexConfig[ENV]);
const express = require('express');
const uuid = require('uuid/v4');
const router = express.Router();
const Auth = require('../auth/auth');
//************************************** ROUTES ***************************************/
//*************************************************************************************/
router.post('/create', function(req, res) {
let orderObj = {};
const { cart, userId, total, order_number} = req.body;
orderObj.user_id = userId;
orderObj.total = total;
orderObj.order_number = uuid().substring(0,7);
knex
.insert(orderObj)
.into('orders')
.returning('orders.id')
.then(function(data) {
for(let item of cart) {
middleTableEntry(item, data[0]);
}
}).then(function() {
for(let item of cart) {
updateQuantity(item);
}
});
function updateQuantity(item) {
let newQuant = item.quantity_available - item.cart_quantity;
let quantObj = {quantity_available: newQuant};
knex
.select('*')
.from('deals')
.where({id: item.deal_id})
.update(quantObj)
.then()
.error(err => console.log(err));
}
function middleTableEntry(item, data) {
let entryObj = {};
entryObj.deal_id = item.deal_id;
entryObj.order_id = data;
entryObj.deal_price_purchased = item.current_price;
entryObj.total_price_purchased = (item.current_price * item.cart_quantity).toFixed(2);
entryObj.quantity_purchased = item.cart_quantity;
knex
.insert(entryObj)
.into('orders_deals')
.then();
}
});
//[GET] user deals
router.get('/:id/view', function(req, res) {
knex
.select("*")
.from("orders")
.where("orders.user_id", req.params.id)
.then((data) => {
res.json(data);
});
});
router.get('/user/:id', Auth, function(req, res) {
knex
.select('orders.id as order_id',
'orders.user_id as user_id',
'orders.order_number as order_number',
'orders.total as total',
'orders_deals.deal_id as deal_id',
'orders.created_at as created_at',
'orders_deals.quantity_purchased as quantity',
'orders_deals.deal_price_purchased as deal_price',
'deals.merchant_id as merchant_id',
'merchants.business_name as merchant_name',
'deals.name as product_name',
'deals.image_path as image' )
.from('orders')
.innerJoin('orders_deals', 'orders.id', 'order_id')
.innerJoin('deals', 'orders_deals.deal_id', 'deals.id')
.innerJoin('merchants', 'merchants.id', 'deals.merchant_id')
.where('user_id', req.params.id)
.then( result => res.json(result))
.catch(error => res.json({message: error}))
})
module.exports = router;
|
/* global it, expect, describe */
// @flow
import React from 'react'
import { mount } from 'enzyme'
import renderer from 'react-test-renderer'
import Input from '../index'
describe('Input', () => {
it('Input with className', () => {
const input = mount(
<Input theme={{ input: 'is-small' }} />,
)
expect(input.find('.is-small').prop('className')).toEqual('input is-small')
})
it('Input with className', () => {
const component = renderer.create(<Input theme={{ input: 'is-small' }} />)
const tree = component.toJSON()
expect(tree).toMatchSnapshot()
})
})
|
function myMenuButton() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
};
$('#title').fadeOut(5000);
function randColor(tag) {
rand = Math.random();
if ($(tag).hasClass('fa fa-square')) {
if (rand <= 0.05) {
color='#375235';//'#7CA26E';
} else if (rand > 0.05 && rand <= 0.1) {
color='#42633F';
}
else if (rand > 0.1 && rand <= 0.7) {
color='#617B6F';
} else {
color='#333333';
}
} else {
color='#617B6F';
}
return color
}
function appendBoxes(tag, side, size='3.5vw') {
$(tag).appendTo($(side)).css({'font-size':size, 'color':randColor(tag)});
}
function createBoxes(side) {
let tag;
for (let i = 0; i <= 140; i++) {
if (side==='#left') {
switch (i) {
case 0:
tag = '<a href="https://nl.linkedin.com/in/sander-dudok-34675488" target="_blank"><i class="fa fa-linkedin-square"></i></a>';
break;
case 1:
tag = '<a href="https://github.com/dudok" target="_blank"><i class="fa fa-github-square"></i></a>';
break;
case 2:
tag = '<a href="#sander.dudok@gmail.com"><i class="fa fa-envelope-square"></i></a>';
break;
default:
tag = '<i class="fa fa-square"></i>';
}
} else {
tag = '<i class="fa fa-square"></i>';
}
appendBoxes(tag, side);
};
};
createBoxes('#left');
createBoxes('#right');
|
$(function(){
var Name = JSON.parse(localStorage.getItem("loginName"))
if(Name!=null){
$(".header_top .top ul>li:nth-child(2)").text(Name);
$(".header_top .top ul>li:nth-child(4)").text("安全退出");
if($(".header_top .top ul>li:nth-child(2)").text()==Name){
$(".header_top .top ul>li:nth-child(2)").click(function(){
window.setTimeout("window.location='user.html'")
})
}
}
if($(".header_top .top ul>li:nth-child(4)").text()=="安全退出"){
$(".header_top .top ul>li:nth-child(4)").click(function(){
localStorage.setItem("loginName",null)
window.setTimeout("window.location='login.html'")
})
}
if($(".header_top .top ul>li:nth-child(2)").text()=="登录"){
$(".header_top .top ul>li:nth-child(2)").click(function(){
window.setTimeout("window.location='login.html'")
})
}
if($(".header_top .top ul>li:nth-child(4)").text()=="注册"){
$(".header_top .top ul>li:nth-child(4)").click(function(){
window.setTimeout("window.location='register.html'")
})
}
})
|
import React from 'react';
import { Auth, I18n } from 'aws-amplify';
import { Header } from '../fsc/Header';
import { Button } from '../fsc/Button';
export class Options extends React.Component {
signOut() {
Auth.signOut()
.then(() => window.location.reload())
.catch(err => console.log(err));
}
render() {
return (
<div>
<Header title="Options" />
<div className="container">
<div className="row justify-content-center">
<div className="col-12 my-3">
<Button title="Shift History" color="btn-primary rounded-0 btn-block" onClick={() => this.props.history.push('/shiftHistory')} />
<Button title="Log Hours" color="btn-primary rounded-0 btn-block" onClick={() => this.props.history.push('/logHours')} />
<Button title={I18n.get('Sign Out')} color="btn-danger rounded-0 btn-block" onClick={this.signOut} />
</div>
</div>
</div>
</div>
);
}
}
export default Options;
|
import {
FETCH_STARTED_ORDER_LIST,
FETCH_SECCESS_ORDER_LIST,
FETCH_FAILURI_ORDER_LIST,
COMMENT_ADD,
COMMENT_CANCEL,
COMMENT_UPDATA
} from './actionTypes'
export const fetchStarted = () => ({
type: FETCH_STARTED_ORDER_LIST
});
export const fetchSuccess = (data) => ({
type: FETCH_SECCESS_ORDER_LIST,
data
});
export const fetchFailure = (err) => ({
type: FETCH_FAILURI_ORDER_LIST,
err
});
export const commentAdd = (id) => ({
type: COMMENT_ADD,
id: id
});
export const commentCancel = (id) => ({
type: COMMENT_CANCEL,
id: id
});
export const commentUpdata = (id, value) => ({
type: COMMENT_UPDATA,
id: id,
value: value
});
|
import * as linkInsert from './linkinsert.js'
let backgroundPagePort;
chrome.runtime.onConnect.addListener(function connectListener(port) {
backgroundPagePort = port;
backgroundPagePort.onDisconnect.addListener(function disconnectListener() {
linkInsert.removeLinks();
backgroundPagePort.onDisconnect.removeListener(disconnectListener);
});
chrome.runtime.onConnect.removeListener(connectListener);
});
function openSourceFile(url, lineNumber) {
backgroundPagePort && backgroundPagePort.postMessage({
sourceUrl: url,
lineNumber: lineNumber
});
}
function onLoaded() {
linkInsert.insertLinks(Array.from(document.body.children), openSourceFile);
const mutationObserver = new MutationObserver(function(mutationRecords) {
mutationRecords.forEach(function(mutationRecord) {
if (mutationRecord.type == 'childList') {
linkInsert.insertLinks(Array.from(mutationRecord.addedNodes), openSourceFile);
}
});
});
mutationObserver.observe(document.body, {
subtree: true,
characterData: true,
childList: true
});
}
if (document.readyState == 'loading') {
document.addEventListener('readystatechange', function onReadyStateChange() {
if (document.readyState == 'interactive') {
onLoaded();
document.removeEventListener('readystatechange', onReadyStateChange);
}
});
} else {
onLoaded();
}
|
"use strict";
function SpeechService(roomService) {
// Fields
let me = this;
this.speechSynthesis = null;
this.voices = null;
this.selectedVoice = null;
// Methods
this.speakCurrentLocation = function (room) {
return roomService.getBuilding(room.building).then((building) => {
return new Promise((resolve, reject) => {
let speechString = "You are currently near room " + room.legalName + ", in building " + building.name + ", on floor " + room.floor + ".";
let utterance = new SpeechSynthesisUtterance(speechString);
if (me.selectedVoice) {
utterance.voice = me.selectedVoice;
}
me.speechSynthesis.speak(utterance);
utterance.onend = (event) => { resolve(); };
utterance.onerror = reject;
});
});
};
this.speakStep = function (text) {
return new Promise((resolve, reject) => {
let utterance = new SpeechSynthesisUtterance(text);
if (me.selectedVoice) {
utterance.voice = me.selectedVoice;
}
me.speechSynthesis.speak(utterance);
utterance.onend = (event) => { resolve(); };
utterance.onerror = reject;
resolve();
});
};
// Init
this.init = function () {
return new Promise((resolve, reject) => {
me.speechSynthesis = window.speechSynthesis;
// Retreive all voices
me.voices = me.speechSynthesis.getVoices();
if (me.voices.length >= 1) {
resolve();
}
if (me.speechSynthesis.onvoiceschanged !== undefined) {
me.speechSynthesis.onvoiceschanged = (event) => {
me.voices = me.speechSynthesis.getVoices();
resolve();
};
}
}).then(() => {
// Search for an English voice
let englishVoicePred = (voice) => { return voice.lang.toLowerCase().includes("en"); };
let britVoicePred = (voice) => { return voice.lang.toLowerCase().includes("gb"); };
let amerVoicePred = (voice) => { return voice.lang.toLowerCase().includes("us"); };
let englishVoices = me.voices.filter(englishVoicePred);
let britVoices = englishVoices.filter(britVoicePred);
let amerVoices = englishVoices.filter(amerVoicePred);
// Put them in a certain priority and select the best one
let priorityVoices = amerVoices.concat(britVoices).concat(englishVoices);
if (priorityVoices.length >= 1) {
me.selectedVoice = priorityVoices[0];
}
});
};
}
|
/*eslint-env browser*/
var btnMenu = document.getElementById('btnmenu');
var nav = document.getElementById('nave');
document.getElementById('btnmenu').addEventListener('click', function () {
"use strict";
document.getElementById('nave').classList.toggle('mostrar');
});
|
/**
* @author YuBing
*/
/*
* 根据不同的浏览器,获取Ajax对象
*/
function getAjaxObject() {
var xmlHttpRequest;
// 判断是否把XMLHttpRequest实现为一个本地javascript对象
if(window.XMLHttpRequest){
xmlHttpRequest = new XMLHttpRequest();
}else if(window.ActiveXObject){ // 判断是否支持ActiveX控件
try{
// 通过实例化ActiveXObject的一个新实例来创建XMLHttpRequest对象
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP"); // msxml3以上版本
}catch(e){
try{
// 通过实例化ActiveXObject的一个新实例来创建XMLHttpRequest对象
xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP"); // msxml3以下版本
}catch(e){}
}
}
if ( !xmlHttpRequest ) {
alert("创建Ajax对象失败,您将无法正常浏览网页");
}
return xmlHttpRequest;
}
|
import React, { Component } from 'react';
import moment from 'moment';
import PropTypes from 'prop-types';
const defaultStyles = {
clockStyle: {
height: '8rem',
margin: 0,
padding: 0,
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
flexDirection: 'row',
fontSize: '61px',
fontFamily: 'sans-serif',
letterSpacing: '5px',
textShadow: '0 0 10px #fff',
textTransform: 'uppercase'
},
clockHeaderStyle: {
margin: '13px',
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-between',
alignItems: 'center'
},
clockSubHeader: {
marginBottom: '10px',
fontSize: '13px',
letterSpacing: 'initial'
}
};
class ReactClock extends Component {
static propTypes = {
startDate: PropTypes.string,
color: PropTypes.string,
size: PropTypes.number,
clockShadow: PropTypes.string,
day: PropTypes.bool,
clockDigitStyle: PropTypes.string,
clockSeparator: PropTypes.string
};
state = {
dateTimestamp: Date.now()
};
componentDidMount() {
this.interval = setInterval(this.tick, 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
tick = () => {
this.setState({ dateTimestamp: Date.now() });
}
calculateNumberOfDaysLeft = startDate => {
return moment().diff(startDate, 'days');
}
// pad string with zero
pad = (str, max = 2) => str.length < max ? `0 ${str}` : str;
static Day = ({ daysLeft, startDate, isDayEnabled }) => {
return <div>
{
isDayEnabled ?
<div style={{ ...defaultStyles.clockHeaderStyle }}>
<div style={{ ...defaultStyles.clockSubHeader }}> {startDate ? 'DAYS' : 'DAY'} </div>
<div>{startDate ? daysLeft : moment().format('DD')}</div>
</div> :
''
}
</div>;
}
static Seperator = ({ clockSeparator, shouldShow = true }) => {
return <span>{shouldShow ? (clockSeparator ? clockSeparator : '.') : ''}</span>;
}
static Hour = () => {
return <div style={{ ...defaultStyles.clockHeaderStyle }}>
<div style={{ ...defaultStyles.clockSubHeader }}> hours </div>
<div>{moment().format('HH')}</div>
</div>;
}
static Minutes = () => {
return <div style={{ ...defaultStyles.clockHeaderStyle }}>
<div style={{ ...defaultStyles.clockSubHeader }}> minutes </div>
<div>{moment().format('mm')}</div>
</div>
}
static Seconds = () => {
return <div style={{ ...defaultStyles.clockHeaderStyle }}>
<div style={{ ...defaultStyles.clockSubHeader }}> seconds </div>
<div>{moment().format('ss')}</div>
</div>
}
render() {
const { startDate, day, style, clockSeparator } = this.props;
const daysLeft = this.pad(this.calculateNumberOfDaysLeft(startDate).toString());
const isDayEnabled = day === undefined ? false : day;
return (
<div
style={{
...defaultStyles.clockStyle,
...style
}}>
<ReactClock.Day daysLeft={daysLeft} startDate={startDate} isDayEnabled={isDayEnabled} />
<ReactClock.Seperator clockSeparator={clockSeparator} shouldShow={isDayEnabled} />
<ReactClock.Hour />
<ReactClock.Seperator clockSeparator={clockSeparator} />
<ReactClock.Minutes />
<ReactClock.Seperator clockSeparator={clockSeparator} />
<ReactClock.Seconds />
</div>
);
}
}
export default ReactClock;
|
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const WebpackBar = require('webpackbar')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const ESLintPlugin = require('eslint-webpack-plugin')
module.exports = {
entry: ['@babel/polyfill', './src/index.tsx'],
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name][hash:12].js'
},
resolve: {
extensions: ['.tsx', '.ts', '.js', '.jsx', '.css', '.less', '.scss', '.json'],
alias: {
'@': path.resolve(__dirname, 'src')
}
},
module: {
rules: [
{
test: /\.(css|less)$/,
use: [process.env.NODE_ENV === 'development' ? 'style-loader' : {
loader: MiniCssExtractPlugin.loader
}, 'css-loader', 'postcss-loader', 'cache-loader', 'thread-loader', {
loader: 'less-loader',
options: {
lessOptions: {
javascriptEnabled: true
}
}
}]
},
{
test: /\.s[ac]ss$/i,
use: [
// 将 JS 字符串生成为 style 节点
process.env.NODE_ENV === 'development' ? 'style-loader' : {
loader: MiniCssExtractPlugin.loader
},
// 将 CSS 转化成 CommonJS 模块
'css-loader',
'cache-loader',
'thread-loader',
// 将 Sass 编译成 CSS
'sass-loader'
]
},
{
test: /\.(png|jpe?g|gif)$/i,
include: path.resolve(__dirname, 'src'),
use: [{
loader: 'file-loader',
options: {
name: '[name][hash:6].[ext]',
outputPath: 'image'
}
}]
},
{
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['@babel/preset-react']
}
},
{
loader: '@svgr/webpack',
options: {
babel: false,
icon: true,
},
},
{
loader: 'file-loader',
options: {
name: '[name][hash:6].[ext]',
outputPath: 'image'
}
}
],
},
{
test: /\.m?(js|jsx)$/,
exclude: /node_modules/,
include: path.resolve(__dirname, 'src'),
use: [
{
loader: 'babel-loader?cacheDirectory=true',
options: {
presets: ['@babel/preset-env', '@babel/preset-react'],
plugins: ['@babel/plugin-transform-runtime']
}
}]
},
{
test: /\.m?(ts|tsx)$/,
exclude: /node_modules/,
include: path.resolve(__dirname, 'src'),
use: [
{
loader: 'babel-loader?cacheDirectory=true',
options: {
presets: ['@babel/preset-env', '@babel/preset-react', '@babel/preset-typescript'],
plugins: ['@babel/plugin-transform-runtime']
}
}]
}
]
},
plugins: [
new HtmlWebpackPlugin({
title: '首页',
template: 'public/index.html',
inject: true,
chunks: ['main']
}),
new ESLintPlugin({
context: './src',
extensions: ['js', 'jsx', 'ts', 'tsx']
}),
new WebpackBar(),
new CleanWebpackPlugin()
]
}
|
//-------------
// GLOBAL VAR
//-------------
//-- IMPORT MODULES
var app = require('express')(),
http = require('http').Server(app),
Gpio = require('onoff').Gpio;
//-- DEFINE LEDS
var led_red = new Gpio(17, 'out'), // Red light
led_green = new Gpio(18, 'out'); // Green light
//-- MAKE ARRAY LEDS
var leds = [led_red,led_green];
//-------------
// APPLICATION
//-------------
//-- TURN ON THE LIGHT
app.get('/on/:led', function(req, res){
var this_led = req.params.led;
leds[this_led].writeSync(1);
console.info("Switch on the light "+this_led);
res.send("Turn on the light "+this_led);
});
//-- TURN OFF THE LIGHT
app.get('/off/:led', function(req, res){
var this_led = req.params.led;
leds[this_led].writeSync(0);
console.info("Switch off the light "+this_led);
res.send("Turn off the light "+this_led);
});
//-- GET STATUS
app.get('/status/:led', function(req, res){
leds[this_led].readSync();
console.info(leds[this_led].readSync());
res.send(leds[this_led].readSynch());
});
//-- Listen 3000
http.listen(3000, function(){
console.info("Start app on :3000");
});
|
// Get Current Date
let today = new Date(); // new Date object
// now concatenate formatted output
let date = (today.getMonth() + 1) + " / " + today.getDate() + " / " + today.getFullYear();
document.getElementById('currentdate').innerHTML = date;
// Defining Table
// INPUT: Get first name from input box
// PROCESSING: Add first name in favorite scripture on click
// OUTPUT: Display the with first name
function insertName() {
//INPUT
let name = document.getElementById("name").value;
//PROCESSING
let output = ` - Behold, thou art ${name}, and I have spoken unto thee because of thy desires; therefore treasure up these words in thy heart. Be faithful and diligent in keeping the commandments of God, and I will encircle thee in the arms of my love.`;
// OUTPUT
const scripture = document.getElementById("output");
scripture.innerHTML = output;
}
|
import React, { Component } from "react";
import "../Style/contact.css";
import axios from "axios";
class Contact extends Component {
state = {
social: [
{ name: "Git", src: "social-git.png" },
{ name: "Facebook", src: "social-fb.png" },
{ name: "Twitter", src: "social-tw.png" },
{ name: "Mail", src: "social-mail.png" },
{ name: "Instagram", src: "social-ig.png" }
],
mail: {
name: "",
email: "",
subject: "",
message: ""
}
};
constructor() {
super();
this.handleUpdate = this.handleUpdate.bind(this);
this.handleSUbmit = this.handleSubmit.bind(this);
}
handleSubmit = async e => {
e.preventDefault();
const form = await axios({
method: "POST",
url: "/api/form",
data: {
type: "mail",
name: this.state.mail.name,
email: this.state.mail.email,
subject: this.state.mail.subject,
message: this.state.mail.message
}
})
.then(response => {
console.log("response");
console.log(response);
})
.catch(error => {
console.log("error.response");
console.log(error.response);
});
this.setState({
mail: {
name: "",
email: "",
subject: "",
message: ""
}
});
document.getElementById("name").value = "";
document.getElementById("email").value = "";
document.getElementById("subject").value = "";
document.getElementById("msg").value = "";
};
handleUpdate = (e = {}) => {
let mail = Object.assign({}, this.state.mail);
const stateName = e.target.name;
mail[stateName] = e.target.value;
this.setState({ mail });
};
render() {
return (
<React.Fragment>
<h2 className="form-title">Get in touch!</h2>
<form onSubmit={this.handleSubmit}>
<div className="form-container small-container">
<div className="form-wrapper small">
<label htmlFor="name">Name</label>
<input
id="name"
name="name"
placeholder="What is your name?"
type="text"
className="small"
value={this.state.mail.name}
onChange={this.handleUpdate}
/>
</div>
</div>
<div className="form-container small-container">
<div className="form-wrapper small">
<label htmlFor="email">Email</label>
<input
id="email"
name="email"
placeholder="What is your e-mail adress?"
type="email"
className="small"
value={this.state.mail.email}
onChange={this.handleUpdate}
/>
</div>
</div>
<div className="form-container small-container">
<div className="form-wrapper small">
<label htmlFor="subject">Subject</label>
<input
id="subject"
name="subject"
placeholder="What do you want to talk about?"
type="text"
className="small"
value={this.state.mail.subject}
onChange={this.handleUpdate}
/>
</div>
</div>
<div className="form-container">
<div className="form-wrapper big">
<label htmlFor="msg">Message</label>
<textarea
name="message"
id="msg"
cols="30"
rows="8"
placeholder="Your message here."
value={this.state.mail.message}
onChange={this.handleUpdate}
/>
</div>
</div>
<input type="submit" value="Send message!" />
</form>
<div className="social">
{this.state.social.map(social => (
<div className="social-items" title={social.name}>
<img src={require("../Images/" + social.src)} alt={social.name} />
</div>
))}
</div>
</React.Fragment>
);
}
}
export default Contact;
|
import React, { useContext } from 'react'
import { Link } from 'react-router-dom'
import IngredientContext from '../../context/ingredient/ingredientContext'
import IngredientItem from './IngredientItem'
const Ingredients = () => {
const ingredientContext = useContext(IngredientContext)
const { ingredients } = ingredientContext
return (
<div className="row">
<div className="col s12">
<h3>Ingredients</h3>
<div className="grid-wrapper">
{ingredients.map(ingredient => (
<IngredientItem key={ingredient.id} ingredient={ingredient} />
))}
</div>
</div>
</div>
)
}
export default Ingredients
|
import React, { Component } from 'react';
import Track from './Track';
class Playlist extends Component {
constructor(props) {
super(props);
this.state = {
tracks: []
}
this.playDisabled = false;
this.pollID = null;
}
getData = () => {
if (this.props.playlist_id === '' || this.props.playlist_id === undefined) {
this.props.setPlaylistName("No playlist selected");
this.props.setPlaylistURI("");
return;
}
fetch(`/playlists/one/${this.props.playlist_id}`, { credentials: 'include' })
.then(res => res.json())
.then(data => {
this.setState({
tracks: data.tracks.items
});
this.props.setPlaylistURI(data.uri);
this.props.setPlaylistName(data.name);
})
.catch(err => console.log(err));
this.pollID = setTimeout(this.getData.bind(this), 60000);
}
componentDidMount() {
if (this.props.playlist_id !== '') this.getData();
}
componentDidUpdate(prevProps) {
if (prevProps.playlist_id !== this.props.playlist_id) {
clearTimeout(this.pollID);
this.getData();
}
}
componentWillUnmount() {
clearTimeout(this.pollID);
}
isSelected = (index) => {
if (index === this.props.playing) return "select list-item";
return "select pointer list-item";
}
render() {
return (
<React.Fragment>
{this.props.playlist_id !== ''
? <div className="list" id="playlist">
{this.state.tracks.length !== 0
? this.state.tracks.map((obj, index) =>
<div
onClick={() => this.props.onPlay(index)}
className={"select pointer list-item"}
key={index}
data-value={index}
>
<Track
name={obj.track.name}
offset={index}
artist={obj.track.artists[0].name}
album_img={obj.track.album.images[2].url}>
</Track>
</div>
)
: <div className="list-item" key="lonely boi">Playlist is empty. Start adding songs!</div>
}
</div>
: <></>
}
</React.Fragment>
);
}
}
export default Playlist;
|
/*
* Checkout page object
*
* @package: Blueacorn Checkout.js
* @version: 1.0
* @Author: Luke Fitzgerald
* @Copyright: Copyright 2015-09-04 13:14:33 Blue Acorn, Inc.
*/
'use strict';
function Checkout() {
var url = 'checkout/onepage';
var checkoutHeading = 'body > div.wrapper > div > div.main-container.col2-right-layout > div > div.col-main > div > h1';
var guestCheckoutButton = '#onepage-guest-register-button';
var loginForm = '#login-form';
var email = '#login-email';
var pw = '#login-password';
var loginButton = '#checkout-step-login > div > div.col-2 > div:nth-child(1) > div > button';
var forgotPwLink = '#login-form > div > ul > li:nth-child(3) > a';
var billingStepTitle = '#opc-billing > div.step-title';
var billingForm = '#co-billing-form';
var billingFirstName = '#billing-new-address-form > div > ul > li:nth-child(1) > div > div.field.name-firstname > div > input';
var billingLastName = '#billing-new-address-form > div > ul > li:nth-child(1) > div > div.field.name-lastname > div > input';
var billingEmail = '#billing-new-address-form > div > ul > li:nth-child(2) > div:nth-child(2) > div > input';
var billingAddress = '#billing-new-address-form > div > ul > li:nth-child(3) > div > input';
var billingCity = '#billing-new-address-form > div > ul > li:nth-child(5) > div:nth-child(1) > div > input';
var billingState = '#billing-new-address-form > div > ul > li:nth-child(5) > div:nth-child(2) > div > div > span';
var billingStateDropdownOpen = '#billing-new-address-form > div > ul > li:nth-child(5) > div:nth-child(2) > div > div.ba-select.ba-select-box.ba-over.open';
var billingStateSc = '#billing-new-address-form > div > ul > li:nth-child(5) > div:nth-child(2) > div > div.ba-select.ba-select-box.ba-over.open > div > ul > li:nth-child(55)';
var billingStateSelect = '#billing-new-address-form > div > ul > li:nth-child(5) > div:nth-child(2) > div > select';
var billingZip = '#billing-new-address-form > div > ul > li:nth-child(6) > div:nth-child(1) > div > input';
var billingCountry = '#billing-new-address-form > div > ul > li:nth-child(6) > div:nth-child(2) > div > div > span';
var billingPhone = '#billing-new-address-form > div > ul > li:nth-child(7) > div > div > input';
var billingContinueButton = '#billing-buttons-container > button.button.continue';
var billingShipToThisAddressRadioButton = '#co-billing-form > div > ul > li:nth-child(2) > input';
var billingShipToAnotherAddressRadioButton = '#co-billing-form > div > ul > li:nth-child(3) > input';
var billingShipToThisAddressRadioButtonLabel = '#co-billing-form > div > ul > li:nth-child(2) > label';
var billingShipToAnotherAddressRadioButtonLabel = '#co-billing-form > div > ul > li:nth-child(3) > label';
//
// Enter shipping address variables here
//
var shippingMethodSubheading = '#checkout-shipping-method-load > dl > dt';
var shippingMethodForm = '#co-shipping-method-form';
var shippingMethodRadioButtonLabel = '#checkout-shipping-method-load > dl > dd > ul > li:nth-child(1) > label';
var shippingMethodContinueButton = '#shipping-method-buttons-container > button.button.continue';
var paymentInfoForm = '#co-payment-form';
var paymentOptionLabel = '#dt_method_braintree > label';
var ccNum = '#braintree_cc_number';
var ccvNum = '#braintree_cc_cid';
var paymentInfoContinueButton = '#payment-buttons-container > button.button.continue';
var orderReviewBlock = '#checkout-review-load';
var orderReviewBlockTotal = '#checkout-review-table > tfoot > tr.last > td.a-right.last > strong > span';
var submitOrderButton = '#review-buttons-container > button';
this.getUrl = function() {
return url;
};
this.getCheckoutHeading = function() {
return checkoutHeading;
};
this.getGuestCheckoutButton = function() {
return guestCheckoutButton;
};
this.getLoginForm = function() {
return loginForm;
};
this.getEmail = function() {
return email;
};
this.getPw = function() {
return pw;
};
this.getLoginButton = function() {
return loginButton;
};
this.getForgotPwLink = function() {
return forgotPwLink;
};
this.getBillingStepTitle = function() {
return billingStepTitle;
};
this.getBillingForm = function() {
return billingForm;
};
this.getBillingFirstName = function() {
return billingFirstName;
};
this.getBillingLastName = function() {
return billingLastName;
};
this.getBillingEmail = function() {
return billingEmail;
};
this.getBillingAddress = function() {
return billingAddress;
};
this.getBillingCity = function() {
return billingCity;
};
this.getBillingState = function() {
return billingState;
};
this.getBillingStateDropdownOpen = function() {
return billingStateDropdownOpen;
};
this.getBillingStateSc = function() {
return billingStateSc;
};
this.getBillingStateSelect = function() {
return billingStateSelect;
};
this.getBillingZip = function() {
return billingZip;
};
this.getBillingCountry = function() {
return billingCountry;
};
this.getBillingPhone = function() {
return billingPhone;
};
this.getBillingContinueButton = function() {
return billingContinueButton;
};
this.getBillingShipToThisAddressRadioButton = function() {
return billingShipToThisAddressRadioButton;
};
this.getBillingShipToAnotherAddressRadioButton = function() {
return billingShipToAnotherAddressRadioButton;
};
this.getBillingShipToThisAddressRadioButtonLabel = function() {
return billingShipToThisAddressRadioButtonLabel;
};
this.getBillingShipToAnotherAddressRadioButtonLabel = function() {
return billingShipToAnotherAddressRadioButtonLabel;
};
this.getShippingMethodSubheading = function() {
return shippingMethodSubheading;
};
this.getShippingMethodForm = function() {
return shippingMethodForm;
};
this.getShippingMethodRadioButtonLabel = function() {
return shippingMethodRadioButtonLabel;
};
this.getShippingMethodContinueButton = function() {
return shippingMethodContinueButton;
};
this.getPaymentInfoForm = function() {
return paymentInfoForm;
};
this.getPaymentOptionLabel = function() {
return paymentOptionLabel;
};
this.getCcNum = function() {
return ccNum;
};
this.getCcvNum = function() {
return ccvNum;
};
this.getPaymentInfoContinueButton = function() {
return paymentInfoContinueButton;
};
this.getOrderReviewBlock = function() {
return orderReviewBlock;
};
this.getOrderReviewBlockTotal = function() {
return orderReviewBlockTotal;
};
this.getSubmitOrderButton = function() {
return submitOrderButton;
};
};
|
ymaps.ready(function () {
var myMap = new ymaps.Map('map', {
center: [55.648447, 37.540186],
zoom: 16,
controls: ['zoomControl']
}, {
searchControlProvider: 'yandex#search'
}),
// Создаём макет содержимого.
MyIconContentLayout = ymaps.templateLayoutFactory.createClass(
'<div style="color: #FFFFFF; font-weight: bold;">$[properties.iconContent]</div>'
),
myPlacemarkWithContent = new ymaps.Placemark([55.648, 37.540186], {
hintContent: 'ул. Бутлерова, д. 17 Б',
balloonContentHeader: 'Квадроком-персонал',
balloonContentBody: 'Москва, ул. Бутлерова, д. 17 Б, офис 60.'
}, {
preset: "islands#redStretchyIcon",
// Опции.
// Необходимо указать данный тип макета.
iconLayout: 'default#imageWithContent',
// Своё изображение иконки метки.
iconImageHref: './img/placeholder.png',
// Размеры метки.
iconImageSize: [48, 48],
// Смещение левого верхнего угла иконки относительно
// её "ножки" (точки привязки).
iconImageOffset: [-10, -80]
});
//myMap.controls.add('zoomControl');
myMap.geoObjects.add(myPlacemarkWithContent),
myMap.behaviors.disable('scrollZoom');
});
|
// User inputs the numbers/digits of Fahrenheit temperature
var inputBox = document.getElementById('numbersInputF');
var calculateC = document.getElementById("calculateC");
calculateC.onclick = function(){
if (inputBox.value ==+ "")
{ window.alert("Please input a valid temperature");
}
else {
var calculateC = Math.round((inputBox.value - 32)*(5/9)) + "°C";
resultC.innerHTML= calculateC;
}
};
var inputBoxC = document.getElementById('numbersInputC');
var calculateF = document.getElementById("calculateF");
calculateF.onclick = function(){
if (inputBoxC.value === "")
{ window.alert("Please input a valid temperature");
}
else {
var fahrenheit = Math.round((inputBoxC.value*(9/5) + 32)) + "°F";
resultF.innerHTML= fahrenheit;
}
};
// Now it's time to make the real complete calculator
|
var vm = new Vue({
el: '#app',
data: {
userName: "",
password: "",
},
methods: {
getCommodityList: function () {
console.log(vm.userName)
console.log(vm.password)
$.ajax({
type: "post",
url: "/loginapi",
data: {userName: vm.userName, passwordMd: md5(vm.password)},
success: function (data) {
console.log(data.data)
if (data.code === 200) {
var str = JSON.stringify(data.data);
$.cookie('userInfo', str);
if(document.referrer){
console.log(document.referrer)
window.location.href = document.referrer;
}else{
console.log("么有获取到 referrer,返回主页")
window.location.href = "/index.html"
}
}else{
alert("用户名密码不正确!")
}
}
});
}
}
})
|
var searchData=
[
['pagedarray_0',['PagedArray',['../class_paged_array.html',1,'']]],
['parray_1',['pArray',['../class_file_scanner.html#aa133ef6bf6e3120235efc64573404aba',1,'FileScanner']]],
['partition_2',['partition',['../class_to_quick_sort.html#a94c64b1385f47bd3d874a5f75e24798f',1,'ToQuickSort']]],
['printarray_3',['printArray',['../class_to_quick_sort.html#a94f629fce84ee769df4126537202aa20',1,'ToQuickSort']]]
];
|
import React, { Component } from 'react';
import MainLayout from "../components/layouts/mainLayout";
import Message from "../components/includes/message";
import Router from "next/router";
class About extends Component {
handleRouterStart = url => {
console.log('App is changing to : ', url);
}
handleRouterChangeComplete = url => {
console.log('App changed : ', url);
}
handleBeforeHistoryChange = url => {
console.log('App is changed to : ', url);
}
componentDidMount() {
// console.log(Router.push)
// console.log(Router.query)
// Router.beforePopState(({url, as, options}) => {
// if (as === '/contact') {
// window.location.href = "/whatever"; // redirect page to back
// window.location.href = as; // refresh page to back
// return false
// }
//
// return true
// })
// Router.replace('/contact'); // redirect page to contact
// Router.replace('/contact', '/contact/123'); // redirect page to contact
Router.events.on('routeChangeStart', this.handleRouterStart);
Router.events.on('routeChangeComplete', this.handleRouterChangeComplete);
Router.events.on('beforeHistoryChange', this.handleBeforeHistoryChange);
}
render() {
return (
<>
<MainLayout>
<h1>About Page</h1>
<Message/>
<div>
<span onClick={()=> Router.push('/users/profile/1')}>
Click Me now!!
</span>
</div>
</MainLayout>
</>
)
}
}
export default About;
|
function InitPage(module) {
InitDatepicker();
//var module = '@Model.result.tbActive';
//if ('@string.IsNullOrEmpty(Model.result.tbActive)' == "True") {
// module = "product";
//}
var liID = "li-" + module;
var tabID = module + "-tab";
$("#" + liID).addClass("active");
$("#" + tabID).addClass("active");
// Add custom class to pagination div
$.fn.dataTableExt.oStdClasses.sPaging = 'dataTables_paginate paging_bootstrap paging_custom';
$('div.dataTables_filter input').addClass('form-control');
$('div.dataTables_length select').addClass('form-control');
/*************************************************/
/************* DATATABLE *************/
/*************************************************/
/* Define two custom functions (asc and desc) for string sorting */
jQuery.fn.dataTableExt.oSort['string-case-asc'] = function (x, y) {
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
};
jQuery.fn.dataTableExt.oSort['string-case-desc'] = function (x, y) {
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
};
/* Get the rows which are currently selected */
function fnGetSelected(oTable01Local) {
return oTable01Local.$('tr.row_selected');
};
/*************************************************/
/************* DATATABLE *************/
/*************************************************/
// Add custom class to pagination div
$.fn.dataTableExt.oStdClasses.sPaging = 'dataTables_paginate paging_bootstrap paging_custom';
$('div.dataTables_filter input').addClass('form-control');
$('div.dataTables_length select').addClass('form-control');
/*************************************************/
/************* Designation DATATABLE *************/
/*************************************************/
/* Define two custom functions (asc and desc) for string sorting */
jQuery.fn.dataTableExt.oSort['string-case-asc'] = function (x, y) {
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
};
jQuery.fn.dataTableExt.oSort['string-case-desc'] = function (x, y) {
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
};
/* Add a click handler to the rows - this could be used as a callback */
$("#productDataTable tbody tr").click(function (e) {
if ($(this).hasClass('row_selected')) {
$(this).removeClass('row_selected');
}
else {
oTable01.$('tr.row_selected').removeClass('row_selected');
$(this).addClass('row_selected');
}
});
/* Add a click handler to the rows - this could be used as a callback */
$("#categoryDataTable tbody tr").click(function (e) {
if ($(this).hasClass('row_selected')) {
$(this).removeClass('row_selected');
}
else {
oTable01.$('tr.row_selected').removeClass('row_selected');
$(this).addClass('row_selected');
}
});
/* Build the DataTable with third column using our custom sort functions */
var oTable01 = $('#productDataTable').dataTable({
"sDom":
"R<'row'<'col-md-6'l><'col-md-6'f>r>" +
"t" +
"<'row'<'col-md-4 sm-center'i><'col-md-4'><'col-md-4 text-right sm-center'p>>",
"oLanguage": {
"sSearch": ""
},
"aaSorting": [[0, 'asc']],
"fnInitComplete": function (oSettings, json) {
$('.dataTables_filter input').attr("placeholder", "Search");
}
});
/* Build the DataTable with third column using our custom sort functions */
var oTable01 = $('#categoryDataTable').dataTable({
"sDom":
"R<'row'<'col-md-6'l><'col-md-6'f>r>" +
"t" +
"<'row'<'col-md-4 sm-center'i><'col-md-4'><'col-md-4 text-right sm-center'p>>",
"oLanguage": {
"sSearch": ""
},
"aaSorting": [[0, 'asc']],
"fnInitComplete": function (oSettings, json) {
$('.dataTables_filter input').attr("placeholder", "Search");
}
});
/* Get the rows which are currently selected */
function fnGetSelected(oTable01Local) {
return oTable01Local.$('tr.row_selected');
};
//initialize chosen
$('.dataTables_length select').chosen({ disable_search_threshold: 10 });
// Add custom class
$('div.dataTables_filter input').addClass('form-control');
$('div.dataTables_length select').addClass('form-control');
}
function InitDataTable(id) {
}
//function printBarcode(productCode, productName, price) {
// $("#barcodeprint").barcode(productCode, "code128", { barWidth: 1.8, barHeight: 29 });
// $("#itemnameprint").text(productName);
// $("#itempriceprint").text('$ ' + price);
// var contents = $("#barcodeSlipPrint").html();
// var frame1 = $('<iframe />');
// frame1[0].name = "frame1";
// frame1.css({ "position": "absolute", "top": "-1000000px" });
// $("body").append(frame1);
// var frameDoc = frame1[0].contentWindow ? frame1[0].contentWindow : frame1[0].contentDocument.document ? frame1[0].contentDocument.document : frame1[0].contentDocument;
// frameDoc.document.open();
// //Create a new HTML document.
// frameDoc.document.write('<html><head><title>Inventory</title>');
// frameDoc.document.write('</head><body>');
// frameDoc.document.write(contents);
// frameDoc.document.write('</body></html>');
// frameDoc.document.close();
// setTimeout(function () {
// window.frames["frame1"].focus();
// window.frames["frame1"].print();
// frame1.remove();
// }, 500);
//};
|
import React from "react";
import {Circle, Popup} from 'react-leaflet';
import numeral from 'numeral'
const caseTypeColor = {
cases: {
hex: "#cc1034",
multiplier: 800
},
recovered: {
hex: "#7dd71d",
multiplier: 1200
},
deaths: {
hex: "fb4443",
multiplier: 2000
},
};
export const showDataOnMap = (data, caseType) => {
return(
data.map((country, i)=> (
<Circle
// 用pathoptions才能修改資料
pathOptions={{color: caseTypeColor[caseType].hex,
fillColor:caseTypeColor[caseType].hex}}
key={i}
center={[country.countryInfo.lat, country.countryInfo.long]}
// color={caseTypeColor[caseType].hex}
// fillColor={caseTypeColor[caseType].hex}
fillOpacity={0.4}
radius={Math.sqrt(country[caseType])*caseTypeColor[caseType].multiplier}
>
<Popup>
<div className="info-container">
<img className="info-flag" src={country.countryInfo.flag} alt=""/>
{/* <div className="info-flag" style={{background:`url(${country.countryInfo.flag})`}}></div> */}
<div className="info-name">{country.country}</div>
<div className="info-confirmed">Cases: {numeral(country.cases).format('0,0')}</div>
<div className="info-recovered">Recovered: {numeral(country.recovered).format('0,0')}</div>
<div className="info-deaths">Deaths: {numeral(country.deaths).format('0,0')}</div>
</div>
</Popup>
</Circle>
))
)};
|
import React,{ Component } from 'react';
import { Layout, Menu, Icon } from 'antd';
import { NavLink } from 'react-router-dom';
const { SubMenu } = Menu;
const { Sider } = Layout;
import './index.css';
class AdminSider extends Component {
render(){
return (
<div className="AdminSider">
<Sider width={200} style={{ background: '#fff' }}>
<Menu
mode="inline"
style={{ minHeight: 880, borderRight: 0 }}
>
<Menu.Item key="1">
<NavLink exact to="/">首页</NavLink>
</Menu.Item>
<Menu.Item key="2">
<NavLink to="/user">用户管理</NavLink>
</Menu.Item>
</Menu>
</Sider>
</div>
)
}
}
export default AdminSider;
|
$(document).ready(function () {
$('input[type=checkbox]').css('margin-right', '10px');
$('input[type=checkbox]').on('click', function () {
var amenId = [];
$('input:checked').each(function () {
amenId[$(this).attr('data-id')] = $(this).attr('data-name');
});
$('input:disabled').each(function () {
$(amenId).removeData($(this).attr('data-id'));
});
var list = [];
for (var name in amenId) {
list.push(amenId[name]);
}
$('.amenities h4').text(list.join(', '));
});
});
|
import { logout } from '../actions/auth';
import { CLEAR_DATA } from '../actions';
export const getLocalStorageJWT = () => {
try {
return JSON.parse(localStorage.getItem('state.auth.tokens')) || undefined;
} catch (e) {
return undefined;
}
};
export const saveJWT = (state) => {
if (!state.auth || !state.auth.tokens) {
return;
}
if (Object.entries(state.auth.tokens).length === 0 && state.auth.tokens.constructor === Object) {
localStorage.removeItem('state.auth.tokens');
} else {
localStorage.setItem('state.auth.tokens', JSON.stringify(state.auth.tokens));
}
};
export const isLoggedIn = (state) => {
return state.auth.tokens.refreshExpiration > Date.now();
};
export const isAdmin = (state) => {
return isLoggedIn(state) && state.auth.user && state.auth.user.isStaff;
};
export const getCookieValue = (name) => {
const value = document.cookie.match('(^|[^;]+)\\s*' + name + '\\s*=\\s*([^;]+)');
return value ? value.pop() : '';
};
export const logoutAndReset = (history) => {
return (dispatch) => {
dispatch(logout());
dispatch({ type: CLEAR_DATA });
if (history) {
history.push('/');
}
};
};
|
import React, { Component } from "react";
import propTypes from "prop-types";
import { FlipGameCard, FlipGameOptions } from "components";
import GamePage from "containers/GamePage";
import UserContext from "containers/App/UserContext";
import coinFlipBet from "lib/api/coinFlip";
import Cache from "../../lib/cache/cache";
import { find } from "lodash";
import { connect } from "react-redux";
import { compose } from 'lodash/fp';
import { setWonPopupMessageDispatcher } from "../../lib/redux";
const defaultState = {
edge : 0,
flipResult: null,
hasWon: null,
game_name : 'CoinFlip',
isCoinSpinning : false,
game : {
edge : 0
},
amount: 0
}
class FlipPage extends Component {
static contextType = UserContext;
static propTypes = {
onHandleLoginOrRegister: propTypes.func.isRequired
};
constructor(props){
super(props);
this.state = defaultState;
}
componentDidMount(){
this.getGame()
}
handleAnimationEnd = () => {
this.setState({ isCoinSpinning: false }, () => {
this.handleUpdateBalance();
});
};
handleAnimationStart = () => {
this.setState({ isCoinSpinning: true });
};
handleUpdateBalance = async () => {
const { profile } = this.props;
const { amount } = this.state;
const { result, hasWon, winAmount, userDelta, totalBetAmount } = this.state.betObjectResult;
setWonPopupMessageDispatcher(winAmount);
await profile.updateBalance({ userDelta, amount, totalBetAmount });
this.addToHistory({result : `${result} `, won : hasWon})
};
handleEnableControls = () => {
this.setState({ disableControls: false, flipResult: null });
};
addToHistory = ({result, won}) => {
try {
let history = Cache.getFromCache("flipHistory");
history = history ? history : [];
history.unshift({ value: result, win : won });
Cache.setToCache("flipHistory", history);
} catch (error) {
console.log(error);
}
}
onBet = async form => {
this.setState({onBet : true, disableControls : true})
let res = await this.handleBet(form);
this.setState({onBet : false});
return res;
}
handleBet = async ({amount, side}) => {
try{
const { user } = this.context;
const { onHandleLoginOrRegister } = this.props;
if (!user) return onHandleLoginOrRegister("register");
const res = await coinFlipBet({
betAmount : amount,
side,
user
});
const { result, hasWon } = res;
this.setState({
flipResult : result,
betObjectResult :res,
hasWon,
isCoinSpinning : true,
amount
});
return res;
}catch(err){
return this.setState({
flipResult : 0,
hasWon : false,
disableControls: false
});
}
};
getOptions = () => {
const { disableControls } = this.state;
const { profile } = this.props;
return (
<FlipGameOptions
onBet={this.onBet}
profile={profile}
game={this.state.game}
isCoinSpinning={this.state.isCoinSpinning}
disableControls={disableControls}
/>
);
};
getGameCard = () => {
const { flipResult, hasWon } = this.state;
const { profile } = this.props;
return (
<FlipGameCard
updateBalance={this.handleUpdateBalance}
flipResult={flipResult}
profile={profile}
onBetTrigger={this.state.onBet}
handleAnimationEnd={this.handleAnimationEnd}
handleAnimationStart={this.handleAnimationStart}
isCoinSpinning={this.state.isCoinSpinning}
game={this.state.game}
hasWon={hasWon}
onResult={this.handleEnableControls}
/>
);
};
getGame = () => {
const appInfo = Cache.getFromCache("appInfo");
if(appInfo){
let game = find(appInfo.games, { name: this.state.game_name });
this.setState({...this.state, game});
}
};
render() {
const { onTableDetails } = this.props;
return (
<GamePage
options={this.getOptions()}
game={this.getGameCard()}
history="flipHistory"
gameMetaName={this.state.game.metaName}
onTableDetails={onTableDetails}
/>
);
}
}
function mapStateToProps(state){
return {
profile: state.profile,
ln : state.language
};
}
export default compose(connect(mapStateToProps))(FlipPage);
|
import React from 'react';
import './dashboard.css'
import {withRouter} from 'react-router-dom'
class Dashboard extends React.Component {
constructor(props){
super(props);
this.state={
selectedCategory:'',
buttonclicked:true
}
}
onchangeSelcet=(e)=>{
// console.log(e.target.value)
this.setState({selectedCategory:e.target.value})
}
dashboardform=(e)=>{
e.preventDefault();
// console.log('hello')
this.setState({buttonclicked:true})
// console.log(this.state.selectedCategory)
// console.log(this.state.buttonclicked)
this.props.parentcategory(this.state.selectedCategory)
}
componentDidMount(){
if(localStorage.getItem('loggedIn') === null){
this.props.history.push('/');
}
}
render() {
return (
<div className="dashboardCss">
<h1>Dashboard</h1>
<div className="dashboard-form">
<form onSubmit={this.dashboardform}>
<table>
<thead></thead>
<tbody>
<tr>
<td><span className="star">*</span><b>Select Category</b></td>
<td>
<select onChange={this.onchangeSelcet} required>
<option value=''>Select One</option>
<option value="Groceries">Groceries</option>
<option value="Electronics">Electronics</option>
<option value="Vegitables">Vegitables</option>
<option values="Fruits">Fruits</option>
</select>
</td>
</tr>
<tr>
<td>
</td>
<td><button type="submit">Submit</button></td>
</tr>
</tbody>
</table>
</form>
</div>
</div>
);
}
}
export default withRouter(Dashboard);
|
document.addEventListener("DOMContentLoaded", function() {
var mouse = {
click: false,
move: false,
pos: {x:0, y:0},
pos_prev: false
};
var canvas = document.getElementById('doodle');
var context = canvas.getContext('2d');
//Establish the WebSocket connection and set up event handlers
var socket = new WebSocket("ws://" + location.hostname + ":" + location.port + "/doodle");
canvas.onmousedown = function(e) {
startDrawing();
};
handleTouchStart = function(e) {
e.preventDefault();
startDrawing();
}
startDrawing = function() {
mouse.click = true;
//re-establish the websocket on clicks so that we can keep doodling after heroku kills us
if (socket.readyState === 0) {
socket = new WebSocket("ws://" + location.hostname + ":" + location.port + "/doodle");
}
}
sendWhenConnected = function (message, interval) {
if (socket.readyState === 1) {
socket.send(message);
} else {
setTimeout(function () {
sendWhenConnected(socket.send(message), interval);
}, interval);
}
};
canvas.onmouseup = function(e) {
stopDrawing();
};
handleTouchStop = function(e) {
stopDrawing();
}
stopDrawing = function() {
mouse.click = false;
}
canvas.onmousemove = function(e) {
sendPenPosition(e.clientX, e.clientY);
};
handleTouchMove = function(e) {
sendPenPosition(e.changedTouches[0].clientX, e.changedTouches[0].clientY);
}
sendPenPosition = function(xpos, ypos) {
mouse.pos.x = xpos;
mouse.pos.y = ypos;
mouse.move = true;
}
canvas.addEventListener("touchstart", handleTouchStart, false);
canvas.addEventListener("touchmove", handleTouchMove, false);
canvas.addEventListener("touchCancel", handleTouchStop, false);
canvas.addEventListener("touchEnd", handleTouchStop, false);
var eraser = document.getElementById('eraser');
eraser.onclick = function() {
context.clearRect(0, 0, canvas.width, canvas.height);
}
socket.onmessage = function (event) {
var parsedData = JSON.parse(event.data);
var line = parsedData.line;
context.beginPath();
context.moveTo(line[0].x, line[0].y);
context.lineTo(line[1].x, line[1].y);
context.stroke();
};
// main loop, running every 25ms
function loop() {
// check if the user is drawing
if (mouse.click && mouse.move && mouse.pos_prev) {
// send line to to the server
var data = {line: [{x: mouse.pos.x, y: mouse.pos.y}, {x: mouse.pos_prev.x, y: mouse.pos_prev.y}]};
sendWhenConnected(JSON.stringify(data), 1000);
mouse.move = false;
}
// conditional to avoid always drawing a line from the origin on touch events
if (mouse.pos.x != 0) {
mouse.pos_prev = {x: mouse.pos.x, y: mouse.pos.y};
}
setTimeout(loop, 25);
}
loop();
});
|
'use strict';
angular.module('myShoppinglistApp')
.controller
(
'ShoppinglistCtrl'
, function ($scope, $location, $http, $mdDialog)
{
var vm = this;
vm.queryString = $location.search();
vm.thisShoppinglist = '';
vm.iconMap = {"true":"maps:beenhere", "false":"action:done"};
$http.get('/api/shoppinglists/'+vm.queryString.id).success(
function(data)
{
vm.thisShoppinglist = data;
/*$http.get('/api/user/'+vm.thisShoppinglist.owner).then(
function(data){
vm.listOwner = data;
},function(data)
{});*/
}
);
$http.get('/api/stores').success(
function(data)
{
vm.allStores = data;
}
);
$http.get('/api/items').success(
function(data)
{
vm.allItems = data;
}
);
vm.newAdd = function()
{
var data =
{
name:vm.selectedItem.name,
description:vm.selectedItem.description,
store :
{
name:vm.selectedStore.name,
description:vm.selectedStore.description,
street:vm.selectedStore.street,
city:vm.selectedStore.city,
state:vm.selectedStore.state,
geocode:vm.selectedStore.geocode,
},
cost : vm.selectedItem.cost,
taxflag : vm.newTax,
done:false
};
vm.addItem(data);
vm.newLabel = "Added: " + data;
};
vm.saveChanges = function ()
{
$http.put('/api/shoppinglists/'+vm.thisShoppinglist._id, vm.thisShoppinglist);
console.log(vm.thisShoppinglist._id);
};
vm.deleteItem = function(item)
{
var index = vm.thisShoppinglist.listItems.indexOf(item);
vm.thisShoppinglist.listItems.splice(index, 1);
//$http.put('/api/shoppinglists/'+vm.thisShoppinglist._id, vm.thisShoppinglist);
};
vm.addItem = function(data)
{
vm.thisShoppinglist.listItems.push(data);
$http.put('/api/shoppinglists/'+vm.thisShoppinglist._id, vm.thisShoppinglist);
};
//mdDialog
/*
var alert;
vm.showAlert = showAlert;
vm.showDialog = showCustomGreeting;
vm.listItems=[1,2,3];
// Dialog #1 - Show simple alert dialog and cache
// reference to dialog instance
function showAlert() {
alert = $mdDialog.alert()
.title('Attention, ' + vm.userName)
.content('This is an example of how easy dialogs can be!')
.ok('OK');
$mdDialog
.show( alert )
.finally(function() {
alert = undefined;
});
}
function showCustomGreeting($event) {
var parentEl = angular.element(document.body);
$mdDialog.show({
parent: parentEl,
targetEvent: $event,
template:
'<md-dialog aria-label="Add Item Dialog">' +
' <md-dialog-content>'+
' <md-list>'+
' <md-list-item ng-repeat="item in items">'+
' <p>Number {{item}}</p>' +
' '+
' </md-list-item></md-list>'+
' </md-dialog-content>' +
' <md-dialog-actions>' +
' <md-button ng-click="closeDialog()" class="md-primary">' +
' Close Dialog' +
' </md-button>' +
' </md-dialog-actions>' +
'</md-dialog>',
locals: {
items: vm.listItems
},
controller: DialogController
});
function DialogController($scope, $mdDialog, items) {
vm.listItems = items;
vm.closeDialog = function() {
$mdDialog.hide();
}
}
}*/
}
);
|
// want to test firebase app out. Want to have app that interacts
//with the user,and uses in app messaging with FireBase
//will need a main function with the ability to add users to an object
//or an array to document and leave open the ability to communicate with
//each user.
//within the function I will need a loop to check for responses
// buttons for submission (may use a Form Style format on Bootstrap)
//will need vars but not sure where yet putting them here until I find a spot
//will have a userComment
const userComment= "";
//creating an on click function tied to the created class1 in the empty div
$(document).on("click", ".class1", function(){
//trying to set up a var for class1 so that I can console log it easier
let class1 = $(".class1");
console.log("This is class1: " + class1);
})
|
(function (ko, $p, toastr) {
ko.components.register('ticket-editor', {
viewModel: function (params) {
$p.guard(params.eventId, 'eventId');
var me = this,
adDesignService = new $p.AdDesignService(params.adId),
eventService = new $p.EventService(),
resendGuestNotifications = false;
me.eventId = ko.observable(params.eventId); // Must be set!
me.eventTicketId = ko.observable();
me.ticketName = ko.observable();
me.isActive = ko.observable(true);
me.availableQuantity = ko.observable(); // Only available in create
me.remainingQuantity = ko.observable(); // Only available in edit
me.price = ko.observable();
me.eventTicketFields = ko.observableArray();
me.editMode = ko.observable(false);
me.soldQty = ko.observable();
me.colourCode = ko.observable();
me.displayGuestPurchasesWarning = ko.observable(false);
me.displayNotificationProgress = ko.observable(false);
me.ticketHasPurchases = ko.observable(false);
me.guestsAffected = ko.observable(0);
me.guestsNotified = ko.observable(0);
me.ticketImage = ko.observable();
me.onSave = params.onSave;
var ticketDetails = params.ticketDetails;
if (ticketDetails) {
me.eventTicketId(ticketDetails.eventTicketId);
me.editMode(true);
me.ticketName(ticketDetails.ticketName);
me.availableQuantity(ticketDetails.availableQuantity);
me.remainingQuantity(ticketDetails.remainingQuantity);
me.isActive(ticketDetails.isActive);
me.price(ticketDetails.price);
me.colourCode(ticketDetails.colourCode);
me.ticketHasPurchases(ticketDetails.soldQty > 0);
me.soldQty(ticketDetails.soldQty);
me.ticketImage(ticketDetails.ticketImage);
_.each(ticketDetails.eventTicketFields, function (field) {
me.eventTicketFields.push(new $p.models.DynamicFieldDefinition(me, field));
});
}
me.addField = function () {
me.eventTicketFields.push(new $p.models.DynamicFieldDefinition(me));
if (me.ticketHasPurchases() === true) {
me.displayGuestPurchasesWarning(true);
}
}
me.removeField = function (field) {
me.eventTicketFields.remove(field);
if (me.ticketHasPurchases() === true) {
me.displayGuestPurchasesWarning(true);
}
}
me.saveTicket = function (model, event) {
me.saveWithoutSendingNotifications(model, event);
}
me.ticketName.subscribe(function () {
if (me.ticketHasPurchases()) {
me.displayGuestPurchasesWarning(true);
}
});
me.saveWithoutSendingNotifications = function (model, event) {
resendGuestNotifications = false;
save(model, event);
}
me.saveAndSendNotifications = function (model, event) {
resendGuestNotifications = true;
save(model, event);
}
me.removeImage = function (imageId) {
me.ticketImage(null);
}
function save(model, event, options) {
if (!$p.checkValidity(me)) {
return;
}
var $btn = $(event.target);
$btn.loadBtn();
// maps to UpdateEventTicketViewModel.cs
var data = _.extend(options, {
eventTicket: ko.toJS(me)
});
if (me.editMode()) {
adDesignService.editTicket(data)
.then(handleResponse)
.then(notify)
.then(function (pr) {
pr.then(function () {
me.displayNotificationProgress(false);
$btn.resetBtn();
});
});
}
else {
adDesignService.addEventTicket(data.eventTicket).then(function (newTicket) {
if (me.onSave) {
me.onSave(newTicket);
}
// Clear the current data
me.ticketName(null);
me.price(null);
me.eventTicketFields.removeAll();
me.availableQuantity(null);
me.isActive(true);
me.remainingQuantity(null);
});
}
}
function handleResponse(resp) {
return new Promise(function (resolve, reject) {
if (resp.errors) {
if (_.some(resp.errors, ['key', 'GuestCountIncreased'])) {
me.displayGuestPurchasesWarning(true);
reject(resp);
}
reject(resp);
}
if (resendGuestNotifications === false) {
toastr.success("Ticket details saved successfully");
}
resolve(resp);
});
}
function notify() {
return new Promise(function (resolve, reject) {
if (resendGuestNotifications === false) {
resolve();
me.displayGuestPurchasesWarning(false);
return;
}
eventService.getGuestsForTicket(me.eventId(), me.eventTicketId()).then(function (guests) {
if (guests.errors) {
reject(guests.errors);
}
me.displayNotificationProgress(true);
me.guestsAffected(guests.length);
me.guestsNotified(1);
var emailFuncs = _.map(guests, function (g) {
return function () {
return new Promise(function (resendResolve) {
eventService.resendGuestEmail(g.ticketNumber)
.then(function (res) {
resendResolve(res);
});
});
}
});
$p.processPromises(emailFuncs, function () {
me.guestsNotified(me.guestsNotified() + 1);
}).then(function () {
resolve(guests);
me.displayGuestPurchasesWarning(false);
me.displayNotificationProgress(false);
toastr.success('Done! The guests should receive an email with updated ticket information.');
});
});
});
}
},
template: { path: $p.baseUrl + 'Scripts/app/events/ticketEditor/ticket-editor.html' }
});
})(ko, $paramount, toastr);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.